context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public class Main_AudioSync : MonoBehaviour
{
public bool debugMode;
// original ship location
public GameObject shiporigin;
// the ship
public GameObject ship;
public GameObject[] powerups;
public GameObject animationTrigger;
// audio source containing the track
public AudioSource audio1;
// map of <Object spawn time:spawned object id> based on music
private SortedDictionary<int, int> audio1Map;
// index of the previous obstacle
private int prevObstacleID = 0;
// index of the next object to be loaded
private int nextObstacleID = 0;
// index of the previous powerup
private int prevPOID = 0;
// index of the next powerup
private int nextPOID = 0;
//Animator for player shield
private Animator shieldAnim;
// actualy the ships shields/hp
public int health = 100;
public int shields = 100;
// score
public int score; //score
// max left/right movement
public float XLimit;
// relative velocity of the objects to the ship
public float shipSpeed;
// distance in front of player objects pop at
public int setTimeInFrontOfPlayer;
public GameObject initialterrain;
// pool of terrain objects
public GameObject[] terrainMap;
// time for each terrain object to fly past player(256/shipspeed)
public float terrainDuration;
// id of previous
private int prevTerrain = 0;
// index of next terrain chunk
private int nextTerrain = 0;
// spawn of the terrain objects
public GameObject terrainOrigin;
public int objectSpawnYOffset;
private bool hasStarted = false;
float songtime;
private Animator shipAnimator;
// Acceleration for ship side movement
public float currentVelocity = 0.0f;
public float accelerationRate = 1.0f;
private float direction = 0.0f;
private float turnLeft = 0f;
private float turnRight = 0f;
//for music calculations DONT CHANGE
int ppqn = 480;
int tempo = 260;
// MenuSystem script for Game navigation
private MenuSystem menuSystem;
//score multiplier
public float scoreMultiplier = 1;
// First Song Length
// For level complete state testing
private int songLengthMilliseconds = 5000;
public int ticks;
int previousFrameTimer;
// Starts the game by initialising all variables
void Start()
{
shipAnimator = GetComponentsInChildren<Animator>()[0];
// initialising vriables
terrainDuration = 200 / shipSpeed;
//audio1 = GetComponent<AudioSource>();
// sets the ship to the origin
this.gameObject.transform.position = shiporigin.transform.position;
// Get MenuSystem
menuSystem = GameObject.Find("ShipCamera").GetComponent<MenuSystem>();
initialterrain.transform.position = terrainOrigin.transform.position - Vector3.forward * 256;
initialterrain.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, -shipSpeed);
//begin music
//audio1.Play();
songtime = 0F;
shieldAnim = GameObject.Find("Shield").GetComponent<Animator> ();
}
// Update is called once per frame
void Update()
{
songtime += Time.deltaTime;
// current audio playtime
double playtime = songtime;// audio1.time;
// convert time in seconds to time in ms
int timeMS = (int)(playtime * 1000);
// generate terrain
if (timeMS > terrainDuration * nextTerrain * 1000)
{
int maxTerrain = terrainMap.Length;
//print(maxTerrain
int nextTerrainIndex = nextTerrain % maxTerrain;
// print (nextTerrainIndex);
GameObject spawned = terrainMap[nextTerrainIndex];// [next.Value];
spawned.transform.position = terrainOrigin.transform.position;
spawned.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, -shipSpeed);
nextTerrain++;
}
// Movement check gameover
if (!menuSystem.isActive())
{
if ((Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow) || Input.GetButtonDown("B")) && this.gameObject.transform.position.x <= XLimit)
{
CalcAcceleration(1f);
if (turnRight < 1f)
{
turnRight += 0.2f;
}
performMove();
}
else {
turnRight = 0;
}
if ((Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow) || Input.GetButtonDown("X")) && this.gameObject.transform.position.x >= -XLimit)
{
CalcAcceleration(-1f);
if (turnLeft < 1f)
{
turnLeft += 0.2f;
}
performMove();
}
else {
turnLeft = 0;
}
shipAnimator.SetFloat("LeftAmount", turnLeft);
shipAnimator.SetFloat("RightAmount", turnRight);
//Friction
currentVelocity *= 0.9f;
}
// Level Complete
if (!menuSystem.isActive() && audio1.time >= audio1.clip.length)
{
menuSystem.levelComplete();
}
}
private void spawnAndMove(GameObject obj)
{
Vector3 spawnPoint = new Vector3(this.transform.position.x, this.transform.position.y - objectSpawnYOffset,
animationTrigger.transform.position.z + setTimeInFrontOfPlayer * shipSpeed) + Vector3.left * UnityEngine.Random.Range(-10, 10);
obj.transform.position = spawnPoint;
obj.GetComponent<Rigidbody>().velocity = new Vector3(0f, 0f, -shipSpeed);
}
void performMove()
{
if (this.gameObject.transform.position.x > XLimit)
{
this.gameObject.transform.position = new Vector3(
XLimit,
this.gameObject.transform.position.y,
this.gameObject.transform.position.z
);
}
else if (this.gameObject.transform.position.x < -XLimit)
{
this.gameObject.transform.position = new Vector3(
-XLimit,
this.gameObject.transform.position.y,
this.gameObject.transform.position.z
);
}
else {
this.gameObject.transform.position = new Vector3(
this.gameObject.transform.position.x + (currentVelocity),
this.gameObject.transform.position.y,
this.gameObject.transform.position.z
);
}
}
void CalcAcceleration(float dir)
{
currentVelocity += ((dir * accelerationRate) * Time.deltaTime);
}
//test for collision
//test for collision
void OnCollisionEnter(Collision collision)
{
// do nothing if hit terrain
if (collision.gameObject.tag == "Terrain")
{
// print ("Hit terrain");
return;
}
// add shields, do nothing if at max shields
else if (collision.gameObject.tag == "Shield")
{
pickupShields();
collision.gameObject.SetActive(false);
}
// add health, do nothing if at max health
else if (collision.gameObject.tag == "Health")
{
pickupHealth();
collision.gameObject.SetActive(false);
}
// hit a score tag object
else if (collision.gameObject.tag == "Score")
{
//print("HIT SCORE!!!!!");
//pickupScore();
//Destroy(collision.gameObject);
}
// disable tracer visual on hit(should not happeN)
else if (collision.gameObject.tag == "Tracer")
{
collision.gameObject.SetActive(false);
}
// hit a bad object
else if(!debugMode) {
//reset score multiplier
scoreMultiplier = 1;
// hit something with ship shields remaining
if (shields > 0)
{
collisionShields();
shields = shields - 25;
if (shields < 0) shields = 0;
}
// hit something reduce health
else if (health > 0)
{
collisionHealth();
health = health - 25;
if (health < 0) health = 0;
}
// no more player health gameover
if (health <= 0)
{
GameOver();
}
collision.gameObject.SetActive(false);
}
collision.gameObject.SetActive(false);
}
// Sounds for Shield Collisions
private void collisionShields()
{
shieldAnim.SetTrigger ("TakeHit");
// Camera Shake!
GameObject.Find("ShipCamera").GetComponent<CameraShake>().shakeDuration = 1.0f;
GameObject.Find("ShipCamera").GetComponent<CameraShake>().shakeAmount = 0.7f;
// Audio for shields hit
AudioSource shieldsCollisionAudio = GameObject.Find("ShieldCollision").GetComponent<AudioSource>();
shieldsCollisionAudio.Play();
}
// Sounds for Health Collisions
private void collisionHealth()
{
// Camera Shake!
GameObject.Find("ShipCamera").GetComponent<CameraShake>().shakeDuration = 1.0f;
GameObject.Find("ShipCamera").GetComponent<CameraShake>().shakeAmount = 0.7f;
// Audio for Health hit
AudioSource shieldsCollisionAudio = GameObject.Find("HealthCollision").GetComponent<AudioSource>();
shieldsCollisionAudio.Play();
}
private void pickupScore()
{
// Audio for score pickups
AudioSource audio = GameObject.Find("Pickup1").GetComponent<AudioSource>();
audio.Play();
}
private void pickupHealth()
{
if (health >= 100)
{
// health is full, add to score instead
ScoreController _score = GameObject.Find("GameManager").GetComponent<ScoreController>();
ScorePickupController scoreC = FindObjectOfType<ScorePickupController>() as ScorePickupController;
_score.incrementScore(scoreC.scoreAmount);
}
else
{
// add to health
health = health + 25;
if (health > 100) health = 100;
}
// Audio for Health pickups
AudioSource audio = GameObject.Find("Pickup2").GetComponent<AudioSource>();
audio.Play();
}
private void pickupShields()
{
if (shields >= 100)
{
// shields are full, add to score instead
ScoreController score = FindObjectOfType<ScoreController>() as ScoreController;
ScorePickupController scoreC = FindObjectOfType<ScorePickupController>() as ScorePickupController;
score.incrementScore(scoreC.scoreAmount);
}
else
{
// add to shields
shields = shields + 25;
if (shields > 100) shields = 100;
}
// Audio for shield pickups
AudioSource audio = GameObject.Find("Pickup3").GetComponent<AudioSource>();
audio.Play();
}
public void GameOver()
{
// Call menuSystem GameOver
menuSystem.gameOver();
}
public AudioSource getAudio()
{
return audio1;
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Metadata;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Cms;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Microsoft.Xrm.Portal.Web.UI.WebControls
{
/// <summary>
/// Renders a web link set (adx_weblinkset) as a list of links.
/// </summary>
public class WebLinks : EditableCrmEntityDataBoundControl // MSBug #120119: Won't seal, Inheritance is expected extension point.
{
private bool _showCopy = true;
private bool _showLinkDescriptions = true;
private bool _showImage = true;
private bool _showTitle = true;
/// <summary>
/// Gets or sets a CSS class value to be added to the hyperlink if the target node of
/// the hyperlink is the current site map node.
/// </summary>
[Description("A CSS class value to be added to a weblink if the target node of the weblink is the current site map node")]
[Category("Data")]
[DefaultValue((string)null)]
public string CurrentSiteMapNodeCssClass { get; set; }
/// <summary>
/// Gets or sets a CSS class value to be added to the hyperlink if the current site map
/// node is a descendant of the target node of the hyperlink.
/// </summary>
[Description("A CSS class value to be added to a weblink if the current site map node is a descendant of the target node of the weblink")]
[Category("Data")]
[DefaultValue((string)null)]
public string ParentOfCurrentSiteMapNodeCssClass { get; set; }
public string DescriptionCssClass { get; set; }
public bool ShowCopy
{
get { return _showCopy; }
set { _showCopy = value; }
}
public bool ShowImage
{
get { return _showImage; }
set { _showImage = value; }
}
public bool ShowLinkDescriptions
{
get { return _showLinkDescriptions; }
set { _showLinkDescriptions = value; }
}
public bool ShowTitle
{
get { return _showTitle; }
set { _showTitle = value; }
}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}
public string WebLinkSetName { get; set; }
protected override void OnLoad(EventArgs args)
{
Entity webLinkSet;
if (TryGetWebLinkSetEntity(WebLinkSetName, out webLinkSet))
{
DataItem = webLinkSet;
}
base.OnLoad(args);
}
protected override void PerformDataBindingOfCrmEntity(Entity entity)
{
var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
var context = portal.ServiceContext;
entity = context.MergeClone(entity);
if (ShowTitle)
{
Controls.Add(new Property
{
PropertyName = GetPropertyName(context, entity, "adx_title"),
CssClass = "weblinkset-title",
EditType = "text",
DataItem = entity
});
}
if (ShowCopy)
{
Controls.Add(new Property
{
PropertyName = GetPropertyName(context, entity, "adx_copy"),
CssClass = "weblinkset-copy",
EditType = "html",
DataItem = entity
});
}
var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName);
var weblinks = entity.GetRelatedEntities(context, "adx_weblinkset_weblink")
.Where(e => securityProvider.TryAssert(context, e, CrmEntityRight.Read))
.OrderBy(weblink => weblink.GetAttributeValue<int?>("adx_displayorder"))
.ToList();
var weblinkCount = weblinks.Count();
var listItems = weblinks.Select((weblink, index) =>
{
var li = new HtmlGenericControl("li");
SetPositionalClassAttribute(li, weblinkCount, index);
if (ItemTemplate != null)
{
var item = CreateItem(this, index, ListItemType.Item, true, weblink);
Controls.Remove(item);
li.Controls.Add(item);
}
else
{
li.Controls.Add(GetHyperLinkForWebLink(weblink));
if (ShowLinkDescriptions)
{
var description = new HtmlGenericControl("div");
description.Controls.Add(new Property
{
PropertyName = GetPropertyName(context, weblink, "adx_description"),
DataItem = weblink,
Literal = true
});
if (!string.IsNullOrEmpty(DescriptionCssClass))
{
description.Attributes["class"] = DescriptionCssClass;
}
li.Controls.Add(description);
}
}
return li;
});
var container = new HtmlGenericControl("div");
var containerCssClasses = new List<string> { "weblinkset-weblinks" };
Controls.Add(container);
if (listItems.Any())
{
var list = new HtmlGenericControl("ul");
foreach (var li in listItems)
{
list.Controls.Add(li);
}
container.Controls.Add(list);
}
if (Editable)
{
containerCssClasses.Add("xrm-entity");
containerCssClasses.Add("xrm-editable-{0}".FormatWith(entity.LogicalName));
if (HasEditPermission(entity))
{
var metadataProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityEditingMetadataProvider>();
metadataProvider.AddEntityMetadata(PortalName, this, container, entity);
this.RegisterClientSideDependencies();
}
}
container.Attributes["class"] = string.Join(" ", containerCssClasses.ToArray());
}
protected override void PerformDataBindingOfCrmEntityProperty(Entity entity, string propertyName, string value)
{
PerformDataBindingOfCrmEntity(entity);
}
private HyperLink GetHyperLinkForWebLink(Entity weblink)
{
var hyperLink = new WebLinkHyperLink
{
WebLink = weblink, ShowImage = ShowImage, CurrentSiteMapNodeCssClass = CurrentSiteMapNodeCssClass, ParentOfCurrentSiteMapNodeCssClass = ParentOfCurrentSiteMapNodeCssClass, PortalName = PortalName
};
if (Editable)
{
hyperLink.CssClass = "xrm-weblink {0}".FormatWith(hyperLink.CssClass);
}
return hyperLink;
}
private bool TryGetWebLinkSetEntity(string webLinkSetName, out Entity webLinkSet)
{
webLinkSet = null;
if (string.IsNullOrEmpty(webLinkSetName))
{
return false;
}
var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
var context = portal.ServiceContext;
webLinkSet = context.GetLinkSetByName(portal.Website, WebLinkSetName);
var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName);
return webLinkSet != null && securityProvider.TryAssert(context, webLinkSet, CrmEntityRight.Read);
}
private static void SetPositionalClassAttribute(HtmlControl control, int weblinkCount, int index)
{
var positionalCssClasses = new List<string>();
if (index == 0)
{
positionalCssClasses.Add("first");
}
if (index == (weblinkCount - 1))
{
positionalCssClasses.Add("last");
}
if (weblinkCount == 1)
{
positionalCssClasses.Add("only");
}
if (positionalCssClasses.Count > 0)
{
control.Attributes["class"] = string.Join(" ", positionalCssClasses.ToArray());
}
}
private static string GetPropertyName(OrganizationServiceContext context, Entity entity, string logicalName)
{
EntitySetInfo esi;
AttributeInfo ai;
if (OrganizationServiceContextInfo.TryGet(context, entity, out esi)
&& esi.Entity.AttributesByLogicalName.TryGetValue(logicalName, out ai))
{
return ai.Property.Name;
}
throw new InvalidOperationException("The '{0}' entity does not contain an attribute with the logical name '{1}'.".FormatWith(entity, logicalName));
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using hihapi.Models;
namespace hihapi
{
public class hihDataContext : DbContext
{
public hihDataContext()
{
TestingMode = false;
}
public hihDataContext(DbContextOptions<hihDataContext> options, bool testingMode = false) : base(options)
{
TestingMode = testingMode;
}
// Testing mode
public Boolean TestingMode { get; private set; }
public DbSet<Currency> Currencies { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<HomeDefine> HomeDefines { get; set; }
public DbSet<HomeMember> HomeMembers { get; set; }
public DbSet<DBVersion> DBVersions { get; set; }
public DbSet<FinanceAccountCategory> FinAccountCategories { get; set; }
public DbSet<FinanceAssetCategory> FinAssetCategories { get; set; }
public DbSet<FinanceDocumentType> FinDocumentTypes { get; set; }
public DbSet<FinanceTransactionType> FinTransactionType { get; set; }
public DbSet<FinanceAccount> FinanceAccount { get; set; }
public DbSet<FinanceAccountExtraDP> FinanceAccountExtraDP { get; set; }
public DbSet<FinanceAccountExtraAS> FinanceAccountExtraAS { get; set; }
public DbSet<FinanceAccountExtraLoan> FinanceAccountExtraLoan { get; set; }
public DbSet<FinanceDocument> FinanceDocument { get; set; }
public DbSet<FinanceDocumentItem> FinanceDocumentItem { get; set; }
public DbSet<FinanceTmpDPDocument> FinanceTmpDPDocument { get; set; }
public DbSet<FinanceTmpLoanDocument> FinanceTmpLoanDocument { get; set; }
public DbSet<FinanceControlCenter> FinanceControlCenter { get; set; }
public DbSet<FinanceOrder> FinanceOrder { get; set; }
public DbSet<FinanceOrderSRule> FinanceOrderSRule { get; set; }
public DbSet<FinancePlan> FinancePlan { get; set; }
public DbSet<FinanceDocumentItemView> FinanceDocumentItemView { get; set; }
public DbSet<FinanceReporAccountGroupView> FinanceReporAccountGroupView { get; set; }
public DbSet<FinanceReporAccountGroupAndExpenseView> FinanceReporAccountGroupAndExpenseView { get; set; }
//public DbSet<FinanceReportAccountBalanceView> FinanceReportAccountBalanceView { get; set; }
public DbSet<FinanceReportControlCenterGroupView> FinanceReportControlCenterGroupView { get; set; }
public DbSet<FinanceReportControlCenterGroupAndExpenseView> FinanceReportControlCenterGroupAndExpenseView { get; set; }
// public DbSet<FinanceReportControlCenterBalanceView> FinanceReportControlCenterBalanceView { get; set; }
public DbSet<FinanceReportOrderGroupView> FinanceReportOrderGroupView { get; set; }
public DbSet<FinanceReportOrderGroupAndExpenseView> FinanceReportOrderGroupAndExpenseView { get; set; }
// public DbSet<FinanceReportOrderBalanceView> FinanceReportOrderBalanceView { get; set; }
public DbSet<LearnCategory> LearnCategories { get; set; }
public DbSet<LearnObject> LearnObjects { get; set; }
public DbSet<BlogFormat> BlogFormats { get; set; }
public DbSet<BlogUserSetting> BlogUserSettings { get; set; }
public DbSet<BlogCollection> BlogCollections { get; set; }
public DbSet<BlogPost> BlogPosts { get; set; }
public DbSet<BlogPostCollection> BlogPostCollections { get; set; }
public DbSet<BlogPostTag> BlogPostTags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Currency>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
// entity.Property(e => e.Curr)
// .HasColumnName("CURR")
// .ValueGeneratedNever();
});
modelBuilder.Entity<Language>(entity =>
{
entity.Property(e => e.Lcid)
.HasColumnName("LCID")
.ValueGeneratedNever();
if (!TestingMode)
{
entity.Property(e => e.AppFlag)
.HasDefaultValueSql("((0))");
}
});
modelBuilder.Entity<DBVersion>(entity =>
{
entity.Property(e => e.VersionID)
.ValueGeneratedNever();
if (!TestingMode)
{
entity.Property(e => e.AppliedDate)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.AppliedDate)
.HasDefaultValueSql("CURRENT_DATE");
}
});
modelBuilder.Entity<HomeDefine>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
//.ValueGeneratedOnAdd();
}
else
{
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
}
entity.HasIndex(e => e.Name)
.HasDatabaseName("UK_t_homedef_NAME")
.IsUnique();
});
modelBuilder.Entity<HomeMember>(entity =>
{
entity.HasKey(e => new { e.HomeID, e.User });
entity.HasIndex(e => new { e.HomeID, e.User })
.HasDatabaseName("UK_t_homemem_USER")
.IsUnique();
entity.HasOne(d => d.HomeDefinition)
.WithMany(p => p.HomeMembers)
.HasForeignKey(d => d.HomeID)
.HasConstraintName("FK_t_homemem_HID");
});
// [t_homemsg]
modelBuilder.Entity<FinanceAccountCategory>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
//.ValueGeneratedOnAdd();
entity.Property(e => e.AssetFlag)
.HasColumnType<Boolean>("BIT")
.HasDefaultValueSql("((1))");
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.AssetFlag)
.HasColumnType<Boolean>("INTEGER");
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceAccountCategories)
.HasForeignKey(d => d.HomeID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_account_ctgy_HID");
});
modelBuilder.Entity<FinanceAssetCategory>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
//.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceAssetCategories)
.HasForeignKey(d => d.HomeID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_asset_ctgy_HID");
});
modelBuilder.Entity<FinanceDocumentType>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.HasColumnType("SMALLINT")
.UseIdentityColumn();
//.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceDocumentTypes)
.HasForeignKey(d => d.HomeID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_doctype_HID");
});
modelBuilder.Entity<FinanceTransactionType>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceTransactionTypes)
.HasForeignKey(d => d.HomeID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_trantype_HID");
});
modelBuilder.Entity<FinanceAccount> (entity => {
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceAccounts)
.HasForeignKey(d => d.HomeID)
.HasConstraintName("FK_t_account_HID");
});
modelBuilder.Entity<FinanceAccountExtraAS>(entity => {
if (TestingMode)
{
entity.Property(e => e.AccountID).HasConversion(v => v, v => v);
}
entity.HasOne(d => d.AccountHeader)
.WithOne(p => p.ExtraAsset)
.HasForeignKey<FinanceAccountExtraAS>(p => p.AccountID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_account_ext_as_ACNT");
entity.HasOne(d => d.AssetCategory)
.WithMany(p => p.AccountExtraAsset)
.HasForeignKey(p => p.CategoryID)
.HasConstraintName("FK_t_fin_account_ext_as_CTGY");
});
modelBuilder.Entity<FinanceAccountExtraDP>(entity => {
if (TestingMode)
{
entity.Property(e => e.AccountID).HasConversion(v => v, v => v);
}
entity.HasOne(d => d.AccountHeader)
.WithOne(p => p.ExtraDP)
.HasForeignKey<FinanceAccountExtraDP>(p => p.AccountID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_account_ext_dp_ACNT");
});
modelBuilder.Entity<FinanceAccountExtraLoan>(entity => {
if (TestingMode)
{
entity.Property(e => e.AccountID).HasConversion(v => v, v => v);
}
entity.HasOne(d => d.AccountHeader)
.WithOne(p => p.ExtraLoan)
.HasForeignKey<FinanceAccountExtraLoan>(p => p.AccountID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_account_ext_loan_ACNT");
});
modelBuilder.Entity<FinanceDocument>(entity => {
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceDocuments)
.HasForeignKey(d => d.HomeID)
.HasConstraintName("FK_t_fin_document_HID");
});
modelBuilder.Entity<FinanceDocumentItem>(entity => {
entity.HasKey(p => new { p.DocID, p.ItemID });
entity.HasOne(d => d.DocumentHeader)
.WithMany(p => p.Items)
.HasForeignKey(d => d.DocID)
.HasConstraintName("FK_t_fin_document_header");
});
modelBuilder.Entity<FinanceTmpLoanDocument>(entity =>
{
//if (!TestingMode)
//{
// entity.Property(e => e.DocumentID)
// .UseIdentityColumn();
//}
//else
//{
// entity.Property(e => e.DocumentID)
// .HasColumnType("INTEGER")
// .ValueGeneratedOnAdd();
//}
entity.HasKey(p => new { p.DocumentID, p.AccountID, p.HomeID });
entity.HasOne(d => d.AccountExtra)
.WithMany(p => p.LoanTmpDocs)
.HasForeignKey(d => d.AccountID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_tmpdoc_loan_ACCOUNTEXT");
});
modelBuilder.Entity<FinanceTmpDPDocument>(entity =>
{
//if (!TestingMode)
//{
// entity.Property(e => e.DocumentID)
// .UseIdentityColumn();
//}
//else
//{
// entity.Property(e => e.DocumentID)
// .HasColumnType("INTEGER")
// .ValueGeneratedOnAdd();
//}
entity.HasKey(p => new { p.DocumentID, p.AccountID, p.HomeID });
entity.HasOne(d => d.AccountExtra)
.WithMany(p => p.DPTmpDocs)
.HasForeignKey(d => d.AccountID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_fin_tmpdocdp_ACCOUNTEXT");
});
modelBuilder.Entity<FinanceControlCenter>(entity => {
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceControlCenters)
.HasForeignKey(d => d.HomeID)
.HasConstraintName("FK_t_fin_cc_HID");
});
modelBuilder.Entity<FinanceOrder>(entity => {
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinanceOrders)
.HasForeignKey(d => d.HomeID)
.HasConstraintName("FK_t_fin_order_HID");
});
modelBuilder.Entity<FinanceOrderSRule>(entity => {
entity.HasKey(p => new { p.OrderID, p.RuleID });
entity.HasOne(d => d.Order)
.WithMany(p => p.SRule)
.HasForeignKey(d => d.OrderID)
.HasConstraintName("FK_t_fin_order_srule_order");
});
modelBuilder.Entity<FinancePlan>(entity => {
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.FinancePlans)
.HasForeignKey(d => d.HomeID)
.HasConstraintName("FK_t_fin_plan_HID");
});
modelBuilder.Entity<FinanceDocumentItemView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_DOCUMENT_ITEM");
});
modelBuilder.Entity<FinanceReporAccountGroupView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_GRP_ACNT");
});
modelBuilder.Entity<FinanceReporAccountGroupAndExpenseView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_GRP_ACNT_TRANEXP");
});
modelBuilder.Entity<FinanceReportAccountBalanceView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_REPORT_BS");
});
modelBuilder.Entity<FinanceReportControlCenterGroupView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_GRP_CC");
});
modelBuilder.Entity<FinanceReportControlCenterGroupAndExpenseView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_GRP_CC_TRANEXP");
});
modelBuilder.Entity<FinanceReportControlCenterBalanceView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_REPORT_CC");
});
modelBuilder.Entity<FinanceReportOrderGroupView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_GRP_ORD");
});
modelBuilder.Entity<FinanceReportOrderGroupAndExpenseView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_GRP_ORD_TRANEXP");
});
modelBuilder.Entity<FinanceReportOrderBalanceView>(entity =>
{
entity.HasNoKey();
entity.ToView("V_FIN_REPORT_ORDER");
});
modelBuilder.Entity<LearnCategory>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.LearnCategories)
.HasForeignKey(d => d.HomeID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_learn_ctgy_HID");
});
modelBuilder.Entity<LearnObject>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
entity.HasOne(d => d.CurrentHome)
.WithMany(p => p.LearnObjects)
.HasForeignKey(d => d.HomeID)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_t_learn_obj_HID");
});
// Blogs part
modelBuilder.Entity<BlogUserSetting>(entity =>
{
});
modelBuilder.Entity<BlogFormat>(entity =>
{
});
modelBuilder.Entity<BlogCollection>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
}
});
modelBuilder.Entity<BlogPost>(entity =>
{
if (!TestingMode)
{
entity.Property(e => e.ID)
.UseIdentityColumn();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("(getdate())");
}
else
{
// Workaround for Sqlite in testing mode
// entity.Property(e => e.ID).HasConversion(v => v, v => v);
entity.Property(e => e.ID)
.HasColumnType("INTEGER")
.ValueGeneratedOnAdd();
entity.Property(e => e.CreatedAt)
.HasDefaultValueSql("CURRENT_DATE");
entity.Property(e => e.UpdatedAt)
.HasDefaultValueSql("CURRENT_DATE");
}
});
modelBuilder.Entity<BlogPostCollection>(entity =>
{
entity.HasKey(e => new { e.PostID, e.CollectionID });
entity.HasOne(d => d.BlogCollection)
.WithMany(p => p.BlogPostCollections)
.HasForeignKey(d => d.CollectionID)
.HasConstraintName("FK_t_blog_post_coll_coll");
entity.HasOne(d => d.BlogPost)
.WithMany(p => p.BlogPostCollections)
.HasForeignKey(d => d.PostID)
.HasConstraintName("FK_t_blog_post_coll_post");
});
modelBuilder.Entity<BlogPostTag>(entity =>
{
entity.HasKey(e => new { e.PostID, e.Tag });
entity.HasOne(d => d.BlogPost)
.WithMany(p => p.BlogPostTags)
.HasForeignKey(d => d.PostID)
.HasConstraintName("FK_t_blog_post_tag_post");
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.AddressBook;
using MonoTouch.AddressBookUI;
using System.Drawing;
namespace Example_SharedResources.Screens.iPhone.Contacts
{
public partial class AddressBookScreen : UIViewController
{
/// <summary>
/// Our address book picker control
/// </summary>
protected ABPeoplePickerNavigationController addressBookPicker;
/// <summary>
/// The table data source that will bind the phone numbers
/// </summary>
protected PhoneNumberTableSource tableDataSource;
/// <summary>
/// The ID of our person
/// </summary>
protected int contactID;
/// <summary>
/// Used to resize the scroll view to allow for keyboard
/// </summary>
RectangleF contentViewSize = RectangleF.Empty;
#region Constructors
// The IntPtr and initWithCoder constructors are required for items that need
// to be able to be created from a xib rather than from managed code
public AddressBookScreen (IntPtr handle) : base(handle)
{
Initialize ();
}
[Export("initWithCoder:")]
public AddressBookScreen (NSCoder coder) : base(coder)
{
Initialize ();
}
public AddressBookScreen () : base("AddressBookScreen", null)
{
Initialize ();
}
void Initialize ()
{
contentViewSize = View.Frame;
scrlMain.ContentSize = contentViewSize.Size;
}
#endregion
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Address Book";
// add a button to the nav bar that will select a contact to edit
UIButton btnSelectContact = UIButton.FromType (UIButtonType.RoundedRect);
btnSelectContact.SetTitle ("Select Contact", UIControlState.Normal);
NavigationItem.SetRightBarButtonItem (new UIBarButtonItem (UIBarButtonSystemItem.Action, SelectContact), false);
// wire up keyboard hiding
txtPhoneLabel.ShouldReturn += (t) => { t.ResignFirstResponder (); return true; };
txtPhoneNumber.ShouldReturn += (t) => { t.ResignFirstResponder (); return true; };
txtFirstName.ShouldReturn += (t) => { t.ResignFirstResponder (); return true; };
txtLastName.ShouldReturn += (t) => { t.ResignFirstResponder (); return true; };
// wire up event handlers
btnSaveChanges.TouchUpInside += BtnSaveChangesTouchUpInside;
btnAddPhoneNumber.TouchUpInside += BtnAddPhoneNumberTouchUpInside;
#region -= Sample code showing how to loop through all the records =-
//==== This block of code writes out each person contact in the address book and
// each phone number for that person to the console, just to illustrate the code
// neccessary to access each item
// instantiate a reference to the address book
using(ABAddressBook addressBook = new ABAddressBook ()) {
// if you want to subscribe to changes
addressBook.ExternalChange += (object sender, ExternalChangeEventArgs e) => {
// code to deal with changes
};
// for each record
foreach(ABRecord item in addressBook) {
Console.WriteLine(item.Type.ToString () + " " + item.Id);
// there are two possible record types, person and group
if (item.Type == ABRecordType.Person) {
// since we've already tested it to be a person, just create a shortcut to that
// type
ABPerson person = item as ABPerson;
Console.WriteLine (person.FirstName + " " + person.LastName);
// get the phone numbers
ABMultiValue<string> phones = person.GetPhones ();
foreach(ABMultiValueEntry<string> val in phones) {
Console.Write(val.Label + ": " + val.Value);
}
}
}
// save changes (if you were to have made any)
//addressBook.Save();
// or cancel them
//addressBook.Revert();
}
//====
#endregion
#region -= keyboard stuff =-
// wire up our keyboard events
NSNotificationCenter.DefaultCenter.AddObserver (
UIKeyboard.WillShowNotification, delegate (NSNotification n) { KeyboardOpenedOrClosed (n, "Open"); });
NSNotificationCenter.DefaultCenter.AddObserver (
UIKeyboard.WillHideNotification, delegate (NSNotification n) { KeyboardOpenedOrClosed (n, "Close"); });
#endregion
}
protected void BtnAddPhoneNumberTouchUpInside (object sender, EventArgs e)
{
// get a reference to the contact
using(ABAddressBook addressBook = new ABAddressBook ())
{
ABPerson contact = addressBook.GetPerson (contactID);
// get the phones and copy them to a mutable set of multivalues (so we can edit)
ABMutableMultiValue<string> phones = contact.GetPhones ().ToMutableMultiValue ();
// add the phone number to the phones via the multivalue.Add method
phones.Add (new NSString (txtPhoneLabel.Text), new NSString (txtPhoneNumber.Text));
// attach the phones back to the contact
contact.SetPhones (phones);
// save the address book changes
addressBook.Save ();
// show an alert, letting the user know the number addition was successful
new UIAlertView ("Alert", "Phone Number Added", null, "OK", null).Show();
// update the page
PopulatePage (contact);
// we have to call reload to refresh the table because the action didn't originate
// from the table.
tblPhoneNumbers.ReloadData ();
}
}
// Called when a phone number is swiped for deletion. Illustrates how to delete a multivalue property
protected void DeletePhoneNumber (int phoneNumberID)
{
using(ABAddressBook addressBook = new ABAddressBook ()) {
ABPerson contact = addressBook.GetPerson (contactID);
// get the phones and copy them to a mutable set of multivalues (so we can edit)
ABMutableMultiValue<string> phones = contact.GetPhones ().ToMutableMultiValue ();
// loop backwards and delete the phone number
for (int i = phones.Count - 1; i >= 0 ; i--) {
if (phones[i].Identifier == phoneNumberID)
phones.RemoveAt(i);
}
// attach the phones back to the contact
contact.SetPhones (phones);
// save the changes
addressBook.Save ();
// show an alert, letting the user know the number deletion was successful
new UIAlertView ("Alert", "Phone Number Deleted", null, "OK", null).Show ();
// repopulate the page
PopulatePage (contact);
}
}
protected void BtnSaveChangesTouchUpInside (object sender, EventArgs e)
{
}
protected void PopulatePage (ABPerson contact)
{
// save the ID of our person
contactID = contact.Id;
// set the data on the page
txtFirstName.Text = contact.FirstName;
txtLastName.Text = contact.LastName;
tableDataSource = new AddressBookScreen.PhoneNumberTableSource (contact.GetPhones ());
tblPhoneNumbers.Source = tableDataSource;
// wire up our delete clicked handler
tableDataSource.DeleteClicked +=
(object sender, PhoneNumberTableSource.PhoneNumberClickedEventArgs e) => { DeletePhoneNumber (e.PhoneNumberID); };
}
// Opens up a contact picker and then populates the screen, based on the contact chosen
protected void SelectContact (object s, EventArgs e)
{
// create the picker control
addressBookPicker = new ABPeoplePickerNavigationController ();
NavigationController.PresentModalViewController (addressBookPicker, true);
// wire up the cancelled event to dismiss the picker
addressBookPicker.Cancelled += (sender, eventArgs) => { NavigationController.DismissModalViewControllerAnimated (true); };
// when a contact is chosen, populate the page and then dismiss the picker
addressBookPicker.SelectPerson += (object sender, ABPeoplePickerSelectPersonEventArgs args) => {
PopulatePage (args.Person);
NavigationController.DismissModalViewControllerAnimated (true);
};
}
#region -= table binding stuff (not important to understanding the address API) =-
/// <summary>
/// A simple table view source to bind our phone numbers to the table
/// </summary>
protected class PhoneNumberTableSource : UITableViewSource
{
public event EventHandler<PhoneNumberClickedEventArgs> DeleteClicked;
protected ABMultiValue<string> phoneNumbers { get; set; }
public PhoneNumberTableSource(ABMultiValue<string> phoneNumbers)
{ this.phoneNumbers = phoneNumbers; }
public override int NumberOfSections (UITableView tableView) { return 1; }
public override int RowsInSection (UITableView tableview, int section) { return phoneNumbers.Count; }
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
EditablePhoneTableCell cell = tableView.DequeueReusableCell ("PhoneCell") as EditablePhoneTableCell;
if(cell == null)
cell = new EditablePhoneTableCell ("PhoneCell");
cell.PhoneLabel = phoneNumbers[indexPath.Row].Label.ToString ().Replace ("_$!<", "").Replace (">!$_", "");
cell.PhoneNumber = phoneNumbers[indexPath.Row].Value.ToString ();
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
return cell;
}
public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { return true; }
public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath)
{ return UITableViewCellEditingStyle.Delete; }
public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
{
if(editingStyle == UITableViewCellEditingStyle.Delete) {
if (DeleteClicked != null)
DeleteClicked (this, new PhoneNumberClickedEventArgs(phoneNumbers[indexPath.Row].Identifier));
}
}
// We use this so we can pass the id of the phone number that was clicked along with the event
public class PhoneNumberClickedEventArgs : EventArgs
{
public int PhoneNumberID { get; set; }
public PhoneNumberClickedEventArgs(int phoneNumberID) : base()
{ PhoneNumberID = phoneNumberID; }
}
}
/// <summary>
/// A simple, two text box cell, that will hold our phone label, and our phone number.
/// </summary>
protected class EditablePhoneTableCell : UITableViewCell
{
// label and phone number text boxes
UITextField txtLabel = new UITextField(new RectangleF(10, 5, 110, 33));
UITextField txtPhoneNumber = new UITextField(new RectangleF(130, 5, 140, 33));
// properties
public string PhoneLabel { get { return txtLabel.Text; } set { txtLabel.Text = value; } }
public string PhoneNumber { get { return txtPhoneNumber.Text; } set { txtPhoneNumber.Text = value; } }
public EditablePhoneTableCell(string reuseIdentifier) : base(UITableViewCellStyle.Default, reuseIdentifier)
{
AddSubview(txtLabel);
AddSubview(txtPhoneNumber);
txtLabel.ReturnKeyType = UIReturnKeyType.Done;
txtLabel.BorderStyle = UITextBorderStyle.Line;
txtLabel.ShouldReturn += (t) => { t.ResignFirstResponder(); return true; };
txtPhoneNumber.ReturnKeyType= UIReturnKeyType.Done;
txtPhoneNumber.BorderStyle = UITextBorderStyle.Line;
txtPhoneNumber.ShouldReturn += (t) => { t.ResignFirstResponder(); return true; };
}
}
#endregion
#region -= keyboard/screen resizing =-
/// <summary>
/// resizes the view when the keyboard comes up or goes away, allows our scroll view to work
/// </summary>
protected void KeyboardOpenedOrClosed (NSNotification n, string openOrClose)
{
// if it's opening
if (openOrClose == "Open")
{
Console.WriteLine ("Keyboard opening");
// declare vars
RectangleF kbdFrame = UIKeyboard.BoundsFromNotification (n);
double animationDuration = UIKeyboard.AnimationDurationFromNotification (n);
RectangleF newFrame = contentViewSize;
// resize our frame depending on whether the keyboard pops in or out
newFrame.Height -= kbdFrame.Height;
// apply the size change
UIView.BeginAnimations ("ResizeForKeyboard");
UIView.SetAnimationDuration (animationDuration);
scrlMain.Frame = newFrame;
UIView.CommitAnimations ();
} else // if it's closing, resize
{
// declare vars
double animationDuration = UIKeyboard.AnimationDurationFromNotification (n);
// apply the size change
UIView.BeginAnimations ("ResizeForKeyboard");
UIView.SetAnimationDuration (animationDuration);
scrlMain.Frame = contentViewSize;
UIView.CommitAnimations ();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts;
using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts.Definition;
using Moq;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.Release
{
public sealed class JenkinsArtifactL0
{
private Mock<IExecutionContext> _ec;
private Mock<IGenericHttpClient> _httpClient;
private Mock<IExtensionManager> _extensionManager;
private ArtifactDefinition _artifactDefinition;
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void IfNoCommitVersionExistsInArtifactDetailsNoIssueShouldBeAdded()
{
using (TestHostContext tc = Setup())
{
var trace = tc.GetTrace();
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, "test");
_ec.Verify(x => x.AddIssue(It.Is<Issue>(y => y.Type == IssueType.Warning)), Times.Never);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void ShouldLogAnIssueIfEndVersionIsInvalidInArtifactDetail()
{
using (TestHostContext tc = Setup())
{
var trace = tc.GetTrace();
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.EndCommitArtifactVersion = "xx";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, "test");
_ec.Verify(x => x.AddIssue(It.Is<Issue>(y => y.Type == IssueType.Warning)), Times.Once);
}
}
[Fact]
[TraitAttribute("Level", "L0")]
[TraitAttribute("Category", "Worker")]
public async void MissingStartVersionShouldDownloadCommitsFromSingleBuild()
{
using (TestHostContext tc = Setup())
{
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.EndCommitArtifactVersion = "10";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
string expectedUrl = $"{details.Url}/job/{details.JobName}/{details.EndCommitArtifactVersion}/api/json?tree=number,result,changeSet[items[commitId,date,msg,author[fullName]]]";
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, tc.GetDirectory(WellKnownDirectory.Root));
_httpClient.Verify(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(expectedUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
}
[Fact]
[TraitAttribute("Level", "L0")]
[TraitAttribute("Category", "Worker")]
public async void JenkinsCommitsShouldBeFetchedBetweenBuildRange()
{
using (TestHostContext tc = Setup())
{
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.StartCommitArtifactVersion = "10";
details.EndCommitArtifactVersion = "20";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
SetupBuildRangeQuery(details, "{ \"allBuilds\": [{ \"number\": 20 }, { \"number\": 10 }, { \"number\": 2 } ] }");
string expectedUrl = $"{details.Url}/job/{details.JobName}/api/json?tree=builds[number,result,changeSet[items[commitId,date,msg,author[fullName]]]]{{0,1}}";
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, tc.GetDirectory(WellKnownDirectory.Root));
_httpClient.Verify(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(expectedUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
}
[Fact]
[TraitAttribute("Level", "L0")]
[TraitAttribute("Category", "Worker")]
public async void JenkinsRollbackCommitsShouldBeFetched()
{
using (TestHostContext tc = Setup())
{
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.StartCommitArtifactVersion = "20";
details.EndCommitArtifactVersion = "10";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
SetupBuildRangeQuery(details, "{ \"allBuilds\": [{ \"number\": 20 }, { \"number\": 10 }, { \"number\": 2 } ] }");
string expectedUrl = $"{details.Url}/job/{details.JobName}/api/json?tree=builds[number,result,changeSet[items[commitId,date,msg,author[fullName]]]]{{0,1}}";
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, tc.GetDirectory(WellKnownDirectory.Root));
_httpClient.Verify(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(expectedUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
}
[Fact]
[TraitAttribute("Level", "L0")]
[TraitAttribute("Category", "Worker")]
public async void JenkinsCommitsShouldLogAnIssueIfBuildIsDeleted()
{
using (TestHostContext tc = Setup())
{
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.StartCommitArtifactVersion = "10";
details.EndCommitArtifactVersion = "20";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
SetupBuildRangeQuery(details, "{ \"allBuilds\": [{ \"number\": 30 }, { \"number\": 29 }, { \"number\": 28 } ] }");
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, tc.GetDirectory(WellKnownDirectory.Root));
_ec.Verify(x => x.AddIssue(It.Is<Issue>(y => y.Type == IssueType.Warning)), Times.Once);
}
}
[Fact]
[TraitAttribute("Level", "L0")]
[TraitAttribute("Category", "Worker")]
public async void CommitsShouldBeUploadedAsAttachment()
{
using (TestHostContext tc = Setup())
{
string commitRootDirectory = Path.Combine(tc.GetDirectory(WellKnownDirectory.Work), Guid.NewGuid().ToString("D"));
Directory.CreateDirectory(commitRootDirectory);
try
{
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.StartCommitArtifactVersion = "10";
details.EndCommitArtifactVersion = "20";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
SetupBuildRangeQuery(details, "{ \"allBuilds\": [{ \"number\": 20 }, { \"number\": 10 }, { \"number\": 2 } ] }");
string commitResult = " {\"builds\": [{ \"number\":9, \"result\":\"SUCCESS\", \"changeSet\": { \"items\": [{ \"commitId\" : \"2869c7ccd0b1b649ba6765e89ee5ff36ef6d4805\", \"author\": { \"fullName\" : \"testuser\" }, \"msg\":\"test\" }]}}]}";
string commitsUrl = $"{details.Url}/job/{details.JobName}/api/json?tree=builds[number,result,changeSet[items[commitId,date,msg,author[fullName]]]]{{0,1}}";
_httpClient.Setup(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(commitsUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns(Task.FromResult(commitResult));
string commitFilePath = Path.Combine(commitRootDirectory, $"commits_{details.Alias}_1.json");
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, commitRootDirectory);
_ec.Verify(x => x.QueueAttachFile(It.Is<string>(y => y.Equals(CoreAttachmentType.FileAttachment)), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
finally
{
IOUtil.DeleteDirectory(commitRootDirectory, CancellationToken.None);
}
}
}
[Fact]
[TraitAttribute("Level", "L0")]
[TraitAttribute("Category", "Worker")]
public async void CommitsShoulHaveUrlIfItsGitRepo()
{
using (TestHostContext tc = Setup())
{
string commitRootDirectory = Path.Combine(tc.GetDirectory(WellKnownDirectory.Work), Guid.NewGuid().ToString("D"));
Directory.CreateDirectory(commitRootDirectory);
try
{
JenkinsArtifactDetails details = _artifactDefinition.Details as JenkinsArtifactDetails;
details.StartCommitArtifactVersion = "10";
details.EndCommitArtifactVersion = "20";
var artifact = new JenkinsArtifact();
artifact.Initialize(tc);
SetupBuildRangeQuery(details, "{ \"allBuilds\": [{ \"number\": 20 }, { \"number\": 10 }, { \"number\": 2 } ] }");
string commitResult = " {\"builds\": [{ \"number\":9, \"result\":\"SUCCESS\", \"changeSet\": { \"items\": [{ \"commitId\" : \"2869c7ccd0b1b649ba6765e89ee5ff36ef6d4805\", \"author\": { \"fullName\" : \"testuser\" }, \"msg\":\"test\" }]}}]}";
string commitsUrl = $"{details.Url}/job/{details.JobName}/api/json?tree=builds[number,result,changeSet[items[commitId,date,msg,author[fullName]]]]{{0,1}}";
_httpClient.Setup(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(commitsUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns(Task.FromResult(commitResult));
string repoUrl = $"{details.Url}/job/{details.JobName}/{details.EndCommitArtifactVersion}/api/json?tree=actions[remoteUrls],changeSet[kind]";
string repoResult = "{ \"actions\": [ { \"remoteUrls\": [ \"https://github.com/TestUser/TestRepo\" ] }, ], \"changeSet\": { \"kind\": \"git\" } }";
_httpClient.Setup(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(repoUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns(Task.FromResult(repoResult));
string commitFilePath = Path.Combine(commitRootDirectory, $"commits_{details.Alias}_1.json");
string expectedCommitUrl = "https://github.com/TestUser/TestRepo/commit/2869c7ccd0b1b649ba6765e89ee5ff36ef6d4805";
await artifact.DownloadCommitsAsync(_ec.Object, _artifactDefinition, commitRootDirectory);
_ec.Verify(x => x.QueueAttachFile(It.Is<string>(y => y.Equals(CoreAttachmentType.FileAttachment)), It.IsAny<string>(), It.Is<string>(z => string.Join("", File.ReadAllLines(z)).Contains(expectedCommitUrl))), Times.Once);
}
finally
{
IOUtil.DeleteDirectory(commitRootDirectory, CancellationToken.None);
}
}
}
private void SetupBuildRangeQuery(JenkinsArtifactDetails details, string result)
{
string buildIndexUrl = $"{details.Url}/job/{details.JobName}/api/json?tree=allBuilds[number]";
_httpClient.Setup(x => x.GetStringAsync(It.Is<string>(y => y.StartsWith(buildIndexUrl)), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns(Task.FromResult(result));
}
private TestHostContext Setup([CallerMemberName] string name = "")
{
TestHostContext hc = new TestHostContext(this, name);
_ec = new Mock<IExecutionContext>();
_httpClient = new Mock<IGenericHttpClient>();
_artifactDefinition = new ArtifactDefinition
{
Details = new JenkinsArtifactDetails
{
Url = new Uri("http://localhost"),
JobName = "jenkins",
Alias = "jenkins"
}
};
_extensionManager = new Mock<IExtensionManager>();
hc.SetSingleton<IExtensionManager>(_extensionManager.Object);
hc.SetSingleton<IGenericHttpClient>(_httpClient.Object);
return hc;
}
}
}
| |
/*
* FileTable.cs - Manage the file descriptor table.
*
* This file is part of the Portable.NET "C language support" library.
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace OpenSystem.C
{
using System;
using System.IO;
//
// The file descriptor table maps integer descriptors for C
// into C# stream objects. File descriptor functions can
// call C# stream methods to perform the required functionality.
//
public sealed class FileTable
{
// Structure of a stream reference, which also keeps track
// of the number of times that it has been dup'ed.
private sealed class StreamRef
{
public Stream stream;
public int count;
public byte[] buffer;
public StreamRef(Stream stream)
{
this.stream = stream;
this.count = 1;
this.buffer = null;
}
} // class StreamRef
// Internal state.
public const int MaxDescriptors = 256;
private static StreamRef[] fds = new StreamRef [MaxDescriptors];
// Set a file descriptor to a specific stream. The previous
// association is lost, so it should only be used on a slot
// that is known to be empty.
public static void SetFileDescriptor(int fd, Stream stream)
{
lock(typeof(FileTable))
{
StreamRef[] table = fds;
StreamRef sref;
if(fd >= 0 && fd < MaxDescriptors)
{
if((sref = table[fd]) == null)
{
table[fd] = new StreamRef(stream);
}
else
{
sref.stream = stream;
sref.count = 1;
sref.buffer = null;
}
}
}
}
// Get the stream that is associated with a file descriptor.
// Returns "null" if there is no stream associated.
public static Stream GetStream(int fd)
{
lock(typeof(FileTable))
{
if(fd >= 0 && fd < MaxDescriptors)
{
StreamRef sref = fds[fd];
if(sref != null)
{
return sref.stream;
}
else
{
return null;
}
}
else
{
return null;
}
}
}
// Get the stream that is associated with a file descriptor,
// together with a buffer that can be used for reads and writes.
// Returns "null" if there is no stream associated.
public static Stream GetStreamAndBuffer(int fd, out byte[] buffer)
{
lock(typeof(FileTable))
{
if(fd >= 0 && fd < MaxDescriptors)
{
StreamRef sref = fds[fd];
if(sref != null)
{
if(sref.buffer == null)
{
sref.buffer = new byte [1024];
}
buffer = sref.buffer;
return sref.stream;
}
else
{
buffer = null;
return null;
}
}
else
{
buffer = null;
return null;
}
}
}
// Find a free file descriptor. Returns -1 if nothing is free.
private static int NewFD()
{
StreamRef[] table = fds;
int fd;
for(fd = 0; fd < MaxDescriptors; ++fd)
{
if(table[fd] == null)
{
return fd;
}
}
return -1;
}
private static int NewFD(int after)
{
StreamRef[] table = fds;
int fd;
for(fd = after; fd >= 0 && fd < MaxDescriptors; ++fd)
{
if(table[fd] == null)
{
return fd;
}
}
return -1;
}
// Allocate a new file descriptor, with no stream association.
public static int AllocFD()
{
lock(typeof(FileTable))
{
int newFD = NewFD();
if(newFD != -1)
{
fds[newFD] = new StreamRef(null);
}
return newFD;
}
}
// Release a file descriptor that was allocated with "AllocFD",
// but is no longer required due to error conditions.
public static void ReleaseFD(int fd)
{
lock(typeof(FileTable))
{
if(fd >= 0 && fd < MaxDescriptors)
{
fds[fd] = null;
}
}
}
// Duplicate a file descriptor. Returns -1 if there are
// no free descriptors, or -2 if the descriptor is invalid.
public static int Dup(int fd)
{
lock(typeof(FileTable))
{
if(fd < 0 || fd >= MaxDescriptors || fds[fd] == null)
{
return -2;
}
int newFd = NewFD();
if(newFd == -1)
{
return -1;
}
StreamRef sref = fds[fd];
++(sref.count);
fds[newFd] = sref;
return newFd;
}
}
// Duplicate a file descriptor, starting at a particular position.
public static int DupAfter(int fd, int after)
{
lock(typeof(FileTable))
{
if(fd < 0 || fd >= MaxDescriptors || fds[fd] == null)
{
return -2;
}
int newFd = NewFD(after);
if(newFd == -1)
{
return -1;
}
StreamRef sref = fds[fd];
++(sref.count);
fds[newFd] = sref;
return newFd;
}
}
// Duplicate a file descriptor and replace another one.
// Returns -1 if either of the descriptors are invalid.
public static int Dup2(int oldfd, int newfd)
{
Stream streamToClose = null;
lock(typeof(FileTable))
{
StreamRef[] table = fds;
if(oldfd < 0 || oldfd >= MaxDescriptors ||
table[oldfd] == null)
{
return -1;
}
if(newfd < 0 || newfd >= MaxDescriptors)
{
return -1;
}
StreamRef sref = table[oldfd];
if(sref == table[newfd])
{
// The new stream is already the same as the old.
return newfd;
}
if(table[newfd] != null)
{
if(--(table[newfd].count) == 0)
{
streamToClose = table[newfd].stream;
}
}
table[newfd] = sref;
++(sref.count);
}
if(streamToClose != null)
{
streamToClose.Close();
}
return newfd;
}
// Close a file descriptor. Returns 0 if OK, or -1 if
// the descriptor is invalid.
public static int Close(int fd)
{
Stream streamToClose = null;
lock(typeof(FileTable))
{
StreamRef[] table = fds;
if(fd < 0 || fd >= MaxDescriptors || table[fd] == null)
{
return -1;
}
if(--(table[fd].count) == 0)
{
streamToClose = table[fd].stream;
}
table[fd] = null;
}
if(streamToClose != null)
{
streamToClose.Close();
}
return 0;
}
} // class FileTable
} // namespace OpenSystem.C
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Fairweather.Service
{
/// <summary>
/// This class allows you to read csv records one after another from a stream.
/// It does the job of parsing the fields, figuring out where each record ends and
/// throwing meaningful exceptions in case of formatting errors.
///
/// It does not handle headers, fields per record count restrictions, etc.
/// </summary>
public class Csv_Parser : IDisposable
{
// Csv format references
// http://www.csvreader.com/csv_format.php
// http://en.wikipedia.org/wiki/Comma-separated_values
// http://tools.ietf.org/html/rfc4180
public Csv_Parser(TextReader tr) {
this.lc = tr as Line_Counter ?? new Line_Counter(tr);
//this.reader = new Reader(lc);
}
public void Dispose() {
lc.Dispose();
}
// ****************************
/// <summary>
/// After this call, 'next' will contain the
/// initial character on the line.
/// </summary>
public void Skip_To_Next_Line() {
while (true) {
read_first = true;
next = lc.Read();
if (next == lf || next == eof)
return;
}
}
public bool End_Of_File { get { return next == -1; } }
public bool Last_Char_Was_Comma { get; private set; }
const char comma = ',';
const char cr = '\r';
const char lf = '\n';
const char qq = '"';
const char hash = '#';
const int eof = -1;
const int max_len = 2000;
public int Line {
get {
return lc.Line;
}
}
public int Column {
get {
return lc.Col;
}
}
public int Record {
get {
return record;
}
}
// ****************************
/* State */
// ****************************
bool read_first;
int next;
//bool last_was_comma;
int record = -1;
readonly char[] chars = new char[max_len];
readonly Line_Counter lc;
// ****************************
void Runaway_Quote_Error(bool _length_exceeded, int? open_quote_line, int? open_quote_col) {
var msg = _length_exceeded ? "Maximum field length exceeded" : "Terminating \" not found";
// open_quote_col.tifn();
msg += " (unmatched opening \" on line {0}, position {1}?)".spf(open_quote_line + 1, open_quote_col);
msg += ".";
Error(msg, Csv_Error_Type.Runaway_Quote, true, true);
}
void Error(Csv_Error_Type error_type, bool fatal, bool increment_record) {
string msg = null;
Error(msg, error_type, fatal, increment_record);
}
void Error(string msg, Csv_Error_Type error_type, bool fatal, bool increment_record) {
if (increment_record)
++record;
throw new XCsv(msg, error_type, fatal, lc.Line, lc.Col, Record);
}
// ****************************
/// <summary>
/// Single '\n' or cr-lf pair is the record delimiter.
/// </summary>
/// <returns></returns>
public List<string>
Get_Next_Record() {
int line;
int index;
return Get_Next_Record(out line, out index);
}
const bool are_all_errors_fatal = false;
/// <summary>
/// Single '\n' or cr-lf pair is the record delimiter.
/// return.Count == (number of delimiting commas) + 1
/// </summary>
/// <returns></returns>
public List<string>
Get_Next_Record(out int line, out int index) {
line = -1;
index = -1;
if (End_Of_File)
return null;
var lst = new List<string>(15);
int cnt = 0;
var open_quote = false;
var any_non_ws = false;
var closing_quote_seen = false;
// the following two variables are non-null iff the currently
// examined field is escaped.
// the line of the current escaped field's opening "
int? open_quote_line = null;
// the line position of the current escaped field's opening "
// open_quote_col == 1 iff the " was the first character on the line
int? open_quote_col = null;
#region inlined lambdas
//Action add_char = () =>
//{
// try {
// chars[cnt++]=ch;
// }
// catch (IndexOutOfRangeException) {
// runaway_quote_error(true);
// }
//};
//Action<bool> add_field = force =>
//{
// if (!force && pos == 0)
// return;
// var s = new string(chars, pos);
// //if (in_quoted)
// // (s == s.Trim()).tiff();
// pos = 0;
// open_quote = false;
// any_non_ws = false;
// closing_quote_seen = false;
// open_quote_line = null;
// open_quote_col = null;
// lst.Add(s);
//};
#endregion
// [ ] empty fields
// [ ] trailing characters in the file
// [ ] quoted fields
// [ ] multiline records
// [ ] unquoted fields
// [ ] unquoted fields with leading/trailing whitespace
// [ ] blank lines
// [ ] commented lines
if (!read_first) {
read_first = true;
next = lc.Read();
}
while (true) {
NEXT_LINE:
do {
if (End_Of_File)
return null;
if (next == hash)
Skip_To_Next_Line();
else
break;
} while (true);
line = lc.Line;
var non_ws_on_line = false;
while (true) {
// inline verified on 03.06.10
#region read_next()
if (next == eof)
return null;
var ch = unchecked((char)next);
next = lc.Read();
var is_last = (next == -1);
#endregion
if (ch == qq) {
if (!open_quote) {
if (closing_quote_seen) {
Error(Csv_Error_Type.Trailing_Quote, are_all_errors_fatal, true); // alpha,"bravo" ",
}
else if (any_non_ws) {
Error(Csv_Error_Type.Unexpected_Quote, are_all_errors_fatal, true); // al"pha,bravo,
}
else if (open_quote_col == null) {
// entering quoted field
// forget preceding whitespace
cnt = 0;
open_quote_col = lc.Col - 1;
open_quote_line = lc.Line;
}
else {
// skip every other quote in an escaped field
// this will make sure that the terminating " is ignored
any_non_ws = true;
//last_was_comma = false;
// inline verified on 03.06.10
#region add_char();
try {
chars[cnt++] = ch;
}
catch (IndexOutOfRangeException) {
Runaway_Quote_Error(true, open_quote_line, open_quote_col);
}
#endregion
}
}
open_quote = !open_quote;
non_ws_on_line = true;
}
else {
var is_ws = false;
if (ch == comma) {
non_ws_on_line = true;
if (!open_quote || closing_quote_seen) { // sic
// delimiter
// inline verified on 03.06.10
#region add_field(true)
var s = new string(chars, 0, cnt);
cnt = 0;
open_quote = false;
any_non_ws = false;
closing_quote_seen = false;
open_quote_line = null;
open_quote_col = null;
lst.Add(s);
#endregion
if (is_last)
goto LAST; // sorry
continue;
}
}
else if (ch == cr) {
is_ws = true;
if (!open_quote && next == lf)
continue;
if (!open_quote && is_last)
ch = lf; // this hack is better than the alternative
// if it's in an escaped field or if it's alone,
// treat it as an ordinary character
}
else if (ch == ' ' || ch == '\t') {
is_ws = true;
}
if (ch == lf) {
is_ws = true;
if (!open_quote || closing_quote_seen) {
// inline verified on 03.06.10
#region add_field(false)
if (non_ws_on_line) {
var s = new string(chars, 0, cnt);
cnt = 0;
open_quote = false;
any_non_ws = false;
closing_quote_seen = false;
open_quote_line = null;
open_quote_col = null;
lst.Add(s);
}
#endregion
// inline verified on 03.06.10
#region return value
if (!non_ws_on_line) {
if (is_last)
return null;
goto NEXT_LINE;
}
index = ++record;
return lst;
#endregion
}
// otherwise throw error in the final if:
// if (is_last) {
}
non_ws_on_line |= !is_ws;
if ((open_quote_col != null) &&
!open_quote &&
!closing_quote_seen) {
closing_quote_seen = true;
}
if (closing_quote_seen) {
if (is_ws) {
// ignore trailing ws
if (is_last)
goto LAST;
continue;
}
else {
Error(Csv_Error_Type.Trailing_Chars, are_all_errors_fatal, true);// alpha,"brav" o,
}
}
// inline verified on 03.06.10
#region add_char();
try {
chars[cnt++] = ch;
}
catch (IndexOutOfRangeException) {
Runaway_Quote_Error(true, open_quote_line, open_quote_col);
}
#endregion
if (!is_ws) {
any_non_ws = true;
//last_was_comma = ch != ',';
}
}
LAST:
if (is_last) {
// open_quote.tiff();
if (open_quote && ch != qq)
Runaway_Quote_Error(false, open_quote_line, open_quote_col);
// inline verified on 03.06.10
#region add_field(false)
if (non_ws_on_line) {
var s = new string(chars, 0, cnt);
cnt = 0;
open_quote = false;
any_non_ws = false;
closing_quote_seen = false;
open_quote_line = null;
open_quote_col = null;
lst.Add(s);
}
#endregion
// inline verified on 03.06.10
#region return value
if (!non_ws_on_line)
return null;
index = ++record;
return lst;
#endregion
}
}
}
}
// ****************************
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Rest.Generator.Logging;
using Microsoft.Rest.Generator.Properties;
using Microsoft.Rest.Generator.Utilities;
using Newtonsoft.Json;
namespace Microsoft.Rest.Generator.Extensibility
{
public static class ExtensionsLoader
{
/// <summary>
/// The name of the AutoRest configuration file.
/// </summary>
internal const string ConfigurationFileName = "AutoRest.json";
/// <summary>
/// Gets the code generator specified in the provided Settings.
/// </summary>
/// <param name="settings">The code generation settings</param>
/// <returns>Code generator specified in Settings.CodeGenerator</returns>
public static CodeGenerator GetCodeGenerator(Settings settings)
{
Logger.LogInfo(Resources.InitializingCodeGenerator);
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (string.IsNullOrEmpty(settings.CodeGenerator))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
Resources.ParameterValueIsMissing, "CodeGenerator"));
}
CodeGenerator codeGenerator = null;
string configurationFile = GetConfigurationFileContent(settings);
if (configurationFile != null)
{
try
{
var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile);
codeGenerator = LoadTypeFromAssembly<CodeGenerator>(config.CodeGenerators, settings.CodeGenerator,
settings);
codeGenerator.PopulateSettings(settings.CustomSettings);
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
}
}
else
{
throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
}
Logger.LogInfo(Resources.GeneratorInitialized,
settings.CodeGenerator,
codeGenerator.GetType().Assembly.GetName().Version);
return codeGenerator;
}
/// <summary>
/// Gets the modeler specified in the provided Settings.
/// </summary>
/// <param name="settings">The code generation settings</param>
/// <returns>Modeler specified in Settings.Modeler</returns>
public static Modeler GetModeler(Settings settings)
{
Logger.LogInfo(Resources.InitializingModeler);
if (settings == null)
{
throw new ArgumentNullException("settings", "settings or settings.Modeler cannot be null.");
}
if (string.IsNullOrEmpty(settings.Modeler))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
Resources.ParameterValueIsMissing, "Modeler"));
}
Modeler modeler = null;
string configurationFile = GetConfigurationFileContent(settings);
if (configurationFile != null)
{
try
{
var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile);
modeler = LoadTypeFromAssembly<Modeler>(config.Modelers, settings.Modeler, settings);
Settings.PopulateSettings(modeler, settings.CustomSettings);
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
}
}
else
{
throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
}
Logger.LogInfo(Resources.ModelerInitialized,
settings.Modeler,
modeler.GetType().Assembly.GetName().Version);
return modeler;
}
public static string GetConfigurationFileContent(Settings settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (settings.FileSystem == null)
{
throw new InvalidOperationException("FileSystem is null in settings.");
}
string path = ConfigurationFileName;
if (!settings.FileSystem.FileExists(path))
{
path = Path.Combine(Directory.GetCurrentDirectory(), ConfigurationFileName);
}
if (!settings.FileSystem.FileExists(path))
{
path = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof (Settings)).Location),
ConfigurationFileName);
}
if (!settings.FileSystem.FileExists(path))
{
return null;
}
return settings.FileSystem.ReadFileAsText(path);
}
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
public static T LoadTypeFromAssembly<T>(IDictionary<string, AutoRestProviderConfiguration> section,
string key, Settings settings)
{
T instance = default(T);
if (settings != null && section != null && !section.IsNullOrEmpty() && section.ContainsKey(key))
{
string fullTypeName = section[key].TypeName;
if (string.IsNullOrEmpty(fullTypeName))
{
throw ErrorManager.CreateError(Resources.ExtensionNotFound, key);
}
int indexOfComma = fullTypeName.IndexOf(',');
if (indexOfComma < 0)
{
throw ErrorManager.CreateError(Resources.TypeShouldBeAssemblyQualified, fullTypeName);
}
string typeName = fullTypeName.Substring(0, indexOfComma).Trim();
string assemblyName = fullTypeName.Substring(indexOfComma + 1).Trim();
try
{
Assembly loadedAssembly;
try
{
loadedAssembly = Assembly.Load(assemblyName);
}
catch(FileNotFoundException)
{
loadedAssembly = Assembly.LoadFrom(assemblyName + ".dll");
if(loadedAssembly == null)
{
throw;
}
}
Type loadedType = loadedAssembly.GetTypes()
.Single(t => string.IsNullOrEmpty(typeName) ||
t.Name == typeName ||
t.FullName == typeName);
instance = (T) loadedType.GetConstructor(
new[] {typeof (Settings)}).Invoke(new object[] {settings});
if (!section[key].Settings.IsNullOrEmpty())
{
foreach (var settingFromFile in section[key].Settings)
{
settings.CustomSettings[settingFromFile.Key] = settingFromFile.Value;
}
}
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorLoadingAssembly, key, ex.Message);
}
return instance;
}
throw ErrorManager.CreateError(Resources.ExtensionNotFound, key);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web;
using Jayrock.Json;
/// <summary>
/// Summary description for CareerOpportunity
/// </summary>
public class CareerOpportunity
{
//object for DB access
private DatabaseAccess dbAccess = new DatabaseAccess();
public void save(CareerOpportunityInfo careeroppty)
{
string sql = " INSERT INTO [CareerOpportunity] "
+ " ([Type] ,[SerialNo] ,[JobFunction] ,[Experience] ,[CareerLevel] ,[Qualification] ,[Division],[Department],[Location] , "
+ " [EmploymentType] ,[Email] ,[Details], [Disclaimer] ,[Status] ,[CreateDate] ,[CreateBy]) "
+ " VALUES "
+ " (@Type ,@SerialNo, @JobFunction ,@Experience ,@CareerLevel ,@Qualification ,@Division ,@Department ,@Location , "
+ " @EmploymentType ,@Email ,@Details, @Disclaimer ,@Status ,getDate() ,@CreateBy) ";
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("@Type", careeroppty.Type);
dict.Add("@SerialNo", careeroppty.SerialNo);
dict.Add("@JobFunction", careeroppty.JobFunction);
dict.Add("@Experience", careeroppty.Experience);
dict.Add("@CareerLevel", careeroppty.CareerLevel);
dict.Add("@Qualification", careeroppty.Qualification);
//dict.Add("@Salary", careeroppty.Salary);
dict.Add("@Division", careeroppty.Division);
dict.Add("@Department", careeroppty.Department);
dict.Add("@Location", careeroppty.Location);
dict.Add("@EmploymentType", careeroppty.EmploymentType);
dict.Add("@Email", careeroppty.Email);
dict.Add("@Details", careeroppty.Details);
dict.Add("@Disclaimer", careeroppty.Disclaimer);
dict.Add("@Status", careeroppty.Status);
dict.Add("@CreateBy", careeroppty.CreateBy);
this.dbAccess.open();
try
{
this.dbAccess.update(sql, dict);
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.dbAccess.close();
}
}
public void update(CareerOpportunityInfo careeroppty)
{
string sql = " UPDATE [CareerOpportunity]"
+ " SET [Type] = @Type"
+ " ,[VersionNo] = @VersionNo"
+ " ,[SerialNo] = @SerialNo"
+ " ,[JobFunction] = @JobFunction"
+ " ,[Experience] = @Experience"
+ " ,[CareerLevel] = @CareerLevel"
+ " ,[Qualification] = @Qualification"
+ " ,[Division] = @Division"
+ " ,[Department] = @Department"
+ " ,[Location] = @Location"
+ " ,[EmploymentType] = @EmploymentType"
+ " ,[Email] = @Email"
+ " ,[Details] = @Details "
+ " ,[Disclaimer] = @Disclaimer "
+ " ,[UpdateDate] = getDate() "
+ " ,[UpdateBy] = @UpdateBy "
+ " WHERE ID=@ID";
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("@Type", careeroppty.Type);
dict.Add("@VersionNo", careeroppty.VersionNo);
dict.Add("@SerialNo", careeroppty.SerialNo);
dict.Add("@JobFunction", careeroppty.JobFunction);
dict.Add("@Experience", careeroppty.Experience);
dict.Add("@CareerLevel", careeroppty.CareerLevel);
dict.Add("@Qualification", careeroppty.Qualification);
dict.Add("@Division", careeroppty.Division);
dict.Add("@Department", careeroppty.Department);
dict.Add("@Location", careeroppty.Location);
dict.Add("@EmploymentType", careeroppty.EmploymentType);
dict.Add("@Email", careeroppty.Email);
dict.Add("@Details", careeroppty.Details);
dict.Add("@Disclaimer", careeroppty.Disclaimer);
dict.Add("@UpdateBy", careeroppty.UpdateBy);
dict.Add("@ID", careeroppty.ID);
this.dbAccess.open();
try
{
this.dbAccess.update(sql, dict);
}
catch (Exception ex)
{
throw ex;
}
finally
{
this.dbAccess.close();
}
}
public void updateStatus(string articleIDs, string newStatus)
{
//create database access object
String sql = string.Format("UPDATE [CareerOpportunity] SET [Status] = '{0}' where ID in ({1}) ",
newStatus,
articleIDs);
dbAccess.open();
try
{
dbAccess.update(sql);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbAccess.close();
}
}
public JsonArray getAllCareerOpportunities()
{
JsonArray ja = new JsonArray();
JsonObject jo;
String tmpStr;
dbAccess.open();
try
{
string sql = " select [CareerOpportunity].ID, SerialNo, PositionPara.Description Title,Status,'Career' Category, SystemPara.Description Type, left(CONVERT(VARCHAR, [CreateDate], " + GlobalSetting.DatabaseDateTimeFormat + "),10) EffectiveDate from [CareerOpportunity] "
+ " left outer join SystemPara on category = 'CareerType' and [CareerOpportunity].type = SystemPara.ID "
+ " left outer join SystemPara PositionPara on PositionPara.category = 'Position' and [CareerOpportunity].JobFunction = PositionPara.ID "
+ " where status <> 'Trashed' order by status, CreateDate desc, SerialNo ";
System.Data.DataTable dt = dbAccess.select(sql);
foreach (System.Data.DataRow dr in dt.Rows)
{
jo = new JsonObject();
foreach (System.Data.DataColumn col in dt.Columns)
{
tmpStr = dr[col.ColumnName].ToString();
jo.Accumulate(col.ColumnName.ToLower(), tmpStr);
}
ja.Add(jo);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbAccess.close();
}
return ja;
}
public CareerOpportunityInfo getCareerOpportunity(int ID)
{
CareerOpportunityInfo careerinfo = new CareerOpportunityInfo();
dbAccess.open();
try
{
string sql = "select * from [CareerOpportunity] where ID = " + ID.ToString();
System.Data.DataTable dt = dbAccess.select(sql);
careerinfo.Type = Convert.ToInt32(dt.Rows[0]["Type"].ToString());
careerinfo.VersionNo = Convert.ToSingle(dt.Rows[0]["VersionNo"]);
careerinfo.SerialNo = dt.Rows[0]["SerialNo"].ToString();
careerinfo.Division = Convert.ToInt32(dt.Rows[0]["Division"]);
careerinfo.Department = Convert.ToInt32(dt.Rows[0]["Department"]);
careerinfo.CareerLevel = dt.Rows[0]["CareerLevel"].ToString();
careerinfo.CreateBy = Convert.ToInt32(dt.Rows[0]["CreateBy"]);
careerinfo.Details = dt.Rows[0]["Details"].ToString();
careerinfo.Email = dt.Rows[0]["Email"].ToString();
careerinfo.EmploymentType = Convert.ToInt32(dt.Rows[0]["EmploymentType"]);
careerinfo.Experience = Convert.ToSingle(dt.Rows[0]["Experience"]);
careerinfo.JobFunction = Convert.ToInt32(dt.Rows[0]["JobFunction"]);
careerinfo.Location = dt.Rows[0]["Location"].ToString();
careerinfo.Qualification = Convert.ToInt32(dt.Rows[0]["Qualification"]);
careerinfo.Disclaimer = dt.Rows[0]["Disclaimer "].ToString();
//careerinfo.Salary = Convert.ToInt32(dt.Rows[0]["Salary"]);
careerinfo.Status = dt.Rows[0]["Status"].ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbAccess.close();
}
return careerinfo;
}
public List<CareerOpportunityInfo> getLatestCareerOpportunities(int total)
{
List<CareerOpportunityInfo> list = new List<CareerOpportunityInfo>();
CareerOpportunityInfo careerOpportunityInfo;
dbAccess.open();
try
{
string sql;
if (total != 0) {
sql = string.Format("select top {0} * from [CareerOpportunity] "
+ " join SystemPara para1 on para1.ID = JobFunction"
+ " join SystemPara para2 on para2.ID = Division"
+ " where status = '{1}' order by para2.[Description], para1.[Description]",
total,
GlobalSetting.ArticleStatus.Published);
}
else {
sql = string.Format("select * from [CareerOpportunity] "
+ " join SystemPara para1 on para1.ID = JobFunction"
+ " join SystemPara para2 on para2.ID = Division"
+ " where status = '{0}' order by para2.[Description], para1.[Description]",
GlobalSetting.ArticleStatus.Published);
}
System.Data.DataTable dt = dbAccess.select(sql);
foreach (System.Data.DataRow row in dt.Rows)
{
careerOpportunityInfo = new CareerOpportunityInfo();
careerOpportunityInfo.CareerLevel = row["CareerLevel"].ToString();
careerOpportunityInfo.CreateBy = Convert.ToInt32(row["CreateBy"]);
careerOpportunityInfo.CreateDate = Convert.ToDateTime(row["CreateDate"]);
careerOpportunityInfo.Division = Convert.ToInt32(row["Division"]);
careerOpportunityInfo.Details = row["Details"].ToString();
careerOpportunityInfo.Email = row["Email"].ToString();
careerOpportunityInfo.EmploymentType = Convert.ToInt32(row["EmploymentType"]);
careerOpportunityInfo.Experience = Convert.ToSingle(row["Experience"]);
careerOpportunityInfo.ID = Convert.ToInt32(row["ID"]);
careerOpportunityInfo.JobFunction = Convert.ToInt32(row["JobFunction"]);
careerOpportunityInfo.Location = row["Location"].ToString();
careerOpportunityInfo.Qualification = Convert.ToInt32(row["Qualification"]);
//careerOpportunityInfo.Salary = Convert.ToInt32(row["Salary"]);
careerOpportunityInfo.Status = row["Status"].ToString();
list.Add(careerOpportunityInfo);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbAccess.close();
}
return list;
}
public System.Text.StringBuilder getLatestCareerOpportunitiesStr(int total)
{
List<CareerOpportunityInfo> latestCareerOpportunityList = this.getLatestCareerOpportunities(0);
System.Text.StringBuilder careerOpportunities = new System.Text.StringBuilder();
int lastDivision = 0;
careerOpportunities.Append("<ul class='list'>");
int count = 0;
foreach (CareerOpportunityInfo careerOppty in latestCareerOpportunityList)
{
if (count == total && total != 0) break;
if (lastDivision == 0)
{
careerOpportunities.Append("<li><a>");
careerOpportunities.Append(SystemPara.getDescription(careerOppty.Division));
//careerOpportunities.Append(careerOppty.Division);
careerOpportunities.Append("</a>");
careerOpportunities.Append("<ul class='margin20px'>");
lastDivision = careerOppty.Division;
count++;
}
else if (lastDivision != 0 && lastDivision != careerOppty.Division)
{
careerOpportunities.Append("</ul>");
careerOpportunities.Append("</li>");
careerOpportunities.Append("<li><a>");
careerOpportunities.Append(SystemPara.getDescription(careerOppty.Division));
careerOpportunities.Append("</a>");
careerOpportunities.Append("<ul class='margin20px'>");
lastDivision = careerOppty.Division;
count++;
}
careerOpportunities.Append("<li class='file'><a href=ViewCareer.aspx?ID=");
careerOpportunities.Append(careerOppty.ID.ToString());
careerOpportunities.Append(">");
careerOpportunities.Append(SystemPara.getDescription(careerOppty.JobFunction));
careerOpportunities.Append("</a>");
careerOpportunities.Append("</li>");
}
careerOpportunities.Append("</ul>");
careerOpportunities.Append("</li>");
careerOpportunities.Append("</ul>");
return careerOpportunities;
}
}
| |
// 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.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Internal
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal unsafe struct MemoryBlock
{
internal readonly byte* Pointer;
internal readonly int Length;
internal MemoryBlock(byte* buffer, int length)
{
Debug.Assert(length >= 0 && (buffer != null || length == 0));
this.Pointer = buffer;
this.Length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length)
{
ThrowOutOfBounds();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowOutOfBounds()
{
throw new BadImageFormatException(MetadataResources.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowReferenceOverflow()
{
throw new BadImageFormatException(MetadataResources.RowIdOrHeapOffsetTooLarge);
}
internal byte[] ToArray()
{
return Pointer == null ? null : PeekBytes(0, Length);
}
private string GetDebuggerDisplay()
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
return GetDebuggerDisplay(out displayedBytes);
}
internal string GetDebuggerDisplay(out int displayedBytes)
{
displayedBytes = Math.Min(Length, 64);
string result = BitConverter.ToString(PeekBytes(0, displayedBytes));
if (displayedBytes < Length)
{
result += "-...";
}
return result;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(Pointer + offset, length);
}
internal Byte PeekByte(int offset)
{
CheckBounds(offset, sizeof(Byte));
return Pointer[offset];
}
internal Int32 PeekInt32(int offset)
{
CheckBounds(offset, sizeof(Int32));
return *(Int32*)(Pointer + offset);
}
internal UInt32 PeekUInt32(int offset)
{
CheckBounds(offset, sizeof(UInt32));
return *(UInt32*)(Pointer + offset);
}
/// <summary>
/// Decodes an compressed integer value starting at offset.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="offset">Offset to the start of the compressed data.</param>
/// <param name="numberOfBytesRead">Bytes actually read.</param>
/// <returns>
/// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid.
/// </returns>
internal int PeekCompressedInteger(int offset, out int numberOfBytesRead)
{
CheckBounds(offset, 0);
byte* ptr = Pointer + offset;
long limit = Length - offset;
if (limit == 0)
{
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
byte headerByte = ptr[0];
if ((headerByte & 0x80) == 0)
{
numberOfBytesRead = 1;
return headerByte;
}
else if ((headerByte & 0x40) == 0)
{
if (limit >= 2)
{
numberOfBytesRead = 2;
return ((headerByte & 0x3f) << 8) | ptr[1];
}
}
else if ((headerByte & 0x20) == 0)
{
if (limit >= 4)
{
numberOfBytesRead = 4;
return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
}
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
internal UInt16 PeekUInt16(int offset)
{
CheckBounds(offset, sizeof(UInt16));
return *(UInt16*)(Pointer + offset);
}
// When reference has tag bits.
internal UInt32 PeekTaggedReference(int offset, bool smallRefSize)
{
return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset);
}
// When reference has at most 24 bits.
internal UInt32 PeekReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!TokenTypeIds.IsValidRowId(value))
{
ThrowReferenceOverflow();
}
return value;
}
internal Guid PeekGuid(int offset)
{
CheckBounds(offset, sizeof(Guid));
return *(Guid*)(Pointer + offset);
}
internal string PeekUtf16(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
// doesn't allocate a new string if byteCount == 0
return new string((char*)(Pointer + offset), 0, byteCount / sizeof(char));
}
internal string PeekUtf8(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
return Encoding.UTF8.GetString(Pointer + offset, byteCount);
}
/// <summary>
/// Read UTF8 at the given offset up to the given terminator, null terminator or end-of-block.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="prefix">UTF-8 encoded prefix to prepend to the bytes at the offset before decoding.</param>
/// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocatiing a new one.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <returns>The decoded string.</returns>
internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0')
{
Debug.Assert(terminator <= 0x7F);
CheckBounds(offset, 0);
int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator);
return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder);
}
/// <summary>
/// Get number of bytes from offset to given terminator, null terminator, or end-of-block.
/// (whichever comes first). returned length does not include the terminator, but numberOfBytesRead
/// out paramater does.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <returns>Length (byte count) not including terminator.</returns>
internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7f);
byte* start = Pointer + offset;
byte* end = Pointer + Length;
byte* current = start;
while (current < end)
{
byte b = *current;
if (b == 0 || b == terminator)
{
break;
}
current++;
}
int length = (int)(current - start);
numberOfBytesRead = length;
if (current < end)
{
// we also read the terminator
numberOfBytesRead++;
}
return length;
}
internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar)
{
CheckBounds(startOffset, 0);
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
for (int i = startOffset; i < Length; i++)
{
byte b = Pointer[i];
if (b == 0)
{
break;
}
if (b == asciiChar)
{
return i;
}
}
return -1;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedEquals(int offset, string text, char terminator = '\0')
{
bool isPrefix;
return Utf8NullTerminatedEquals(offset, text, out isPrefix, terminator);
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
private bool Utf8NullTerminatedEquals(int offset, string text, out bool isPrefix, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7F);
isPrefix = false;
byte* startPointer = Pointer + offset;
byte* endPointer = Pointer + Length;
byte* iteratorPointer = startPointer;
int cur = 0;
while (cur < text.Length)
{
byte b;
if (iteratorPointer == endPointer || ((b = *iteratorPointer++) == 0) || b == terminator)
{
break;
}
if ((b & 0x80) == 0)
{
if (text[cur++] != b)
{
return false;
}
continue;
}
char ch;
byte b1;
if (iteratorPointer == endPointer || ((b1 = *iteratorPointer++) == 0) || b1 == terminator)
{
// Dangling lead byte, do not decompose
if (text[cur++] != b)
{
return false;
}
break;
}
if ((b & 0x20) == 0)
{
ch = (char)(((b & 0x1F) << 6) | (b1 & 0x3F));
}
else
{
byte b2;
if (iteratorPointer == endPointer || ((b2 = *iteratorPointer++) == 0) || b2 == terminator)
{
// Dangling lead bytes, do not decompose
if (text[cur++] != (char)((b << 8) | b1))
{
return false;
}
break;
}
uint char32;
if ((b & 0x10) == 0)
{
char32 = (uint)(((b & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F));
}
else
{
byte b3;
if (iteratorPointer == endPointer || ((b3 = *iteratorPointer++) == 0) || b3 == terminator)
{
// Dangling lead bytes, do not decompose
if (text[cur++] != (char)((b << 8) | b1))
{
return false;
}
if (cur == text.Length)
{
return false;
}
if (text[cur++] != b2)
{
return false;
}
break;
}
char32 = (uint)(((b & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F));
}
if ((char32 & 0xFFFF0000) == 0)
{
ch = (char)char32;
}
else
{
char32 -= 0x10000;
// break up into UTF16 surrogate pair
if (text[cur++] != (char)((char32 >> 10) | 0xD800))
{
return false;
}
ch = (char)((char32 & 0x3FF) | 0xDC00);
}
}
if (cur == text.Length)
{
return false;
}
if (text[cur++] != ch)
{
return false;
}
}
return (isPrefix = cur == text.Length) && (iteratorPointer == endPointer || *iteratorPointer == 0 || *iteratorPointer == terminator);
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStartsWith(int offset, string text, char terminator = '\0')
{
bool isPrefix;
Utf8NullTerminatedEquals(offset, text, out isPrefix, terminator);
return isPrefix;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTermintatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix)
{
// Assumes stringAscii conly contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
// Make sure that we won't read beyond the block even if the block doesn't end with 0 byte.
if (asciiPrefix.Length > Length - offset)
{
return false;
}
byte* p = Pointer + offset;
for (int i = 0; i < asciiPrefix.Length; i++)
{
Debug.Assert((int)asciiPrefix[i] > 0 && (int)asciiPrefix[i] <= 0x7f);
if (asciiPrefix[i] != *p)
{
return false;
}
p++;
}
return true;
}
internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString)
{
// Assumes stringAscii conly contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
byte* p = Pointer + offset;
int limit = Length - offset;
for (int i = 0; i < asciiString.Length; i++)
{
Debug.Assert((int)asciiString[i] > 0 && (int)asciiString[i] <= 0x7f);
if (i > limit)
{
// Heap value is shorter.
return -1;
}
if (*p != asciiString[i])
{
// If we hit the end of the heap value (*p == 0)
// the heap value is shorter than the string, so we return negative value.
return *p - asciiString[i];
}
p++;
}
// Either the heap value name matches exactly the given string or
// it is longer so it is considered "greater".
return (*p == 0) ? 0 : +1;
}
internal byte[] PeekBytes(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
if (byteCount == 0)
{
return EmptyArray<byte>.Instance;
}
byte[] result = new byte[byteCount];
Marshal.Copy((IntPtr)(Pointer + offset), result, 0, byteCount);
return result;
}
internal int IndexOf(byte b, int start)
{
CheckBounds(start, 0);
byte* p = Pointer + start;
byte* end = Pointer + Length;
while (p < end)
{
if (*p == b)
{
return (int)(p - Pointer);
}
p++;
}
return -1;
}
// same as Array.BinarySearch, but without using IComparer
internal int BinarySearch(string[] asciiKeys, int offset)
{
var low = 0;
var high = asciiKeys.Length - 1;
while (low <= high)
{
var middle = low + ((high - low) >> 1);
var midValue = asciiKeys[middle];
int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue);
if (comparison == 0)
{
return middle;
}
if (comparison < 0)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return ~low;
}
// Returns row number [0..RowCount) or -1 if not found.
internal int BinarySearchForSlot(
uint rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = (int)rowCount - 1;
uint startValue = PeekReference(startRowNumber * rowSize + referenceOffset, isReferenceSmall);
uint endValue = PeekReference(endRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (endRowNumber == 1)
{
if (referenceValue >= endValue)
{
return endRowNumber;
}
return startRowNumber;
}
while ((endRowNumber - startRowNumber) > 1)
{
if (referenceValue <= startValue)
{
return referenceValue == startValue ? startRowNumber : startRowNumber - 1;
}
else if (referenceValue >= endValue)
{
return referenceValue == endValue ? endRowNumber : endRowNumber + 1;
}
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReference(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber;
startValue = midReferenceValue;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber;
endValue = midReferenceValue;
}
else
{
return midRowNumber;
}
}
return startRowNumber;
}
// Returns row number [0..RowCount) or -1 if not found.
internal int BinarySearchReference(
uint rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = (int)rowCount - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReference(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
// Row number [0, ptrTable.Length) or -1 if not found.
internal int BinarySearchReference(
uint[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = ptrTable.Length - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReference(((int)ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
uint rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, rowCount) or -1
out int endRowNumber) // [0, rowCount) or -1
{
int foundRowNumber = BinarySearchReference(
rowCount,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReference((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < rowCount &&
PeekReference((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
uint[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, ptrTable.Length) or -1
out int endRowNumber) // [0, ptrTable.Length) or -1
{
int foundRowNumber = BinarySearchReference(
ptrTable,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReference(((int)ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < ptrTable.Length &&
PeekReference(((int)ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
// Always RowNumber....
internal int LinearSearchReference(
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int currOffset = referenceOffset;
int totalSize = this.Length;
while (currOffset < totalSize)
{
uint currReference = PeekReference(currOffset, isReferenceSmall);
if (currReference == referenceValue)
{
return currOffset / rowSize;
}
currOffset += rowSize;
}
return -1;
}
internal bool IsOrderedByReferenceAscending(
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
uint previous = 0;
while (offset < totalSize)
{
uint current = PeekReference(offset, isReferenceSmall);
if (current < previous)
{
return false;
}
previous = current;
offset += rowSize;
}
return true;
}
internal uint[] BuildPtrTable(
int numberOfRows,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
uint[] ptrTable = new uint[numberOfRows];
uint[] unsortedReferences = new uint[numberOfRows];
for (int i = 0; i < ptrTable.Length; i++)
{
ptrTable[i] = (uint)(i + 1);
}
ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall);
Array.Sort(ptrTable, (uint a, uint b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); });
return ptrTable;
}
private void ReadColumn(
uint[] result,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
int i = 0;
while (offset < totalSize)
{
result[i] = PeekTaggedReference(offset, isReferenceSmall);
offset += rowSize;
i++;
}
Debug.Assert(i == result.Length);
}
internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size)
{
int bytesRead;
int numberOfBytes = PeekCompressedInteger(index, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
offset = 0;
size = 0;
return false;
}
offset = index + bytesRead;
size = numberOfBytes;
return true;
}
}
}
| |
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.IO;
using Xunit;
namespace NeinLinq.Tests;
public class EntityFrameworkRealTest
{
[Fact]
public async Task AsNoTracking_MarksQuery()
{
using var context = CreateContext();
var rewriter = new TestExpressionVisitor();
var query = context.Models.DbRewrite(rewriter);
var result = await query.AsNoTracking().ToListAsync();
Assert.True(rewriter.VisitCalled);
Assert.Equal(3, result.Count);
}
[Fact]
public async Task Include_MarksQuery()
{
using var context = CreateContext();
var rewriter = new TestExpressionVisitor();
var query = context.Models.DbRewrite(rewriter);
var result = await query.Include(d => d.Other).ToListAsync();
Assert.True(rewriter.VisitCalled);
Assert.All(result, r => Assert.Equal(r.Name, r.Other?.Name));
}
[Fact]
public async Task SubQuery_ResolvesQuery()
{
using var context = CreateContext();
var innerRewriter = new TestExpressionVisitor();
var innerQuery = context.Models.DbRewrite(innerRewriter);
var outerRewriter = new TestExpressionVisitor();
var outerQuery = context.Models.DbRewrite(outerRewriter)
.Where(m => innerQuery.Any(n => n.Id < m.Id));
var result = await outerQuery.ToListAsync();
Assert.True(outerRewriter.VisitCalled);
Assert.True(innerRewriter.VisitCalled);
Assert.Equal(2, result.Count);
}
[Fact]
public async Task SubQuery_WithProjection_ResolvesQuery()
{
using var context = CreateContext();
var innerRewriter = new TestExpressionVisitor();
var innerQuery = context.Models.DbRewrite(innerRewriter)
.Select(m => new { m.Id });
var outerRewriter = new TestExpressionVisitor();
var outerQuery = context.Models.DbRewrite(outerRewriter)
.Where(m => innerQuery.Any(n => n.Id < m.Id));
var result = await outerQuery.ToListAsync();
Assert.True(outerRewriter.VisitCalled);
Assert.True(innerRewriter.VisitCalled);
Assert.Equal(2, result.Count);
}
[Fact]
public async Task SubQuery_WithInclude_ResolvesQuery()
{
using var context = CreateContext();
var innerRewriter = new TestExpressionVisitor();
var innerQuery = context.Models.DbRewrite(innerRewriter);
var outerRewriter = new TestExpressionVisitor();
var outerQuery = context.Models.DbRewrite(outerRewriter)
.Where(m => innerQuery.Any(n => n.Id < m.Id))
.Include(m => m.Other);
var result = await outerQuery.ToListAsync();
Assert.All(result, r => Assert.Equal(r.Name, r.Other?.Name));
Assert.True(outerRewriter.VisitCalled);
Assert.True(innerRewriter.VisitCalled);
Assert.Equal(2, result.Count);
}
[Fact]
public async Task SubQuery_WithAsNoTracking_ResolvesQuery()
{
using var context = CreateContext();
var innerRewriter = new TestExpressionVisitor();
var innerQuery = context.Models.DbRewrite(innerRewriter);
var outerRewriter = new TestExpressionVisitor();
var outerQuery = context.Models.DbRewrite(outerRewriter)
.Where(m => innerQuery.Any(n => n.Id < m.Id))
.AsNoTracking();
var result = await outerQuery.ToListAsync();
Assert.True(outerRewriter.VisitCalled);
Assert.True(innerRewriter.VisitCalled);
Assert.Equal(2, result.Count);
}
[Fact]
public async Task ToListAsync_ListsAsync()
{
using var context = CreateContext();
var result = await context.Models.ToListAsync();
Assert.Equal(3, result.Count);
}
[Fact]
public async Task ToListAsync_WithRewrite_ListsAsync()
{
using var context = CreateContext();
var rewriter = new TestExpressionVisitor();
var query = context.Models.DbRewrite(rewriter);
var result = await query.ToListAsync();
Assert.Equal(3, result.Count);
}
[Fact]
public async Task SumAsync_SumsAsync()
{
using var context = CreateContext();
var result = await context.Models.SumAsync(m => m.Number);
Assert.Equal(194.48f, result, 2);
}
[Fact]
public async Task SumAsync_WithRewrite_SumsAsync()
{
using var context = CreateContext();
var rewriter = new TestExpressionVisitor();
var query = context.Models.DbRewrite(rewriter);
var result = await query.SumAsync(m => m.Number);
Assert.Equal(194.48f, result, 2);
}
[Fact]
public async Task GetAsyncEnumerator_MovesNextAsync()
{
using var context = CreateContext();
var rewriter = new TestExpressionVisitor();
var query = context.Models.DbRewrite(rewriter);
var result = await ((IDbAsyncEnumerable)query).GetAsyncEnumerator().MoveNextAsync(default);
Assert.True(rewriter.VisitCalled);
Assert.True(result);
}
[Fact]
public async Task ExecuteAsync_ExecutesAsync()
{
using var context = CreateContext();
var rewriter = new TestExpressionVisitor();
var query = context.Models.DbRewrite(rewriter);
var result = await ((IDbAsyncQueryProvider)query.Provider).ExecuteAsync(
Expression.Call(typeof(Queryable), nameof(Queryable.Count), new[] { typeof(Model) }, query.Expression),
default
);
Assert.True(rewriter.VisitCalled);
Assert.Equal(3, (int)result);
}
private static TestContext CreateContext()
{
using var init = new TestContext();
init.CreateDatabase(
new Model
{
Name = "Asdf",
Number = 123.45f,
Other = new OtherModel
{
Name = "Asdf"
}
},
new Model
{
Name = "Qwer",
Number = 67.89f,
Other = new OtherModel
{
Name = "Qwer"
}
},
new Model
{
Name = "Narf",
Number = 3.14f,
Other = new OtherModel
{
Name = "Narf"
}
}
);
return new TestContext();
}
private class Model
{
public int Id { get; set; }
public string? Name { get; set; }
public float Number { get; set; }
public int OtherId { get; set; }
public OtherModel? Other { get; set; }
}
private class OtherModel
{
public int Id { get; set; }
public string? Name { get; set; }
}
private class TestContext : DbContext
{
public DbSet<Model> Models { get; }
public TestContext() : base("Data Source=EntityFrameworkRealTest.db")
{
Models = Set<Model>();
}
public void CreateDatabase(params Model[] seed)
{
if (File.Exists("EntityFrameworkRealTest.db"))
return;
File.Create("EntityFrameworkRealTest.db").Close();
_ = Database.ExecuteSqlCommand(@"
CREATE TABLE Models (
Id INTEGER PRIMARY KEY NOT NULL,
Name TEXT,
Number REAL NOT NULL,
OtherId INTEGER NOT NULL
)"
);
_ = Database.ExecuteSqlCommand(@"
CREATE TABLE OtherModels (
Id INTEGER PRIMARY KEY NOT NULL,
Name TEXT
)"
);
_ = Models.AddRange(seed);
_ = SaveChanges();
}
}
private class TestExpressionVisitor : ExpressionVisitor
{
public bool VisitCalled { get; set; }
public override Expression? Visit(Expression? node)
{
VisitCalled = true;
return base.Visit(node);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.VisualStudioTools.Navigation;
using Microsoft.VisualStudioTools.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudioTools
{
public abstract class CommonPackage : Package, IOleComponent
{
private uint _componentID;
private LibraryManager _libraryManager;
private IOleComponentManager _compMgr;
private static readonly object _commandsLock = new object();
private static readonly Dictionary<Command, MenuCommand> _commands = new Dictionary<Command, MenuCommand>();
#region Language-specific abstracts
public abstract Type GetLibraryManagerType();
internal abstract LibraryManager CreateLibraryManager(CommonPackage package);
public abstract bool IsRecognizedFile(string filename);
// TODO:
// public abstract bool TryGetStartupFileAndDirectory(out string filename, out string dir);
#endregion
internal CommonPackage()
{
#if DEBUG
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
if (e.IsTerminating)
{
var ex = e.ExceptionObject as Exception;
if (ex != null)
{
Debug.Fail(
string.Format("An unhandled exception is about to terminate the process:\n\n{0}", ex.Message),
ex.ToString()
);
}
else
{
Debug.Fail(string.Format(
"An unhandled exception is about to terminate the process:\n\n{0}",
e.ExceptionObject
));
}
}
};
#endif
}
internal static Dictionary<Command, MenuCommand> Commands => _commands;
internal static object CommandsLock => _commandsLock;
protected override void Dispose(bool disposing)
{
try
{
if (this._componentID != 0)
{
var mgr = GetService(typeof(SOleComponentManager)) as IOleComponentManager;
if (mgr != null)
{
mgr.FRevokeComponent(this._componentID);
}
this._componentID = 0;
}
if (null != this._libraryManager)
{
this._libraryManager.Dispose();
this._libraryManager = null;
}
}
finally
{
base.Dispose(disposing);
}
}
private object CreateService(IServiceContainer container, Type serviceType)
{
if (GetLibraryManagerType() == serviceType)
{
return this._libraryManager = CreateLibraryManager(this);
}
return null;
}
internal void RegisterCommands(IEnumerable<Command> commands, Guid cmdSet)
{
var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (null != mcs)
{
lock (_commandsLock)
{
foreach (var command in commands)
{
var beforeQueryStatus = command.BeforeQueryStatus;
var toolwndCommandID = new CommandID(cmdSet, command.CommandId);
var menuToolWin = new OleMenuCommand(command.DoCommand, toolwndCommandID);
if (beforeQueryStatus != null)
{
menuToolWin.BeforeQueryStatus += beforeQueryStatus;
}
mcs.AddCommand(menuToolWin);
_commands[command] = menuToolWin;
}
}
}
}
/// <summary>
/// Gets the current IWpfTextView that is the active document.
/// </summary>
/// <returns></returns>
public static IWpfTextView GetActiveTextView(System.IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
Debug.Assert(false, "No service provider");
return null;
}
var monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));
if (monitorSelection == null)
{
return null;
}
object curDocument;
if (ErrorHandler.Failed(monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out curDocument)))
{
// TODO: Report error
return null;
}
var frame = curDocument as IVsWindowFrame;
if (frame == null)
{
// TODO: Report error
return null;
}
object docView = null;
if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView)))
{
// TODO: Report error
return null;
}
if (docView is IVsCodeWindow)
{
IVsTextView textView;
if (ErrorHandler.Failed(((IVsCodeWindow)docView).GetPrimaryView(out textView)))
{
// TODO: Report error
return null;
}
var model = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
var adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
var wpfTextView = adapterFactory.GetWpfTextView(textView);
return wpfTextView;
}
return null;
}
[Obsolete("ComponentModel should be retrieved from an IServiceProvider")]
public static IComponentModel ComponentModel => (IComponentModel)GetGlobalService(typeof(SComponentModel));
internal static CommonProjectNode GetStartupProject(System.IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
Debug.Assert(false, "No service provider");
return null;
}
var buildMgr = (IVsSolutionBuildManager)serviceProvider.GetService(typeof(IVsSolutionBuildManager));
IVsHierarchy hierarchy;
if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out hierarchy)) && hierarchy != null)
{
return hierarchy.GetProject().GetCommonProject();
}
return null;
}
protected override void Initialize()
{
var container = (IServiceContainer)this;
UIThread.EnsureService(this);
container.AddService(GetLibraryManagerType(), this.CreateService, true);
var componentManager = this._compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager));
var crinfo = new OLECRINFO[1];
crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime;
crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff;
crinfo[0].uIdleTimeInterval = 0;
ErrorHandler.ThrowOnFailure(componentManager.FRegisterComponent(this, crinfo, out this._componentID));
base.Initialize();
}
internal static void OpenWebBrowser(string url)
{
var uri = new Uri(url);
Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
return;
}
internal static void OpenVsWebBrowser(System.IServiceProvider serviceProvider, string url)
{
serviceProvider.GetUIThread().Invoke(() =>
{
var web = serviceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;
if (web == null)
{
OpenWebBrowser(url);
return;
}
IVsWindowFrame frame;
ErrorHandler.ThrowOnFailure(web.Navigate(url, (uint)__VSWBNAVIGATEFLAGS.VSNWB_ForceNew, out frame));
frame.Show();
});
}
#region IOleComponent Members
public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked)
{
return 1;
}
public virtual int FDoIdle(uint grfidlef)
{
if (null != this._libraryManager)
{
this._libraryManager.OnIdle(this._compMgr);
}
var onIdle = OnIdle;
if (onIdle != null)
{
onIdle(this, new ComponentManagerEventArgs(this._compMgr));
}
return 0;
}
internal event EventHandler<ComponentManagerEventArgs> OnIdle;
public int FPreTranslateMessage(MSG[] pMsg)
{
return 0;
}
public int FQueryTerminate(int fPromptUser)
{
return 1;
}
public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam)
{
return 1;
}
public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved)
{
return IntPtr.Zero;
}
public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved)
{
}
public void OnAppActivate(int fActive, uint dwOtherThreadID)
{
}
public void OnEnterState(uint uStateID, int fEnter)
{
}
public void OnLoseActivation()
{
}
public void Terminate()
{
}
#endregion
}
internal class ComponentManagerEventArgs : EventArgs
{
private readonly IOleComponentManager _compMgr;
public ComponentManagerEventArgs(IOleComponentManager compMgr)
{
this._compMgr = compMgr;
}
public IOleComponentManager ComponentManager => this._compMgr;
}
}
| |
namespace Macabresoft.Macabre2D.UI.Editor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Windows.Input;
using Avalonia.Threading;
using Macabresoft.AvaloniaEx;
using Macabresoft.Macabre2D.Framework;
using Macabresoft.Macabre2D.UI.Common;
using ReactiveUI;
using Unity;
/// <summary>
/// A view model for the scene view.
/// </summary>
public sealed class SceneTreeViewModel : BaseViewModel {
private readonly IContentService _contentService;
private readonly ICommonDialogService _dialogService;
private readonly IUndoService _undoService;
/// <summary>
/// Initializes a new instance of the <see cref="SceneTreeViewModel" /> class.
/// </summary>
/// <remarks>This constructor only exists for design time XAML.</remarks>
public SceneTreeViewModel() {
}
/// <summary>
/// Initializes a new instance of the <see cref="SceneTreeViewModel" /> class.
/// </summary>
/// <param name="contentService">The content service.</param>
/// <param name="dialogService">The dialog service.</param>
/// <param name="editorService">The editor service.</param>
/// <param name="entityService">The selection service.</param>
/// <param name="sceneService">The scene service.</param>
/// <param name="systemService">The system service.</param>
/// <param name="undoService">The undo service.</param>
[InjectionConstructor]
public SceneTreeViewModel(
IContentService contentService,
ICommonDialogService dialogService,
IEditorService editorService,
IEntityService entityService,
ISceneService sceneService,
ISystemService systemService,
IUndoService undoService) {
this._contentService = contentService;
this._dialogService = dialogService;
this.EditorService = editorService;
this.EntityService = entityService;
this.SceneService = sceneService;
this.SystemService = systemService;
this._undoService = undoService;
this.AddEntityCommand = ReactiveCommand.CreateFromTask<Type>(async x => await this.AddEntity(x));
this.RemoveEntityCommand = ReactiveCommand.Create<IEntity>(this.RemoveEntity);
this.AddSystemCommand = ReactiveCommand.CreateFromTask<Type>(async x => await this.AddSystem(x));
this.RemoveSystemCommand = ReactiveCommand.Create<IUpdateableSystem>(this.RemoveSystem);
this.RenameEntityCommand = ReactiveCommand.Create<string>(this.RenameEntity);
this.RenameSystemCommand = ReactiveCommand.Create<string>(this.RenameSystem);
this.ConvertToInstanceCommand = ReactiveCommand.Create<IEntity>(this.ConvertToInstance);
this.CreatePrefabCommand = ReactiveCommand.CreateFromTask<IEntity>(async x => await this.CreateFromPrefab(x));
this.AddEntityModels = this.EntityService.AvailableTypes.OrderBy(x => x.Name)
.Select(x => new MenuItemModel(x.Name, x.FullName, this.AddEntityCommand, x)).ToList();
this.AddSystemModels = this.SystemService.AvailableTypes.OrderBy(x => x.Name)
.Select(x => new MenuItemModel(x.Name, x.FullName, this.AddSystemCommand, x)).ToList();
}
private void ConvertToInstance(IEntity entity) {
if (entity.Parent is { } parent &&
!Entity.IsNullOrEmpty(parent, out _) &&
entity is PrefabContainer container &&
container.PrefabReference.Asset?.Content is IEntity content &&
content.TryClone(out var clone)) {
clone.LocalPosition = entity.LocalPosition;
clone.LocalScale = entity.LocalScale;
this._undoService.Do(() => {
parent.AddChild(clone);
parent.RemoveChild(entity);
}, () => {
parent.AddChild(entity);
parent.RemoveChild(clone);
});
}
}
/// <summary>
/// Gets a collection of <see cref="MenuItemModel"/> for adding entities.
/// </summary>
public IReadOnlyCollection<MenuItemModel> AddEntityModels { get; }
/// <summary>
/// Gets a collection of <see cref="MenuItemModel"/> for adding systems.
/// </summary>
public IReadOnlyCollection<MenuItemModel> AddSystemModels { get; }
/// <summary>
/// Gets a command to add an entity.
/// </summary>
public ICommand AddEntityCommand { get; }
/// <summary>
/// Gets a command to add a system.
/// </summary>
public ICommand AddSystemCommand { get; }
/// <summary>
/// Gets a command to create a prefab.
/// </summary>
public ICommand CreatePrefabCommand { get; }
/// <summary>
/// Gets a command to convert a prefab into an instance.
/// </summary>
public ICommand ConvertToInstanceCommand { get; }
/// <summary>
/// Gets the editor service.
/// </summary>
public IEditorService EditorService { get; }
/// <summary>
/// Gets the selection service.
/// </summary>
public IEntityService EntityService { get; }
/// <summary>
/// Gets a command to remove an entity.
/// </summary>
public ICommand RemoveEntityCommand { get; }
/// <summary>
/// Gets a command to remove a system.
/// </summary>
public ICommand RemoveSystemCommand { get; }
/// <summary>
/// Gets a command for renaming an entity.
/// </summary>
public ICommand RenameEntityCommand { get; }
/// <summary>
/// Gets a command for renaming a system.
/// </summary>
public ICommand RenameSystemCommand { get; }
/// <summary>
/// Gets the scene service.
/// </summary>
public ISceneService SceneService { get; }
/// <summary>
/// Gets the system service.
/// </summary>
public ISystemService SystemService { get; }
/// <summary>
/// Moves the source entity to be a child of the target entity.
/// </summary>
/// <param name="sourceEntity">The source entity.</param>
/// <param name="targetEntity">The target entity.</param>
public void MoveEntity(IEntity sourceEntity, IEntity targetEntity) {
if (CanMoveEntity(sourceEntity, targetEntity)) {
var originalParent = sourceEntity.Parent;
this._undoService.Do(() => { targetEntity.AddChild(sourceEntity); }, () => { originalParent.AddChild(sourceEntity); });
}
}
private async Task AddEntity(Type type) {
type ??= await this._dialogService.OpenTypeSelectionDialog(this.EntityService.AvailableTypes);
if (type != null && Activator.CreateInstance(type) is IEntity child) {
if (type.GetCustomAttribute(typeof(DataContractAttribute)) is DataContractAttribute attribute) {
child.Name = string.IsNullOrEmpty(attribute.Name) ? type.Name : attribute.Name;
}
else {
child.Name = type.Name;
}
var parent = this.EntityService.Selected ?? this.SceneService.CurrentScene;
if (parent != null) {
this._undoService.Do(() => {
Dispatcher.UIThread.Post(() => {
parent.AddChild(child);
this.SceneService.Selected = child;
});
}, () => {
Dispatcher.UIThread.Post(() => {
parent.RemoveChild(child);
this.SceneService.Selected = parent;
});
});
}
}
}
private async Task AddSystem(Type type) {
if (this.SceneService.CurrentScene is { } scene) {
type ??= await this._dialogService.OpenTypeSelectionDialog(this.SystemService.AvailableTypes);
if (type != null && Activator.CreateInstance(type) is IUpdateableSystem system) {
var originallySelected = this.SystemService.Selected;
this._undoService.Do(() => {
Dispatcher.UIThread.Post(() => {
scene.AddSystem(system);
this.SceneService.Selected = system;
});
}, () => {
Dispatcher.UIThread.Post(() => {
scene.RemoveSystem(system);
this.SceneService.Selected = originallySelected;
});
});
}
}
}
private static bool CanMoveEntity(IEntity sourceEntity, IEntity targetEntity) {
return sourceEntity != null &&
targetEntity != null &&
sourceEntity != targetEntity &&
!targetEntity.IsDescendentOf(sourceEntity);
}
private async Task CreateFromPrefab(IEntity entity) {
await this._contentService.CreatePrefab(entity);
}
private void RemoveEntity(object selected) {
if (selected is IEntity entity) {
var parent = entity.Parent;
this._undoService.Do(() => {
Dispatcher.UIThread.Post(() => {
parent.RemoveChild(entity);
this.SceneService.Selected = null;
});
}, () => {
Dispatcher.UIThread.Post(() => {
parent.AddChild(entity);
this.SceneService.Selected = entity;
});
});
}
}
private void RemoveSystem(object selected) {
if (selected is IUpdateableSystem system && this.SceneService.CurrentScene is { } scene) {
this._undoService.Do(() => {
Dispatcher.UIThread.Post(() => {
scene.RemoveSystem(system);
this.SceneService.Selected = null;
});
}, () => {
Dispatcher.UIThread.Post(() => {
scene.AddSystem(system);
this.SceneService.Selected = system;
});
});
}
}
private void RenameEntity(string updatedName) {
if (this.EntityService.Selected is { } entity && entity.Name != updatedName) {
var originalName = entity.Name;
this._undoService.Do(
() => { Dispatcher.UIThread.Post(() => { entity.Name = updatedName; }); }, () => { Dispatcher.UIThread.Post(() => { entity.Name = originalName; }); });
}
}
private void RenameSystem(string updatedName) {
if (this.SystemService.Selected is { } system && system.Name != updatedName) {
var originalName = system.Name;
this._undoService.Do(
() => { Dispatcher.UIThread.Post(() => { system.Name = updatedName; }); },
() => { Dispatcher.UIThread.Post(() => { system.Name = originalName; }); });
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.GroupsModels
{
/// <summary>
/// Accepts an outstanding invitation to to join a group if the invited entity is not blocked by the group. Nothing is
/// returned in the case of success.
/// </summary>
[Serializable]
public class AcceptGroupApplicationRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Type of the entity to accept as. Must be the same entity as the claimant or an entity that is a child of the claimant
/// entity.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Accepts an outstanding invitation to join the group if the invited entity is not blocked by the group. Only the invited
/// entity or a parent in its chain (e.g. title) may accept the invitation on the invited entity's behalf. Nothing is
/// returned in the case of success.
/// </summary>
[Serializable]
public class AcceptGroupInvitationRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Adds members to a group or role. Existing members of the group will added to roles within the group, but if the user is
/// not already a member of the group, only title claimants may add them to the group, and others must use the group
/// application or invite system to add new members to a group. Returns nothing if successful.
/// </summary>
[Serializable]
public class AddMembersRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// List of entities to add to the group. Only entities of type title_player_account and character may be added to groups.
/// </summary>
public List<EntityKey> Members;
/// <summary>
/// Optional: The ID of the existing role to add the entities to. If this is not specified, the default member role for the
/// group will be used. Role IDs must be between 1 and 64 characters long.
/// </summary>
public string RoleId;
}
/// <summary>
/// Creates an application to join a group. Calling this while a group application already exists will return the same
/// application instead of an error and will not refresh the time before the application expires. By default, if the entity
/// has an invitation to join the group outstanding, this will accept the invitation to join the group instead and return an
/// error indicating such, rather than creating a duplicate application to join that will need to be cleaned up later.
/// Returns information about the application or an error indicating an invitation was accepted instead.
/// </summary>
[Serializable]
public class ApplyToGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// Optional, default true. Automatically accept an outstanding invitation if one exists instead of creating an application
/// </summary>
public bool? AutoAcceptOutstandingInvite;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Describes an application to join a group
/// </summary>
[Serializable]
public class ApplyToGroupResponse : PlayFabResultCommon
{
/// <summary>
/// Type of entity that requested membership
/// </summary>
public EntityWithLineage Entity;
/// <summary>
/// When the application to join will expire and be deleted
/// </summary>
public DateTime Expires;
/// <summary>
/// ID of the group that the entity requesting membership to
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Blocks a list of entities from joining a group. Blocked entities may not create new applications to join, be invited to
/// join, accept an invitation, or have an application accepted. Failure due to being blocked does not clean up existing
/// applications or invitations to the group. No data is returned in the case of success.
/// </summary>
[Serializable]
public class BlockEntityRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Changes the role membership of a list of entities from one role to another in in a single operation. The destination
/// role must already exist. This is equivalent to adding the entities to the destination role and removing from the origin
/// role. Returns nothing if successful.
/// </summary>
[Serializable]
public class ChangeMemberRoleRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The ID of the role that the entities will become a member of. This must be an existing role. Role IDs must be between 1
/// and 64 characters long.
/// </summary>
public string DestinationRoleId;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// List of entities to move between roles in the group. All entities in this list must be members of the group and origin
/// role.
/// </summary>
public List<EntityKey> Members;
/// <summary>
/// The ID of the role that the entities currently are a member of. Role IDs must be between 1 and 64 characters long.
/// </summary>
public string OriginRoleId;
}
/// <summary>
/// Creates a new group, as well as administration and member roles, based off of a title's group template. Returns
/// information about the group that was created.
/// </summary>
[Serializable]
public class CreateGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The name of the group. This is unique at the title level by default.
/// </summary>
public string GroupName;
}
[Serializable]
public class CreateGroupResponse : PlayFabResultCommon
{
/// <summary>
/// The ID of the administrator role for the group.
/// </summary>
public string AdminRoleId;
/// <summary>
/// The server date and time the group was created.
/// </summary>
public DateTime Created;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// The name of the group.
/// </summary>
public string GroupName;
/// <summary>
/// The ID of the default member role for the group.
/// </summary>
public string MemberRoleId;
/// <summary>
/// The current version of the profile, can be used for concurrency control during updates.
/// </summary>
public int ProfileVersion;
/// <summary>
/// The list of roles and names that belong to the group.
/// </summary>
public Dictionary<string,string> Roles;
}
/// <summary>
/// Creates a new role within an existing group, with no members. Both the role ID and role name must be unique within the
/// group, but the name can be the same as the ID. The role ID is set at creation and cannot be changed. Returns information
/// about the role that was created.
/// </summary>
[Serializable]
public class CreateGroupRoleRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// The ID of the role. This must be unique within the group and cannot be changed. Role IDs must be between 1 and 64
/// characters long.
/// </summary>
public string RoleId;
/// <summary>
/// The name of the role. This must be unique within the group and can be changed later. Role names must be between 1 and
/// 100 characters long
/// </summary>
public string RoleName;
}
[Serializable]
public class CreateGroupRoleResponse : PlayFabResultCommon
{
/// <summary>
/// The current version of the group profile, can be used for concurrency control during updates.
/// </summary>
public int ProfileVersion;
/// <summary>
/// ID for the role
/// </summary>
public string RoleId;
/// <summary>
/// The name of the role
/// </summary>
public string RoleName;
}
/// <summary>
/// Deletes a group and all roles, invitations, join requests, and blocks associated with it. Permission to delete is only
/// required the group itself to execute this action. The group and data cannot be cannot be recovered once removed, but any
/// abuse reports about the group will remain. No data is returned in the case of success.
/// </summary>
[Serializable]
public class DeleteGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// ID of the group or role to remove
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Returns information about the role
/// </summary>
[Serializable]
public class DeleteRoleRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// The ID of the role to delete. Role IDs must be between 1 and 64 characters long.
/// </summary>
public string RoleId;
}
[Serializable]
public class EmptyResponse : PlayFabResultCommon
{
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey : PlayFabBaseModel
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types
/// </summary>
public string Type;
}
[Serializable]
public class EntityMemberRole : PlayFabBaseModel
{
/// <summary>
/// The list of members in the role
/// </summary>
public List<EntityWithLineage> Members;
/// <summary>
/// The ID of the role.
/// </summary>
public string RoleId;
/// <summary>
/// The name of the role
/// </summary>
public string RoleName;
}
/// <summary>
/// Entity wrapper class that contains the entity key and the entities that make up the lineage of the entity.
/// </summary>
[Serializable]
public class EntityWithLineage : PlayFabBaseModel
{
/// <summary>
/// The entity key for the specified entity
/// </summary>
public EntityKey Key;
/// <summary>
/// Dictionary of entity keys for related entities. Dictionary key is entity type.
/// </summary>
public Dictionary<string,EntityKey> Lineage;
}
/// <summary>
/// Returns the ID, name, role list and other non-membership related information about a group.
/// </summary>
[Serializable]
public class GetGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// The full name of the group
/// </summary>
public string GroupName;
}
[Serializable]
public class GetGroupResponse : PlayFabResultCommon
{
/// <summary>
/// The ID of the administrator role for the group.
/// </summary>
public string AdminRoleId;
/// <summary>
/// The server date and time the group was created.
/// </summary>
public DateTime Created;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// The name of the group.
/// </summary>
public string GroupName;
/// <summary>
/// The ID of the default member role for the group.
/// </summary>
public string MemberRoleId;
/// <summary>
/// The current version of the profile, can be used for concurrency control during updates.
/// </summary>
public int ProfileVersion;
/// <summary>
/// The list of roles and names that belong to the group.
/// </summary>
public Dictionary<string,string> Roles;
}
/// <summary>
/// Describes an application to join a group
/// </summary>
[Serializable]
public class GroupApplication : PlayFabBaseModel
{
/// <summary>
/// Type of entity that requested membership
/// </summary>
public EntityWithLineage Entity;
/// <summary>
/// When the application to join will expire and be deleted
/// </summary>
public DateTime Expires;
/// <summary>
/// ID of the group that the entity requesting membership to
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Describes an entity that is blocked from joining a group.
/// </summary>
[Serializable]
public class GroupBlock : PlayFabBaseModel
{
/// <summary>
/// The entity that is blocked
/// </summary>
public EntityWithLineage Entity;
/// <summary>
/// ID of the group that the entity is blocked from
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Describes an invitation to a group.
/// </summary>
[Serializable]
public class GroupInvitation : PlayFabBaseModel
{
/// <summary>
/// When the invitation will expire and be deleted
/// </summary>
public DateTime Expires;
/// <summary>
/// The group that the entity invited to
/// </summary>
public EntityKey Group;
/// <summary>
/// The entity that created the invitation
/// </summary>
public EntityWithLineage InvitedByEntity;
/// <summary>
/// The entity that is invited
/// </summary>
public EntityWithLineage InvitedEntity;
/// <summary>
/// ID of the role in the group to assign the user to.
/// </summary>
public string RoleId;
}
/// <summary>
/// Describes a group role
/// </summary>
[Serializable]
public class GroupRole : PlayFabBaseModel
{
/// <summary>
/// ID for the role
/// </summary>
public string RoleId;
/// <summary>
/// The name of the role
/// </summary>
public string RoleName;
}
/// <summary>
/// Describes a group and the roles that it contains
/// </summary>
[Serializable]
public class GroupWithRoles : PlayFabBaseModel
{
/// <summary>
/// ID for the group
/// </summary>
public EntityKey Group;
/// <summary>
/// The name of the group
/// </summary>
public string GroupName;
/// <summary>
/// The current version of the profile, can be used for concurrency control during updates.
/// </summary>
public int ProfileVersion;
/// <summary>
/// The list of roles within the group
/// </summary>
public List<GroupRole> Roles;
}
/// <summary>
/// Invites a player to join a group, if they are not blocked by the group. An optional role can be provided to
/// automatically assign the player to the role if they accept the invitation. By default, if the entity has an application
/// to the group outstanding, this will accept the application instead and return an error indicating such, rather than
/// creating a duplicate invitation to join that will need to be cleaned up later. Returns information about the new
/// invitation or an error indicating an existing application to join was accepted.
/// </summary>
[Serializable]
public class InviteToGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// Optional, default true. Automatically accept an application if one exists instead of creating an invitation
/// </summary>
public bool? AutoAcceptOutstandingApplication;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// Optional. ID of an existing a role in the group to assign the user to. The group's default member role is used if this
/// is not specified. Role IDs must be between 1 and 64 characters long.
/// </summary>
public string RoleId;
}
/// <summary>
/// Describes an invitation to a group.
/// </summary>
[Serializable]
public class InviteToGroupResponse : PlayFabResultCommon
{
/// <summary>
/// When the invitation will expire and be deleted
/// </summary>
public DateTime Expires;
/// <summary>
/// The group that the entity invited to
/// </summary>
public EntityKey Group;
/// <summary>
/// The entity that created the invitation
/// </summary>
public EntityWithLineage InvitedByEntity;
/// <summary>
/// The entity that is invited
/// </summary>
public EntityWithLineage InvitedEntity;
/// <summary>
/// ID of the role in the group to assign the user to.
/// </summary>
public string RoleId;
}
/// <summary>
/// Checks to see if an entity is a member of a group or role within the group. A result indicating if the entity is a
/// member of the group is returned, or a permission error if the caller does not have permission to read the group's member
/// list.
/// </summary>
[Serializable]
public class IsMemberRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// Optional: ID of the role to check membership of. Defaults to any role (that is, check to see if the entity is a member
/// of the group in any capacity) if not specified.
/// </summary>
public string RoleId;
}
[Serializable]
public class IsMemberResponse : PlayFabResultCommon
{
/// <summary>
/// A value indicating whether or not the entity is a member.
/// </summary>
public bool IsMember;
}
/// <summary>
/// Lists all outstanding requests to join a group. Returns a list of all requests to join, as well as when the request will
/// expire. To get the group applications for a specific entity, use ListMembershipOpportunities.
/// </summary>
[Serializable]
public class ListGroupApplicationsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
[Serializable]
public class ListGroupApplicationsResponse : PlayFabResultCommon
{
/// <summary>
/// The requested list of applications to the group.
/// </summary>
public List<GroupApplication> Applications;
}
/// <summary>
/// Lists all entities blocked from joining a group. A list of blocked entities is returned
/// </summary>
[Serializable]
public class ListGroupBlocksRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
[Serializable]
public class ListGroupBlocksResponse : PlayFabResultCommon
{
/// <summary>
/// The requested list blocked entities.
/// </summary>
public List<GroupBlock> BlockedEntities;
}
/// <summary>
/// Lists all outstanding invitations for a group. Returns a list of entities that have been invited, as well as when the
/// invitation will expire. To get the group invitations for a specific entity, use ListMembershipOpportunities.
/// </summary>
[Serializable]
public class ListGroupInvitationsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
[Serializable]
public class ListGroupInvitationsResponse : PlayFabResultCommon
{
/// <summary>
/// The requested list of group invitations.
/// </summary>
public List<GroupInvitation> Invitations;
}
/// <summary>
/// Gets a list of members and the roles they belong to within the group. If the caller does not have permission to view the
/// role, and the member is in no other role, the member is not displayed. Returns a list of entities that are members of
/// the group.
/// </summary>
[Serializable]
public class ListGroupMembersRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// ID of the group to list the members and roles for
/// </summary>
public EntityKey Group;
}
[Serializable]
public class ListGroupMembersResponse : PlayFabResultCommon
{
/// <summary>
/// The requested list of roles and member entity IDs.
/// </summary>
public List<EntityMemberRole> Members;
}
/// <summary>
/// Lists all outstanding group applications and invitations for an entity. Anyone may call this for any entity, but data
/// will only be returned for the entity or a parent of that entity. To list invitations or applications for a group to
/// check if a player is trying to join, use ListGroupInvitations and ListGroupApplications.
/// </summary>
[Serializable]
public class ListMembershipOpportunitiesRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class ListMembershipOpportunitiesResponse : PlayFabResultCommon
{
/// <summary>
/// The requested list of group applications.
/// </summary>
public List<GroupApplication> Applications;
/// <summary>
/// The requested list of group invitations.
/// </summary>
public List<GroupInvitation> Invitations;
}
/// <summary>
/// Lists the groups and roles that an entity is a part of, checking to see if group and role metadata and memberships
/// should be visible to the caller. If the entity is not in any roles that are visible to the caller, the group is not
/// returned in the results, even if the caller otherwise has permission to see that the entity is a member of that group.
/// </summary>
[Serializable]
public class ListMembershipRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class ListMembershipResponse : PlayFabResultCommon
{
/// <summary>
/// The list of groups
/// </summary>
public List<GroupWithRoles> Groups;
}
public enum OperationTypes
{
Created,
Updated,
Deleted,
None
}
/// <summary>
/// Removes an existing application to join the group. This is used for both rejection of an application as well as
/// withdrawing an application. The applying entity or a parent in its chain (e.g. title) may withdraw the application, and
/// any caller with appropriate access in the group may reject an application. No data is returned in the case of success.
/// </summary>
[Serializable]
public class RemoveGroupApplicationRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Removes an existing invitation to join the group. This is used for both rejection of an invitation as well as rescinding
/// an invitation. The invited entity or a parent in its chain (e.g. title) may reject the invitation by calling this
/// method, and any caller with appropriate access in the group may rescind an invitation. No data is returned in the case
/// of success.
/// </summary>
[Serializable]
public class RemoveGroupInvitationRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Removes members from a group. A member can always remove themselves from a group, regardless of permissions. Returns
/// nothing if successful.
/// </summary>
[Serializable]
public class RemoveMembersRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// List of entities to remove
/// </summary>
public List<EntityKey> Members;
/// <summary>
/// The ID of the role to remove the entities from.
/// </summary>
public string RoleId;
}
/// <summary>
/// Unblocks a list of entities from joining a group. No data is returned in the case of success.
/// </summary>
[Serializable]
public class UnblockEntityRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
}
/// <summary>
/// Updates data about a group, such as the name or default member role. Returns information about whether the update was
/// successful. Only title claimants may modify the administration role for a group.
/// </summary>
[Serializable]
public class UpdateGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// Optional: the ID of an existing role to set as the new administrator role for the group
/// </summary>
public string AdminRoleId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Optional field used for concurrency control. By specifying the previously returned value of ProfileVersion from the
/// GetGroup API, you can ensure that the group data update will only be performed if the group has not been updated by any
/// other clients since the version you last loaded.
/// </summary>
public int? ExpectedProfileVersion;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// Optional: the new name of the group
/// </summary>
public string GroupName;
/// <summary>
/// Optional: the ID of an existing role to set as the new member role for the group
/// </summary>
public string MemberRoleId;
}
[Serializable]
public class UpdateGroupResponse : PlayFabResultCommon
{
/// <summary>
/// Optional reason to explain why the operation was the result that it was.
/// </summary>
public string OperationReason;
/// <summary>
/// New version of the group data.
/// </summary>
public int ProfileVersion;
/// <summary>
/// Indicates which operation was completed, either Created, Updated, Deleted or None.
/// </summary>
public OperationTypes? SetResult;
}
/// <summary>
/// Updates the role name. Returns information about whether the update was successful.
/// </summary>
[Serializable]
public class UpdateGroupRoleRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Optional field used for concurrency control. By specifying the previously returned value of ProfileVersion from the
/// GetGroup API, you can ensure that the group data update will only be performed if the group has not been updated by any
/// other clients since the version you last loaded.
/// </summary>
public int? ExpectedProfileVersion;
/// <summary>
/// The identifier of the group
/// </summary>
public EntityKey Group;
/// <summary>
/// ID of the role to update. Role IDs must be between 1 and 64 characters long.
/// </summary>
public string RoleId;
/// <summary>
/// The new name of the role
/// </summary>
public string RoleName;
}
[Serializable]
public class UpdateGroupRoleResponse : PlayFabResultCommon
{
/// <summary>
/// Optional reason to explain why the operation was the result that it was.
/// </summary>
public string OperationReason;
/// <summary>
/// New version of the role data.
/// </summary>
public int ProfileVersion;
/// <summary>
/// Indicates which operation was completed, either Created, Updated, Deleted or None.
/// </summary>
public OperationTypes? SetResult;
}
}
#endif
| |
using System;
using Server.Multis;
using System.Collections.Generic;
using Server.Gumps;
namespace Server.Items
{
public class EnhancedBandage : Bandage
{
public static int HealingBonus { get { return 10; } }
public override int LabelNumber { get { return 1152441; } } // enhanced bandage
[Constructable]
public EnhancedBandage() : this( 1 )
{
}
[Constructable]
public EnhancedBandage( int amount ) : base( amount )
{
Hue = 0x8A5;
}
public EnhancedBandage( Serial serial ) : base( serial )
{
}
public override bool Dye( Mobile from, DyeTub sender )
{
return false;
}
public override void AddNameProperties(ObjectPropertyList list)
{
base.AddNameProperties(list);
list.Add(1075216); // these bandages have been enhanced
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); //version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
[FlipableAttribute( 0x2AC0, 0x2AC3 )]
public class FountainOfLife : BaseAddonContainer
{
public override BaseAddonContainerDeed Deed
{
get { return new FountainOfLifeDeed( m_Charges ); }
}
public override bool OnDragLift(Mobile from)
{
return false;
}
public virtual TimeSpan RechargeTime { get { return TimeSpan.FromDays( 1 ); } }
public override int LabelNumber { get { return 1075197; } } // Fountain of Life
public override int DefaultGumpID { get { return 0x484; } }
public override int DefaultDropSound { get { return 66; } }
public override int DefaultMaxItems { get { return 125; } }
private int m_Charges;
[CommandProperty( AccessLevel.GameMaster )]
public int Charges
{
get { return m_Charges; }
set { m_Charges = Math.Min( value, 10 ); InvalidateProperties(); }
}
private Timer m_Timer;
[Constructable]
public FountainOfLife() : this( 10 )
{
}
[Constructable]
public FountainOfLife( int charges ) : base( 0x2AC0 )
{
m_Charges = charges;
m_Timer = Timer.DelayCall( RechargeTime, RechargeTime, new TimerCallback( Recharge ) );
}
public FountainOfLife( Serial serial ) : base( serial )
{
}
public override bool OnDragDrop( Mobile from, Item dropped )
{
if ( dropped is Bandage )
{
bool allow = base.OnDragDrop( from, dropped );
if ( allow )
Enhance(from);
return allow;
}
else
{
from.SendLocalizedMessage( 1075209 ); // Only bandages may be dropped into the fountain.
return false;
}
}
public override bool OnDragDropInto( Mobile from, Item item, Point3D p )
{
if ( item is Bandage )
{
bool allow = base.OnDragDropInto( from, item, p );
if ( allow )
Enhance(from);
return allow;
}
else
{
from.SendLocalizedMessage( 1075209 ); // Only bandages may be dropped into the fountain.
return false;
}
}
public override void AddNameProperties( ObjectPropertyList list )
{
base.AddNameProperties( list );
list.Add( 1075217, m_Charges.ToString() ); // ~1_val~ charges remaining
}
public override void OnDelete()
{
if ( m_Timer != null )
m_Timer.Stop();
base.OnDelete();
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); //version
writer.Write( m_Charges );
writer.Write( (DateTime) m_Timer.Next );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
m_Charges = reader.ReadInt();
DateTime next = reader.ReadDateTime();
if ( next < DateTime.Now )
m_Timer = Timer.DelayCall( TimeSpan.Zero, RechargeTime, new TimerCallback( Recharge ) );
else
m_Timer = Timer.DelayCall( next - DateTime.Now, RechargeTime, new TimerCallback( Recharge ) );
}
public void Recharge()
{
m_Charges = 10;
Enhance(null);
}
public void Enhance(Mobile from)
{
for (int i = Items.Count - 1; i >= 0 && m_Charges > 0; --i)
{
if (Items[i] is EnhancedBandage)
continue;
Bandage bandage = Items[i] as Bandage;
if (bandage != null)
{
Item enhanced;
if (bandage.Amount > m_Charges)
{
bandage.Amount -= m_Charges;
enhanced = new EnhancedBandage(m_Charges);
m_Charges = 0;
}
else
{
enhanced = new EnhancedBandage(bandage.Amount);
m_Charges -= bandage.Amount;
bandage.Delete();
}
if (from == null || !TryDropItem(from, enhanced, false)) // try stacking first
DropItem(enhanced);
}
}
InvalidateProperties();
}
}
public class FountainOfLifeDeed : BaseAddonContainerDeed
{
public override int LabelNumber { get { return 1075197; } } // Fountain of Life
public override BaseAddonContainer Addon { get { return new FountainOfLife(m_Charges); } }
private int m_Charges;
[CommandProperty(AccessLevel.GameMaster)]
public int Charges
{
get { return m_Charges; }
set { m_Charges = Math.Min(value, 10); InvalidateProperties(); }
}
[Constructable]
public FountainOfLifeDeed()
: this(10)
{
}
[Constructable]
public FountainOfLifeDeed(int charges)
: base()
{
LootType = LootType.Blessed;
m_Charges = charges;
}
public FountainOfLifeDeed(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); //version
writer.Write(m_Charges);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
m_Charges = reader.ReadInt();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml.Linq;
namespace DocumentFormat.OpenXml.Linq
{
/// <summary>
/// Declares XNamespace and XName fields for the xmlns:emma="http://www.w3.org/2003/04/emma" namespace.
/// </summary>
public static class EMMA
{
/// <summary>
/// Defines the XML namespace associated with the emma prefix.
/// </summary>
public static readonly XNamespace emma = "http://www.w3.org/2003/04/emma";
/// <summary>
/// Represents the emma:arc XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="lattice" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="info" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="confidence" />, <see cref="cost" />, <see cref="duration" />, <see cref="end" />, <see cref="lang" />, <see cref="medium" />, <see cref="mode" />, <see cref="offset_to_start" />, <see cref="source" />, <see cref="start" />, <see cref="NoNamespace.from" />, <see cref="NoNamespace.to" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Arc.</description></item>
/// </list>
/// </remarks>
public static readonly XName arc = emma + "arc";
/// <summary>
/// Represents the emma:confidence XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="node" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Confidence, Group.Confidence, Interpretation.Confidence, Node.Confidence, OneOf.Confidence, Sequence.Confidence.</description></item>
/// </list>
/// </remarks>
public static readonly XName confidence = emma + "confidence";
/// <summary>
/// Represents the emma:cost XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="node" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Cost, Group.Cost, Interpretation.Cost, Node.Cost, OneOf.Cost, Sequence.Cost.</description></item>
/// </list>
/// </remarks>
public static readonly XName cost = emma + "cost";
/// <summary>
/// Represents the emma:derivation XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="emma_" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Derivation.</description></item>
/// </list>
/// </remarks>
public static readonly XName derivation = emma + "derivation";
/// <summary>
/// Represents the emma:derived-from XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.composite" />, <see cref="NoNamespace.resource" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DerivedFrom.</description></item>
/// </list>
/// </remarks>
public static readonly XName derived_from = emma + "derived-from";
/// <summary>
/// Represents the emma:dialog-turn XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.DialogTurn, Interpretation.DialogTurn, OneOf.DialogTurn, Sequence.DialogTurn.</description></item>
/// </list>
/// </remarks>
public static readonly XName dialog_turn = emma + "dialog-turn";
/// <summary>
/// Represents the emma:duration XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Duration, Group.Duration, Interpretation.Duration, OneOf.Duration, Sequence.Duration.</description></item>
/// </list>
/// </remarks>
public static readonly XName duration = emma + "duration";
/// <summary>
/// Represents the emma:emma XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="INKML.annotationXML" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="derivation" />, <see cref="endpoint_info" />, <see cref="grammar" />, <see cref="group" />, <see cref="info" />, <see cref="interpretation" />, <see cref="model" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.version" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Emma.</description></item>
/// </list>
/// </remarks>
public static readonly XName emma_ = emma + "emma";
/// <summary>
/// Represents the emma:end XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.End, Group.End, Interpretation.End, OneOf.End, Sequence.End.</description></item>
/// </list>
/// </remarks>
public static readonly XName end = emma + "end";
/// <summary>
/// Represents the emma:endpoint XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="endpoint_info" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="endpoint_address" />, <see cref="endpoint_pair_ref" />, <see cref="endpoint_role" />, <see cref="media_type" />, <see cref="medium" />, <see cref="message_id" />, <see cref="mode" />, <see cref="port_num" />, <see cref="port_type" />, <see cref="service_name" />, <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: EndPoint.</description></item>
/// </list>
/// </remarks>
public static readonly XName endpoint = emma + "endpoint";
/// <summary>
/// Represents the emma:endpoint-address XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.EndPointAddress.</description></item>
/// </list>
/// </remarks>
public static readonly XName endpoint_address = emma + "endpoint-address";
/// <summary>
/// Represents the emma:endpoint-info XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="emma_" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: EndPointInfo.</description></item>
/// </list>
/// </remarks>
public static readonly XName endpoint_info = emma + "endpoint-info";
/// <summary>
/// Represents the emma:endpoint-info-ref XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.EndpointInfoRef, Interpretation.EndpointInfoRef, OneOf.EndpointInfoRef, Sequence.EndpointInfoRef.</description></item>
/// </list>
/// </remarks>
public static readonly XName endpoint_info_ref = emma + "endpoint-info-ref";
/// <summary>
/// Represents the emma:endpoint-pair-ref XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.EndpointPairRef.</description></item>
/// </list>
/// </remarks>
public static readonly XName endpoint_pair_ref = emma + "endpoint-pair-ref";
/// <summary>
/// Represents the emma:endpoint-role XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.EndpointRole.</description></item>
/// </list>
/// </remarks>
public static readonly XName endpoint_role = emma + "endpoint-role";
/// <summary>
/// Represents the emma:function XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.Function, Interpretation.Function, OneOf.Function, Sequence.Function.</description></item>
/// </list>
/// </remarks>
public static readonly XName function = emma + "function";
/// <summary>
/// Represents the emma:grammar XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="emma_" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.id" />, <see cref="NoNamespace.@ref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Grammar.</description></item>
/// </list>
/// </remarks>
public static readonly XName grammar = emma + "grammar";
/// <summary>
/// Represents the emma:grammar-ref XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.GrammarRef, Interpretation.GrammarRef, OneOf.GrammarRef, Sequence.GrammarRef.</description></item>
/// </list>
/// </remarks>
public static readonly XName grammar_ref = emma + "grammar-ref";
/// <summary>
/// Represents the emma:group XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="derivation" />, <see cref="emma_" />, <see cref="group" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="derived_from" />, <see cref="group" />, <see cref="group_info" />, <see cref="info" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="confidence" />, <see cref="cost" />, <see cref="dialog_turn" />, <see cref="duration" />, <see cref="end" />, <see cref="endpoint_info_ref" />, <see cref="function" />, <see cref="grammar_ref" />, <see cref="lang" />, <see cref="media_type" />, <see cref="medium" />, <see cref="mode" />, <see cref="model_ref" />, <see cref="offset_to_start" />, <see cref="process" />, <see cref="signal" />, <see cref="signal_size" />, <see cref="source" />, <see cref="start" />, <see cref="time_ref_anchor_point" />, <see cref="time_ref_uri" />, <see cref="tokens" />, <see cref="verbal" />, <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Group.</description></item>
/// </list>
/// </remarks>
public static readonly XName group = emma + "group";
/// <summary>
/// Represents the emma:group-info XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="group" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.@ref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: GroupInfo.</description></item>
/// </list>
/// </remarks>
public static readonly XName group_info = emma + "group-info";
/// <summary>
/// Represents the emma:info XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="arc" />, <see cref="emma_" />, <see cref="group" />, <see cref="interpretation" />, <see cref="node" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Info.</description></item>
/// </list>
/// </remarks>
public static readonly XName info = emma + "info";
/// <summary>
/// Represents the emma:interpretation XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="derivation" />, <see cref="emma_" />, <see cref="group" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="derived_from" />, <see cref="info" />, <see cref="lattice" />, <see cref="literal" />, <see cref="MSINK.context" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="confidence" />, <see cref="cost" />, <see cref="dialog_turn" />, <see cref="duration" />, <see cref="end" />, <see cref="endpoint_info_ref" />, <see cref="function" />, <see cref="grammar_ref" />, <see cref="lang" />, <see cref="media_type" />, <see cref="medium" />, <see cref="mode" />, <see cref="model_ref" />, <see cref="no_input" />, <see cref="offset_to_start" />, <see cref="process" />, <see cref="signal" />, <see cref="signal_size" />, <see cref="source" />, <see cref="start" />, <see cref="time_ref_anchor_point" />, <see cref="time_ref_uri" />, <see cref="tokens" />, <see cref="uninterpreted" />, <see cref="verbal" />, <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Interpretation.</description></item>
/// </list>
/// </remarks>
public static readonly XName interpretation = emma + "interpretation";
/// <summary>
/// Represents the emma:lang XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Language, Group.Language, Interpretation.Language, OneOf.Language, Sequence.Language.</description></item>
/// </list>
/// </remarks>
public static readonly XName lang = emma + "lang";
/// <summary>
/// Represents the emma:lattice XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="interpretation" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="arc" />, <see cref="node" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="time_ref_anchor_point" />, <see cref="time_ref_uri" />, <see cref="NoNamespace.final" />, <see cref="NoNamespace.initial" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Lattice.</description></item>
/// </list>
/// </remarks>
public static readonly XName lattice = emma + "lattice";
/// <summary>
/// Represents the emma:literal XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="interpretation" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Literal.</description></item>
/// </list>
/// </remarks>
public static readonly XName literal = emma + "literal";
/// <summary>
/// Represents the emma:media-type XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.MediaType, Group.MediaType, Interpretation.MediaType, OneOf.MediaType, Sequence.MediaType.</description></item>
/// </list>
/// </remarks>
public static readonly XName media_type = emma + "media-type";
/// <summary>
/// Represents the emma:medium XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="endpoint" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Medium, EndPoint.Medium, Group.Medium, Interpretation.Medium, OneOf.Medium, Sequence.Medium.</description></item>
/// </list>
/// </remarks>
public static readonly XName medium = emma + "medium";
/// <summary>
/// Represents the emma:message-id XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.MessageId.</description></item>
/// </list>
/// </remarks>
public static readonly XName message_id = emma + "message-id";
/// <summary>
/// Represents the emma:mode XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="endpoint" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Mode, EndPoint.Mode, Group.Mode, Interpretation.Mode, OneOf.Mode, Sequence.Mode.</description></item>
/// </list>
/// </remarks>
public static readonly XName mode = emma + "mode";
/// <summary>
/// Represents the emma:model XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="emma_" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.id" />, <see cref="NoNamespace.@ref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Model.</description></item>
/// </list>
/// </remarks>
public static readonly XName model = emma + "model";
/// <summary>
/// Represents the emma:model-ref XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.ModelRef, Interpretation.ModelRef, OneOf.ModelRef, Sequence.ModelRef.</description></item>
/// </list>
/// </remarks>
public static readonly XName model_ref = emma + "model-ref";
/// <summary>
/// Represents the emma:no-input XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="interpretation" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Interpretation.NoInput.</description></item>
/// </list>
/// </remarks>
public static readonly XName no_input = emma + "no-input";
/// <summary>
/// Represents the emma:node XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="lattice" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="info" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="confidence" />, <see cref="cost" />, <see cref="NoNamespace.node_number" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Node.</description></item>
/// </list>
/// </remarks>
public static readonly XName node = emma + "node";
/// <summary>
/// Represents the emma:offset-to-start XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.OffsetToStart, Group.OffsetToStart, Interpretation.OffsetToStart, OneOf.OffsetToStart, Sequence.OffsetToStart.</description></item>
/// </list>
/// </remarks>
public static readonly XName offset_to_start = emma + "offset-to-start";
/// <summary>
/// Represents the emma:one-of XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="derivation" />, <see cref="emma_" />, <see cref="group" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="derived_from" />, <see cref="group" />, <see cref="info" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.disjunction_type" />, <see cref="confidence" />, <see cref="cost" />, <see cref="dialog_turn" />, <see cref="duration" />, <see cref="end" />, <see cref="endpoint_info_ref" />, <see cref="function" />, <see cref="grammar_ref" />, <see cref="lang" />, <see cref="media_type" />, <see cref="medium" />, <see cref="mode" />, <see cref="model_ref" />, <see cref="offset_to_start" />, <see cref="process" />, <see cref="signal" />, <see cref="signal_size" />, <see cref="source" />, <see cref="start" />, <see cref="time_ref_anchor_point" />, <see cref="time_ref_uri" />, <see cref="tokens" />, <see cref="verbal" />, <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: OneOf.</description></item>
/// </list>
/// </remarks>
public static readonly XName one_of = emma + "one-of";
/// <summary>
/// Represents the emma:port-num XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.PortNumber.</description></item>
/// </list>
/// </remarks>
public static readonly XName port_num = emma + "port-num";
/// <summary>
/// Represents the emma:port-type XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.PortType.</description></item>
/// </list>
/// </remarks>
public static readonly XName port_type = emma + "port-type";
/// <summary>
/// Represents the emma:process XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.Process, Interpretation.Process, OneOf.Process, Sequence.Process.</description></item>
/// </list>
/// </remarks>
public static readonly XName process = emma + "process";
/// <summary>
/// Represents the emma:sequence XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="derivation" />, <see cref="emma_" />, <see cref="group" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="derived_from" />, <see cref="group" />, <see cref="info" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="confidence" />, <see cref="cost" />, <see cref="dialog_turn" />, <see cref="duration" />, <see cref="end" />, <see cref="endpoint_info_ref" />, <see cref="function" />, <see cref="grammar_ref" />, <see cref="lang" />, <see cref="media_type" />, <see cref="medium" />, <see cref="mode" />, <see cref="model_ref" />, <see cref="offset_to_start" />, <see cref="process" />, <see cref="signal" />, <see cref="signal_size" />, <see cref="source" />, <see cref="start" />, <see cref="time_ref_anchor_point" />, <see cref="time_ref_uri" />, <see cref="tokens" />, <see cref="verbal" />, <see cref="NoNamespace.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Sequence.</description></item>
/// </list>
/// </remarks>
public static readonly XName sequence = emma + "sequence";
/// <summary>
/// Represents the emma:service-name XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="endpoint" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: EndPoint.ServiceName.</description></item>
/// </list>
/// </remarks>
public static readonly XName service_name = emma + "service-name";
/// <summary>
/// Represents the emma:signal XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.Signal, Interpretation.Signal, OneOf.Signal, Sequence.Signal.</description></item>
/// </list>
/// </remarks>
public static readonly XName signal = emma + "signal";
/// <summary>
/// Represents the emma:signal-size XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.SignalSize, Interpretation.SignalSize, OneOf.SignalSize, Sequence.SignalSize.</description></item>
/// </list>
/// </remarks>
public static readonly XName signal_size = emma + "signal-size";
/// <summary>
/// Represents the emma:source XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Source, Group.Source, Interpretation.Source, OneOf.Source, Sequence.Source.</description></item>
/// </list>
/// </remarks>
public static readonly XName source = emma + "source";
/// <summary>
/// Represents the emma:start XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="arc" />, <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Arc.Start, Group.Start, Interpretation.Start, OneOf.Start, Sequence.Start.</description></item>
/// </list>
/// </remarks>
public static readonly XName start = emma + "start";
/// <summary>
/// Represents the emma:time-ref-anchor-point XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="lattice" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.TimeReferenceAnchorPoint, Interpretation.TimeReferenceAnchorPoint, Lattice.TimeReferenceAnchorPoint, OneOf.TimeReferenceAnchorPoint, Sequence.TimeReferenceAnchorPoint.</description></item>
/// </list>
/// </remarks>
public static readonly XName time_ref_anchor_point = emma + "time-ref-anchor-point";
/// <summary>
/// Represents the emma:time-ref-uri XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="lattice" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.TimeReference, Interpretation.TimeReference, Lattice.TimeReference, OneOf.TimeReference, Sequence.TimeReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName time_ref_uri = emma + "time-ref-uri";
/// <summary>
/// Represents the emma:tokens XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.Tokens, Interpretation.Tokens, OneOf.Tokens, Sequence.Tokens.</description></item>
/// </list>
/// </remarks>
public static readonly XName tokens = emma + "tokens";
/// <summary>
/// Represents the emma:uninterpreted XML attribute.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="interpretation" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Interpretation.Uninterpreted.</description></item>
/// </list>
/// </remarks>
public static readonly XName uninterpreted = emma + "uninterpreted";
/// <summary>
/// Represents the emma:verbal XML attributes.
/// </summary>
/// <remarks>
/// <para>As an XML attribute, it:</para>
/// <list type="bullet">
/// <item><description>is contained in the following XML elements: <see cref="group" />, <see cref="interpretation" />, <see cref="one_of" />, <see cref="sequence" />.</description></item>
/// <item><description>corresponds to the following strongly-typed properties: Group.Verbal, Interpretation.Verbal, OneOf.Verbal, Sequence.Verbal.</description></item>
/// </list>
/// </remarks>
public static readonly XName verbal = emma + "verbal";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Tests
{
public class CastTests : EnumerableBasedTests
{
[Fact]
public void CastIntToLongThrows()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst = q.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void CastByteToUShortThrows()
{
var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 }
select x;
var rst = q.AsQueryable().Cast<ushort>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void EmptySource()
{
object[] source = { };
Assert.Empty(source.AsQueryable().Cast<int>());
}
[Fact]
public void NullableIntFromAppropriateObjects()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
int?[] expected = { -4, 1, 2, 3, 9, i };
Assert.Equal(expected, source.AsQueryable().Cast<int?>());
}
[Fact]
public void LongFromNullableIntInObjectsThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LongFromNullableIntInObjectsIncludingNullThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromAppropriateObjectsIncludingNull()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
int?[] expected = { -4, 1, 2, 3, 9, null, i };
Assert.Equal(expected, source.AsQueryable().Cast<int?>());
}
[Fact]
public void ThrowOnUncastableItem()
{
object[] source = { -4, 1, 2, 3, 9, "45" };
int[] expectedBeginning = { -4, 1, 2, 3, 9 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
Assert.Equal(expectedBeginning, cast.Take(5));
Assert.Throws<InvalidCastException>(() => cast.ElementAt(5));
}
[Fact]
public void ThrowCastingIntToDouble()
{
int[] source = new int[] { -4, 1, 2, 9 };
IQueryable<double> cast = source.AsQueryable().Cast<double>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
private static void TestCastThrow<T>(object o)
{
byte? i = 10;
object[] source = { -1, 0, o, i };
IQueryable<T> cast = source.AsQueryable().Cast<T>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowOnHeterogenousSource()
{
TestCastThrow<long?>(null);
TestCastThrow<long>(9L);
}
[Fact]
public void CastToString()
{
object[] source = { "Test1", "4.5", null, "Test2" };
string[] expected = { "Test1", "4.5", null, "Test2" };
Assert.Equal(expected, source.AsQueryable().Cast<string>());
}
[Fact]
public void ArrayConversionThrows()
{
Assert.Throws<InvalidCastException>(() => new[] { -4 }.AsQueryable().Cast<long>().ToList());
}
[Fact]
public void FirstElementInvalidForCast()
{
object[] source = { "Test", 3, 5, 10 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LastElementInvalidForCast()
{
object[] source = { -5, 9, 0, 5, 9, "Test" };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromNullsAndInts()
{
object[] source = { 3, null, 5, -4, 0, null, 9 };
int?[] expected = { 3, null, 5, -4, 0, null, 9 };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowCastingIntToLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingIntToNullableLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9 };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToNullableLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9, null };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void CastingNullToNonnullableIsNullReferenceException()
{
int?[] source = new int?[] { -4, 1, null, 3 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<NullReferenceException>(() => cast.ToList());
}
[Fact]
public void NullSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<object>)null).Cast<string>());
}
[Fact]
public void Cast()
{
var count = (new object[] { 0, 1, 2 }).AsQueryable().Cast<int>().Count();
Assert.Equal(3, count);
}
}
}
| |
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
// [START program]
// [START import]
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Google.OrTools.Sat;
// [END import]
public class ScheduleRequestsSat
{
// [START assigned_task]
private class AssignedTask : IComparable
{
public int jobID;
public int taskID;
public int start;
public int duration;
public AssignedTask(int jobID, int taskID, int start, int duration)
{
this.jobID = jobID;
this.taskID = taskID;
this.start = start;
this.duration = duration;
}
public int CompareTo(object obj)
{
if (obj == null)
return 1;
AssignedTask otherTask = obj as AssignedTask;
if (otherTask != null)
{
if (this.start != otherTask.start)
return this.start.CompareTo(otherTask.start);
else
return this.duration.CompareTo(otherTask.duration);
}
else
throw new ArgumentException("Object is not a Temperature");
}
}
// [END assigned_task]
public static void Main(String[] args)
{
// [START data]
var allJobs =
new[] {
new[] {
// job0
new { machine = 0, duration = 3 }, // task0
new { machine = 1, duration = 2 }, // task1
new { machine = 2, duration = 2 }, // task2
}
.ToList(),
new[] {
// job1
new { machine = 0, duration = 2 }, // task0
new { machine = 2, duration = 1 }, // task1
new { machine = 1, duration = 4 }, // task2
}
.ToList(),
new[] {
// job2
new { machine = 1, duration = 4 }, // task0
new { machine = 2, duration = 3 }, // task1
}
.ToList(),
}
.ToList();
int numMachines = 0;
foreach (var job in allJobs)
{
foreach (var task in job)
{
numMachines = Math.Max(numMachines, 1 + task.machine);
}
}
int[] allMachines = Enumerable.Range(0, numMachines).ToArray();
// Computes horizon dynamically as the sum of all durations.
int horizon = 0;
foreach (var job in allJobs)
{
foreach (var task in job)
{
horizon += task.duration;
}
}
// [END data]
// Creates the model.
// [START model]
CpModel model = new CpModel();
// [END model]
// [START variables]
Dictionary<Tuple<int, int>, Tuple<IntVar, IntVar, IntervalVar>> allTasks =
new Dictionary<Tuple<int, int>, Tuple<IntVar, IntVar, IntervalVar>>(); // (start, end, duration)
Dictionary<int, List<IntervalVar>> machineToIntervals = new Dictionary<int, List<IntervalVar>>();
for (int jobID = 0; jobID < allJobs.Count(); ++jobID)
{
var job = allJobs[jobID];
for (int taskID = 0; taskID < job.Count(); ++taskID)
{
var task = job[taskID];
String suffix = $"_{jobID}_{taskID}";
IntVar start = model.NewIntVar(0, horizon, "start" + suffix);
IntVar end = model.NewIntVar(0, horizon, "end" + suffix);
IntervalVar interval = model.NewIntervalVar(start, task.duration, end, "interval" + suffix);
var key = Tuple.Create(jobID, taskID);
allTasks[key] = Tuple.Create(start, end, interval);
if (!machineToIntervals.ContainsKey(task.machine))
{
machineToIntervals.Add(task.machine, new List<IntervalVar>());
}
machineToIntervals[task.machine].Add(interval);
}
}
// [END variables]
// [START constraints]
// Create and add disjunctive constraints.
foreach (int machine in allMachines)
{
model.AddNoOverlap(machineToIntervals[machine]);
}
// Precedences inside a job.
for (int jobID = 0; jobID < allJobs.Count(); ++jobID)
{
var job = allJobs[jobID];
for (int taskID = 0; taskID < job.Count() - 1; ++taskID)
{
var key = Tuple.Create(jobID, taskID);
var nextKey = Tuple.Create(jobID, taskID + 1);
model.Add(allTasks[nextKey].Item1 >= allTasks[key].Item2);
}
}
// [END constraints]
// [START objective]
// Makespan objective.
IntVar objVar = model.NewIntVar(0, horizon, "makespan");
List<IntVar> ends = new List<IntVar>();
for (int jobID = 0; jobID < allJobs.Count(); ++jobID)
{
var job = allJobs[jobID];
var key = Tuple.Create(jobID, job.Count() - 1);
ends.Add(allTasks[key].Item2);
}
model.AddMaxEquality(objVar, ends);
model.Minimize(objVar);
// [END objective]
// Solve
// [START solve]
CpSolver solver = new CpSolver();
CpSolverStatus status = solver.Solve(model);
Console.WriteLine($"Solve status: {status}");
// [END solve]
// [START print_solution]
if (status == CpSolverStatus.Optimal || status == CpSolverStatus.Feasible)
{
Console.WriteLine("Solution:");
Dictionary<int, List<AssignedTask>> assignedJobs = new Dictionary<int, List<AssignedTask>>();
for (int jobID = 0; jobID < allJobs.Count(); ++jobID)
{
var job = allJobs[jobID];
for (int taskID = 0; taskID < job.Count(); ++taskID)
{
var task = job[taskID];
var key = Tuple.Create(jobID, taskID);
int start = (int)solver.Value(allTasks[key].Item1);
if (!assignedJobs.ContainsKey(task.machine))
{
assignedJobs.Add(task.machine, new List<AssignedTask>());
}
assignedJobs[task.machine].Add(new AssignedTask(jobID, taskID, start, task.duration));
}
}
// Create per machine output lines.
String output = "";
foreach (int machine in allMachines)
{
// Sort by starting time.
assignedJobs[machine].Sort();
String solLineTasks = $"Machine {machine}: ";
String solLine = " ";
foreach (var assignedTask in assignedJobs[machine])
{
String name = $"job_{assignedTask.jobID}_task_{assignedTask.taskID}";
// Add spaces to output to align columns.
solLineTasks += $"{name,-15}";
String solTmp = $"[{assignedTask.start},{assignedTask.start+assignedTask.duration}]";
// Add spaces to output to align columns.
solLine += $"{solTmp,-15}";
}
output += solLineTasks + "\n";
output += solLine + "\n";
}
// Finally print the solution found.
Console.WriteLine($"Optimal Schedule Length: {solver.ObjectiveValue}");
Console.WriteLine($"\n{output}");
}
else
{
Console.WriteLine("No solution found.");
}
// [END print_solution]
// [START statistics]
Console.WriteLine("Statistics");
Console.WriteLine($" conflicts: {solver.NumConflicts()}");
Console.WriteLine($" branches : {solver.NumBranches()}");
Console.WriteLine($" wall time: {solver.WallTime()}s");
// [END statistics]
}
}
// [END program]
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Asn1;
using System.Text;
namespace Internal.Cryptography.Pal
{
internal enum GeneralNameType
{
OtherName = 0,
Rfc822Name = 1,
// RFC 822: Standard for the format of ARPA Internet Text Messages.
// That means "email", and an RFC 822 Name: "Email address"
Email = Rfc822Name,
DnsName = 2,
X400Address = 3,
DirectoryName = 4,
EdiPartyName = 5,
UniformResourceIdentifier = 6,
IPAddress = 7,
RegisteredId = 8,
}
internal struct CertificateData
{
internal struct AlgorithmIdentifier
{
public AlgorithmIdentifier(AlgorithmIdentifierAsn algorithmIdentifier)
{
AlgorithmId = algorithmIdentifier.Algorithm.Value;
Parameters = algorithmIdentifier.Parameters?.ToArray() ?? Array.Empty<byte>();
}
internal string AlgorithmId;
internal byte[] Parameters;
}
private CertificateAsn certificate;
internal byte[] RawData;
internal byte[] SubjectPublicKeyInfo;
internal X500DistinguishedName Issuer;
internal X500DistinguishedName Subject;
internal List<X509Extension> Extensions;
internal int Version => certificate.TbsCertificate.Version;
internal byte[] SerialNumber => certificate.TbsCertificate.SerialNumber.ToArray();
internal DateTime NotBefore => certificate.TbsCertificate.Validity.NotBefore.GetValue().UtcDateTime;
internal DateTime NotAfter => certificate.TbsCertificate.Validity.NotAfter.GetValue().UtcDateTime;
internal AlgorithmIdentifier PublicKeyAlgorithm => new AlgorithmIdentifier(certificate.TbsCertificate.SubjectPublicKeyInfo.Algorithm);
internal byte[] PublicKey => certificate.TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.ToArray();
internal byte[] IssuerUniqueId => certificate.TbsCertificate.IssuerUniqueId?.ToArray();
internal byte[] SubjectUniqueId => certificate.TbsCertificate.SubjectUniqueId?.ToArray();
internal AlgorithmIdentifier SignatureAlgorithm => new AlgorithmIdentifier(certificate.SignatureAlgorithm);
internal byte[] SignatureValue => certificate.SignatureValue.ToArray();
internal CertificateData(byte[] rawData)
{
#if DEBUG
try
{
#endif
RawData = rawData;
certificate = CertificateAsn.Decode(rawData, AsnEncodingRules.DER);
certificate.TbsCertificate.ValidateVersion();
Issuer = new X500DistinguishedName(certificate.TbsCertificate.Issuer.ToArray());
Subject = new X500DistinguishedName(certificate.TbsCertificate.Subject.ToArray());
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
certificate.TbsCertificate.SubjectPublicKeyInfo.Encode(writer);
SubjectPublicKeyInfo = writer.Encode();
}
Extensions = new List<X509Extension>();
if (certificate.TbsCertificate.Extensions != null)
{
foreach (X509ExtensionAsn rawExtension in certificate.TbsCertificate.Extensions)
{
X509Extension extension = new X509Extension(
rawExtension.ExtnId,
rawExtension.ExtnValue.ToArray(),
rawExtension.Critical);
Extensions.Add(extension);
}
}
#if DEBUG
}
catch (Exception e)
{
throw new CryptographicException(
$"Error in reading certificate:{Environment.NewLine}{PemPrintCert(rawData)}",
e);
}
#endif
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
// Algorithm behaviors (pseudocode). When forIssuer is true, replace "Subject" with "Issuer" and
// SAN (Subject Alternative Names) with IAN (Issuer Alternative Names).
//
// SimpleName: Subject[CN] ?? Subject[OU] ?? Subject[O] ?? Subject[E] ?? Subject.Rdns.FirstOrDefault() ??
// SAN.Entries.FirstOrDefault(type == GEN_EMAIL);
// EmailName: SAN.Entries.FirstOrDefault(type == GEN_EMAIL) ?? Subject[E];
// UpnName: SAN.Entries.FirsOrDefaultt(type == GEN_OTHER && entry.AsOther().OID == szOidUpn).AsOther().Value;
// DnsName: SAN.Entries.FirstOrDefault(type == GEN_DNS) ?? Subject[CN];
// DnsFromAlternativeName: SAN.Entries.FirstOrDefault(type == GEN_DNS);
// UrlName: SAN.Entries.FirstOrDefault(type == GEN_URI);
if (nameType == X509NameType.SimpleName)
{
X500DistinguishedName name = forIssuer ? Issuer : Subject;
string candidate = GetSimpleNameInfo(name);
if (candidate != null)
{
return candidate;
}
}
// Check the Subject Alternative Name (or Issuer Alternative Name) for the right value;
{
string extensionId = forIssuer ? Oids.IssuerAltName : Oids.SubjectAltName;
GeneralNameType? matchType = null;
string otherOid = null;
// Currently all X509NameType types have a path where they look at the SAN/IAN,
// but we need to figure out which kind they want.
switch (nameType)
{
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
matchType = GeneralNameType.DnsName;
break;
case X509NameType.SimpleName:
case X509NameType.EmailName:
matchType = GeneralNameType.Email;
break;
case X509NameType.UpnName:
matchType = GeneralNameType.OtherName;
otherOid = Oids.UserPrincipalName;
break;
case X509NameType.UrlName:
matchType = GeneralNameType.UniformResourceIdentifier;
break;
}
if (matchType.HasValue)
{
foreach (X509Extension extension in Extensions)
{
if (extension.Oid.Value == extensionId)
{
string candidate = FindAltNameMatch(extension.RawData, matchType.Value, otherOid);
if (candidate != null)
{
return candidate;
}
}
}
}
else
{
Debug.Fail($"Unresolved matchType for X509NameType.{nameType}");
}
}
// Subject-based fallback
{
string expectedKey = null;
switch (nameType)
{
case X509NameType.EmailName:
expectedKey = Oids.EmailAddress;
break;
case X509NameType.DnsName:
// Note: This does not include DnsFromAlternativeName, since
// the subject (or issuer) is not the Alternative Name.
expectedKey = Oids.CommonName;
break;
}
if (expectedKey != null)
{
X500DistinguishedName name = forIssuer ? Issuer : Subject;
foreach (var kvp in ReadReverseRdns(name))
{
if (kvp.Key == expectedKey)
{
return kvp.Value;
}
}
}
}
return "";
}
private static string GetSimpleNameInfo(X500DistinguishedName name)
{
string ou = null;
string o = null;
string e = null;
string firstRdn = null;
foreach (var kvp in ReadReverseRdns(name))
{
string oid = kvp.Key;
string value = kvp.Value;
// TODO: Check this (and the OpenSSL-using version) if OU/etc are specified more than once.
// (Compare against Windows)
switch (oid)
{
case Oids.CommonName:
return value;
case Oids.OrganizationalUnit:
ou = value;
break;
case Oids.Organization:
o = value;
break;
case Oids.EmailAddress:
e = value;
break;
default:
if (firstRdn == null)
{
firstRdn = value;
}
break;
}
}
return ou ?? o ?? e ?? firstRdn;
}
private static string FindAltNameMatch(byte[] extensionBytes, GeneralNameType matchType, string otherOid)
{
// If Other, have OID, else, no OID.
Debug.Assert(
(otherOid == null) == (matchType != GeneralNameType.OtherName),
$"otherOid has incorrect nullarity for matchType {matchType}");
Debug.Assert(
matchType == GeneralNameType.UniformResourceIdentifier ||
matchType == GeneralNameType.DnsName ||
matchType == GeneralNameType.Email ||
matchType == GeneralNameType.OtherName,
$"matchType ({matchType}) is not currently supported");
Debug.Assert(
otherOid == null || otherOid == Oids.UserPrincipalName,
$"otherOid ({otherOid}) is not supported");
AsnReader reader = new AsnReader(extensionBytes, AsnEncodingRules.DER);
AsnReader sequenceReader = reader.ReadSequence();
reader.ThrowIfNotEmpty();
while (sequenceReader.HasData)
{
GeneralNameAsn.Decode(sequenceReader, out GeneralNameAsn generalName);
switch (matchType)
{
case GeneralNameType.OtherName:
// If the OtherName OID didn't match, move to the next entry.
if (generalName.OtherName.HasValue && generalName.OtherName.Value.TypeId == otherOid)
{
// Currently only UPN is supported, which is a UTF8 string per
// https://msdn.microsoft.com/en-us/library/ff842518.aspx
AsnReader nameReader = new AsnReader(generalName.OtherName.Value.Value, AsnEncodingRules.DER);
string udnName = nameReader.ReadCharacterString(UniversalTagNumber.UTF8String);
nameReader.ThrowIfNotEmpty();
return udnName;
}
break;
case GeneralNameType.Rfc822Name:
if (generalName.Rfc822Name != null)
{
return generalName.Rfc822Name;
}
break;
case GeneralNameType.DnsName:
if (generalName.DnsName != null)
{
return generalName.DnsName;
}
break;
case GeneralNameType.UniformResourceIdentifier:
if (generalName.Uri != null)
{
return generalName.Uri;
}
break;
}
}
return null;
}
private static IEnumerable<KeyValuePair<string, string>> ReadReverseRdns(X500DistinguishedName name)
{
AsnReader x500NameReader = new AsnReader(name.RawData, AsnEncodingRules.DER);
AsnReader sequenceReader = x500NameReader.ReadSequence();
var rdnReaders = new Stack<AsnReader>();
x500NameReader.ThrowIfNotEmpty();
while (sequenceReader.HasData)
{
rdnReaders.Push(sequenceReader.ReadSetOf());
}
while (rdnReaders.Count > 0)
{
AsnReader rdnReader = rdnReaders.Pop();
while (rdnReader.HasData)
{
AsnReader tavReader = rdnReader.ReadSequence();
string oid = tavReader.ReadObjectIdentifierAsString();
string value = tavReader.ReadAnyAsnString();
tavReader.ThrowIfNotEmpty();
yield return new KeyValuePair<string, string>(oid, value);
}
}
}
#if DEBUG
private static string PemPrintCert(byte[] rawData)
{
const string PemHeader = "-----BEGIN CERTIFICATE-----";
const string PemFooter = "-----END CERTIFICATE-----";
StringBuilder builder = new StringBuilder(PemHeader.Length + PemFooter.Length + rawData.Length * 2);
builder.Append(PemHeader);
builder.AppendLine();
builder.Append(Convert.ToBase64String(rawData, Base64FormattingOptions.InsertLineBreaks));
builder.AppendLine();
builder.Append(PemFooter);
builder.AppendLine();
return builder.ToString();
}
#endif
}
}
| |
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 Cards.Extensions.Tfs.Api.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;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
/// <summary>
/// Stores and handles all orthello sounds
/// </summary>
public class OTSounds : MonoBehaviour {
/// <summary>
/// mute all sounds when true
/// </summary>
public bool mute = false;
/// <summary>
/// General sound volume
/// </summary>
public float volume = 1f;
static OTSounds _instance;
public static OTSounds instance
{
get
{
return _instance;
}
}
public OTSoundClip[] soundClips;
public Dictionary<string,OTSoundClip> lookup = new Dictionary<string, OTSoundClip>();
public List<OTSound> sounds = new List<OTSound>();
void Awake()
{
_instance = this;
if (Application.isPlaying)
{
if (soundClips!=null)
{
for (int i=0; i<soundClips.Length; i++)
{
soundClips[i].Load();
if (!lookup.ContainsKey(soundClips[i].name.ToLower()))
lookup.Add(soundClips[i].name.ToLower(),soundClips[i]);
}
}
}
}
// Update is called once per frame
void Update () {
if (volume<0) volume = 0;
if (volume>1) volume = 1;
if (Application.isPlaying)
{
float vol = (mute)?0:volume;
if (vol!=AudioListener.volume)
AudioListener.volume = vol;
}
int s = 0;
while (s<sounds.Count)
{
OTSound sound = sounds[s];
if (!sound.ready)
continue;
if (sound.tick == 0)
{
// lets skip first tick so sound will be started on 2nd tick
// and we have a tick to setup the sound
sound.tick++;
continue;
}
// lets start play the sound if no delay on this 2nd tick
if (sound.tick == 1 && !sound._boolMessage(OTSound.MessageType.HasDelay))
sound._boolMessage(OTSound.MessageType.Play);
sound.tick++;
if (sound._boolMessage(OTSound.MessageType.HasDelay))
{
sound._boolMessage(OTSound.MessageType.Wait,Time.deltaTime);
if (!sound._boolMessage(OTSound.MessageType.HasDelay))
sound._boolMessage(OTSound.MessageType.Play);
}
else
{
sound._boolMessage(OTSound.MessageType.Playing,Time.deltaTime);
if (!sound.isPlaying)
{
if (!sound._boolMessage(OTSound.MessageType.Repeat))
{
sound._boolMessage(OTSound.MessageType.Destroy);
continue;
}
}
else
{
if (sound._boolMessage(OTSound.MessageType.Expired))
{
sound._boolMessage(OTSound.MessageType.Destroy);
continue;
}
}
}
s++;
}
}
}
/// <summary>
/// OT sound class
/// </summary>
/// <remarks>
/// This class is used to play a sound (fire and forget) or
/// store a sound and play it later.
/// </remarks>
public class OTSound
{
public float time = 0;
public int tick = 0;
public AudioSource source;
// sound settings
int count = 1;
float delay = 0;
float duration = 0;
float fadeIn = 0;
float fadeOut = 0;
// private attributes
OTSoundClip soundClip;
GameObject gameObject = null;
bool firstPlay = true;
int _count = 1;
float _delay = 0;
float _duration = 0;
float _volume = 1;
float _pan = 0;
float _pitch = 1;
string _name = "";
/// <summary>
/// All available sounds known to orthello
/// </summary>
static List<OTSound> sounds
{
get
{
return OTSounds.instance.sounds;
}
}
/// <summary>
/// Name of this sound
/// </summary>
public string name
{
get
{
return _name;
}
}
/// <summary>
/// Indicates if the sound is valid
/// </summary>
public bool valid
{
get
{
return (found && ready);
}
}
/// <summary>
/// Indicates if the sound was found (by name)
/// </summary>
public bool found
{
get
{
return (soundClip != null);
}
}
/// <summary>
/// Indicates if the sound is ready to be played
/// </summary>
public bool ready
{
get
{
return (soundClip != null && soundClip.ready && source!=null);
}
}
/// <summary>
/// Indicates if this sound is playing
/// </summary>
public bool isPlaying
{
get
{
return (ready && source.isPlaying);
}
}
void InitSound()
{
gameObject = new GameObject();
gameObject.name = "Orthello sound "+soundClip.name;
source = gameObject.AddComponent<AudioSource>();
tick = 0;
time = 0;
count = _count;
delay = _delay;
duration = _duration;
source.clip = soundClip.clip;
source.pan = _pan;
source.pitch = _pitch;
source.volume = _volume;
if (count == -1)
source.loop = true;
sounds.Add(this);
}
/// <summary>
/// Create a new OTSound object from the passed sound names
/// </summary>
public static OTSound RandomSound(string[] sounds)
{
int s = Random.Range(0,sounds.Length);
return new OTSound(sounds[s]);
}
/// <summary>
/// Instantiates a new sound of type 'name'
/// </summary>
public OTSound(string name)
{
_name = name.ToLower();
if (OTSounds.instance.lookup.ContainsKey(_name))
soundClip = OTSounds.instance.lookup[_name];
if (soundClip == null)
{
AudioClip audio = Resources.Load("sounds/"+_name, typeof(AudioClip)) as AudioClip;
if (audio==null) audio = Resources.Load("Sounds/"+_name, typeof(AudioClip)) as AudioClip;
if (audio!=null)
{
soundClip = new OTSoundClip();
soundClip.name = _name;
soundClip.clip = audio;
System.Array.Resize<OTSoundClip>(ref OTSounds.instance.soundClips,OTSounds.instance.soundClips.Length+1);
OTSounds.instance.soundClips[OTSounds.instance.soundClips.Length-1] = soundClip;
}
}
if (soundClip !=null)
InitSound();
}
public enum MessageType { Expired, HasDelay, Wait, Playing, Play, Destroy, Repeat };
public bool _boolMessage(MessageType mt, float val)
{
if (!ready)
return false;
switch(mt)
{
case MessageType.Expired:
return (duration>0 && time > duration);
case MessageType.HasDelay:
return (delay > 0);
case MessageType.Wait:
delay -= val;
break;
case MessageType.Playing:
time += val;
if (fadeIn!=0)
{
if (time > fadeIn && time < duration - fadeOut)
{
if (source.volume!=1)
source.volume = 1;
}
else
if (time < fadeIn)
source.volume = (time / fadeIn) * _volume;
}
if (fadeOut!=0)
{
if (time > duration - fadeOut)
source.volume = _volume - ((time - (duration - fadeOut))/fadeOut);
}
break;
case MessageType.Play:
if (firstPlay)
{
firstPlay = false;
if (duration == 0 && count>-1)
duration = count * (source.clip.length / ((source.pitch>0)?source.pitch:1));
}
if (source.isPlaying)
source.Stop();
source.Play();
break;
case MessageType.Destroy:
if (source.isPlaying)
source.Stop();
if (gameObject!=null)
{
OT.Destroy(gameObject);
gameObject = null;
}
if (sounds.Contains(this))
sounds.Remove(this);
firstPlay = true;
break;
case MessageType.Repeat:
count--;
if (count == 0)
return false;
else
{
source.Play();
return true;
}
}
return true;
}
public bool _boolMessage(MessageType mt)
{
return _boolMessage(mt,0);
}
/// <summary>
/// Stop the sound
/// </summary>
public void Stop()
{
_boolMessage(MessageType.Destroy);
}
/// <summary>
/// Clones a sound
/// </summary>
OTSound Clone()
{
OTSound s = new OTSound(_name);
s.Count(_count);
s.Pan(_pan);
s.Pitch(_pitch);
s.Delay(_delay);
s.Volume(_volume);
s.Duration(_duration);
s.FadeIn(fadeIn);
s.FadeOut(fadeOut);
return s;
}
/// <summary>
/// Plays the sound
/// </summary>
/// <param name='clone'>
/// If true, a new sound instance (clone) is launched and played
/// If flase, the current sound is played or stopped and re-played
/// </param>
public OTSound Play(bool clone)
{
if (clone)
{
OTSound s = Clone();
s.Play(false);
return s;
}
else
{
_boolMessage(MessageType.Destroy);
InitSound();
return this;
}
}
/// <summary>
/// (Re)-plays the sound
/// </summary>
public OTSound Play()
{
return Play(false);
}
/// <summary>
/// Plays the sound as a new instance (clone)
/// </summary>
public OTSound PlayClone()
{
return Play(true);
}
/// <summary>
/// Sets this sound in idle state
/// </summary>
public OTSound Idle()
{
_boolMessage(MessageType.Destroy);
return this;
}
/// <summary>
/// Sets the sound source pitch value
/// </summary>
public OTSound Pitch(float val)
{
_pitch = val;
if (source!=null)
source.pitch = val;
return this;
}
/// <summary>
/// Sets the sound source pan value
/// </summary>
public OTSound Pan(float val)
{
_pan = val;
if (source!=null)
source.pan = val;
return this;
}
/// <summary>
/// Sets the number of times the sound will be played
/// </summary>
public OTSound Count(int val)
{
_count = val;
count = val;
if (val == -1 && source!=null)
source.loop = true;
return this;
}
/// <summary>
/// Sets sound volume
/// </summary>
public OTSound Volume(float val)
{
_volume = val;
if (source!=null)
source.volume = val;
return this;
}
/// <summary>
/// Sound will be looping
/// </summary>
public OTSound Loop()
{
return Count(-1);
}
/// <summary>
/// Sets sound delay
/// </summary>
public OTSound Delay(float val)
{
_delay = val;
delay = val;
return this;
}
/// <summary>
/// Sets volume FadeIn Time
/// </summary>
public OTSound FadeIn(float time)
{
fadeIn = time;
if (source!=null)
source.volume = 0;
return this;
}
/// <summary>
/// Sets volume FadeIn Time
/// </summary>
public OTSound FadeOut(float time)
{
fadeOut = time;
return this;
}
/// <summary>
/// Sets sound duration
/// </summary>
public OTSound Duration(float val)
{
_duration = val;
duration = val;
return this;
}
}
[System.Serializable]
public class OTSoundClip
{
public string name;
public AudioClip clip;
public string url = "";
public bool ready
{
get
{
if (url!="")
return clip.isReadyToPlay;
else
return true;
}
}
public void Load()
{
if (url!="")
{
WWW wwwRequest = new WWW(url);
clip = wwwRequest.GetAudioClip(false,true);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using Object = UnityEngine.Object;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{
class MasterPreviewView : VisualElement
{
PreviewManager m_PreviewManager;
GraphData m_Graph;
PreviewRenderData m_PreviewRenderHandle;
Image m_PreviewTextureView;
public Image previewTextureView
{
get { return m_PreviewTextureView; }
}
Vector2 m_PreviewScrollPosition;
ObjectField m_PreviewMeshPicker;
IMasterNode m_MasterNode;
Mesh m_PreviousMesh;
bool m_Expanded = true;
public bool expanded
{
get { return m_Expanded; }
}
bool m_RecalculateLayout;
Vector2 m_ExpandedPreviewSize;
VisualElement m_CollapsePreviewContainer;
ResizeBorderFrame m_PreviewResizeBorderFrame;
public ResizeBorderFrame previewResizeBorderFrame
{
get { return m_PreviewResizeBorderFrame; }
}
VisualElement m_Preview;
Label m_Title;
public VisualElement preview
{
get { return m_Preview; }
}
List<string> m_DoNotShowPrimitives = new List<string>(new string[] {PrimitiveType.Plane.ToString()});
static Type s_ContextualMenuManipulator = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypesOrNothing()).FirstOrDefault(t => t.FullName == "UnityEngine.UIElements.ContextualMenuManipulator");
static Type s_ObjectSelector = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypesOrNothing()).FirstOrDefault(t => t.FullName == "UnityEditor.ObjectSelector");
public string assetName
{
get { return m_Title.text; }
set { m_Title.text = value; }
}
public MasterPreviewView(PreviewManager previewManager, GraphData graph)
{
cacheAsBitmap = true;
style.overflow = Overflow.Hidden;
m_PreviewManager = previewManager;
m_Graph = graph;
styleSheets.Add(Resources.Load<StyleSheet>("Styles/MasterPreviewView"));
m_PreviewRenderHandle = previewManager.masterRenderData;
if (m_PreviewRenderHandle != null)
{
m_PreviewRenderHandle.onPreviewChanged += OnPreviewChanged;
}
var topContainer = new VisualElement() { name = "top" };
{
m_Title = new Label() { name = "title" };
m_Title.text = "Main Preview";
// Add preview collapse button on top of preview
m_CollapsePreviewContainer = new VisualElement { name = "collapse-container" };
m_CollapsePreviewContainer.AddToClassList("collapse-container");
topContainer.Add(m_Title);
topContainer.Add(m_CollapsePreviewContainer);
}
Add(topContainer);
m_Preview = new VisualElement {name = "middle"};
{
m_PreviewTextureView = CreatePreview(Texture2D.blackTexture);
m_PreviewScrollPosition = new Vector2(0f, 0f);
preview.Add(m_PreviewTextureView);
preview.AddManipulator(new Scrollable(OnScroll));
}
Add(preview);
m_PreviewResizeBorderFrame = new ResizeBorderFrame(previewTextureView, this) { name = "resizeBorderFrame" };
m_PreviewResizeBorderFrame.maintainAspectRatio = true;
Add(m_PreviewResizeBorderFrame);
m_ExpandedPreviewSize = new Vector2(256f, 256f);
m_RecalculateLayout = false;
previewTextureView.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
Image CreatePreview(Texture texture)
{
if (m_PreviewRenderHandle?.texture != null)
{
texture = m_PreviewRenderHandle.texture;
}
var image = new Image { name = "preview", image = texture };
image.AddManipulator(new Draggable(OnMouseDragPreviewMesh, true));
image.AddManipulator((IManipulator)Activator.CreateInstance(s_ContextualMenuManipulator, (Action<ContextualMenuPopulateEvent>)BuildContextualMenu));
return image;
}
void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
foreach (var primitiveTypeName in Enum.GetNames(typeof(PrimitiveType)))
{
if (m_DoNotShowPrimitives.Contains(primitiveTypeName))
continue;
evt.menu.AppendAction(primitiveTypeName, e => ChangePrimitiveMesh(primitiveTypeName), DropdownMenuAction.AlwaysEnabled);
}
evt.menu.AppendAction("Custom Mesh", e => ChangeMeshCustom(), DropdownMenuAction.AlwaysEnabled);
}
void DirtyMasterNode(ModificationScope scope)
{
m_Graph?.outputNode?.Dirty(scope);
}
void OnPreviewChanged()
{
m_PreviewTextureView.image = m_PreviewRenderHandle?.texture ?? Texture2D.blackTexture;
if (m_PreviewRenderHandle != null && m_PreviewRenderHandle.shaderData.isCompiling)
m_PreviewTextureView.tintColor = new Color(1.0f, 1.0f, 1.0f, 0.3f);
else
m_PreviewTextureView.tintColor = Color.white;
m_PreviewTextureView.MarkDirtyRepaint();
}
void ChangePrimitiveMesh(string primitiveName)
{
Mesh changedPrimitiveMesh = Resources.GetBuiltinResource(typeof(Mesh), string.Format("{0}.fbx", primitiveName)) as Mesh;
ChangeMesh(changedPrimitiveMesh);
}
void ChangeMesh(Mesh mesh)
{
Mesh changedMesh = mesh;
DirtyMasterNode(ModificationScope.Node);
if (m_Graph.previewData.serializedMesh.mesh != changedMesh)
{
m_Graph.previewData.rotation = Quaternion.identity;
}
m_Graph.previewData.serializedMesh.mesh = changedMesh;
}
private static EditorWindow Get()
{
PropertyInfo P = s_ObjectSelector.GetProperty("get", BindingFlags.Public | BindingFlags.Static);
return P.GetValue(null, null) as EditorWindow;
}
void OnMeshChanged(Object obj)
{
var mesh = obj as Mesh;
if (mesh == null)
mesh = m_PreviousMesh;
ChangeMesh(mesh);
}
void ChangeMeshCustom()
{
MethodInfo ShowMethod = s_ObjectSelector.GetMethod("Show", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, Type.DefaultBinder, new[] {typeof(Object), typeof(Type), typeof(SerializedProperty), typeof(bool), typeof(List<int>), typeof(Action<Object>), typeof(Action<Object>)}, new ParameterModifier[7]);
m_PreviousMesh = m_Graph.previewData.serializedMesh.mesh;
ShowMethod.Invoke(Get(), new object[] { null, typeof(Mesh), null, false, null, (Action<Object>)OnMeshChanged, (Action<Object>)OnMeshChanged });
}
void OnGeometryChanged(GeometryChangedEvent evt)
{
if (m_RecalculateLayout)
{
WindowDockingLayout dockingLayout = new WindowDockingLayout();
dockingLayout.CalculateDockingCornerAndOffset(layout, parent.layout);
dockingLayout.ClampToParentWindow();
dockingLayout.ApplyPosition(this);
m_RecalculateLayout = false;
}
if (!expanded)
return;
var currentWidth = m_PreviewRenderHandle?.texture != null ? m_PreviewRenderHandle.texture.width : -1;
var currentHeight = m_PreviewRenderHandle?.texture != null ? m_PreviewRenderHandle.texture.height : -1;
var targetWidth = Mathf.Max(1f, m_PreviewTextureView.contentRect.width);
var targetHeight = Mathf.Max(1f, m_PreviewTextureView.contentRect.height);
if (Mathf.Approximately(currentWidth, targetHeight) && Mathf.Approximately(currentHeight, targetWidth))
return;
m_PreviewManager.ResizeMasterPreview(new Vector2(targetWidth, targetHeight));
}
void OnScroll(float scrollValue)
{
float rescaleAmount = -scrollValue * .03f;
m_Graph.previewData.scale = Mathf.Clamp(m_Graph.previewData.scale + rescaleAmount, 0.2f, 5f);
DirtyMasterNode(ModificationScope.Node);
}
void OnMouseDragPreviewMesh(Vector2 deltaMouse)
{
Vector2 previewSize = m_PreviewTextureView.contentRect.size;
m_PreviewScrollPosition -= deltaMouse * (Event.current.shift ? 3f : 1f) / Mathf.Min(previewSize.x, previewSize.y) * 140f;
m_PreviewScrollPosition.y = Mathf.Clamp(m_PreviewScrollPosition.y, -90f, 90f);
Quaternion previewRotation = Quaternion.Euler(m_PreviewScrollPosition.y, 0, 0) * Quaternion.Euler(0, m_PreviewScrollPosition.x, 0);
m_Graph.previewData.rotation = previewRotation;
DirtyMasterNode(ModificationScope.Node);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using SevenDigital.Messaging.EventHooks;
using SevenDigital.Messaging.Integration.Tests._Helpers.Handlers;
using SevenDigital.Messaging.Integration.Tests._Helpers.Messages;
using SevenDigital.Messaging.Logging;
using SevenDigital.Messaging.MessageReceiving;
// ReSharper disable InconsistentNaming
namespace SevenDigital.Messaging.Integration.Tests.MessageSending.BaseCases
{
public abstract class SendingAndReceivingBase
{
IReceiver _receiver;
private ISenderNode _sender;
protected TimeSpan LongInterval { get { return TimeSpan.FromSeconds(20); } }
protected TimeSpan ShortInterval { get { return TimeSpan.FromSeconds(2); } }
/// <summary>
/// Concretes should setup their specific messaging configs here
/// </summary>
public abstract void ConfigureMessaging();
[SetUp]
public void SetUp()
{
ConfigureMessaging();
_receiver = MessagingSystem.Receiver();
_sender = MessagingSystem.Sender();
MessagingSystem.Events.ClearEventHooks();
MessagingSystem.Events.AddEventHook<ConsoleEventHook>();
}
[TearDown]
public void Stop() { MessagingSystem.Control.Shutdown(); }
[Test]
public void Handler_should_react_for_all_message_types_it_is_handling()
{
using (_receiver.Listen(_=>_
.Handle<IColourMessage>().With<AllColourMessagesHandler>()
.Handle<ITwoColoursMessage>().With<AllColourMessagesHandler>()
))
{
AllColourMessagesHandler.Prepare();
_sender.SendMessage(new RedMessage());
var signal1 = AllColourMessagesHandler.AutoResetEventForColourMessage.WaitOne(LongInterval);
_sender.SendMessage(new GreenWhiteMessage());
var signal2 = AllColourMessagesHandler.AutoResetEventForTwoColourMessage.WaitOne(LongInterval);
Assert.That(signal1, Is.True);
Assert.That(signal2, Is.True);
}
}
[Test]
public void Handler_should_react_when_a_registered_message_type_is_received_for_unnamed_endpoint()
{
using (_receiver.Listen(_=>_
.Handle<IColourMessage>().With<ColourMessageHandler>()))
{
_sender.SendMessage(new RedMessage());
var colourSignal = ColourMessageHandler.AutoResetEvent.WaitOne(LongInterval);
Assert.That(colourSignal, Is.True);
}
}
[Test]
public void Handler_should_react_when_a_registered_message_type_is_received_for_named_endpoint()
{
using (_receiver.TakeFrom(
new Endpoint("Test_listener_registered-message-endpoint"),
_=>_.Handle<IColourMessage>().With<ColourMessageHandler>()
))
{
_sender.SendMessage(new RedMessage());
var colourSignal = ColourMessageHandler.AutoResetEvent.WaitOne(LongInterval);
Assert.That(colourSignal, Is.True);
}
}
[Test]
public void Handler_should_get_message_with_proper_correlation_id()
{
using (_receiver.Listen(_=>_
.Handle<ITwoColoursMessage>().With<TwoColourMessageHandler>()))
{
var message = new GreenWhiteMessage();
TwoColourMessageHandler.Prepare();
_sender.SendMessage(message);
var colourSignal = TwoColourMessageHandler.AutoResetEvent.WaitOne(ShortInterval);
Assert.That(colourSignal, Is.True, "Did not get message!");
Assert.That(TwoColourMessageHandler.ReceivedCount, Is.EqualTo(1), "Got a wrong number of messages");
Assert.That(TwoColourMessageHandler.ReceivedMessage.CorrelationId, Is.EqualTo(message.CorrelationId));
}
}
[Test]
public void Handler_should_not_react_when_an_unregistered_message_type_is_received_for_unnamed_endpoint()
{
using (_receiver.Listen(_ => _.Handle<IColourMessage>().With<ColourMessageHandler>()))
{
_sender.SendMessage(new JokerMessage());
var colourSignal = ColourMessageHandler.AutoResetEvent.WaitOne(ShortInterval);
Assert.That(colourSignal, Is.False);
}
}
[Test]
public void Handler_should_not_react_when_an_unregistered_message_type_is_received_for_named_endpoint()
{
ColourMessageHandler.AutoResetEvent.Reset();
using (_receiver.TakeFrom(
new Endpoint("Test_listener_unregistered-message-endpoint"),
_ => _.Handle<IColourMessage>().With<ColourMessageHandler>()))
{
_sender.SendMessage(new JokerMessage());
var colourSignal = ColourMessageHandler.AutoResetEvent.WaitOne(ShortInterval);
Assert.That(colourSignal, Is.False);
}
}
[Test]
public void Only_one_handler_should_fire_when_competing_for_an_endpoint()
{
using (_receiver.TakeFrom("Test_listener_shared-endpoint", _ => _.Handle<IComicBookCharacterMessage>().With<SuperHeroMessageHandler>()))
using (_receiver.TakeFrom("Test_listener_shared-endpoint", _ => _.Handle<IComicBookCharacterMessage>().With<VillainMessageHandler>()))
{
_sender.SendMessage(new BatmanMessage());
var superheroSignal = SuperHeroMessageHandler.AutoResetEvent.WaitOne(ShortInterval);
var villanSignal = VillainMessageHandler.AutoResetEvent.WaitOne(ShortInterval);
Assert.That(superheroSignal || villanSignal, Is.True);
Assert.That(superheroSignal && villanSignal, Is.False);
}
}
[Test]
public void Should_use_all_registered_handlers_when_a_message_is_received()
{
using (_receiver.Listen(_ => _
.Handle<IComicBookCharacterMessage>().With<SuperHeroMessageHandler>()
.Handle<IComicBookCharacterMessage>().With<VillainMessageHandler>()
))
{
_sender.SendMessage(new JokerMessage());
var superheroSignal = SuperHeroMessageHandler.AutoResetEvent.WaitOne(LongInterval);
var villainSignal = VillainMessageHandler.AutoResetEvent.WaitOne(LongInterval);
Assert.That(superheroSignal, Is.True);
Assert.That(villainSignal, Is.True);
}
}
[Test]
public void Handler_which_sends_a_new_message_should_get_that_message_handled()
{
using (_receiver.Listen(_ => _
.Handle<IColourMessage>().With<ChainHandler>()
.Handle<IComicBookCharacterMessage>().With<VillainMessageHandler>()
))
{
_sender.SendMessage(new GreenMessage());
var villainSignal = VillainMessageHandler.AutoResetEvent.WaitOne(LongInterval);
Assert.That(villainSignal, Is.True);
}
}
[Test]
public void should_be_able_to_register_handlers_with_lot_of_messages_on_a_queue()
{
MessagingSystem.Testing.AddTestEventHook();
Log.Instance().RegisterAction(m => Console.WriteLine(m.LogDate + " " +m.Message));
using(_receiver.TakeFrom("Backlog.Integration.Queue", _ =>_
.Handle<IComicBookCharacterMessage>().With<SuperHeroMessageHandler>()
.Handle<IComicBookCharacterMessage>().With<VillainMessageHandler>()))
{
}
using (var receiverNode = _receiver.TakeFrom("Backlog.Integration.Queue", _ => { }))
{
for (int i = 0; i < 100; i++)
{
_sender.SendMessage(new JokerMessage());
}
Thread.Sleep(500);
receiverNode.Register(
new Binding()
.Handle<IComicBookCharacterMessage>().With<SuperHeroMessageHandler>()
.Handle<IComicBookCharacterMessage>().With<VillainMessageHandler>()
);
var superheroSignal = SuperHeroMessageHandler.AutoResetEvent.WaitOne(ShortInterval);
var villainSignal = VillainMessageHandler.AutoResetEvent.WaitOne(LongInterval);
Assert.That(superheroSignal, Is.True, "superhero signal");
Assert.That(villainSignal, Is.True, "villain signal");
var sent = MessagingSystem.Testing.LoopbackEvents().SentMessages.Count();
int recvd = 0;
var expected = (2 * sent);
var sw = new Stopwatch();
sw.Start();
while (sw.Elapsed < TimeSpan.FromSeconds(20) && recvd < expected)
{
recvd = MessagingSystem.Testing.LoopbackEvents().ReceivedMessages.Count();
}
Assert.That(recvd, Is.EqualTo(expected),
"Sent: "+sent+"; Received: "+recvd);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Caliburn.Micro;
using csCommon.csMapCustomControls.CircularMenu;
using csImb;
using csShared;
using csShared.Controls.SlideTab;
using csShared.Interfaces;
using csShared.TabItems;
using csShared.Utils;
namespace csCommon.Plugins.NotebookPlugin
{
[Export(typeof(IPlugin))]
public class ScreenshotPlugin : PropertyChangedBase, IPlugin
{
public bool CanStop { get { return true; } }
private NotebookCollection notebooks;
public NotebookCollection Notebooks
{
get { return notebooks; }
set { notebooks = value; NotifyOfPropertyChange(()=>Notebooks); }
}
private ISettingsScreen settings;
public ISettingsScreen Settings
{
get { return settings; }
set { settings = value; NotifyOfPropertyChange(() => Settings); }
}
private IPluginScreen screen;
public IPluginScreen Screen
{
get { return screen; }
set { screen = value; NotifyOfPropertyChange(() => Screen); }
}
private bool hideFromSettings;
public bool HideFromSettings
{
get { return hideFromSettings; }
set { hideFromSettings = value; NotifyOfPropertyChange(() => HideFromSettings); }
}
public const string ShowButton = "Notebook.ShowScreenshotButton";
public const string ShowTab = "Notebook.ShowNotebookTab";
public bool ShowScreenshotButton
{
get { return AppState.Config.GetBool(ShowButton, false); }
set
{
AppState.Config.SetLocalConfig(ShowButton, value.ToString(),true);
NotifyOfPropertyChange(()=>ShowScreenshotButton);
UpdateButtons();
}
}
public bool ShowNotebookTab
{
get { return AppState.Config.GetBool(ShowTab, false); }
set
{
AppState.Config.SetLocalConfig(ShowTab, value.ToString(),true);
NotifyOfPropertyChange(() => ShowNotebookTab);
UpdateButtons();
}
}
public int Priority
{
get { return 1; }
}
public string Icon
{
get { return @"/csCommon;component/Resources/Icons/Camerawhite.png"; }
}
private bool isRunning;
public bool IsRunning
{
get { return isRunning; }
set { isRunning = value; NotifyOfPropertyChange(() => IsRunning); }
}
public AppStateSettings AppState { get; set; }
public string Name
{
get { return "Screenshot"; }
}
public void Init()
{
Notebooks = new NotebookCollection();
Notebooks.Load();
var c = Notebooks.FirstOrDefault(k=>k.Name == Notebooks.ActiveNotebookConfig);
if (c != null) Notebooks.ActiveNotebook = c;
if (Notebooks.ActiveNotebook == null && Notebooks.Any()) Notebooks.ActiveNotebook = Notebooks[0];
}
private NoteTabViewModel timeTabViewModel;
public void UpdateButtons()
{
if (ShowScreenshotButton && circularMenuItem==null)
{
circularMenuItem = new CircularMenuItem {Title = "Take Screenshot"};
circularMenuItem.Selected += TakeScreenshot;
circularMenuItem.Id = Guid.NewGuid().ToString();
circularMenuItem.Icon = "pack://application:,,,/csCommon;component/Resources/Icons/Camerablack.png";
AppState.AddCircularMenu(circularMenuItem);
}
if (!ShowScreenshotButton && circularMenuItem!=null)
{
AppState.RemoveCircularMenu(circularMenuItem.Id);
circularMenuItem = null;
}
if (ShowNotebookTab && st==null)
{
timeTabViewModel = new NoteTabViewModel() { Plugin = this };
st = new StartPanelTabItem
{
Name = "Background",
HeaderStyle = TabHeaderStyle.Image,
Image = new BitmapImage(new Uri("pack://application:,,,/csCommon;component/Resources/Icons/Book-Open.png")),
ModelInstance = timeTabViewModel
};
AppState.AddStartPanelTabItem(st);
}
if (!ShowNotebookTab && st != null)
{
AppState.RemoveStartPanelTabItem(st);
st = null;
}
}
public StartPanelTabItem st { get; set; }
public void Clear()
{
((NotificationViewModel) screen).EndNotifications();
}
private CircularMenuItem circularMenuItem;
private List<string> screenshotFolder;
private static readonly ImageSource cameraImage = new BitmapImage(new Uri("pack://application:,,,/csCommon;component/Resources/Icons/Camerawhite.png"));
public List<string> ScreenshotFolder
{
get
{
if (screenshotFolder != null) return screenshotFolder;
var cc = AppState.Config.Get("Screenshot.Folder", @"%TEMP%\cs\Screenshots\");
screenshotFolder = new List<string>();
if (string.IsNullOrEmpty(cc)) return screenshotFolder;
foreach (var c in cc.Split(','))
{
if (string.IsNullOrEmpty(c)) continue;
var r = c;
if (r[r.Length - 1] != '\\') r += @"\";
r = Environment.ExpandEnvironmentVariables(r);
screenshotFolder.Add(r);
}
return screenshotFolder;
}
}
private NotebookConfigViewModel config;
public void Start()
{
IsRunning = true;
UpdateButtons();
AppState.ScriptCommand += AppState_ScriptCommand;
config = new NotebookConfigViewModel() {DisplayName = "Notebooks", Plugin = this};
AppState.ConfigTabs.Add(config);
}
void AppState_ScriptCommand(object sender, string command)
{
if (command.ToLower().StartsWith("notebookscreenshot"))
{
Execute.OnUIThread(()=>TakeScreenshot(this,null));
}
}
void TakeScreenshot(object sender, MenuItemEventArgs e) {
try {
var now = DateTime.Now;
if (Notebooks.ActiveNotebook != null)
{
var f = Notebooks.ActiveNotebook.Folder;
if (Directory.Exists(f))
{
var filename = Path.Combine(f,
string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH_mm_ss} Screenshot.png", now));
// f + @"\Screenshot-" + DateTime.Now.Ticks + ".jpg";
Screenshots.SaveImageOfControl(Application.Current.MainWindow, filename);
AppState.TriggerNotification(
"Screenshot has been stored", "Screenshot",
image: cameraImage);
}
Notebooks.ActiveNotebook.LoadItems();
}
else
{
AppState.TriggerNotification(
"No screenshots have been stored - no Notebook active.", "Screenshot",
image: cameraImage);
}
//foreach (var folder in ScreenshotFolder) {
// if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
// var filename = Path.Combine(folder,
// string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH_mm_ss} Screenshot.png", now));
// // f + @"\Screenshot-" + DateTime.Now.Ticks + ".jpg";
// Screenshots.SaveImageOfControl(Application.Current.MainWindow, filename);
//}
//if (Notebooks.ActiveNotebook!=null)
// Notebooks.ActiveNotebook.LoadItems();
}
catch (SystemException ex) {
Logger.Log("ScreenshotPlugin", "Error saving screenshot", ex.Message, Logger.Level.Error, true, true);
}
}
public void Pause()
{
IsRunning = false;
}
public void Stop()
{
IsRunning = false;
if (circularMenuItem != null)
AppState.RemoveCircularMenu(circularMenuItem.Id);
AppState.RemoveStartPanelTabItem(st);
AppState.ConfigTabs.Remove(config);
}
}
}
| |
/*
* 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.Client.Cache
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Client.Cache.Query;
using Apache.Ignite.Core.Impl.Common;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Client cache implementation.
/// </summary>
internal sealed class CacheClient<TK, TV> : ICacheClient<TK, TV>, ICacheInternal
{
/** Scan query filter platform code: .NET filter. */
private const byte FilterPlatformDotnet = 2;
/** Cache name. */
private readonly string _name;
/** Cache id. */
private readonly int _id;
/** Ignite. */
private readonly IgniteClient _ignite;
/** Marshaller. */
private readonly Marshaller _marsh;
/** Keep binary flag. */
private readonly bool _keepBinary;
/// <summary>
/// Initializes a new instance of the <see cref="CacheClient{TK, TV}" /> class.
/// </summary>
/// <param name="ignite">Ignite.</param>
/// <param name="name">Cache name.</param>
/// <param name="keepBinary">Binary mode flag.</param>
public CacheClient(IgniteClient ignite, string name, bool keepBinary = false)
{
Debug.Assert(ignite != null);
Debug.Assert(name != null);
_name = name;
_ignite = ignite;
_marsh = _ignite.Marshaller;
_id = BinaryUtils.GetCacheId(name);
_keepBinary = keepBinary;
}
/** <inheritDoc /> */
public string Name
{
get { return _name; }
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return Get(key); }
set { Put(key, value); }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinity(ClientOp.CacheGet, key, UnmarshalNotNull<TV>);
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheGet, key, w => w.WriteObjectDetached(key), UnmarshalNotNull<TV>);
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpAffinity(ClientOp.CacheGet, key, UnmarshalCacheResult<TV>);
value = res.Value;
return res.Success;
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheGet, key, w => w.WriteObjectDetached(key),
UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp(ClientOp.CacheGetAll, w => w.WriteEnumerable(keys), s => ReadCacheEntries(s));
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpAsync(ClientOp.CacheGetAll, w => w.WriteEnumerable(keys), s => ReadCacheEntries(s));
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
DoOutOpAffinity(ClientOp.CachePut, key, val);
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAffinityAsync(ClientOp.CachePut, key, w => WriteKeyVal(w, key, val));
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinity(ClientOp.CacheContainsKey, key, r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheContainsKey, key, r => r.ReadBool());
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp(ClientOp.CacheContainsKeys, w => w.WriteEnumerable(keys), r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpAsync(ClientOp.CacheContainsKeys, w => w.WriteEnumerable(keys), r => r.ReadBool());
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(ScanQuery<TK, TV> scanQuery)
{
IgniteArgumentCheck.NotNull(scanQuery, "scanQuery");
// Filter is a binary object for all platforms.
// For .NET it is a CacheEntryFilterHolder with a predefined id (BinaryTypeId.CacheEntryPredicateHolder).
return DoOutInOp(ClientOp.QueryScan, w => WriteScanQuery(w, scanQuery),
s => new ClientQueryCursor<TK, TV>(
_ignite, s.ReadLong(), _keepBinary, s, ClientOp.QueryScanCursorGetPage));
}
/** <inheritDoc /> */
[Obsolete]
public IQueryCursor<ICacheEntry<TK, TV>> Query(SqlQuery sqlQuery)
{
IgniteArgumentCheck.NotNull(sqlQuery, "sqlQuery");
IgniteArgumentCheck.NotNull(sqlQuery.Sql, "sqlQuery.Sql");
IgniteArgumentCheck.NotNull(sqlQuery.QueryType, "sqlQuery.QueryType");
return DoOutInOp(ClientOp.QuerySql, w => WriteSqlQuery(w, sqlQuery),
s => new ClientQueryCursor<TK, TV>(
_ignite, s.ReadLong(), _keepBinary, s, ClientOp.QuerySqlCursorGetPage));
}
/** <inheritDoc /> */
public IFieldsQueryCursor Query(SqlFieldsQuery sqlFieldsQuery)
{
IgniteArgumentCheck.NotNull(sqlFieldsQuery, "sqlFieldsQuery");
IgniteArgumentCheck.NotNull(sqlFieldsQuery.Sql, "sqlFieldsQuery.Sql");
return DoOutInOp(ClientOp.QuerySqlFields,
w => WriteSqlFieldsQuery(w, sqlFieldsQuery),
s => GetFieldsCursor(s));
}
/** <inheritDoc /> */
public IQueryCursor<T> Query<T>(SqlFieldsQuery sqlFieldsQuery, Func<IBinaryRawReader, int, T> readerFunc)
{
return DoOutInOp(ClientOp.QuerySqlFields,
w => WriteSqlFieldsQuery(w, sqlFieldsQuery, false),
s => GetFieldsCursorNoColumnNames(s, readerFunc));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinity(ClientOp.CacheGetAndPut, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndPut, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinity(ClientOp.CacheGetAndReplace, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndReplace, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinity(ClientOp.CacheGetAndRemove, key, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndRemove, key, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinity(ClientOp.CachePutIfAbsent, key, val, s => s.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CachePutIfAbsent, key, val, s => s.ReadBool());
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinity(ClientOp.CacheGetAndPutIfAbsent, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndPutIfAbsent, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinity(ClientOp.CacheReplace, key, val, s => s.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheReplace, key, val, s => s.ReadBool());
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutInOpAffinity(ClientOp.CacheReplaceIfEquals, key, w =>
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(oldVal);
w.WriteObjectDetached(newVal);
}, s => s.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutInOpAffinityAsync(ClientOp.CacheReplaceIfEquals, key, w =>
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(oldVal);
w.WriteObjectDetached(newVal);
}, s => s.ReadBool());
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
DoOutOp(ClientOp.CachePutAll, w => w.WriteDictionary(vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
return DoOutOpAsync(ClientOp.CachePutAll, w => w.WriteDictionary(vals));
}
/** <inheritDoc /> */
public void Clear()
{
DoOutOp(ClientOp.CacheClear);
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return DoOutOpAsync(ClientOp.CacheClear);
}
/** <inheritDoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOpAffinity(ClientOp.CacheClearKey, key);
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAffinityAsync(ClientOp.CacheClearKey, key, w => w.WriteObjectDetached(key));
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(ClientOp.CacheClearKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(ClientOp.CacheClearKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinity(ClientOp.CacheRemoveKey, key, r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheRemoveKey, key, r => r.ReadBool());
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinity(ClientOp.CacheRemoveIfEquals, key, val, r => r.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheRemoveIfEquals, key, val, r => r.ReadBool());
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(ClientOp.CacheRemoveKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(ClientOp.CacheRemoveKeys, w => w.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
DoOutOp(ClientOp.CacheRemoveAll);
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return DoOutOpAsync(ClientOp.CacheRemoveAll);
}
/** <inheritDoc /> */
public long GetSize(params CachePeekMode[] modes)
{
return DoOutInOp(ClientOp.CacheGetSize, w => WritePeekModes(modes, w), s => s.ReadLong());
}
/** <inheritDoc /> */
public Task<long> GetSizeAsync(params CachePeekMode[] modes)
{
return DoOutInOpAsync(ClientOp.CacheGetSize, w => WritePeekModes(modes, w), s => s.ReadLong());
}
/** <inheritDoc /> */
public CacheClientConfiguration GetConfiguration()
{
return DoOutInOp(ClientOp.CacheGetConfiguration, null,
s => new CacheClientConfiguration(s, _ignite.ServerVersion));
}
/** <inheritDoc /> */
CacheConfiguration ICacheInternal.GetConfiguration()
{
return GetConfiguration().ToCacheConfiguration();
}
/** <inheritDoc /> */
public ICacheClient<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as ICacheClient<TK1, TV1>;
if (result == null)
{
throw new InvalidOperationException(
"Can't change type of binary cache. WithKeepBinary has been called on an instance of " +
"binary cache with incompatible generic arguments.");
}
return result;
}
return new CacheClient<TK1, TV1>(_ignite, _name, true);
}
/** <inheritDoc /> */
[ExcludeFromCodeCoverage]
public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readFunc)
{
// Should not be called, there are no usages for thin client.
throw IgniteClient.GetClientNotSupportedException();
}
/// <summary>
/// Does the out op.
/// </summary>
private void DoOutOp(ClientOp opId, Action<BinaryWriter> writeAction = null)
{
DoOutInOp<object>(opId, writeAction, null);
}
/// <summary>
/// Does the out op with affinity awareness.
/// </summary>
private void DoOutOpAffinity(ClientOp opId, TK key)
{
DoOutInOpAffinity<object>(opId, key, null);
}
/// <summary>
/// Does the out op with affinity awareness.
/// </summary>
private void DoOutOpAffinity(ClientOp opId, TK key, TV val)
{
DoOutInOpAffinity<object>(opId, key, val, null);
}
/// <summary>
/// Does the out op with affinity awareness.
/// </summary>
private Task DoOutOpAsync(ClientOp opId, Action<BinaryWriter> writeAction = null)
{
return DoOutInOpAsync<object>(opId, writeAction, null);
}
/// <summary>
/// Does the out op with affinity awareness.
/// </summary>
private Task DoOutOpAffinityAsync(ClientOp opId, TK key, Action<BinaryWriter> writeAction = null)
{
return DoOutInOpAffinityAsync<object>(opId, key, writeAction, null);
}
/// <summary>
/// Does the out in op.
/// </summary>
private T DoOutInOp<T>(ClientOp opId, Action<BinaryWriter> writeAction,
Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOp(opId, stream => WriteRequest(writeAction, stream),
readFunc, HandleError<T>);
}
/// <summary>
/// Does the out in op with affinity awareness.
/// </summary>
private T DoOutInOpAffinity<T>(ClientOp opId, TK key, Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinity(
opId,
stream => WriteRequest(w => w.WriteObjectDetached(key), stream),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op with affinity awareness.
/// </summary>
private T DoOutInOpAffinity<T>(ClientOp opId, TK key, Action<BinaryWriter> writeAction,
Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinity(
opId,
stream => WriteRequest(writeAction, stream),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op with affinity awareness.
/// </summary>
private T DoOutInOpAffinity<T>(ClientOp opId, TK key, TV val, Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinity(
opId,
stream => WriteRequest(w =>
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(val);
}, stream),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op.
/// </summary>
private Task<T> DoOutInOpAsync<T>(ClientOp opId, Action<BinaryWriter> writeAction,
Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAsync(opId, stream => WriteRequest(writeAction, stream),
readFunc, HandleError<T>);
}
/// <summary>
/// Does the out in op with affinity awareness.
/// </summary>
private Task<T> DoOutInOpAffinityAsync<T>(ClientOp opId, TK key, Action<BinaryWriter> writeAction,
Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinityAsync(opId, stream => WriteRequest(writeAction, stream),
readFunc, _id, key, HandleError<T>);
}
/// <summary>
/// Does the out in op with affinity awareness.
/// </summary>
private Task<T> DoOutInOpAffinityAsync<T>(ClientOp opId, TK key, TV val, Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinityAsync(
opId,
stream => WriteRequest(w =>
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(val);
}, stream),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op with affinity awareness.
/// </summary>
private Task<T> DoOutInOpAffinityAsync<T>(ClientOp opId, TK key, Func<IBinaryStream, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinityAsync(opId,
stream => WriteRequest(w => w.WriteObjectDetached(key), stream),
readFunc, _id, key, HandleError<T>);
}
/// <summary>
/// Writes the request.
/// </summary>
private void WriteRequest(Action<BinaryWriter> writeAction, IBinaryStream stream)
{
stream.WriteInt(_id);
stream.WriteByte(0); // Flags (skipStore, etc).
if (writeAction != null)
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
_marsh.FinishMarshal(writer);
}
}
/// <summary>
/// Unmarshals the value, throwing an exception for nulls.
/// </summary>
private T UnmarshalNotNull<T>(IBinaryStream stream)
{
var hdr = stream.ReadByte();
if (hdr == BinaryUtils.HdrNull)
{
throw GetKeyNotFoundException();
}
stream.Seek(-1, SeekOrigin.Current);
return _marsh.Unmarshal<T>(stream, _keepBinary);
}
/// <summary>
/// Unmarshals the value, wrapping in a cache result.
/// </summary>
private CacheResult<T> UnmarshalCacheResult<T>(IBinaryStream stream)
{
var hdr = stream.ReadByte();
if (hdr == BinaryUtils.HdrNull)
{
return new CacheResult<T>();
}
stream.Seek(-1, SeekOrigin.Current);
return new CacheResult<T>(_marsh.Unmarshal<T>(stream, _keepBinary));
}
/// <summary>
/// Writes the scan query.
/// </summary>
private void WriteScanQuery(BinaryWriter writer, ScanQuery<TK, TV> qry)
{
Debug.Assert(qry != null);
if (qry.Filter == null)
{
writer.WriteByte(BinaryUtils.HdrNull);
}
else
{
var holder = new CacheEntryFilterHolder(qry.Filter, (key, val) => qry.Filter.Invoke(
new CacheEntry<TK, TV>((TK)key, (TV)val)), writer.Marshaller, _keepBinary);
writer.WriteObject(holder);
writer.WriteByte(FilterPlatformDotnet);
}
writer.WriteInt(qry.PageSize);
writer.WriteInt(qry.Partition ?? -1);
writer.WriteBoolean(qry.Local);
}
/// <summary>
/// Writes the SQL query.
/// </summary>
[Obsolete]
private static void WriteSqlQuery(IBinaryRawWriter writer, SqlQuery qry)
{
Debug.Assert(qry != null);
writer.WriteString(qry.QueryType);
writer.WriteString(qry.Sql);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.Local);
#pragma warning disable 618
writer.WriteBoolean(qry.ReplicatedOnly);
#pragma warning restore 618
writer.WriteInt(qry.PageSize);
writer.WriteTimeSpanAsLong(qry.Timeout);
}
/// <summary>
/// Writes the SQL fields query.
/// </summary>
private static void WriteSqlFieldsQuery(IBinaryRawWriter writer, SqlFieldsQuery qry,
bool includeColumns = true)
{
Debug.Assert(qry != null);
writer.WriteString(qry.Schema);
writer.WriteInt(qry.PageSize);
writer.WriteInt(-1); // maxRows: unlimited
writer.WriteString(qry.Sql);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
// .NET client does not discern between different statements for now.
// We cound have ExecuteNonQuery method, which uses StatementType.Update, for example.
writer.WriteByte((byte)StatementType.Any);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.Local);
#pragma warning disable 618
writer.WriteBoolean(qry.ReplicatedOnly);
#pragma warning restore 618
writer.WriteBoolean(qry.EnforceJoinOrder);
writer.WriteBoolean(qry.Colocated);
writer.WriteBoolean(qry.Lazy);
writer.WriteTimeSpanAsLong(qry.Timeout);
writer.WriteBoolean(includeColumns);
}
/// <summary>
/// Gets the fields cursor.
/// </summary>
private ClientFieldsQueryCursor GetFieldsCursor(IBinaryStream s)
{
var cursorId = s.ReadLong();
var columnNames = ClientFieldsQueryCursor.ReadColumns(_marsh.StartUnmarshal(s));
return new ClientFieldsQueryCursor(_ignite, cursorId, _keepBinary, s,
ClientOp.QuerySqlFieldsCursorGetPage, columnNames);
}
/// <summary>
/// Gets the fields cursor.
/// </summary>
private ClientQueryCursorBase<T> GetFieldsCursorNoColumnNames<T>(IBinaryStream s,
Func<IBinaryRawReader, int, T> readerFunc)
{
var cursorId = s.ReadLong();
var columnCount = s.ReadInt();
return new ClientQueryCursorBase<T>(_ignite, cursorId, _keepBinary, s,
ClientOp.QuerySqlFieldsCursorGetPage, r => readerFunc(r, columnCount));
}
/// <summary>
/// Handles the error.
/// </summary>
private T HandleError<T>(ClientStatusCode status, string msg)
{
switch (status)
{
case ClientStatusCode.CacheDoesNotExist:
throw new IgniteClientException("Cache doesn't exist: " + Name, null, status);
default:
throw new IgniteClientException(msg, null, status);
}
}
/// <summary>
/// Gets the key not found exception.
/// </summary>
private static KeyNotFoundException GetKeyNotFoundException()
{
return new KeyNotFoundException("The given key was not present in the cache.");
}
/// <summary>
/// Writes the peek modes.
/// </summary>
private static void WritePeekModes(ICollection<CachePeekMode> modes, IBinaryRawWriter w)
{
if (modes == null)
{
w.WriteInt(0);
}
else
{
w.WriteInt(modes.Count);
foreach (var m in modes)
{
// Convert bit flag to ordinal.
byte val = 0;
var flagVal = (int)m;
while ((flagVal = flagVal >> 1) > 0)
{
val++;
}
w.WriteByte(val);
}
}
}
/// <summary>
/// Reads the cache entries.
/// </summary>
private ICollection<ICacheEntry<TK, TV>> ReadCacheEntries(IBinaryStream stream)
{
var reader = _marsh.StartUnmarshal(stream, _keepBinary);
var cnt = reader.ReadInt();
var res = new List<ICacheEntry<TK, TV>>(cnt);
for (var i = 0; i < cnt; i++)
{
res.Add(new CacheEntry<TK, TV>(reader.ReadObject<TK>(), reader.ReadObject<TV>()));
}
return res;
}
/// <summary>
/// Writes key and value.
/// </summary>
private static void WriteKeyVal(BinaryWriter w, TK key, TV val)
{
w.WriteObjectDetached(key);
w.WriteObjectDetached(val);
}
}
}
| |
// The decode table would grow to large for 64bit codes, and should not
// be used in this case. However it is very likely that the 64 bit version
// does not work as of yet.
// The actual savings by using a table are small enough, that it is
// normally not worth the associated initialization cost.
// #define V3FCODER_DECODE_TABLE
// The following option is mostly for debugging:
// #define V3FCODER_NO_WARP
using System;
namespace Aardvark.Base
{
/// <summary>
/// A V3fCoder can be used to encode direction vectors in unsigned
/// integers.
/// </summary>
public class V3fCoder
{
// private uint m_raster;
private uint m_r2Sub1;
private double m_doubleRaster;
private double m_invDoubleRaster;
private uint m_edgeBasis;
private uint m_cornerBasis;
#if V3FCODER_DECODE_TABLE
private double[] m_unWarpTable;
#endif
private double m_dRp05;
#region Constructor
/// <summary>
/// Create a V3fCoder with supplied raster. The raster defines the
/// number of discretized directons along an octant of one of the
/// major circumferences of the sphere. Thus on each of the 3 major
/// circumferences of the sphere 8 * raster evenly spaced different
/// directions are encoded.
/// </summary>
/// <param name="raster"></param>
public V3fCoder(uint raster)
{
// m_raster = raster;
m_r2Sub1 = 2 * raster - 1;
m_doubleRaster = (double)raster;
m_invDoubleRaster = 1.0/m_doubleRaster;
m_edgeBasis = 6 * m_r2Sub1 * m_r2Sub1;
m_cornerBasis = m_edgeBasis + 12 * m_r2Sub1;
m_dRp05 = m_doubleRaster + 0.5;
#if V3FCODER_DECODE_TABLE
// build a table for slightly faster decoding
m_unWarpTable = new double[m_r2Sub1];
for (int i = 0; i < m_r2Sub1; i++)
{
double u = (i+1) * m_invDoubleRaster - 1.0;
#if (!V3FCODER_NO_WARP)
u = SphericalOfBox(u);
#endif
m_unWarpTable[i] = u;
}
#endif
}
#endregion
#region Static Creator
public static V3fCoder ForBits(int bits)
{
if (bits < 5) return null;
if (bits > 32) bits = 32;
return s_coderForBits[bits];
}
#endregion
#region Constants
static readonly uint[] s_rasterForBitsTable =
{
// bits raster, used bits
/* 0 */ 0,
/* 1 */ 0,
/* 2 */ 0,
/* 3 */ 0,
/* 4 */ 0,
/* 5 */ 1, // 4.7004397181
/* 6 */ 1, // 4.7004397181
/* 7 */ 2, // 6.6147098441
/* 8 */ 3, // 7.7681843248
/* 9 */ 4, // 8.5924570373
/* 10 */ 6, // 9.7582232147
/* 11 */ 9, // 10.9262959948
/* 12 */ 13, // 11.9865531498
/* 13 */ 18, // 12.9251835194
/* 14 */ 26, // 13.9860197731
/* 15 */ 36, // 14.9249052665
/* 16 */ 52, // 15.9858863980
/* 17 */ 73, // 16.9646341787
/* 18 */ 104, // 17.9858530524
/* 19 */ 147, // 18.9843127540
/* 20 */ 209, // 19.9996835172
/* 21 */ 295, // 20.9941061707
/* 22 */ 418, // 21.9996814530
/* 23 */ 591, // 22.9989914853
/* 24 */ 836, // 23.9996809369
/* 25 */ 1182, // 24.9989912271
/* 26 */ 1672, // 25.9996808079
/* 27 */ 2364, // 26.9989911626
/* 28 */ 3344, // 27.9996807756
/* 29 */ 4729, // 28.9996013590
/* 30 */ 6688, // 29.9996807676
/* 31 */ 9459, // 30.9999064129
/* 32 */ 13377, // 31.9998964715
/*
For the following codes to work, the algorithm
has to be changed to 64-bit ints.
*/
/* 33 */ 18918, // 32.9999064119
/* 34 */ 26754, // 33.9998964710
/* 35 */ 37837, // 34.9999826710
/* 36 */ 53509, // 35.9999503948
/* 37 */ 75674, // 36.9999826710
/* 38 */ 107019, // 37.9999773564
/* 39 */ 151348, // 38.9999826710
/* 40 */ 214039, // 39.9999908371
/* 41 */ 302697, // 40.9999922033
/* 42 */ 428079, // 41.9999975774
/* 43 */ 605395, // 42.9999969694
/* 44 */ 856158, // 43.9999975774
/* 45 */ 1210791, // 44.9999993524
/* 46 */ 1712317, // 45.9999992625
/* 47 */ 2421582, // 46.9999993524
/* 48 */ 3424634, // 47.9999992625
/* 49 */ 4843165, // 48.9999999482
/* 50 */ 6849269, // 49.9999996837
/* 51 */ 9686330, // 50.9999999482
/* 52 */ 13698539, // 51.9999998944
/* 53 */ 19372660, // 52.9999999482
/* 54 */ 27397079, // 53.9999999997
/* 55 */ 38745320, // 54.9999999482
/* 56 */ 54794158, // 55.9999999997
/* 57 */ 77490641, // 56.9999999854
/* 58 */ 109588316, // 57.9999999997
/* 59 */ 154981282, // 58.9999999854
/* 60 */ 219176632, // 59.9999999997
/* 61 */ 309962565, // 60.9999999948
/* 62 */ 438353264, // 61.9999999997
/* 63 */ 619925131, // 62.9999999994
/* 64 */ 876706528, // 63.9999999997
};
const double c_piOver4 = Constant.Pi * 0.25;
const double c_4OverPi = 4.0 / Constant.Pi;
private static V3fCoder[] s_coderForBits =
new V3fCoder[33];
static V3fCoder()
{
for (int bits = 5; bits < 33; bits++)
s_coderForBits[bits] = new V3fCoder(RasterForBits(bits));
}
#endregion
#region Encoding Helpers
public static double SphericalOfBox(double x)
{ return System.Math.Tan(x * c_piOver4); }
public static double BoxOfSpherical(double x)
{ return System.Math.Atan(x) * c_4OverPi; }
#if (!V3FCODER_DECODE_TABLE)
#if (V3FCODER_NO_WARP)
private double Unwarp(uint u)
{ return (u+1) * m_invDoubleRaster - 1.0; }
#else
private double Unwarp(uint u)
{ return System.Math.Tan(((u + 1) * m_invDoubleRaster - 1.0) * c_piOver4); }
#endif
#else
private double Unwarp(uint u) { return m_unWarpTable[u]; }
#endif
/*
The directions are coded based on the faces, edges, and corners
of a cube of size 2, centered at the origin. Within an uint the
first codes are for the faces, then the edges and finally the
corners. The coding within these three groups is performed
according to the following table:
faces:
0: -1 u v
1: v -1 u
2: u v -1
3: +1 u v
4: v +1 u
5: u v +1
edges:
0: u -1 -1 faces 1,-,u 2,u,- corners 0, 1
1: u +1 -1 faces 4,-,u 2,u,+ corners 2, 3
2: u -1 +1 faces 1,+,u 5,u,- corners 4, 5
3: u +1 +1 faces 4,+,u 5,u,+ corners 6, 7
4: -1 u -1 faces 2,-,u 0,u,- corners 0, 2
5: +1 u -1 faces 2,+,u 3,u,- corners 1, 3
6: -1 u +1 faces 5,-,u 0,u,+ corners 4, 6
7: +1 u +1 faces 5,+,u 3,u,+ corners 5, 7
8: -1 -1 u faces 0,-,u 1,u,- corners 0, 4
9: +1 -1 u faces 3,-,u 1,u,+ corners 1, 5
10: -1 +1 u faces 0,+,u 4,u,- corners 2, 6
11: +1 +1 u faces 3,+,u 4,u,+ corners 3, 7
corners:
0: -1 -1 -1 edges 0, 4, 8 faces 0, 1, 2
1: +1 -1 -1 edges 0, 5, 9
2: -1 +1 -1 edges 1, 4, 10
3: +1 +1 -1 edges 1, 5, 11
4: -1 -1 +1 edges 2, 6, 8
5: +1 -1 +1 edges 2, 7, 9
6: -1 +1 +1 edges 3, 6, 10
7: +1 +1 +1 edges 3, 7, 11
*/
uint EncodeCornerIndex(uint corner)
{
return m_cornerBasis + corner;
}
static readonly uint[] s_edgeNegCorner = new uint[]
{ 0, 2, 4, 6, 0, 1, 4, 5, 0, 1, 2, 3 };
static readonly uint[] s_edgePosCorner = new uint[]
{ 1, 3, 5, 7, 2, 3, 6, 7, 4, 5, 6, 7 };
uint EncodeEdgeIndex(uint edge, int iu)
{
if (iu < 0) return m_cornerBasis + s_edgeNegCorner[edge];
if (iu >= m_r2Sub1) return m_cornerBasis + s_edgePosCorner[edge];
return m_edgeBasis + (uint)(edge * m_r2Sub1 + iu);
}
uint RawEncodeEdgeIndex(uint edge, int iu)
{
return m_edgeBasis + (uint)(edge * m_r2Sub1 + iu);
}
static readonly uint[] s_faceNegUedge = new uint[] { 8, 0, 4, 9, 1, 6 };
static readonly uint[] s_facePosUedge = new uint[] { 10, 2, 5, 11, 3, 7 };
static readonly uint[] s_faceNegVedge = new uint[] { 4, 8, 0, 5, 10, 2 };
static readonly uint[] s_facePosVedge = new uint[] { 6, 9, 1, 7, 11, 3 };
uint EncodeFaceIndex(uint face, int iu, int iv)
{
if (iu < 0) return EncodeEdgeIndex(s_faceNegUedge[face], iv);
if (iu >= m_r2Sub1) return EncodeEdgeIndex(s_facePosUedge[face], iv);
if (iv < 0) return EncodeEdgeIndex(s_faceNegVedge[face], iu);
if (iv >= m_r2Sub1) return EncodeEdgeIndex(s_facePosVedge[face], iu);
return (uint)((face * m_r2Sub1 + iv ) * m_r2Sub1 + iu);
}
uint RawEncodeFaceIndex(uint face, int iu, int iv)
{
return (uint)((face * m_r2Sub1 + iv) * m_r2Sub1 + iu);
}
#endregion
#region Encoding
/// <summary>
/// Encode the given direction in an unsigned integer. The direction
/// does not need to be normalized!
/// </summary>
/// <param name="dir">The direction to encode.</param>
/// <returns></returns>
public uint Encode(V3f dir)
{
int mAxis;
double aX = System.Math.Abs(dir.X);
double aY = System.Math.Abs(dir.Y);
double aZ = System.Math.Abs(dir.Z);
double u, v;
if (aX > aY)
{
if (aX > aZ)
{
double invSize = 1.0/aX; mAxis = 0;
u = dir.Y * invSize; v = dir.Z * invSize;
}
else
{
double invSize = 1.0/aZ; mAxis = 2;
u = dir.X * invSize; v = dir.Y * invSize;
}
}
else
{
if (aY > aZ)
{
double invSize = 1.0/aY; mAxis = 1;
u = dir.Z * invSize; v = dir.X * invSize;
}
else
{
double invSize = 1.0/aZ; mAxis = 2;
u = dir.X * invSize; v = dir.Y * invSize;
}
}
#if (!V3FCODER_NO_WARP)
u = BoxOfSpherical(u);
v = BoxOfSpherical(v);
#endif
uint face = (uint)(mAxis + (dir[mAxis] < 0 ? 0 : 3));
return EncodeFaceIndex(face,
(int)(u * m_doubleRaster + m_dRp05) - 1,
(int)(v * m_doubleRaster + m_dRp05) - 1);
}
#endregion
#region Decoding Helpers
static readonly V3f[] s_vecToCornerTableNonNormalized =
{
new V3f( -1.0f, -1.0f, -1.0f ),
new V3f( +1.0f, -1.0f, -1.0f ),
new V3f( -1.0f, +1.0f, -1.0f ),
new V3f( +1.0f, +1.0f, -1.0f ),
new V3f( -1.0f, -1.0f, +1.0f ),
new V3f( +1.0f, -1.0f, +1.0f ),
new V3f( -1.0f, +1.0f, +1.0f ),
new V3f( +1.0f, +1.0f, +1.0f )
};
const float c_oneOverSqrt3 = 0.57735026918962584f;
static readonly V3f[] s_vecToCornerTable =
{
new V3f( -c_oneOverSqrt3, -c_oneOverSqrt3, -c_oneOverSqrt3 ),
new V3f( +c_oneOverSqrt3, -c_oneOverSqrt3, -c_oneOverSqrt3 ),
new V3f( -c_oneOverSqrt3, +c_oneOverSqrt3, -c_oneOverSqrt3 ),
new V3f( +c_oneOverSqrt3, +c_oneOverSqrt3, -c_oneOverSqrt3 ),
new V3f( -c_oneOverSqrt3, -c_oneOverSqrt3, +c_oneOverSqrt3 ),
new V3f( +c_oneOverSqrt3, -c_oneOverSqrt3, +c_oneOverSqrt3 ),
new V3f( -c_oneOverSqrt3, +c_oneOverSqrt3, +c_oneOverSqrt3 ),
new V3f( +c_oneOverSqrt3, +c_oneOverSqrt3, +c_oneOverSqrt3 )
};
static readonly double[] s_uSignOfEdge = { -1, +1, -1, +1 };
static readonly double[] s_vSignOfEdge = { -1, -1, +1, +1 };
static readonly int[] s_uAxis = { 1, 0, 0 };
static readonly int[] s_vAxis = { 2, 2, 1 };
#endregion
#region Decoding
/// <summary>
/// Decode the unsigned integer direction code.
/// </summary>
/// <param name="code"></param>
/// <returns>A normalized direction.</returns>
public V3f Decode(uint code)
{
if (code < m_edgeBasis) // face number is code
{
double u = Unwarp(code % m_r2Sub1);
code /= m_r2Sub1;
double v = Unwarp(code % m_r2Sub1);
code /= m_r2Sub1;
double scale = 1.0 / System.Math.Sqrt(1.0 + u * u + v * v);
switch (code)
{
case 0: return new V3f(-scale, u * scale, v * scale);
case 1: return new V3f(v * scale, -scale, u * scale);
case 2: return new V3f(u * scale, v * scale, -scale);
case 3: return new V3f(+scale, u * scale, v * scale);
case 4: return new V3f(v * scale, +scale, u * scale);
case 5: return new V3f(u * scale, v * scale, +scale);
default: throw new ArgumentException();
}
}
else if (code < m_cornerBasis)
{
code -= m_edgeBasis;
double u = Unwarp(code % m_r2Sub1);
code /= m_r2Sub1; // edge number in code
double scale = 1.0 / System.Math.Sqrt(2.0 + u * u);
uint edge = code & 3; code >>= 2;
V3f dir = new V3f(0, 0, 0); // init to make compiler happy
dir[(int)code] = (float)(u * scale);
dir[s_uAxis[code]] = (float)(s_uSignOfEdge[edge] * scale);
dir[s_vAxis[code]] = (float)(s_vSignOfEdge[edge] * scale);
return dir;
#if NEVERMORE
float edgeOne = (code & 1) == 0 ? -scale : scale;
float edgeTwo = (code & 2) == 0 ? -scale : scale;
switch (code >> 2)
{
case 0: return new V3f((float)(u * scale), edgeOne, edgeTwo);
case 1: return new V3f(edgeOne, (float)(u * scale), edgeTwo);
case 2: return new V3f(edgeOne, edgeTwo, (float)(u * scale));
default: throw new ArgumentException();
}
#endif
}
else
return s_vecToCornerTable[code - m_cornerBasis];
}
public V3f DecodeOnCube(uint code, bool warped)
{
if (code < m_edgeBasis) // face number is code
{
double u = warped
? Unwarp(code % m_r2Sub1)
: (code % m_r2Sub1 + 1) * m_invDoubleRaster - 1.0;
code /= m_r2Sub1;
double v = warped
? Unwarp(code % m_r2Sub1)
: (code % m_r2Sub1 + 1) * m_invDoubleRaster - 1.0;
code /= m_r2Sub1;
switch (code)
{
case 0: return new V3f(-1, u, v);
case 1: return new V3f(v, -1, u);
case 2: return new V3f(u, v, -1);
case 3: return new V3f(+1, u, v);
case 4: return new V3f(v, +1, u);
case 5: return new V3f(u, v, +1);
default: throw new ArgumentException();
}
}
else if (code < m_cornerBasis)
{
code -= m_edgeBasis;
double u = warped
? Unwarp(code % m_r2Sub1)
: (code % m_r2Sub1+1) * m_invDoubleRaster - 1.0;
code /= m_r2Sub1; // edge number in code
uint edge = code & 3; code >>= 2;
V3f dir = new V3f(0, 0, 0); // init to make compiler happy
dir[(int)code] = (float)u;
dir[s_uAxis[code]] = (float)(s_uSignOfEdge[edge]);
dir[s_vAxis[code]] = (float)(s_vSignOfEdge[edge]);
return dir;
#if NEVERMORE
float edgeOne = (code & 1) == 0 ? -1.0f : 1.0f;
float edgeTwo = (code & 2) == 0 ? -1.0f : 1.0f;
switch (code >> 2)
{
case 0: return new V3f((float)u, edgeOne, edgeTwo);
case 1: return new V3f(edgeOne, (float)u, edgeTwo);
case 2: return new V3f(edgeOne, edgeTwo, (float)u);
default: throw new ArgumentException();
}
#endif
}
else
return s_vecToCornerTableNonNormalized[code - m_cornerBasis];
}
#endregion
#region Neighbours Helpers
static readonly uint[] s_edgeFace0
= new uint[] { 1, 4, 1, 4, 2, 2, 5, 5, 0, 3, 0, 3 };
static readonly int[] s_edgeFace0u
= new int[] { 0, 0, 1, 1, 0, 1, 0, 1, 0 ,0, 1, 1 };
static readonly uint[] s_edgeFace1
= new uint[] { 2, 2, 5, 5, 0, 3, 0, 3, 1, 1, 4, 4 };
static readonly int[] s_edgeFace1v
= new int[] { 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1 };
#endregion
#region Neigbours
/// <summary>
/// Fills the array neighbourCodes with the codes of all neigbouring
/// cells of the code discretization.
/// </summary>
/// <param name="code">The code for which to calculate all
/// neighbours.</param>
/// <param name="neighbourCodes">The array that is filled with
/// the neighbourcodes</param>
/// <returns>The number of neigbouring cells (maximal 8).</returns>
public uint NeighbourCodes(uint code, uint[] neighbourCodes)
{
if (code < m_edgeBasis) // face number is code
{
int iu = (int)(code % m_r2Sub1);
code /= m_r2Sub1;
int iv = (int)(code % m_r2Sub1);
code /= m_r2Sub1;
if (iu > 0 && iu < m_r2Sub1 - 1 && iv > 0 && iv < m_r2Sub1 - 1)
{
neighbourCodes[0] = RawEncodeFaceIndex(code, iu - 1, iv - 1);
neighbourCodes[1] = RawEncodeFaceIndex(code, iu - 1, iv);
neighbourCodes[2] = RawEncodeFaceIndex(code, iu - 1, iv + 1);
neighbourCodes[3] = RawEncodeFaceIndex(code, iu, iv - 1);
neighbourCodes[4] = RawEncodeFaceIndex(code, iu, iv + 1);
neighbourCodes[5] = RawEncodeFaceIndex(code, iu + 1, iv - 1);
neighbourCodes[6] = RawEncodeFaceIndex(code, iu + 1, iv);
neighbourCodes[7] = RawEncodeFaceIndex(code, iu + 1, iv + 1);
}
else
{
neighbourCodes[0] = EncodeFaceIndex(code, iu - 1, iv - 1);
neighbourCodes[1] = EncodeFaceIndex(code, iu - 1, iv);
neighbourCodes[2] = EncodeFaceIndex(code, iu - 1, iv + 1);
neighbourCodes[3] = EncodeFaceIndex(code, iu, iv - 1);
neighbourCodes[4] = EncodeFaceIndex(code, iu, iv + 1);
neighbourCodes[5] = EncodeFaceIndex(code, iu + 1, iv - 1);
neighbourCodes[6] = EncodeFaceIndex(code, iu + 1, iv);
neighbourCodes[7] = EncodeFaceIndex(code, iu + 1, iv + 1);
}
return 8;
}
if (code < m_cornerBasis)
{
int nc = 0;
code -= m_edgeBasis;
int iu = (int)(code % m_r2Sub1);
code /= m_r2Sub1; // edge number in code
neighbourCodes[nc++] = EncodeEdgeIndex(code, iu - 1);
neighbourCodes[nc++] = EncodeEdgeIndex(code, iu + 1);
int m = ((int)m_r2Sub1 - 1);
for (int i = -1; i < 2; i++)
{
neighbourCodes[nc++] = EncodeFaceIndex(
s_edgeFace0[code], s_edgeFace0u[code] * m, iu + i);
neighbourCodes[nc++] = EncodeFaceIndex(
s_edgeFace1[code], iu + i, s_edgeFace1v[code] * m);
}
return 8;
}
else
{
code -= m_cornerBasis;
int m = (int)m_r2Sub1 - 1;
switch (code)
{
case 0:
neighbourCodes[0] = RawEncodeFaceIndex(0, 0, 0);
neighbourCodes[1] = RawEncodeFaceIndex(1, 0, 0);
neighbourCodes[2] = RawEncodeFaceIndex(2, 0, 0);
neighbourCodes[3] = RawEncodeEdgeIndex(0, 0);
neighbourCodes[4] = RawEncodeEdgeIndex(4, 0);
neighbourCodes[5] = RawEncodeEdgeIndex(8, 0);
break;
case 1:
neighbourCodes[0] = RawEncodeEdgeIndex(0, m);
neighbourCodes[1] = RawEncodeFaceIndex(1, 0, m);
neighbourCodes[2] = RawEncodeFaceIndex(2, m, 0);
neighbourCodes[3] = RawEncodeFaceIndex(3, 0, 0);
neighbourCodes[4] = RawEncodeEdgeIndex(5, 0);
neighbourCodes[5] = RawEncodeEdgeIndex(9, 0);
break;
case 2:
neighbourCodes[0] = RawEncodeFaceIndex(0, m, 0);
neighbourCodes[1] = RawEncodeEdgeIndex(4, m);
neighbourCodes[2] = RawEncodeFaceIndex(2, 0, m);
neighbourCodes[3] = RawEncodeEdgeIndex(1, 0);
neighbourCodes[4] = RawEncodeFaceIndex(4, 0, 0);
neighbourCodes[5] = RawEncodeEdgeIndex(10, 0);
break;
case 3:
neighbourCodes[0] = RawEncodeEdgeIndex(1, m);
neighbourCodes[1] = RawEncodeEdgeIndex(5, m);
neighbourCodes[2] = RawEncodeFaceIndex(2, m, m);
neighbourCodes[3] = RawEncodeFaceIndex(3, m, 0);
neighbourCodes[4] = RawEncodeFaceIndex(4, 0, m);
neighbourCodes[5] = RawEncodeEdgeIndex(11, 0);
break;
case 4:
neighbourCodes[0] = RawEncodeFaceIndex(0, 0, m);
neighbourCodes[1] = RawEncodeFaceIndex(1, m, 0);
neighbourCodes[2] = RawEncodeEdgeIndex(8, m);
neighbourCodes[3] = RawEncodeEdgeIndex(2, 0);
neighbourCodes[4] = RawEncodeEdgeIndex(6, 0);
neighbourCodes[5] = RawEncodeFaceIndex(5, 0, 0);
break;
case 5:
neighbourCodes[0] = RawEncodeEdgeIndex(2, m);
neighbourCodes[1] = RawEncodeFaceIndex(1, m, m);
neighbourCodes[2] = RawEncodeEdgeIndex(9, m);
neighbourCodes[3] = RawEncodeFaceIndex(3, 0, m);
neighbourCodes[4] = RawEncodeEdgeIndex(7, 0);
neighbourCodes[5] = RawEncodeFaceIndex(5, m, 0);
break;
case 6:
neighbourCodes[0] = RawEncodeFaceIndex(0, m, m);
neighbourCodes[1] = RawEncodeEdgeIndex(6, m);
neighbourCodes[2] = RawEncodeEdgeIndex(10, m);
neighbourCodes[3] = RawEncodeEdgeIndex(3, 0);
neighbourCodes[4] = RawEncodeFaceIndex(4, m, 0);
neighbourCodes[5] = RawEncodeFaceIndex(5, 0, m);
break;
case 7:
neighbourCodes[0] = RawEncodeEdgeIndex(3, m);
neighbourCodes[1] = RawEncodeEdgeIndex(7, m);
neighbourCodes[2] = RawEncodeEdgeIndex(11, m);
neighbourCodes[3] = RawEncodeFaceIndex(3, m, m);
neighbourCodes[4] = RawEncodeFaceIndex(4, m, m);
neighbourCodes[5] = RawEncodeFaceIndex(5, m, m);
break;
}
return 6;
}
}
#endregion
#region Info Methods
/// <summary>
/// Calculate the maximal raster for a given number of bits.
/// Currently maximal 32 bits are supported.
/// </summary>
/// <param name="bits">The number of bits.</param>
/// <returns>The maximal possible raster value.</returns>
public static uint RasterForBits(int bits)
{
if (bits < 5) return 0;
if (bits > 32) bits = 32;
return s_rasterForBitsTable[bits];
}
/// <summary>
/// Calculate the number of different codes that are available.
/// </summary>
/// <returns></returns>
public uint Count
{
get { return m_cornerBasis + 8; }
}
/// <summary>
/// Calculate all directions that are exactly encoded.
/// </summary>
/// <returns>An array of directions.</returns>
public V3f[] GenerateTable()
{
uint dirCount = Count;
V3f[] directionTable = new V3f[dirCount];
for (uint dc = 0; dc < dirCount; dc++)
{
directionTable[dc] = Decode(dc);
}
return directionTable;
}
#endregion
#region Code Generator
/// <summary>
/// Code generation.
/// </summary>
public void WriteCode(uint code)
{
if (code < m_edgeBasis) // face number is code
{
uint iu = code % m_r2Sub1;
code /= m_r2Sub1;
uint iv = code % m_r2Sub1;
code /= m_r2Sub1;
string u = iu == 0 ? "0" : (iu == m_r2Sub1 - 1 ? "m" : "u");
string v = iv == 0 ? "0" : (iv == m_r2Sub1 - 1 ? "m" : "v");
Console.WriteLine("EncodeFaceIndex({0}, {1}, {2});", code, u, v);
}
else if (code < m_cornerBasis)
{
code -= m_edgeBasis;
uint iu = code % m_r2Sub1;
code /= m_r2Sub1; // edge number in code
string u = iu == 0 ? "0" : (iu == m_r2Sub1 - 1 ? "m" : "u");
Console.WriteLine("EncodeEdgeIndex({0}, {1});", code, u);
}
else
Console.WriteLine("EncodeCornerIndex({0});", code - m_cornerBasis);
}
/// <summary>
/// Code generation.
/// </summary>
public void WriteCornerNeighbours(uint corner)
{
V3f v = s_vecToCornerTableNonNormalized[corner];
string f = " neighbourCodes[{0}] = ";
float s = (float)m_invDoubleRaster;
Console.Write(f, 0); WriteCode(Encode(v + s * new V3f(-1, 0, 0)));
Console.Write(f, 1); WriteCode(Encode(v + s * new V3f(0, -1, 0)));
Console.Write(f, 2); WriteCode(Encode(v + s * new V3f(0, 0, -1)));
Console.Write(f, 3); WriteCode(Encode(v + s * new V3f(1, 0, 0)));
Console.Write(f, 4); WriteCode(Encode(v + s * new V3f(0, 1, 0)));
Console.Write(f, 5); WriteCode(Encode(v + s * new V3f(0, 0, 1)));
}
/// <summary>
/// Code generation.
/// </summary>
public void WriteAllCornerNeighbours()
{
for (uint c = 0; c < 8; c++)
{
Console.WriteLine("case {0}:", c);
WriteCornerNeighbours(c);
Console.WriteLine(" break;");
}
}
#endregion
}
}
| |
/*
* PathGradientBrush.cs - Implementation of "System.Drawing.Drawing2D.PathGradientBrush"
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* Contributed by Gopal.V
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Drawing.Drawing2D
{
public class PathGradientBrush : Brush
{
[TODO]
public PathGradientBrush(GraphicsPath path)
{
throw new NotImplementedException(".ctor");
}
[TODO]
public PathGradientBrush(Point[] points)
{
throw new NotImplementedException(".ctor");
}
[TODO]
public PathGradientBrush(PointF[] points)
{
throw new NotImplementedException(".ctor");
}
[TODO]
public PathGradientBrush(Point[] points, WrapMode wrapMode)
{
throw new NotImplementedException(".ctor");
}
[TODO]
public PathGradientBrush(PointF[] points, WrapMode wrapMode)
{
throw new NotImplementedException(".ctor");
}
[TODO]
public Blend Blend
{
get
{
throw new NotImplementedException("Blend");
}
set
{
throw new NotImplementedException("Blend");
}
}
[TODO]
public Color CenterColor
{
get
{
throw new NotImplementedException("CenterColor");
}
set
{
throw new NotImplementedException("CenterColor");
}
}
[TODO]
public PointF CenterPoint
{
get
{
throw new NotImplementedException("CenterPoint");
}
set
{
throw new NotImplementedException("CenterPoint");
}
}
[TODO]
public PointF FocusScales
{
get
{
throw new NotImplementedException("FocusScales");
}
set
{
throw new NotImplementedException("FocusScales");
}
}
[TODO]
public ColorBlend InterpolationColors
{
get
{
throw new NotImplementedException("InterpolationColors");
}
set
{
throw new NotImplementedException("InterpolationColors");
}
}
[TODO]
public RectangleF Rectangle
{
get
{
throw new NotImplementedException("Rectangle");
}
}
[TODO]
public Color[] SurroundColors
{
get
{
throw new NotImplementedException("SurroundColors");
}
set
{
throw new NotImplementedException("SurroundColors");
}
}
[TODO]
public Matrix Transform
{
get
{
throw new NotImplementedException("Transform");
}
set
{
throw new NotImplementedException("Transform");
}
}
[TODO]
public WrapMode WrapMode
{
get
{
throw new NotImplementedException("WrapMode");
}
set
{
throw new NotImplementedException("WrapMode");
}
}
[TODO]
public override Object Clone()
{
throw new NotImplementedException("Clone");
}
[TODO]
public void MultiplyTransform(Matrix matrix)
{
throw new NotImplementedException("MultiplyTransform");
}
[TODO]
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
throw new NotImplementedException("MultiplyTransform");
}
[TODO]
public void ResetTransform()
{
throw new NotImplementedException("ResetTransform");
}
[TODO]
public void RotateTransform(float angle)
{
throw new NotImplementedException("RotateTransform");
}
[TODO]
public void RotateTransform(float angle, MatrixOrder order)
{
throw new NotImplementedException("RotateTransform");
}
[TODO]
public void ScaleTransform(float sx, float sy)
{
throw new NotImplementedException("ScaleTransform");
}
[TODO]
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
throw new NotImplementedException("ScaleTransform");
}
[TODO]
public void SetBlendTriangularShape(float focus)
{
throw new NotImplementedException("SetBlendTriangularShape");
}
[TODO]
public void SetBlendTriangularShape(float focus, float scale)
{
throw new NotImplementedException("SetBlendTriangularShape");
}
[TODO]
public void SetSigmaBellShape(float focus)
{
throw new NotImplementedException("SetSigmaBellShape");
}
[TODO]
public void SetSigmaBellShape(float focus, float scale)
{
throw new NotImplementedException("SetSigmaBellShape");
}
[TODO]
public void TranslateTransform(float dx, float dy)
{
throw new NotImplementedException("TranslateTransform");
}
[TODO]
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
throw new NotImplementedException("TranslateTransform");
}
}
}//namespace
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using CslaGenerator.Metadata;
using CslaGenerator.Util.PropertyBags;
using WeifenLuo.WinFormsUI.Docking;
namespace CslaGenerator.Controls
{
public partial class ObjectRelationsBuilder : DockContent
{
#region Fix for form flicker
// http://www.angryhacker.com/blog/archive/2010/07/21/how-to-get-rid-of-flicker-on-windows-forms-applications.aspx
int _originalExStyle = -1;
private bool _enableFormLevelDoubleBuffering = true;
protected override CreateParams CreateParams
{
get
{
if (_originalExStyle == -1)
_originalExStyle = base.CreateParams.ExStyle;
CreateParams cp = base.CreateParams;
if (_enableFormLevelDoubleBuffering)
cp.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
else
cp.ExStyle = _originalExStyle;
return cp;
}
}
internal void TurnOnFormLevelDoubleBuffering()
{
_enableFormLevelDoubleBuffering = true;
}
internal void TurnOffFormLevelDoubleBuffering()
{
_enableFormLevelDoubleBuffering = false;
MaximizeBox = true;
}
private void ObjectRelationsBuilder_Shown(object sender, EventArgs e)
{
TurnOffFormLevelDoubleBuffering();
}
private void ObjectRelationsBuilder_ResizeBegin(object sender, EventArgs e)
{
SuspendLayout();
TurnOnFormLevelDoubleBuffering();
}
private void ObjectRelationsBuilder_ResizeEnd(object sender, EventArgs e)
{
TurnOffFormLevelDoubleBuffering();
ResumeLayout(true);
}
#endregion
#region Private fields
private AssociativeEntityCollection _associativeEntities;
private bool _suspendFill;
private bool _restoreSelectedItems;
private bool _suspendListUpdates;
private List<AssociativeEntity> _selectedItems1;
private List<AssociativeEntity> _selectedItems2;
private List<AssociativeEntity> _selectedItems3;
#endregion
#region Properties
internal List<AssociativeEntity> View1 { get; private set; }
internal List<AssociativeEntity> View2 { get; private set; }
internal List<AssociativeEntity> View3 { get; private set; }
public PropertyGrid PropertyGrid1
{
set { propGrid1 = value; }
get { return propGrid1; }
}
public PropertyGrid PropertyGrid2
{
set { propGrid2 = value; }
get { return propGrid2; }
}
public PropertyGrid PropertyGrid3
{
set { propGrid3 = value; }
get { return propGrid3; }
}
private bool UnitLoaded()
{
if (_associativeEntities != null)
return true;
MessageBox.Show(@"You need to create a new project first.", @"CslaGenerator", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
public AssociativeEntityCollection AssociativeEntities
{
get { return _associativeEntities; }
set
{
if (_associativeEntities != null)
_associativeEntities.ListChanged -= associativeEntities_ListChanged;
_associativeEntities = value;
if (_associativeEntities != null)
_associativeEntities.ListChanged += associativeEntities_ListChanged;
}
}
#endregion
#region Constructor
public ObjectRelationsBuilder()
{
InitializeComponent();
listEntities1.DrawItem += ListEntities_DrawItem;
listEntities1.DrawMode = DrawMode.OwnerDrawFixed;
listEntities2.DrawItem += ListEntities_DrawItem;
listEntities2.DrawMode = DrawMode.OwnerDrawFixed;
listEntities3.DrawItem += ListEntities_DrawItem;
listEntities3.DrawMode = DrawMode.OwnerDrawFixed;
propGrid1.PropertySortChanged += OnSortTab;
propGrid2.PropertySortChanged += OnSortTab;
propGrid3.PropertySortChanged += OnSortTab;
propGrid1.PropertyValueChanged += OnPropertyValueChanged;
propGrid2.PropertyValueChanged += OnPropertyValueChanged;
propGrid3.PropertyValueChanged += OnPropertyValueChanged;
}
#endregion
#region Event handlers
public void OnSortTab(object sender, EventArgs e)
{
if (GetCurrentPropertyGrid().PropertySort == PropertySort.CategorizedAlphabetical)
GetCurrentPropertyGrid().PropertySort = PropertySort.Categorized;
}
private void OnPropertyValueChanged(object sender, PropertyValueChangedEventArgs e)
{
if (e.ChangedItem.Label == "Primary Loading Scheme" || e.ChangedItem.Label == "Secondary Loading Scheme")
{
FillViews(true);
}
}
private void ListEntities_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
return;
if (e.Index > GetCurrentViewItems().Count - 1)
return;
e.DrawBackground();
var b = new SolidBrush(e.ForeColor);
e.Graphics.DrawString(GetCurrentViewItems()[e.Index].ObjectName, e.Font, b, e.Bounds);
e.DrawFocusRectangle();
}
private void associativeEntities_ListChanged(object sender, ListChangedEventArgs e)
{
if (_suspendListUpdates)
return;
if (e.ListChangedType == ListChangedType.ItemChanged &&
e.PropertyDescriptor.Name != "ObjectName" &&
e.PropertyDescriptor.Name != "RelationType")
{
// if "ObjectName" or "RelationType" didn't change, just refresh
GetCurrentListBox().Refresh();
return;
}
FillViews(false);
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// no need to fire ListEntities_SelectedIndexChanged 4 times
DisableEventSelectedIndexChanged();
// store currency values for later use
var selectedItems1 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
if (listEntities1.SelectedItems.Count == 0 && listEntities1.Items.Count > 0)
listEntities1.SelectedItem = listEntities1.Items[0];
foreach (AssociativeEntity obj in listEntities1.SelectedItems)
selectedItems1.Add(obj);
}
var selectedItems2 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
if (listEntities2.SelectedItems.Count == 0 && listEntities2.Items.Count > 0)
listEntities2.SelectedItem = listEntities2.Items[0];
foreach (AssociativeEntity obj in listEntities2.SelectedItems)
selectedItems2.Add(obj);
}
var selectedItems3 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
if (listEntities3.SelectedItems.Count == 0 && listEntities3.Items.Count > 0)
listEntities3.SelectedItem = listEntities3.Items[0];
foreach (AssociativeEntity obj in listEntities3.SelectedItems)
selectedItems3.Add(obj);
}
// update the ListBox items
FillViewsPresenter();
listEntities1.SelectedIndices.Clear();
listEntities2.SelectedIndices.Clear();
listEntities3.SelectedIndices.Clear();
if (_associativeEntities != null)
{
if (selectedItems1.Count == 0 && listEntities1.Items.Count > 0)
{
_selectedItems1.Clear();
listEntities1.SelectedIndex = listEntities1.Items.Count - 1;
}
if (selectedItems2.Count == 0 && listEntities2.Items.Count > 0)
{
_selectedItems2.Clear();
listEntities2.SelectedIndex = listEntities2.Items.Count - 1;
}
if (selectedItems3.Count == 0 && listEntities3.Items.Count > 0)
{
_selectedItems3.Clear();
listEntities3.SelectedIndex = listEntities3.Items.Count - 1;
}
}
foreach (var obj in selectedItems1)
listEntities1.SelectedItems.Add(obj);
foreach (var obj in selectedItems2)
listEntities2.SelectedItems.Add(obj);
foreach (var obj in selectedItems3)
listEntities3.SelectedItems.Add(obj);
EnableEventSelectedIndexChanged();
ListEntities1_SelectedIndexChanged(this, new EventArgs());
ListEntities2_SelectedIndexChanged(this, new EventArgs());
ListEntities3_SelectedIndexChanged(this, new EventArgs());
return;
}
FillViewsPresenter();
}
private void ListEntities1_SelectedIndexChanged(object sender, EventArgs e)
{
DisableEventSelectedIndexChanged();
if (_restoreSelectedItems)
{
listEntities1.SelectedItems.Clear();
// if empty list, preload with first item
if (_selectedItems1.Count == 0 && listEntities1.Items.Count > 0)
listEntities1.SelectedItems.Add(listEntities1.Items[0]);
else
foreach (var obj in _selectedItems1)
listEntities1.SelectedItems.Add(obj);
}
else
{
_selectedItems1 = new List<AssociativeEntity>();
}
OnSelectedItemsChanged();
EnableEventSelectedIndexChanged();
}
private void ListEntities2_SelectedIndexChanged(object sender, EventArgs e)
{
DisableEventSelectedIndexChanged();
if (_restoreSelectedItems)
{
listEntities2.SelectedItems.Clear();
// if empty list, preload with first item
if (_selectedItems2.Count == 0 && listEntities2.Items.Count > 0)
listEntities2.SelectedItems.Add(listEntities2.Items[0]);
else
foreach (var obj in _selectedItems2)
listEntities2.SelectedItems.Add(obj);
}
else
{
_selectedItems2 = new List<AssociativeEntity>();
}
OnSelectedItemsChanged();
EnableEventSelectedIndexChanged();
}
private void ListEntities3_SelectedIndexChanged(object sender, EventArgs e)
{
DisableEventSelectedIndexChanged();
if (_restoreSelectedItems)
{
listEntities3.SelectedItems.Clear();
// if empty list, preload with first item
if (_selectedItems3.Count == 0 && listEntities3.Items.Count > 0)
listEntities3.SelectedItems.Add(listEntities3.Items[0]);
else
foreach (var obj in _selectedItems3)
listEntities3.SelectedItems.Add(obj);
}
else
{
_selectedItems3 = new List<AssociativeEntity>();
}
OnSelectedItemsChanged();
EnableEventSelectedIndexChanged();
}
private void TabControl_Selected(object sender, TabControlEventArgs e)
{
OnSelectedItemsChanged();
}
private void upButton_Click(object sender, EventArgs e)
{
MoveUpSelected();
}
private void downButton_Click(object sender, EventArgs e)
{
MoveDownSelected();
}
private void addButton_Click(object sender, EventArgs e)
{
AddNewObject();
}
private void removeButton_Click(object sender, EventArgs e)
{
RemoveSelected();
}
private void buildButton_Click(object sender, EventArgs e)
{
var associativeEntity = GetCurrentViewItems()[GetCurrentListBox().SelectedIndex];
ValidateSelected(associativeEntity);
}
private void buildAllButton_Click(object sender, EventArgs e)
{
ValidateAll();
}
#endregion
#region Events
public event EventHandler SelectedItemsChanged;
void OnSelectedItemsChanged()
{
if (SelectedItemsChanged != null)
SelectedItemsChanged(this, EventArgs.Empty);
}
#endregion
#region Methods
public void ClearSelectedItems()
{
_selectedItems1 = new List<AssociativeEntity>();
_selectedItems2 = new List<AssociativeEntity>();
_selectedItems3 = new List<AssociativeEntity>();
}
/// <summary>
/// Applies the filters to the CslaObjectInfoCollection.
/// </summary>
/// <remarks>
/// This method should handle only the filtering of business objects.
/// The view part - handle what is displayed in the ListBox - should be here.
/// </remarks>
public void FillViews(bool updatePresenter)
{
if (_suspendFill)
return;
listEntities1.SuspendLayout();
listEntities2.SuspendLayout();
listEntities3.SuspendLayout();
View1 = new List<AssociativeEntity>();
View2 = new List<AssociativeEntity>();
View3 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
foreach (var obj in _associativeEntities)
{
View1.Add(obj);
if (obj.RelationType == ObjectRelationType.OneToMany)
View2.Add(obj);
else
View3.Add(obj);
}
}
if (updatePresenter)
FillViewsPresenter();
}
public void FillViewsPresenter()
{
if (_suspendFill)
return;
_restoreSelectedItems = true;
// stupid Windows.Forms doesn't fire the event when the DataSource has elements and is assigned an empty collection
var fireEventManually = false;
// store currency values for later use by ListEntities1_SelectedIndexChanged
if (_selectedItems1 == null)
_selectedItems1 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
foreach (AssociativeEntity obj in listEntities1.SelectedItems)
{
if (_associativeEntities.Contains(obj))
_selectedItems1.Add(obj);
}
}
if (listEntities1.DataSource != null)
fireEventManually = ((ICollection) listEntities1.DataSource).Count > 0 && View1.Count == 0;
listEntities1.DataSource = View1; // this sets the list SelectedItem to the first item
if (fireEventManually)
ListEntities1_SelectedIndexChanged(this, new EventArgs());
// store currency values for later use by ListEntities2_SelectedIndexChanged
if (_selectedItems2 == null)
_selectedItems2 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
foreach (AssociativeEntity obj in listEntities2.SelectedItems)
{
if (_associativeEntities.Contains(obj))
_selectedItems2.Add(obj);
}
}
if (listEntities2.DataSource != null)
fireEventManually = ((ICollection) listEntities2.DataSource).Count > 0 && View2.Count == 0;
listEntities2.DataSource = View2; // this sets the list SelectedItem to the first item
if (fireEventManually)
ListEntities2_SelectedIndexChanged(this, new EventArgs());
// store currency values for later use by ListEntities3_SelectedIndexChanged
if (_selectedItems3 == null)
_selectedItems3 = new List<AssociativeEntity>();
if (_associativeEntities != null)
{
foreach (AssociativeEntity obj in listEntities3.SelectedItems)
{
if (_associativeEntities.Contains(obj))
_selectedItems3.Add(obj);
}
}
if (listEntities3.DataSource != null)
fireEventManually = ((ICollection) listEntities3.DataSource).Count > 0 && View3.Count == 0;
listEntities3.DataSource = View3; // this sets the list SelectedItem to the first item
if (fireEventManually)
ListEntities3_SelectedIndexChanged(this, new EventArgs());
_restoreSelectedItems = false;
listEntities1.ResumeLayout();
listEntities2.ResumeLayout();
listEntities3.ResumeLayout();
if (_associativeEntities != null)
{
if (_associativeEntities.Count == 0)
{
PropertyGrid1.SelectedObject = null;
PropertyGrid2.SelectedObject = null;
PropertyGrid3.SelectedObject = null;
}
}
}
#region Tab pages handlers
internal ListBox GetCurrentListBox()
{
return GetListBox(MainTabControl.SelectedTab);
}
private ListBox GetListBox(TabPage page)
{
switch (page.TabIndex)
{
case 0:
return listEntities1;
case 1:
return listEntities2;
default:
return listEntities3;
}
}
internal List<AssociativeEntity> GetCurrentViewItems()
{
return GetViewItems(MainTabControl.SelectedTab);
}
private List<AssociativeEntity> GetViewItems(TabPage page)
{
switch (page.TabIndex)
{
case 0:
return View1;
case 1:
return View2;
default:
return View3;
}
}
internal PropertyGrid GetCurrentPropertyGrid()
{
return GetPropertyGrid(MainTabControl.SelectedTab);
}
private PropertyGrid GetPropertyGrid(TabPage page)
{
switch (page.TabIndex)
{
case 0:
return PropertyGrid1;
case 1:
return PropertyGrid2;
default:
return PropertyGrid3;
}
}
internal void SetAllPropertyGridSelectedObject(AssociativeEntity current)
{
SetPropertyGridSelectedObject(MainTabControl.TabPages[0], current);
SetPropertyGridSelectedObject(MainTabControl.TabPages[1], current);
SetPropertyGridSelectedObject(MainTabControl.TabPages[2], current);
}
private void SetPropertyGridSelectedObject(TabPage page, AssociativeEntity current)
{
switch (page.TabIndex)
{
case 0:
if (current != null)
{
listEntities1.SelectedItem = current;
PropertyGrid1.SelectedObject = new AssociativeEntityPropertyBag(current);
}
else
{
PropertyGrid1.SelectedObject = null;
}
break;
case 1:
if (current != null)
{
listEntities2.SelectedItem = current;
PropertyGrid2.SelectedObject = new AssociativeEntityPropertyBag(current);
}
else
{
PropertyGrid2.SelectedObject = null;
}
break;
default:
if (current != null)
{
listEntities3.SelectedItem = current;
PropertyGrid3.SelectedObject = new AssociativeEntityPropertyBag(current);
}
else
{
PropertyGrid3.SelectedObject = null;
}
break;
}
}
#endregion
public void RemoveSelected()
{
if (!UnitLoaded())
return;
// Suspend filter until it's done
_suspendFill = true;
// Don't restore SelectedItems
_restoreSelectedItems = false;
// What to delete
var deleteList = new List<AssociativeEntity>();
foreach (AssociativeEntity obj in GetCurrentListBox().SelectedItems)
deleteList.Add(obj);
// This is item above the top most selected item
var selectedIndex = GetCurrentListBox().SelectedIndex - 1;
// Now we don't need SelectedIndices any more (and they don't exist anyway)
GetCurrentListBox().SelectedIndices.Clear();
// Do delete
foreach (AssociativeEntity obj in deleteList)
_associativeEntities.Remove(obj);
// Now filter and get ListBox updated
_suspendFill = false;
FillViews(true);
// List is empty
if (GetCurrentListBox().Items.Count == 0)
return;
// Select the first element
if (selectedIndex == -1)
selectedIndex = 0;
switch (MainTabControl.TabIndex)
{
case 0:
_selectedItems1 = new List<AssociativeEntity>();
break;
case 1:
_selectedItems2 = new List<AssociativeEntity>();
break;
default:
_selectedItems3 = new List<AssociativeEntity>();
break;
}
GetCurrentListBox().SelectedIndices.Clear();
// Can't select past the end
if (selectedIndex > GetCurrentListBox().Items.Count - 1)
selectedIndex = GetCurrentListBox().Items.Count - 1;
GetCurrentListBox().SelectedIndex = selectedIndex;
var selectdObject = (AssociativeEntity)GetCurrentListBox().SelectedItem;
switch (MainTabControl.TabIndex)
{
case 0:
_selectedItems1.Add(selectdObject);
break;
case 1:
_selectedItems2.Add(selectdObject);
break;
default:
_selectedItems3.Add(selectdObject);
break;
}
// Now restore SelectedItems
_restoreSelectedItems = true;
FillViewsPresenter();
}
public void DuplicateSelected()
{
if (!UnitLoaded())
return;
var lst = new List<AssociativeEntity>();
foreach (AssociativeEntity obj in GetCurrentListBox().SelectedItems)
lst.Add(obj.Duplicate(GeneratorController.Catalog));
foreach (var obj in lst)
_associativeEntities.Add(obj);
}
public void AddNewObject()
{
if (!UnitLoaded())
return;
var newAssociativeEntity = new AssociativeEntity(GeneratorController.Current.CurrentUnit);
newAssociativeEntity.MainLazyLoad = false;
newAssociativeEntity.SecondaryLazyLoad = false;
_associativeEntities.Add(newAssociativeEntity);
}
private void MoveUpSelected()
{
if (!UnitLoaded())
return;
// Suspend filter until it's done
_suspendListUpdates = true;
DisableEventDrawItem();
var item = GetCurrentViewItems()[GetCurrentListBox().SelectedIndex];
var idx = _associativeEntities.IndexOf(item);
if (idx > 0)
{
_associativeEntities.RemoveAt(idx);
_associativeEntities.Insert(idx - 1, item);
}
// Now filter and get ListBox updated
_suspendListUpdates = false;
EnableEventDrawItem();
FillViews(true);
}
private void MoveDownSelected()
{
if (!UnitLoaded())
return;
// Suspend filter until it's done
_suspendListUpdates = true;
DisableEventDrawItem();
var item = GetCurrentViewItems()[GetCurrentListBox().SelectedIndex];
var idx = _associativeEntities.IndexOf(item);
if (idx < _associativeEntities.Count - 1)
{
_associativeEntities.RemoveAt(idx);
_associativeEntities.Insert(idx + 1, item);
}
// Now filter and get ListBox updated
_suspendListUpdates = false;
EnableEventDrawItem();
FillViews(true);
}
public void ValidateSelected(AssociativeEntity associativeEntity)
{
if (!UnitLoaded())
return;
var validationErrors = associativeEntity.Validate();
if (string.IsNullOrEmpty(validationErrors))
{
var msgBox = MessageBox.Show("Object relation \"" + associativeEntity.ObjectName + "\" is valid.\r\n\r\n" +
"Do you want to build/correct the CSLA objects?",
"Object relation validation", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (msgBox == DialogResult.Yes)
{
associativeEntity.Build();
}
}
else
MessageBox.Show(
"Object relation " + associativeEntity.ObjectName + " is invalid.\r\n" + validationErrors,
"Object relation validation", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ValidateAll()
{
if (!UnitLoaded())
return;
var associativeEntitiesCollection = GetCurrentViewItems();
foreach (var associativeEntity in associativeEntitiesCollection)
{
ValidateSelected(associativeEntity);
}
}
public void Add(CslaObjectInfo mainObject)
{
try
{
_associativeEntities.Add(mainObject);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Object Relations Builder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
MainTabControl.SelectTab(1);
listEntities2.SelectedItems.Clear();
listEntities2.SelectedItem = listEntities2.Items[listEntities2.Items.Count - 1];
}
public void Add(CslaObjectInfo mainObject, CslaObjectInfo secondaryObject)
{
try
{
_associativeEntities.Add(mainObject, secondaryObject);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Object Relations Builder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
MainTabControl.SelectTab(2);
listEntities3.SelectedItems.Clear();
listEntities3.SelectedItem = listEntities3.Items[listEntities3.Items.Count - 1];
}
private void DisableEventSelectedIndexChanged()
{
listEntities1.SelectedIndexChanged -= ListEntities1_SelectedIndexChanged;
listEntities2.SelectedIndexChanged -= ListEntities2_SelectedIndexChanged;
listEntities3.SelectedIndexChanged -= ListEntities3_SelectedIndexChanged;
}
private void EnableEventSelectedIndexChanged()
{
listEntities1.SelectedIndexChanged += ListEntities1_SelectedIndexChanged;
listEntities2.SelectedIndexChanged += ListEntities2_SelectedIndexChanged;
listEntities3.SelectedIndexChanged += ListEntities3_SelectedIndexChanged;
}
private void DisableEventDrawItem()
{
listEntities1.DrawItem -= ListEntities_DrawItem;
listEntities2.DrawItem -= ListEntities_DrawItem;
listEntities3.DrawItem -= ListEntities_DrawItem;
}
private void EnableEventDrawItem()
{
listEntities1.DrawItem += ListEntities_DrawItem;
listEntities2.DrawItem += ListEntities_DrawItem;
listEntities3.DrawItem += ListEntities_DrawItem;
}
#endregion
#region Manage state
internal void GetState()
{
TabPage tabPage = null;
AssociativeEntity selectObject = null;
foreach (var control in Controls)
{
if (control.GetType() == typeof (TabControl))
{
var tabControl = control as TabControl;
if (tabControl != null)
{
foreach (var subControl in tabControl.TabPages)
{
tabPage = subControl as TabPage;
if (tabPage != null && (tabPage.ContainsFocus || tabPage.Visible))
{
foreach (var subSubControl in tabPage.Controls)
{
if (subSubControl.GetType() == typeof (ListBox))
{
var listBox = subSubControl as ListBox;
if (listBox != null && listBox.SelectedItem != null && listBox.SelectedItem.GetType() == typeof(AssociativeEntity))
selectObject = listBox.SelectedItem as AssociativeEntity;
break;
}
}
break;
}
}
}
break;
}
}
if (tabPage != null)
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderTab = tabPage.Name;
else
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderTab = string.Empty;
if (selectObject != null)
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderSelectedObject = selectObject.ObjectName;
else
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderSelectedObject = string.Empty;
var propertyGrid = GetCurrentPropertyGrid();
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderPropertySort = propertyGrid.PropertySort;
if (propertyGrid.SelectedGridItem != null && propertyGrid.SelectedGridItem.PropertyDescriptor != null)
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderSelectedGridItem = propertyGrid.SelectedGridItem.PropertyDescriptor.Name;
if (propertyGrid.PropertySort != PropertySort.Alphabetical)
{
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderCollapsedCategories.Clear();
var root = propertyGrid.SelectedGridItem;
if (root != null)
{
while (root.Parent != null)
{
root = root.Parent;
}
foreach (var item in root.GridItems)
{
var gridItem = item as GridItem;
if (gridItem != null && !gridItem.Expanded)
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderCollapsedCategories.Add(
gridItem.Label);
}
}
}
}
internal void SetState()
{
foreach (var control in Controls)
{
if (control.GetType() == typeof(TabControl))
{
var tabControl = control as TabControl;
if (tabControl != null)
{
ScrollControlIntoView(tabControl);
tabControl.Visible = true;
tabControl.Focus();
for (var index = 0; index < tabControl.TabPages.Count; index++)
{
var tabPage = tabControl.TabPages[index];
if (tabPage.Name == GeneratorController.Current.CurrentUnitLayout.RelationsBuilderTab)
{
tabControl.SelectedIndex = index;
tabPage.Focus();
foreach (var subSubControl in tabPage.Controls)
{
if (subSubControl.GetType() == typeof(ListBox))
{
var listBox = subSubControl as ListBox;
if (listBox != null)
{
foreach (var item in listBox.Items)
{
var itemLine = item as AssociativeEntity;
if (itemLine != null && itemLine.ObjectName == GeneratorController.Current.CurrentUnitLayout.RelationsBuilderSelectedObject)
{
listBox.SelectedItems.Clear();
listBox.SelectedItems.Add(item);
break;
}
}
}
break;
}
}
break;
}
}
}
break;
}
}
var propertyGrid = GetCurrentPropertyGrid();
propertyGrid.PropertySort = GeneratorController.Current.CurrentUnitLayout.RelationsBuilderPropertySort;
var root = propertyGrid.SelectedGridItem;
if (root != null)
{
while (root.Parent != null)
{
root = root.Parent;
}
foreach (var item in root.GridItems)
{
var gridItem = item as GridItem;
if (gridItem != null)
{
gridItem.Expanded = !IsRelationBuilderCategoryCollapsed(gridItem.Label);
foreach (var subItem in gridItem.GridItems)
{
var subGridItem = subItem as GridItem;
if (subGridItem != null && subGridItem.PropertyDescriptor != null)
{
if (subGridItem.PropertyDescriptor.Name ==
GeneratorController.Current.CurrentUnitLayout.RelationsBuilderSelectedGridItem)
subGridItem.Select();
}
}
}
}
}
}
private static bool IsRelationBuilderCategoryCollapsed(string gridItem)
{
foreach (var category in GeneratorController.Current.CurrentUnitLayout.RelationsBuilderCollapsedCategories)
{
if (category == gridItem)
return true;
}
return false;
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System.ServiceModel.Administration;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.ServiceModel.Configuration;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Threading;
using System.Transactions;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Globalization;
[AttributeUsage(ServiceModelAttributeTargets.ServiceBehavior)]
public sealed class ServiceBehaviorAttribute : Attribute, IServiceBehavior
{
internal static IsolationLevel DefaultIsolationLevel = IsolationLevel.Unspecified;
ConcurrencyMode concurrencyMode = ConcurrencyMode.Single;
bool ensureOrderedDispatch = false;
string configurationName;
bool includeExceptionDetailInFaults = false;
InstanceContextMode instanceMode;
bool releaseServiceInstanceOnTransactionComplete = true;
bool releaseServiceInstanceOnTransactionCompleteSet = false;
bool transactionAutoCompleteOnSessionClose = false;
bool transactionAutoCompleteOnSessionCloseSet = false;
object wellKnownSingleton = null; // if the user passes an object to the ServiceHost, it is stored here
object hiddenSingleton = null; // if the user passes a type to the ServiceHost, and instanceMode==Single, we store the instance here
bool validateMustUnderstand = true;
bool ignoreExtensionDataObject = DataContractSerializerDefaults.IgnoreExtensionDataObject;
int maxItemsInObjectGraph = DataContractSerializerDefaults.MaxItemsInObjectGraph;
IsolationLevel transactionIsolationLevel = DefaultIsolationLevel;
bool isolationLevelSet = false;
bool automaticSessionShutdown = true;
IInstanceProvider instanceProvider = null;
TimeSpan transactionTimeout = TimeSpan.Zero;
string transactionTimeoutString;
bool transactionTimeoutSet = false;
bool useSynchronizationContext = true;
string serviceName = null;
string serviceNamespace = null;
AddressFilterMode addressFilterMode = AddressFilterMode.Exact;
[DefaultValue(null)]
public string Name
{
get { return serviceName; }
set { serviceName = value; }
}
[DefaultValue(null)]
public string Namespace
{
get { return serviceNamespace; }
set { serviceNamespace = value; }
}
internal IInstanceProvider InstanceProvider
{
set { this.instanceProvider = value; }
}
[DefaultValue(AddressFilterMode.Exact)]
public AddressFilterMode AddressFilterMode
{
get { return this.addressFilterMode; }
set
{
if (!AddressFilterModeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.addressFilterMode = value;
}
}
[DefaultValue(true)]
public bool AutomaticSessionShutdown
{
get { return this.automaticSessionShutdown; }
set { this.automaticSessionShutdown = value; }
}
[DefaultValue(null)]
public string ConfigurationName
{
get { return this.configurationName; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (value == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value",
SR.GetString(SR.SFxConfigurationNameCannotBeEmpty)));
}
this.configurationName = value;
}
}
public IsolationLevel TransactionIsolationLevel
{
get { return this.transactionIsolationLevel; }
set
{
switch (value)
{
case IsolationLevel.Serializable:
case IsolationLevel.RepeatableRead:
case IsolationLevel.ReadCommitted:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.Snapshot:
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.transactionIsolationLevel = value;
isolationLevelSet = true;
}
}
public bool ShouldSerializeTransactionIsolationLevel()
{
return IsolationLevelSet;
}
internal bool IsolationLevelSet
{
get { return this.isolationLevelSet; }
}
[DefaultValue(false)]
public bool IncludeExceptionDetailInFaults
{
get { return this.includeExceptionDetailInFaults; }
set { this.includeExceptionDetailInFaults = value; }
}
[DefaultValue(ConcurrencyMode.Single)]
public ConcurrencyMode ConcurrencyMode
{
get { return this.concurrencyMode; }
set
{
if (!ConcurrencyModeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.concurrencyMode = value;
}
}
[DefaultValue(false)]
public bool EnsureOrderedDispatch
{
get { return this.ensureOrderedDispatch; }
set { this.ensureOrderedDispatch = value; }
}
[DefaultValue(InstanceContextMode.PerSession)]
public InstanceContextMode InstanceContextMode
{
get { return this.instanceMode; }
set
{
if (!InstanceContextModeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.instanceMode = value;
}
}
public bool ReleaseServiceInstanceOnTransactionComplete
{
get { return releaseServiceInstanceOnTransactionComplete; }
set
{
this.releaseServiceInstanceOnTransactionComplete = value;
this.releaseServiceInstanceOnTransactionCompleteSet = true;
}
}
public bool ShouldSerializeConfigurationName()
{
return this.configurationName != null;
}
public bool ShouldSerializeReleaseServiceInstanceOnTransactionComplete()
{
return ReleaseServiceInstanceOnTransactionCompleteSet;
}
internal bool ReleaseServiceInstanceOnTransactionCompleteSet
{
get { return this.releaseServiceInstanceOnTransactionCompleteSet; }
}
public bool TransactionAutoCompleteOnSessionClose
{
get { return transactionAutoCompleteOnSessionClose; }
set
{
this.transactionAutoCompleteOnSessionClose = value;
this.transactionAutoCompleteOnSessionCloseSet = true;
}
}
public bool ShouldSerializeTransactionAutoCompleteOnSessionClose()
{
return TransactionAutoCompleteOnSessionCloseSet;
}
internal bool TransactionAutoCompleteOnSessionCloseSet
{
get { return this.transactionAutoCompleteOnSessionCloseSet; }
}
public string TransactionTimeout
{
get { return transactionTimeoutString; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
try
{
TimeSpan timeout = TimeSpan.Parse(value, CultureInfo.InvariantCulture);
if (timeout < TimeSpan.Zero)
{
string message = SR.GetString(SR.SFxTimeoutOutOfRange0);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, message));
}
this.transactionTimeout = timeout;
this.transactionTimeoutString = value;
this.transactionTimeoutSet = true;
}
catch (FormatException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SFxTimeoutInvalidStringFormat), "value", e));
}
catch (OverflowException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
}
}
public bool ShouldSerializeTransactionTimeout()
{
return TransactionTimeoutSet;
}
internal TimeSpan TransactionTimeoutTimespan
{
get { return this.transactionTimeout; }
}
internal bool TransactionTimeoutSet
{
get { return this.transactionTimeoutSet; }
}
[DefaultValue(true)]
public bool ValidateMustUnderstand
{
get { return validateMustUnderstand; }
set { validateMustUnderstand = value; }
}
[DefaultValue(DataContractSerializerDefaults.IgnoreExtensionDataObject)]
public bool IgnoreExtensionDataObject
{
get { return ignoreExtensionDataObject; }
set { ignoreExtensionDataObject = value; }
}
[DefaultValue(DataContractSerializerDefaults.MaxItemsInObjectGraph)]
public int MaxItemsInObjectGraph
{
get { return maxItemsInObjectGraph; }
set { maxItemsInObjectGraph = value; }
}
[DefaultValue(true)]
public bool UseSynchronizationContext
{
get { return this.useSynchronizationContext; }
set { this.useSynchronizationContext = value; }
}
public object GetWellKnownSingleton()
{
return this.wellKnownSingleton;
}
public void SetWellKnownSingleton(object value)
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
this.wellKnownSingleton = value;
}
internal object GetHiddenSingleton()
{
return this.hiddenSingleton;
}
internal void SetHiddenSingleton(object value)
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
this.hiddenSingleton = value;
}
[MethodImpl(MethodImplOptions.NoInlining)]
void SetIsolationLevel(ChannelDispatcher channelDispatcher)
{
if (channelDispatcher == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
channelDispatcher.TransactionIsolationLevel = this.transactionIsolationLevel;
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
if (this.concurrencyMode != ConcurrencyMode.Single && this.ensureOrderedDispatch)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNonConcurrentOrEnsureOrderedDispatch, description.Name)));
}
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
{
ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
if (channelDispatcher != null)
{
channelDispatcher.IncludeExceptionDetailInFaults = this.includeExceptionDetailInFaults;
if (channelDispatcher.HasApplicationEndpoints())
{
channelDispatcher.TransactionTimeout = transactionTimeout;
if (isolationLevelSet)
SetIsolationLevel(channelDispatcher);
foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
{
if (endpointDispatcher.IsSystemEndpoint)
{
continue;
}
DispatchRuntime behavior = endpointDispatcher.DispatchRuntime;
behavior.ConcurrencyMode = this.concurrencyMode;
behavior.EnsureOrderedDispatch = this.ensureOrderedDispatch;
behavior.ValidateMustUnderstand = validateMustUnderstand;
behavior.AutomaticInputSessionShutdown = this.automaticSessionShutdown;
behavior.TransactionAutoCompleteOnSessionClose = this.transactionAutoCompleteOnSessionClose;
behavior.ReleaseServiceInstanceOnTransactionComplete = this.releaseServiceInstanceOnTransactionComplete;
if (!this.useSynchronizationContext)
{
behavior.SynchronizationContext = null;
}
if (!endpointDispatcher.AddressFilterSetExplicit)
{
EndpointAddress address = endpointDispatcher.OriginalAddress;
if (address == null || this.AddressFilterMode == AddressFilterMode.Any)
{
endpointDispatcher.AddressFilter = new MatchAllMessageFilter();
}
else if (this.AddressFilterMode == AddressFilterMode.Prefix)
{
endpointDispatcher.AddressFilter = new PrefixEndpointAddressMessageFilter(address);
}
else if (this.AddressFilterMode == AddressFilterMode.Exact)
{
endpointDispatcher.AddressFilter = new EndpointAddressMessageFilter(address);
}
}
}
}
#pragma warning suppress 56506
}
}
DataContractSerializerServiceBehavior.ApplySerializationSettings(description, ignoreExtensionDataObject, maxItemsInObjectGraph);
ApplyInstancing(description, serviceHostBase);
}
void ApplyInstancing(ServiceDescription description, ServiceHostBase serviceHostBase)
{
Type serviceType = description.ServiceType;
InstanceContext singleton = null;
for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
{
ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
if (channelDispatcher != null)
{
foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
{
if (endpointDispatcher.IsSystemEndpoint)
{
continue;
}
DispatchRuntime dispatch = endpointDispatcher.DispatchRuntime;
if (dispatch.InstanceProvider == null)
{
if (instanceProvider == null)
{
if (serviceType == null && this.wellKnownSingleton == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InstanceSettingsMustHaveTypeOrWellKnownObject0)));
if (this.instanceMode != InstanceContextMode.Single && this.wellKnownSingleton != null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxWellKnownNonSingleton0)));
}
else
{
dispatch.InstanceProvider = instanceProvider;
}
}
dispatch.Type = serviceType;
dispatch.InstanceContextProvider = InstanceContextProviderBase.GetProviderForMode(this.instanceMode, dispatch);
if ((this.instanceMode == InstanceContextMode.Single) &&
(dispatch.SingletonInstanceContext == null))
{
if (singleton == null)
{
if (this.wellKnownSingleton != null)
{
singleton = new InstanceContext(serviceHostBase, this.wellKnownSingleton, true, false);
}
else if (this.hiddenSingleton != null)
{
singleton = new InstanceContext(serviceHostBase, this.hiddenSingleton, false, false);
}
else
{
singleton = new InstanceContext(serviceHostBase, false);
}
singleton.AutoClose = false;
}
dispatch.SingletonInstanceContext = singleton;
}
}
}
}
}
}
}
| |
// 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.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Localisation;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Screens.Edit;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
{
/// <summary>
/// A visualisation of a single <see cref="PathControlPoint"/> in a <see cref="Slider"/>.
/// </summary>
public class PathControlPointPiece : BlueprintPiece<Slider>, IHasTooltip
{
public Action<PathControlPointPiece, MouseButtonEvent> RequestSelection;
public List<PathControlPoint> PointsInSegment;
public readonly BindableBool IsSelected = new BindableBool();
public readonly PathControlPoint ControlPoint;
private readonly Slider slider;
private readonly Container marker;
private readonly Drawable markerRing;
[Resolved(CanBeNull = true)]
private IEditorChangeHandler changeHandler { get; set; }
[Resolved(CanBeNull = true)]
private IPositionSnapProvider snapProvider { get; set; }
[Resolved]
private OsuColour colours { get; set; }
private IBindable<Vector2> sliderPosition;
private IBindable<float> sliderScale;
public PathControlPointPiece(Slider slider, PathControlPoint controlPoint)
{
this.slider = slider;
ControlPoint = controlPoint;
// we don't want to run the path type update on construction as it may inadvertently change the slider.
cachePoints(slider);
slider.Path.Version.BindValueChanged(_ =>
{
cachePoints(slider);
updatePathType();
});
controlPoint.Changed += updateMarkerDisplay;
Origin = Anchor.Centre;
AutoSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
marker = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Children = new[]
{
new Circle
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(20),
},
markerRing = new CircularContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(28),
Masking = true,
BorderThickness = 2,
BorderColour = Color4.White,
Alpha = 0,
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
AlwaysPresent = true
}
}
}
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
sliderPosition = slider.PositionBindable.GetBoundCopy();
sliderPosition.BindValueChanged(_ => updateMarkerDisplay());
sliderScale = slider.ScaleBindable.GetBoundCopy();
sliderScale.BindValueChanged(_ => updateMarkerDisplay());
IsSelected.BindValueChanged(_ => updateMarkerDisplay());
updateMarkerDisplay();
}
// The connecting path is excluded from positional input
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => marker.ReceivePositionalInputAt(screenSpacePos);
protected override bool OnHover(HoverEvent e)
{
updateMarkerDisplay();
return false;
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateMarkerDisplay();
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (RequestSelection == null)
return false;
switch (e.Button)
{
case MouseButton.Left:
RequestSelection.Invoke(this, e);
return true;
case MouseButton.Right:
if (!IsSelected.Value)
RequestSelection.Invoke(this, e);
return false; // Allow context menu to show
}
return false;
}
protected override bool OnClick(ClickEvent e) => RequestSelection != null;
private Vector2 dragStartPosition;
private PathType? dragPathType;
protected override bool OnDragStart(DragStartEvent e)
{
if (RequestSelection == null)
return false;
if (e.Button == MouseButton.Left)
{
dragStartPosition = ControlPoint.Position;
dragPathType = PointsInSegment[0].Type;
changeHandler?.BeginChange();
return true;
}
return false;
}
protected override void OnDrag(DragEvent e)
{
Vector2[] oldControlPoints = slider.Path.ControlPoints.Select(cp => cp.Position).ToArray();
var oldPosition = slider.Position;
double oldStartTime = slider.StartTime;
if (ControlPoint == slider.Path.ControlPoints[0])
{
// Special handling for the head control point - the position of the slider changes which means the snapped position and time have to be taken into account
var result = snapProvider?.SnapScreenSpacePositionToValidTime(e.ScreenSpaceMousePosition);
Vector2 movementDelta = Parent.ToLocalSpace(result?.ScreenSpacePosition ?? e.ScreenSpaceMousePosition) - slider.Position;
slider.Position += movementDelta;
slider.StartTime = result?.Time ?? slider.StartTime;
// Since control points are relative to the position of the slider, they all need to be offset backwards by the delta
for (int i = 1; i < slider.Path.ControlPoints.Count; i++)
slider.Path.ControlPoints[i].Position -= movementDelta;
}
else
ControlPoint.Position = dragStartPosition + (e.MousePosition - e.MouseDownPosition);
if (!slider.Path.HasValidLength)
{
for (int i = 0; i < slider.Path.ControlPoints.Count; i++)
slider.Path.ControlPoints[i].Position = oldControlPoints[i];
slider.Position = oldPosition;
slider.StartTime = oldStartTime;
return;
}
// Maintain the path type in case it got defaulted to bezier at some point during the drag.
PointsInSegment[0].Type = dragPathType;
}
protected override void OnDragEnd(DragEndEvent e) => changeHandler?.EndChange();
private void cachePoints(Slider slider) => PointsInSegment = slider.Path.PointsInSegment(ControlPoint);
/// <summary>
/// Handles correction of invalid path types.
/// </summary>
private void updatePathType()
{
if (ControlPoint.Type != PathType.PerfectCurve)
return;
if (PointsInSegment.Count > 3)
ControlPoint.Type = PathType.Bezier;
if (PointsInSegment.Count != 3)
return;
ReadOnlySpan<Vector2> points = PointsInSegment.Select(p => p.Position).ToArray();
RectangleF boundingBox = PathApproximator.CircularArcBoundingBox(points);
if (boundingBox.Width >= 640 || boundingBox.Height >= 480)
ControlPoint.Type = PathType.Bezier;
}
/// <summary>
/// Updates the state of the circular control point marker.
/// </summary>
private void updateMarkerDisplay()
{
Position = slider.StackedPosition + ControlPoint.Position;
markerRing.Alpha = IsSelected.Value ? 1 : 0;
Color4 colour = getColourFromNodeType();
if (IsHovered || IsSelected.Value)
colour = colour.Lighten(1);
marker.Colour = colour;
marker.Scale = new Vector2(slider.Scale);
}
private Color4 getColourFromNodeType()
{
if (!(ControlPoint.Type is PathType pathType))
return colours.Yellow;
switch (pathType)
{
case PathType.Catmull:
return colours.Seafoam;
case PathType.Bezier:
return colours.Pink;
case PathType.PerfectCurve:
return colours.PurpleDark;
default:
return colours.Red;
}
}
public LocalisableString TooltipText => ControlPoint.Type.ToString() ?? string.Empty;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndNotInt64()
{
var test = new SimpleBinaryOpTest__AndNotInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotInt64
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data1 = new Int64[ElementCount];
private static Int64[] _data2 = new Int64[ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64> _dataTable;
static SimpleBinaryOpTest__AndNotInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.AndNot(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.AndNot(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotInt64();
var result = Avx2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
if ((long)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((long)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<Int64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.IO;
using System.IO.Ports;
using System.Collections;
using System.Threading;
namespace ES.Software.Arduino_Windows_Client
{
/// <summary> CommPort class creates a singleton instance
/// of SerialPort (System.IO.Ports) </summary>
/// <remarks> When ready, you open the port.
/// <code>
/// CommPort com = CommPort.Instance;
/// com.StatusChanged += OnStatusChanged;
/// com.DataReceived += OnDataReceived;
/// com.Open();
/// </code>
/// Notice that delegates are used to handle status and data events.
/// When settings are changed, you close and reopen the port.
/// <code>
/// CommPort com = CommPort.Instance;
/// com.Close();
/// com.PortName = "COM4";
/// com.Open();
/// </code>
/// </remarks>
public sealed class CommPort
{
SerialPort _serialPort;
Thread _readThread;
volatile bool _keepReading;
//begin Singleton pattern
static readonly CommPort instance = new CommPort();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static CommPort()
{
}
CommPort()
{
_serialPort = new SerialPort();
_readThread = null;
_keepReading = false;
}
public static CommPort Instance
{
get
{
return instance;
}
}
//end Singleton pattern
//begin Observer pattern
public delegate void EventHandler(string param);
public EventHandler StatusChanged;
public EventHandler DataReceived;
//end Observer pattern
private void StartReading()
{
if (!_keepReading)
{
_keepReading = true;
_readThread = new Thread(ReadPort);
_readThread.Start();
}
}
private void StopReading()
{
if (_keepReading)
{
_keepReading = false;
_readThread.Join(); //block until exits
_readThread = null;
}
}
/// <summary> Get the data and pass it on. </summary>
private void ReadPort()
{
while (_keepReading)
{
if (IsOpenCatched() /*_serialPort.IsOpen*/)
{
byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
try
{
// If there are bytes available on the serial port,
// Read returns up to "count" bytes, but will not block (wait)
// for the remaining bytes. If there are no bytes available
// on the serial port, Read will block until at least one byte
// is available on the port, up until the ReadTimeout milliseconds
// have elapsed, at which time a TimeoutException will be thrown.
int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);
DataReceived(SerialIn);
}
catch (TimeoutException) { }
catch (IOException) { Close(); }
catch (UnauthorizedAccessException) { Close(); }
}
else
{
TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
Thread.Sleep(waitTime);
}
}
}
/// <summary> Open the serial port with current settings. </summary>
public void Open()
{
Close();
try
{
_serialPort.PortName = Settings.Port.PortName;
_serialPort.BaudRate = Settings.Port.BaudRate;
_serialPort.Parity = Settings.Port.Parity;
_serialPort.DataBits = Settings.Port.DataBits;
_serialPort.StopBits = Settings.Port.StopBits;
_serialPort.Handshake = Settings.Port.Handshake;
// Set the read/write timeouts
_serialPort.ReadTimeout = 50;
_serialPort.WriteTimeout = 50;
_serialPort.Open();
StartReading();
}
catch (IOException)
{
StatusChanged("Open: " + String.Format("{0} does not exist", Settings.Port.PortName));
}
catch (UnauthorizedAccessException)
{
StatusChanged("Open: " + String.Format("{0} already in use", Settings.Port.PortName));
}
catch (Exception ex)
{
StatusChanged("Open: " + String.Format("{0}", ex.ToString()));
}
try
{
// Update the status
if (_serialPort.IsOpen)
{
string p = _serialPort.Parity.ToString().Substring(0, 1); //First char
string h = _serialPort.Handshake.ToString();
if (_serialPort.Handshake == Handshake.None)
h = "no handshake"; // more descriptive than "None"
StatusChanged(String.Format("{0}: {1} bps, {2}{3}{4}, {5}",
_serialPort.PortName, _serialPort.BaudRate,
_serialPort.DataBits, p, (int)_serialPort.StopBits, h));
}
else
{
StatusChanged(String.Format("{0} already in use", Settings.Port.PortName));
}
}
catch (IOException)
{
StatusChanged("Status: " + String.Format("{0} does not exist", Settings.Port.PortName));
}
catch (UnauthorizedAccessException)
{
StatusChanged("Status: " + String.Format("{0} already in use", Settings.Port.PortName));
}
catch (Exception ex)
{
StatusChanged("Status: " + String.Format("{0}", ex.ToString()));
}
}
/// <summary> Close the serial port. </summary>
public void Close()
{
try
{
StopReading();
_serialPort.Close();
StatusChanged("connection closed");
}
catch (IOException)
{
StatusChanged("Close: " + String.Format("{0} does not exist", Settings.Port.PortName));
}
catch (UnauthorizedAccessException)
{
StatusChanged("Close: " + String.Format("{0} already in use", Settings.Port.PortName));
}
catch (Exception ex)
{
StatusChanged("Close: " + String.Format("{0}", ex.ToString()));
}
}
/// <summary> Get the status of the serial port. </summary>
public bool IsOpen
{
get
{
return IsOpenCatched(); // _serialPort.IsOpen;
}
}
private bool IsOpenCatched()
{
try
{
return _serialPort.IsOpen;
}
catch
{
}
return false;
}
/// <summary> Get a list of the available ports. Already opened ports
/// are not returend. </summary>
public string[] GetAvailablePorts()
{
return SerialPort.GetPortNames();
}
/// <summary>Send data to the serial port after appending line ending. </summary>
/// <param name="data">An string containing the data to send. </param>
public void Send(string data)
{
try
{
if (IsOpen)
{
string lineEnding = "";
switch (Settings.Option.AppendToSend)
{
case Settings.Option.AppendType.AppendCR:
lineEnding = "\r"; break;
case Settings.Option.AppendType.AppendLF:
lineEnding = "\n"; break;
case Settings.Option.AppendType.AppendCRLF:
lineEnding = "\r\n"; break;
}
_serialPort.Write(data + lineEnding);
}
}
catch (IOException)
{
StatusChanged("Send: " + String.Format("{0} does not exist", Settings.Port.PortName));
}
catch (UnauthorizedAccessException)
{
StatusChanged("Send: " + String.Format("{0} already in use", Settings.Port.PortName));
}
catch (Exception ex)
{
StatusChanged("Send: " + String.Format("{0}", ex.ToString()));
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace CocosSharp
{
public enum CCTableViewVerticalFillOrder
{
FillTopDown,
FillBottomUp
};
// Sole purpose of this delegate is to single touch event in this version.
public interface ICCTableViewDelegate : ICCScrollViewDelegate
{
/**
* Delegate to respond touch event
*
* @param table table contains the given cell
* @param cell cell that is touched
*/
void TableCellTouched(CCTableView table, CCTableViewCell cell);
/**
* Delegate to respond a table cell press event.
*
* @param table table contains the given cell
* @param cell cell that is pressed
*/
void TableCellHighlight(CCTableView table, CCTableViewCell cell);
/**
* Delegate to respond a table cell release event
*
* @param table table contains the given cell
* @param cell cell that is pressed
*/
void TableCellUnhighlight(CCTableView table, CCTableViewCell cell);
/**
* Delegate called when the cell is about to be recycled. Immediately
* after this call the cell will be removed from the scene graph and
* recycled.
*
* @param table table contains the given cell
* @param cell cell that is pressed
*/
void TableCellWillRecycle(CCTableView table, CCTableViewCell cell);
}
/**
* Data source that governs table backend data.
*/
public interface ICCTableViewDataSource
{
/**
* cell height for a given table.
*
* @param table table to hold the instances of Class
* @return cell size
*/
CCSize TableCellSizeForIndex(CCTableView table, int idx);
/**
* a cell instance at a given index
*
* @param idx index to search for a cell
* @return cell found at idx
*/
CCTableViewCell TableCellAtIndex(CCTableView table, int idx);
/**
* Returns number of cells in a given table view.
*
* @return number of cells
*/
int NumberOfCellsInTableView(CCTableView table);
};
/**
* UITableView counterpart for cocos2d for iphone.
*
* this is a very basic, minimal implementation to bring UITableView-like component into cocos2d world.
*
*/
public class CCTableView : CCScrollView, ICCScrollViewDelegate
{
CCTableViewCell touchedCell;
CCTableViewVerticalFillOrder vordering;
CCArrayForObjectSorting cellsUsed;
CCArrayForObjectSorting cellsFreed;
CCScrollViewDirection oldDirection;
List<int> indices;
List<float> cellsPositions;
#region Properties
public ICCTableViewDataSource DataSource { get; set; }
public new ICCTableViewDelegate Delegate { get; set; }
// Determines how cell is ordered and filled in the view.
public CCTableViewVerticalFillOrder VerticalFillOrder
{
get { return vordering; }
set
{
if (vordering != value)
{
vordering = value;
if (cellsUsed.Count > 0)
{
ReloadData();
}
}
}
}
#endregion Properties
#region Constructors
public CCTableView()
{
oldDirection = CCScrollViewDirection.None;
}
public CCTableView(ICCTableViewDataSource dataSource, CCSize size)
: this(dataSource, size, null)
{
}
public CCTableView(ICCTableViewDataSource dataSource, CCSize size, CCNode container) : base(size, container)
{
cellsPositions = new List<float>();
cellsUsed = new CCArrayForObjectSorting();
cellsFreed = new CCArrayForObjectSorting();
indices = new List<int>();
vordering = CCTableViewVerticalFillOrder.FillBottomUp;
Direction = CCScrollViewDirection.Vertical;
base.Delegate = this;
DataSource = dataSource;
UpdateCellPositions();
UpdateContentSize();
}
#endregion Constructors
// reloads data from data source. the view will be refreshed.
public void ReloadData()
{
oldDirection = CCScrollViewDirection.None;
foreach (CCTableViewCell cell in cellsUsed)
{
if (Delegate != null)
{
Delegate.TableCellWillRecycle(this, cell);
}
cellsFreed.Add(cell);
cell.Reset();
if (cell.Parent == Container)
{
Container.RemoveChild(cell, true);
}
}
indices.Clear();
cellsUsed = new CCArrayForObjectSorting();
UpdateCellPositions();
UpdateContentSize();
if (DataSource.NumberOfCellsInTableView(this) > 0)
{
ScrollViewDidScroll(this);
}
}
#region Cell management
/**
* Returns an existing cell at a given index. Returns nil if a cell is nonexistent at the moment of query.
*
* @param idx index
* @return a cell at a given index
*/
public CCTableViewCell CellAtIndex(int idx)
{
CCTableViewCell found = null;
if (indices.Contains(idx))
{
found = (CCTableViewCell)cellsUsed.ObjectWithObjectID(idx);
}
return found;
}
/**
* Updates the content of the cell at a given index.
*
* @param idx index to find a cell
*/
public void UpdateCellAtIndex(int idx)
{
if (idx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
return;
}
var uCountOfItems = DataSource.NumberOfCellsInTableView(this);
if (uCountOfItems == 0 || idx > uCountOfItems - 1)
{
return;
}
var cell = CellAtIndex(idx);
if (cell != null)
{
MoveCellOutOfSight(cell);
}
cell = DataSource.TableCellAtIndex(this, idx);
SetIndexForCell(idx, cell);
AddCellIfNecessary(cell);
}
/**
* Removes a cell at a given index
*
* @param idx index to find a cell
*/
public void RemoveCellAtIndex(int idx)
{
if (idx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
return;
}
var uCountOfItems = DataSource.NumberOfCellsInTableView(this);
if (uCountOfItems == 0 || idx > uCountOfItems - 1)
{
return;
}
int newIdx;
CCTableViewCell cell = CellAtIndex(idx);
if (cell == null)
{
return;
}
newIdx = cellsUsed.IndexOfSortedObject(cell);
//remove first
MoveCellOutOfSight(cell);
indices.Remove(idx);
// [indices shiftIndexesStartingAtIndex:idx+1 by:-1];
for (int i = cellsUsed.Count - 1; i > newIdx; i--)
{
cell = (CCTableViewCell)cellsUsed[i];
SetIndexForCell(cell.Index - 1, cell);
}
}
/**
* Dequeues a free cell if available. nil if not.
*
* @return free cell
*/
public CCTableViewCell DequeueCell()
{
CCTableViewCell cell;
if (cellsFreed.Count == 0)
{
cell = null;
}
else
{
cell = (CCTableViewCell)cellsFreed[0];
cellsFreed.RemoveAt(0);
}
return cell;
}
void AddCellIfNecessary(CCTableViewCell cell)
{
if (cell.Parent != Container)
{
Container.AddChild(cell);
}
cellsUsed.InsertSortedObject(cell);
indices.Add(cell.Index);
}
void MoveCellOutOfSight(CCTableViewCell cell)
{
if (Delegate != null)
{
Delegate.TableCellWillRecycle(this, cell);
}
cellsFreed.Add(cell);
cellsUsed.RemoveSortedObject(cell);
indices.Remove(cell.Index);
cell.Reset();
if (cell.Parent == Container)
{
Container.RemoveChild(cell, true);
}
}
void SetIndexForCell(int index, CCTableViewCell cell)
{
cell.AnchorPoint = CCPoint.Zero;
cell.Position = OffsetFromIndex(index);
cell.Index = index;
}
void UpdateCellPositions()
{
int cellsCount = DataSource.NumberOfCellsInTableView(this);
cellsPositions.Clear();
if (cellsCount > 0)
{
float currentPos = 0;
CCSize cellSize;
for (int i=0; i < cellsCount; i++)
{
cellsPositions.Add(currentPos);
cellSize = DataSource.TableCellSizeForIndex(this, i);
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
currentPos += cellSize.Width;
break;
default:
currentPos += cellSize.Height;
break;
}
}
cellsPositions.Add(currentPos);//1 extra value allows us to get right/bottom of the last cell
}
}
#endregion Cell management
void UpdateContentSize()
{
CCSize size = CCSize.Zero;
int cellsCount = DataSource.NumberOfCellsInTableView(this);
if (cellsCount > 0)
{
float maxPosition = cellsPositions[cellsCount];
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
size = new CCSize(maxPosition, ViewSize.Height);
break;
default:
size = new CCSize(ViewSize.Width, maxPosition);
break;
}
}
ContentSize = size;
if (oldDirection != Direction)
{
if (Direction == CCScrollViewDirection.Horizontal)
{
SetContentOffset(CCPoint.Zero);
}
else
{
SetContentOffset(new CCPoint(0, MinContainerOffset.Y));
}
oldDirection = Direction;
}
}
CCPoint OffsetFromIndex(int index)
{
CCPoint offset;
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
offset = new CCPoint(cellsPositions[index], 0.0f);
break;
default:
offset = new CCPoint(0.0f, cellsPositions[index]);
break;
}
CCSize cellSize = DataSource.TableCellSizeForIndex(this, index);
if (vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y = Container.ContentSize.Height - offset.Y - cellSize.Height;
}
return offset;
}
int IndexFromOffset(CCPoint offset)
{
int index = 0;
int maxIdx = DataSource.NumberOfCellsInTableView(this) - 1;
if (vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y = Container.ContentSize.Height - offset.Y;
}
index = PrimitiveIndexFromOffset(offset);
if (index != -1)
{
index = Math.Max(0, index);
if (index > maxIdx)
{
index = CCArrayForObjectSorting.CC_INVALID_INDEX;
}
}
return index;
}
int PrimitiveIndexFromOffset(CCPoint offset)
{
int low = 0;
int high = DataSource.NumberOfCellsInTableView(this) - 1;
float search;
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
search = offset.X;
break;
default:
search = offset.Y;
break;
}
while (high >= low)
{
int index = low + (high - low) / 2;
float cellStart = cellsPositions[index];
float cellEnd = cellsPositions[index + 1];
if (search >= cellStart && search <= cellEnd)
{
return index;
}
else if (search < cellStart)
{
high = index - 1;
}
else
{
low = index + 1;
}
}
if (low <= 0)
{
return 0;
}
return -1;
}
#region CCScrollViewDelegate Members
public virtual void ScrollViewDidScroll(CCScrollView view)
{
var uCountOfItems = DataSource.NumberOfCellsInTableView(this);
if (uCountOfItems == 0)
{
return;
}
if (Delegate != null)
{
Delegate.ScrollViewDidScroll(this);
}
int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;
CCPoint offset = ContentOffset * -1;
maxIdx = Math.Max(uCountOfItems - 1, 0);
if (vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y = offset.Y + ViewSize.Height / Container.ScaleY;
}
startIdx = IndexFromOffset(offset);
if (startIdx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
startIdx = uCountOfItems - 1;
}
if (vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y -= ViewSize.Height / Container.ScaleY;
}
else
{
offset.Y += ViewSize.Height / Container.ScaleY;
}
offset.X += ViewSize.Width / Container.ScaleX;
endIdx = IndexFromOffset(offset);
if (endIdx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
endIdx = uCountOfItems - 1;
}
#if DEBUG_ // For Testing.
int i = 0;
foreach (object pObj in cellsUsed)
{
var pCell = (CCTableViewCell)pObj;
CCLog.Log("cells Used index {0}, value = {1}", i, pCell.getIdx());
i++;
}
CCLog.Log("---------------------------------------");
i = 0;
foreach(object pObj in cellsFreed)
{
var pCell = (CCTableViewCell)pObj;
CCLog.Log("cells freed index {0}, value = {1}", i, pCell.getIdx());
i++;
}
CCLog.Log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
#endif
if (cellsUsed.Count > 0)
{
var cell = (CCTableViewCell) cellsUsed[0];
idx = cell.Index;
while (idx < startIdx)
{
MoveCellOutOfSight(cell);
if (cellsUsed.Count > 0)
{
cell = (CCTableViewCell) cellsUsed[0];
idx = cell.Index;
}
else
{
break;
}
}
}
if (cellsUsed.Count > 0)
{
var cell = (CCTableViewCell) cellsUsed[cellsUsed.Count - 1];
idx = cell.Index;
while (idx <= maxIdx && idx > endIdx)
{
MoveCellOutOfSight(cell);
if (cellsUsed.Count > 0)
{
cell = (CCTableViewCell) cellsUsed[cellsUsed.Count - 1];
idx = cell.Index;
}
else
{
break;
}
}
}
for (int i = startIdx; i <= endIdx; i++)
{
if (indices.Contains(i))
{
continue;
}
UpdateCellAtIndex(i);
}
}
public virtual void ScrollViewDidZoom(CCScrollView view)
{
}
#endregion
#region Event handling
public void TouchEnded(CCTouch pTouch)
{
if (!Visible)
{
return;
}
if (touchedCell != null)
{
CCRect bb = BoundingBox;
if (bb.ContainsPoint(Layer.ScreenToWorldspace(pTouch.LocationOnScreen)) && Delegate != null)
{
Delegate.TableCellUnhighlight(this, touchedCell);
Delegate.TableCellTouched(this, touchedCell);
}
touchedCell = null;
}
}
// public bool TouchBegan(CCTouch pTouch)
// {
// if (!Visible)
// {
// return false;
// }
//
// //bool touchResult = base.TouchBegan(pTouch);
//
// if (_touches.Count == 1)
// {
// var point = Container.ConvertTouchToNodeSpace(pTouch);
// var index = IndexFromOffset(point);
// if (index == CCArrayForObjectSorting.CC_INVALID_INDEX)
// {
// touchedCell = null;
// }
// else
// {
// touchedCell = CellAtIndex(index);
// }
//
// if (touchedCell != null && Delegate != null)
// {
// Delegate.TableCellHighlight(this, touchedCell);
// }
// }
// else if (touchedCell != null)
// {
// if (Delegate != null)
// {
// Delegate.TableCellUnhighlight(this, touchedCell);
// }
//
// touchedCell = null;
// }
//
// return touchResult;
// }
//
// public void TouchMoved(CCTouch touch)
// {
// base.TouchMoved(touch);
//
// if (touchedCell != null && IsTouchMoved)
// {
// if (Delegate != null)
// {
// Delegate.TableCellUnhighlight(this, touchedCell);
// }
//
// touchedCell = null;
// }
// }
//
// public void TouchCancelled(CCTouch touch)
// {
// base.TouchCancelled(touch);
//
// if (touchedCell != null)
// {
// if (Delegate != null)
// {
// Delegate.TableCellUnhighlight(this, touchedCell);
// }
//
// touchedCell = null;
// }
// }
#endregion Event handling
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Runtime.Serialization;
namespace MsgPack.Serialization.CollectionSerializers
{
/// <summary>
/// Provides basic features for non-dictionary non-generic collection serializers.
/// </summary>
/// <typeparam name="TCollection">The type of the collection.</typeparam>
/// <remarks>
/// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility.
/// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>.
/// </remarks>
public abstract class NonGenericEnumerableMessagePackSerializerBase<TCollection> : MessagePackSerializer<TCollection>, ICollectionInstanceFactory
where TCollection : IEnumerable
{
private readonly IMessagePackSingleObjectSerializer _itemSerializer;
internal IMessagePackSingleObjectSerializer ItemSerializer { get { return this._itemSerializer; } }
/// <summary>
/// Initializes a new instance of the <see cref="NonGenericEnumerableMessagePackSerializerBase{TCollection}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )]
protected NonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema )
: base( ownerContext )
{
this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema );
}
/// <summary>
/// Creates a new collection instance with specified initial capacity.
/// </summary>
/// <param name="initialCapacity">
/// The initial capacy of creating collection.
/// Note that this parameter may <c>0</c> for non-empty collection.
/// </param>
/// <returns>
/// New collection instance. This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format,
/// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count.
/// For example, JSON unpacker cannot supply collection items count efficiently.
/// </remarks>
/// <seealso cref="ICollectionInstanceFactory.CreateInstance"/>
protected abstract TCollection CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TCollection"/> is not collection.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods",
MessageId = "0", Justification = "By design" )]
protected internal sealed override void UnpackToCore( Unpacker unpacker, TCollection collection )
{
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
internal void UnpackToCore( Unpacker unpacker, TCollection collection, int itemsCount )
{
for ( var i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
object item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = this._itemSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
item = this._itemSerializer.UnpackFrom( subtreeUnpacker );
}
}
this.AddItem( collection, item );
}
}
/// <summary>
/// When implemented by derive class,
/// adds the deserialized item to the collection on <typeparamref name="TCollection"/> specific manner
/// to implement <see cref="UnpackToCore(Unpacker,TCollection)"/>.
/// </summary>
/// <param name="collection">The collection to be added.</param>
/// <param name="item">The item to be added.</param>
/// <exception cref="NotSupportedException">
/// This implementation always throws it.
/// </exception>
protected virtual void AddItem( TCollection collection, object item )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TCollection ), null );
}
}
#if UNITY
internal abstract class UnityNonGenericEnumerableMessagePackSerializerBase : NonGenericMessagePackSerializer, ICollectionInstanceFactory
{
private readonly IMessagePackSingleObjectSerializer _itemSerializer;
internal IMessagePackSingleObjectSerializer ItemSerializer { get { return this._itemSerializer; } }
protected UnityNonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema )
: base( ownerContext, targetType )
{
this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema );
}
protected abstract object CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
protected internal sealed override void UnpackToCore( Unpacker unpacker, object collection )
{
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
internal void UnpackToCore( Unpacker unpacker, object collection, int itemsCount )
{
for ( var i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
object item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = this._itemSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
item = this._itemSerializer.UnpackFrom( subtreeUnpacker );
}
}
this.AddItem( collection, item );
}
}
protected virtual void AddItem( object collection, object item )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( this.TargetType, null );
}
}
#endif // UNITY
}
| |
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
// [START program]
// The Stigler diet problem.
// [START import]
using System;
using System.Collections.Generic;
using Google.OrTools.LinearSolver;
// [END import]
public class StiglerDiet
{
static void Main()
{
// [START data_model]
// Nutrient minimums.
(String Name, double Value)[] nutrients =
new[] { ("Calories (kcal)", 3.0), ("Protein (g)", 70.0), ("Calcium (g)", 0.8),
("Iron (mg)", 12.0), ("Vitamin A (kIU)", 5.0), ("Vitamin B1 (mg)", 1.8),
("Vitamin B2 (mg)", 2.7), ("Niacin (mg)", 18.0), ("Vitamin C (mg)", 75.0) };
(String Name, String Unit, double Price, double[] Nutrients)[] data = new[] {
("Wheat Flour (Enriched)", "10 lb.", 36, new double[] { 44.7, 1411, 2, 365, 0, 55.4, 33.3, 441, 0 }),
("Macaroni", "1 lb.", 14.1, new double[] { 11.6, 418, 0.7, 54, 0, 3.2, 1.9, 68, 0 }),
("Wheat Cereal (Enriched)", "28 oz.", 24.2, new double[] { 11.8, 377, 14.4, 175, 0, 14.4, 8.8, 114, 0 }),
("Corn Flakes", "8 oz.", 7.1, new double[] { 11.4, 252, 0.1, 56, 0, 13.5, 2.3, 68, 0 }),
("Corn Meal", "1 lb.", 4.6, new double[] { 36.0, 897, 1.7, 99, 30.9, 17.4, 7.9, 106, 0 }),
("Hominy Grits", "24 oz.", 8.5, new double[] { 28.6, 680, 0.8, 80, 0, 10.6, 1.6, 110, 0 }),
("Rice", "1 lb.", 7.5, new double[] { 21.2, 460, 0.6, 41, 0, 2, 4.8, 60, 0 }),
("Rolled Oats", "1 lb.", 7.1, new double[] { 25.3, 907, 5.1, 341, 0, 37.1, 8.9, 64, 0 }),
("White Bread (Enriched)", "1 lb.", 7.9, new double[] { 15.0, 488, 2.5, 115, 0, 13.8, 8.5, 126, 0 }),
("Whole Wheat Bread", "1 lb.", 9.1, new double[] { 12.2, 484, 2.7, 125, 0, 13.9, 6.4, 160, 0 }),
("Rye Bread", "1 lb.", 9.1, new double[] { 12.4, 439, 1.1, 82, 0, 9.9, 3, 66, 0 }),
("Pound Cake", "1 lb.", 24.8, new double[] { 8.0, 130, 0.4, 31, 18.9, 2.8, 3, 17, 0 }),
("Soda Crackers", "1 lb.", 15.1, new double[] { 12.5, 288, 0.5, 50, 0, 0, 0, 0, 0 }),
("Milk", "1 qt.", 11, new double[] { 6.1, 310, 10.5, 18, 16.8, 4, 16, 7, 177 }),
("Evaporated Milk (can)", "14.5 oz.", 6.7, new double[] { 8.4, 422, 15.1, 9, 26, 3, 23.5, 11, 60 }),
("Butter", "1 lb.", 30.8, new double[] { 10.8, 9, 0.2, 3, 44.2, 0, 0.2, 2, 0 }),
("Oleomargarine", "1 lb.", 16.1, new double[] { 20.6, 17, 0.6, 6, 55.8, 0.2, 0, 0, 0 }),
("Eggs", "1 doz.", 32.6, new double[] { 2.9, 238, 1.0, 52, 18.6, 2.8, 6.5, 1, 0 }),
("Cheese (Cheddar)", "1 lb.", 24.2, new double[] { 7.4, 448, 16.4, 19, 28.1, 0.8, 10.3, 4, 0 }),
("Cream", "1/2 pt.", 14.1, new double[] { 3.5, 49, 1.7, 3, 16.9, 0.6, 2.5, 0, 17 }),
("Peanut Butter", "1 lb.", 17.9, new double[] { 15.7, 661, 1.0, 48, 0, 9.6, 8.1, 471, 0 }),
("Mayonnaise", "1/2 pt.", 16.7, new double[] { 8.6, 18, 0.2, 8, 2.7, 0.4, 0.5, 0, 0 }),
("Crisco", "1 lb.", 20.3, new double[] { 20.1, 0, 0, 0, 0, 0, 0, 0, 0 }),
("Lard", "1 lb.", 9.8, new double[] { 41.7, 0, 0, 0, 0.2, 0, 0.5, 5, 0 }),
("Sirloin Steak", "1 lb.", 39.6, new double[] { 2.9, 166, 0.1, 34, 0.2, 2.1, 2.9, 69, 0 }),
("Round Steak", "1 lb.", 36.4, new double[] { 2.2, 214, 0.1, 32, 0.4, 2.5, 2.4, 87, 0 }),
("Rib Roast", "1 lb.", 29.2, new double[] { 3.4, 213, 0.1, 33, 0, 0, 2, 0, 0 }),
("Chuck Roast", "1 lb.", 22.6, new double[] { 3.6, 309, 0.2, 46, 0.4, 1, 4, 120, 0 }),
("Plate", "1 lb.", 14.6, new double[] { 8.5, 404, 0.2, 62, 0, 0.9, 0, 0, 0 }),
("Liver (Beef)", "1 lb.", 26.8, new double[] { 2.2, 333, 0.2, 139, 169.2, 6.4, 50.8, 316, 525 }),
("Leg of Lamb", "1 lb.", 27.6, new double[] { 3.1, 245, 0.1, 20, 0, 2.8, 3.9, 86, 0 }),
("Lamb Chops (Rib)", "1 lb.", 36.6, new double[] { 3.3, 140, 0.1, 15, 0, 1.7, 2.7, 54, 0 }),
("Pork Chops", "1 lb.", 30.7, new double[] { 3.5, 196, 0.2, 30, 0, 17.4, 2.7, 60, 0 }),
("Pork Loin Roast", "1 lb.", 24.2, new double[] { 4.4, 249, 0.3, 37, 0, 18.2, 3.6, 79, 0 }),
("Bacon", "1 lb.", 25.6, new double[] { 10.4, 152, 0.2, 23, 0, 1.8, 1.8, 71, 0 }),
("Ham, smoked", "1 lb.", 27.4, new double[] { 6.7, 212, 0.2, 31, 0, 9.9, 3.3, 50, 0 }),
("Salt Pork", "1 lb.", 16, new double[] { 18.8, 164, 0.1, 26, 0, 1.4, 1.8, 0, 0 }),
("Roasting Chicken", "1 lb.", 30.3, new double[] { 1.8, 184, 0.1, 30, 0.1, 0.9, 1.8, 68, 46 }),
("Veal Cutlets", "1 lb.", 42.3, new double[] { 1.7, 156, 0.1, 24, 0, 1.4, 2.4, 57, 0 }),
("Salmon, Pink (can)", "16 oz.", 13, new double[] { 5.8, 705, 6.8, 45, 3.5, 1, 4.9, 209, 0 }),
("Apples", "1 lb.", 4.4, new double[] { 5.8, 27, 0.5, 36, 7.3, 3.6, 2.7, 5, 544 }),
("Bananas", "1 lb.", 6.1, new double[] { 4.9, 60, 0.4, 30, 17.4, 2.5, 3.5, 28, 498 }),
("Lemons", "1 doz.", 26, new double[] { 1.0, 21, 0.5, 14, 0, 0.5, 0, 4, 952 }),
("Oranges", "1 doz.", 30.9, new double[] { 2.2, 40, 1.1, 18, 11.1, 3.6, 1.3, 10, 1998 }),
("Green Beans", "1 lb.", 7.1, new double[] { 2.4, 138, 3.7, 80, 69, 4.3, 5.8, 37, 862 }),
("Cabbage", "1 lb.", 3.7, new double[] { 2.6, 125, 4.0, 36, 7.2, 9, 4.5, 26, 5369 }),
("Carrots", "1 bunch", 4.7, new double[] { 2.7, 73, 2.8, 43, 188.5, 6.1, 4.3, 89, 608 }),
("Celery", "1 stalk", 7.3, new double[] { 0.9, 51, 3.0, 23, 0.9, 1.4, 1.4, 9, 313 }),
("Lettuce", "1 head", 8.2, new double[] { 0.4, 27, 1.1, 22, 112.4, 1.8, 3.4, 11, 449 }),
("Onions", "1 lb.", 3.6, new double[] { 5.8, 166, 3.8, 59, 16.6, 4.7, 5.9, 21, 1184 }),
("Potatoes", "15 lb.", 34, new double[] { 14.3, 336, 1.8, 118, 6.7, 29.4, 7.1, 198, 2522 }),
("Spinach", "1 lb.", 8.1, new double[] { 1.1, 106, 0, 138, 918.4, 5.7, 13.8, 33, 2755 }),
("Sweet Potatoes", "1 lb.", 5.1, new double[] { 9.6, 138, 2.7, 54, 290.7, 8.4, 5.4, 83, 1912 }),
("Peaches (can)", "No. 2 1/2", 16.8, new double[] { 3.7, 20, 0.4, 10, 21.5, 0.5, 1, 31, 196 }),
("Pears (can)", "No. 2 1/2", 20.4, new double[] { 3.0, 8, 0.3, 8, 0.8, 0.8, 0.8, 5, 81 }),
("Pineapple (can)", "No. 2 1/2", 21.3, new double[] { 2.4, 16, 0.4, 8, 2, 2.8, 0.8, 7, 399 }),
("Asparagus (can)", "No. 2", 27.7, new double[] { 0.4, 33, 0.3, 12, 16.3, 1.4, 2.1, 17, 272 }),
("Green Beans (can)", "No. 2", 10, new double[] { 1.0, 54, 2, 65, 53.9, 1.6, 4.3, 32, 431 }),
("Pork and Beans (can)", "16 oz.", 7.1, new double[] { 7.5, 364, 4, 134, 3.5, 8.3, 7.7, 56, 0 }),
("Corn (can)", "No. 2", 10.4, new double[] { 5.2, 136, 0.2, 16, 12, 1.6, 2.7, 42, 218 }),
("Peas (can)", "No. 2", 13.8, new double[] { 2.3, 136, 0.6, 45, 34.9, 4.9, 2.5, 37, 370 }),
("Tomatoes (can)", "No. 2", 8.6, new double[] { 1.3, 63, 0.7, 38, 53.2, 3.4, 2.5, 36, 1253 }),
("Tomato Soup (can)", "10 1/2 oz.", 7.6, new double[] { 1.6, 71, 0.6, 43, 57.9, 3.5, 2.4, 67, 862 }),
("Peaches, Dried", "1 lb.", 15.7, new double[] { 8.5, 87, 1.7, 173, 86.8, 1.2, 4.3, 55, 57 }),
("Prunes, Dried", "1 lb.", 9, new double[] { 12.8, 99, 2.5, 154, 85.7, 3.9, 4.3, 65, 257 }),
("Raisins, Dried", "15 oz.", 9.4, new double[] { 13.5, 104, 2.5, 136, 4.5, 6.3, 1.4, 24, 136 }),
("Peas, Dried", "1 lb.", 7.9, new double[] { 20.0, 1367, 4.2, 345, 2.9, 28.7, 18.4, 162, 0 }),
("Lima Beans, Dried", "1 lb.", 8.9, new double[] { 17.4, 1055, 3.7, 459, 5.1, 26.9, 38.2, 93, 0 }),
("Navy Beans, Dried", "1 lb.", 5.9, new double[] { 26.9, 1691, 11.4, 792, 0, 38.4, 24.6, 217, 0 }),
("Coffee", "1 lb.", 22.4, new double[] { 0, 0, 0, 0, 0, 4, 5.1, 50, 0 }),
("Tea", "1/4 lb.", 17.4, new double[] { 0, 0, 0, 0, 0, 0, 2.3, 42, 0 }),
("Cocoa", "8 oz.", 8.6, new double[] { 8.7, 237, 3, 72, 0, 2, 11.9, 40, 0 }),
("Chocolate", "8 oz.", 16.2, new double[] { 8.0, 77, 1.3, 39, 0, 0.9, 3.4, 14, 0 }),
("Sugar", "10 lb.", 51.7, new double[] { 34.9, 0, 0, 0, 0, 0, 0, 0, 0 }),
("Corn Syrup", "24 oz.", 13.7, new double[] { 14.7, 0, 0.5, 74, 0, 0, 0, 5, 0 }),
("Molasses", "18 oz.", 13.6, new double[] { 9.0, 0, 10.3, 244, 0, 1.9, 7.5, 146, 0 }),
("Strawberry Preserves", "1 lb.", 20.5, new double[] { 6.4, 11, 0.4, 7, 0.2, 0.2, 0.4, 3, 0 })
};
// [END data_model]
// [START solver]
// Create the linear solver with the GLOP backend.
Solver solver = Solver.CreateSolver("GLOP");
// [END solver]
// [START variables]
List<Variable> foods = new List<Variable>();
for (int i = 0; i < data.Length; ++i)
{
foods.Add(solver.MakeNumVar(0.0, double.PositiveInfinity, data[i].Name));
}
Console.WriteLine($"Number of variables = {solver.NumVariables()}");
// [END variables]
// [START constraints]
List<Constraint> constraints = new List<Constraint>();
for (int i = 0; i < nutrients.Length; ++i)
{
Constraint constraint =
solver.MakeConstraint(nutrients[i].Value, double.PositiveInfinity, nutrients[i].Name);
for (int j = 0; j < data.Length; ++j)
{
constraint.SetCoefficient(foods[j], data[j].Nutrients[i]);
}
constraints.Add(constraint);
}
Console.WriteLine($"Number of constraints = {solver.NumConstraints()}");
// [END constraints]
// [START objective]
Objective objective = solver.Objective();
for (int i = 0; i < data.Length; ++i)
{
objective.SetCoefficient(foods[i], 1);
}
objective.SetMinimization();
// [END objective]
// [START solve]
Solver.ResultStatus resultStatus = solver.Solve();
// [END solve]
// [START print_solution]
// Check that the problem has an optimal solution.
if (resultStatus != Solver.ResultStatus.OPTIMAL)
{
Console.WriteLine("The problem does not have an optimal solution!");
if (resultStatus == Solver.ResultStatus.FEASIBLE)
{
Console.WriteLine("A potentially suboptimal solution was found.");
}
else
{
Console.WriteLine("The solver could not solve the problem.");
return;
}
}
// Display the amounts (in dollars) to purchase of each food.
double[] nutrientsResult = new double[nutrients.Length];
Console.WriteLine("\nAnnual Foods:");
for (int i = 0; i < foods.Count; ++i)
{
if (foods[i].SolutionValue() > 0.0)
{
Console.WriteLine($"{data[i].Name}: ${365 * foods[i].SolutionValue():N2}");
for (int j = 0; j < nutrients.Length; ++j)
{
nutrientsResult[j] += data[i].Nutrients[j] * foods[i].SolutionValue();
}
}
}
Console.WriteLine($"\nOptimal annual price: ${365 * objective.Value():N2}");
Console.WriteLine("\nNutrients per day:");
for (int i = 0; i < nutrients.Length; ++i)
{
Console.WriteLine($"{nutrients[i].Name}: {nutrientsResult[i]:N2} (min {nutrients[i].Value})");
}
// [END print_solution]
// [START advanced]
Console.WriteLine("\nAdvanced usage:");
Console.WriteLine($"Problem solved in {solver.WallTime()} milliseconds");
Console.WriteLine($"Problem solved in {solver.Iterations()} iterations");
// [END advanced]
}
}
// [END program]
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using Python.Runtime.StateSerialization;
namespace Python.Runtime
{
/// <summary>
/// Implements the "import hook" used to integrate Python with the CLR.
/// </summary>
internal static class ImportHook
{
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
// set in Initialize
private static PyObject root;
private static CLRModule clrModule;
private static PyModule py_clr_module;
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
internal static BorrowedReference ClrModuleReference => py_clr_module.Reference;
private const string LoaderCode = @"
import importlib.abc
import sys
class DotNetLoader(importlib.abc.Loader):
@classmethod
def exec_module(klass, mod):
# This method needs to exist.
pass
@classmethod
def create_module(klass, spec):
import clr
return clr._load_clr_module(spec)
class DotNetFinder(importlib.abc.MetaPathFinder):
@classmethod
def find_spec(klass, fullname, paths=None, target=None):
# Don't import, we might call ourselves recursively!
if 'clr' not in sys.modules:
return None
clr = sys.modules['clr']
clr._add_pending_namespaces()
if clr._available_namespaces and fullname in clr._available_namespaces:
return importlib.machinery.ModuleSpec(fullname, DotNetLoader(), is_package=True)
return None
";
const string _available_namespaces = "_available_namespaces";
/// <summary>
/// Initialization performed on startup of the Python runtime.
/// </summary>
internal static unsafe void Initialize()
{
// Initialize the clr module and tell Python about it.
root = CLRModule.Create(out clrModule).MoveToPyObject();
// create a python module with the same methods as the clr module-like object
py_clr_module = new PyModule(Runtime.PyModule_New("clr").StealOrThrow());
// both dicts are borrowed references
BorrowedReference mod_dict = Runtime.PyModule_GetDict(ClrModuleReference);
using var clr_dict = Runtime.PyObject_GenericGetDict(root);
Runtime.PyDict_Update(mod_dict, clr_dict.BorrowOrThrow());
BorrowedReference dict = Runtime.PyImport_GetModuleDict();
Runtime.PyDict_SetItemString(dict, "CLR", ClrModuleReference);
Runtime.PyDict_SetItemString(dict, "clr", ClrModuleReference);
SetupNamespaceTracking();
SetupImportHook();
}
/// <summary>
/// Cleanup resources upon shutdown of the Python runtime.
/// </summary>
internal static void Shutdown()
{
if (Runtime.Py_IsInitialized() == 0)
{
return;
}
TeardownNameSpaceTracking();
clrModule.ResetModuleMembers();
Runtime.Py_CLEAR(ref py_clr_module!);
root.Dispose();
root = null!;
}
private static Dictionary<PyString, PyObject> GetDotNetModules()
{
BorrowedReference pyModules = Runtime.PyImport_GetModuleDict();
using var items = Runtime.PyDict_Items(pyModules);
nint length = Runtime.PyList_Size(items.BorrowOrThrow());
Debug.Assert(length >= 0);
var modules = new Dictionary<PyString, PyObject>();
for (nint i = 0; i < length; i++)
{
BorrowedReference item = Runtime.PyList_GetItem(items.Borrow(), i);
BorrowedReference name = Runtime.PyTuple_GetItem(item, 0);
BorrowedReference module = Runtime.PyTuple_GetItem(item, 1);
if (ManagedType.IsInstanceOfManagedType(module))
{
modules.Add(new PyString(name), new PyObject(module));
}
}
return modules;
}
internal static ImportHookState SaveRuntimeData()
{
return new()
{
PyCLRModule = py_clr_module,
Root = new PyObject(root),
Modules = GetDotNetModules(),
};
}
private static void RestoreDotNetModules(Dictionary<PyString, PyObject> modules)
{
var pyMoudles = Runtime.PyImport_GetModuleDict();
foreach (var item in modules)
{
var moduleName = item.Key;
var module = item.Value;
int res = Runtime.PyDict_SetItem(pyMoudles, moduleName, module);
PythonException.ThrowIfIsNotZero(res);
item.Key.Dispose();
item.Value.Dispose();
}
modules.Clear();
}
internal static void RestoreRuntimeData(ImportHookState storage)
{
py_clr_module = storage.PyCLRModule;
var rootHandle = storage.Root;
root = new PyObject(rootHandle);
clrModule = (CLRModule)ManagedType.GetManagedObject(rootHandle)!;
BorrowedReference dict = Runtime.PyImport_GetModuleDict();
Runtime.PyDict_SetItemString(dict, "clr", ClrModuleReference);
SetupNamespaceTracking();
RestoreDotNetModules(storage.Modules);
}
static void SetupImportHook()
{
// Create the import hook module
using var import_hook_module = Runtime.PyModule_New("clr.loader");
BorrowedReference mod_dict = Runtime.PyModule_GetDict(import_hook_module.BorrowOrThrow());
Debug.Assert(mod_dict != null);
// Run the python code to create the module's classes.
var builtins = Runtime.PyEval_GetBuiltins();
var exec = Runtime.PyDict_GetItemString(builtins, "exec");
using var args = Runtime.PyTuple_New(2);
PythonException.ThrowIfIsNull(args);
using var codeStr = Runtime.PyString_FromString(LoaderCode);
Runtime.PyTuple_SetItem(args.Borrow(), 0, codeStr.StealOrThrow());
// reference not stolen due to overload incref'ing for us.
Runtime.PyTuple_SetItem(args.Borrow(), 1, mod_dict);
Runtime.PyObject_Call(exec, args.Borrow(), default).Dispose();
// Set as a sub-module of clr.
if(Runtime.PyModule_AddObject(ClrModuleReference, "loader", import_hook_module.Steal()) != 0)
{
throw PythonException.ThrowLastAsClrException();
}
// Finally, add the hook to the meta path
var findercls = Runtime.PyDict_GetItemString(mod_dict, "DotNetFinder");
using var finderCtorArgs = Runtime.PyTuple_New(0);
using var finder_inst = Runtime.PyObject_CallObject(findercls, finderCtorArgs.Borrow());
var metapath = Runtime.PySys_GetObject("meta_path");
PythonException.ThrowIfIsNotZero(Runtime.PyList_Append(metapath, finder_inst.BorrowOrThrow()));
}
/// <summary>
/// Sets up the tracking of loaded namespaces. This makes available to
/// Python, as a Python object, the loaded namespaces. The set of loaded
/// namespaces is used during the import to verify if we can import a
/// CLR assembly as a module or not. The set is stored on the clr module.
/// </summary>
static void SetupNamespaceTracking()
{
using var newset = Runtime.PySet_New(default);
foreach (var ns in AssemblyManager.GetNamespaces())
{
using var pyNs = Runtime.PyString_FromString(ns);
if (Runtime.PySet_Add(newset.Borrow(), pyNs.BorrowOrThrow()) != 0)
{
throw PythonException.ThrowLastAsClrException();
}
}
if (Runtime.PyDict_SetItemString(clrModule.dict, _available_namespaces, newset.Borrow()) != 0)
{
throw PythonException.ThrowLastAsClrException();
}
}
/// <summary>
/// Removes the set of available namespaces from the clr module.
/// </summary>
static void TeardownNameSpaceTracking()
{
// If the C# runtime isn't loaded, then there are no namespaces available
Runtime.PyDict_SetItemString(clrModule.dict, _available_namespaces, Runtime.PyNone);
}
static readonly ConcurrentQueue<string> addPending = new();
public static void AddNamespace(string name) => addPending.Enqueue(name);
internal static int AddPendingNamespaces()
{
int added = 0;
while (addPending.TryDequeue(out string ns))
{
AddNamespaceWithGIL(ns);
added++;
}
return added;
}
internal static void AddNamespaceWithGIL(string name)
{
using var pyNs = Runtime.PyString_FromString(name);
var nsSet = Runtime.PyDict_GetItemString(clrModule.dict, _available_namespaces);
if (!(nsSet.IsNull || nsSet == Runtime.PyNone))
{
if (Runtime.PySet_Add(nsSet, pyNs.BorrowOrThrow()) != 0)
{
throw PythonException.ThrowLastAsClrException();
}
}
}
/// <summary>
/// Because we use a proxy module for the clr module, we somtimes need
/// to force the py_clr_module to sync with the actual clr module's dict.
/// </summary>
internal static void UpdateCLRModuleDict()
{
clrModule.InitializePreload();
// update the module dictionary with the contents of the root dictionary
clrModule.LoadNames();
BorrowedReference py_mod_dict = Runtime.PyModule_GetDict(ClrModuleReference);
using var clr_dict = Runtime.PyObject_GenericGetDict(root);
Runtime.PyDict_Update(py_mod_dict, clr_dict.BorrowOrThrow());
}
/// <summary>
/// Return the clr python module (new reference)
/// </summary>
public static unsafe NewReference GetCLRModule()
{
UpdateCLRModuleDict();
return new NewReference(py_clr_module);
}
/// <summary>
/// The hook to import a CLR module into Python. Returns a new reference
/// to the module.
/// </summary>
public static PyObject Import(string modname)
{
// Traverse the qualified module name to get the named module.
// Note that if
// we are running in interactive mode we pre-load the names in
// each module, which is often useful for introspection. If we
// are not interactive, we stick to just-in-time creation of
// objects at lookup time, which is much more efficient.
// NEW: The clr got a new module variable preload. You can
// enable preloading in a non-interactive python processing by
// setting clr.preload = True
ModuleObject? head = null;
ModuleObject tail = clrModule;
clrModule.InitializePreload();
string[] names = modname.Split('.');
foreach (string name in names)
{
using var nested = tail.GetAttribute(name, true);
if (nested.IsNull() || ManagedType.GetManagedObject(nested.Borrow()) is not ModuleObject module)
{
Exceptions.SetError(Exceptions.ImportError, $"'{name}' Is not a ModuleObject.");
throw PythonException.ThrowLastAsClrException();
}
if (head == null)
{
head = module;
}
tail = module;
if (CLRModule.preload)
{
tail.LoadNames();
}
}
return tail.Alloc().MoveToPyObject();
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript{
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Configuration.Assemblies;
using System.Text;
using System.Security.Permissions;
public class GlobalObject{
internal static readonly GlobalObject commonInstance = new GlobalObject();
public const double Infinity = Double.PositiveInfinity;
public const double NaN = Double.NaN;
public static readonly Empty undefined = null;
protected ActiveXObjectConstructor originalActiveXObjectField;
protected ArrayConstructor originalArrayField;
protected BooleanConstructor originalBooleanField;
protected DateConstructor originalDateField;
protected EnumeratorConstructor originalEnumeratorField;
protected ErrorConstructor originalErrorField;
protected ErrorConstructor originalEvalErrorField;
protected FunctionConstructor originalFunctionField;
protected NumberConstructor originalNumberField;
protected ObjectConstructor originalObjectField;
protected ObjectPrototype originalObjectPrototypeField;
protected ErrorConstructor originalRangeErrorField;
protected ErrorConstructor originalReferenceErrorField;
protected RegExpConstructor originalRegExpField;
protected StringConstructor originalStringField;
protected ErrorConstructor originalSyntaxErrorField;
protected ErrorConstructor originalTypeErrorField;
protected VBArrayConstructor originalVBArrayField;
protected ErrorConstructor originalURIErrorField;
internal GlobalObject(){
this.originalActiveXObjectField = null;
this.originalArrayField = null;
this.originalBooleanField = null;
this.originalDateField = null;
this.originalEnumeratorField = null;
this.originalEvalErrorField = null;
this.originalErrorField = null;
this.originalFunctionField = null;
this.originalNumberField = null;
this.originalObjectField = null;
this.originalObjectPrototypeField = null;
this.originalRangeErrorField = null;
this.originalReferenceErrorField = null;
this.originalRegExpField = null;
this.originalStringField = null;
this.originalSyntaxErrorField = null;
this.originalTypeErrorField = null;
this.originalVBArrayField = null;
this.originalURIErrorField = null;
}
public static ActiveXObjectConstructor ActiveXObject{
get{
return ActiveXObjectConstructor.ob;
}
}
private static void AppendInHex(StringBuilder bs, int value){
bs.Append('%');
int nibble = value >> 4 & 0x0F;
bs.Append((char)(nibble >= 10 ? nibble - 10 + 'A' : nibble + '0'));
nibble = value & 0x0F;
bs.Append((char)(nibble >= 10 ? nibble - 10 + 'A' : nibble + '0'));
}
public static ArrayConstructor Array{
get{
return ArrayConstructor.ob;
}
}
public static BooleanConstructor Boolean{
get{
return BooleanConstructor.ob;
}
}
public static Type boolean{
get{
return Typeob.Boolean;
}
}
public static Type @byte{
get{
return Typeob.Byte;
}
}
public static Type @char{
get{
return Typeob.Char;
}
}
[JSFunctionAttribute(0, JSBuiltin.Global_CollectGarbage)]
public static void CollectGarbage(){
System.GC.Collect();
}
public static DateConstructor Date{
get{
return DateConstructor.ob;
}
}
public static Type @decimal{
get{
return Typeob.Decimal;
}
}
private static String Decode(Object encodedURI, URISetType flags){
String encodedURIStr = Convert.ToString(encodedURI);
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < encodedURIStr.Length; i++){
char ch = encodedURIStr[i];
if (ch != '%')
resultStr.Append(ch);
else{
int start = i;
if (i+2 >= encodedURIStr.Length)
throw new JScriptException(JSError.URIDecodeError);
byte b = HexValue(encodedURIStr[i+1], encodedURIStr[i+2]);
i += 2;
char ch1;
if ((b & 0x80) == 0)
ch1 = (char)b;
else{
int n;
for (n = 1; ((b << n) & 0x80) != 0; n++) ;
if (n == 1 || n > 4 || i + (n-1) * 3 >= encodedURIStr.Length)
throw new JScriptException(JSError.URIDecodeError);
int value = (int)b & 0xFF >> (n+1);
for (; n > 1; n--){
if (encodedURIStr[i+1] != '%')
throw new JScriptException(JSError.URIDecodeError);
b = HexValue(encodedURIStr[i+2], encodedURIStr[i+3]);
i += 3;
// The two leading bits should be 10 for a valid UTF-8 encoding.
if ((b & 0xC0) != 0x80)
throw new JScriptException(JSError.URIDecodeError);
value = value << 6 | (int)(b & 0x3F);
}
if (value >= 0xD800 && value < 0xE000)
throw new JScriptException(JSError.URIDecodeError);
if (value < 0x10000)
ch1 = (char)value;
else{
if (value > 0x10FFFF)
throw new JScriptException(JSError.URIDecodeError);
resultStr.Append((char)((value - 0x10000 >> 10 & 0x3FF) + 0xD800));
resultStr.Append((char)((value - 0x10000 & 0x3FF) + 0xDC00));
continue;
}
}
if (GlobalObject.InURISet(ch1, flags))
resultStr.Append(encodedURIStr, start, i-start+1);
else
resultStr.Append(ch1);
}
}
return resultStr.ToString();
}
[JSFunctionAttribute(0, JSBuiltin.Global_decodeURI)]
public static String decodeURI(Object encodedURI){
return Decode(encodedURI, URISetType.Reserved);
}
[JSFunctionAttribute(0, JSBuiltin.Global_decodeURIComponent)]
public static String decodeURIComponent(Object encodedURI){
return Decode(encodedURI, URISetType.None);
}
public static Type @double{
get{
return Typeob.Double;
}
}
private static String Encode(Object uri, URISetType flags){
String uriStr = Convert.ToString(uri);
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < uriStr.Length; i++){
char ch = uriStr[i];
if (GlobalObject.InURISet(ch, flags))
resultStr.Append(ch);
else{
int value = (int)ch;
if (value >= 0 && value <= 0x7F)
GlobalObject.AppendInHex(resultStr, value);
else if (value >= 0x0080 && value <= 0x07FF){
GlobalObject.AppendInHex(resultStr, value >> 6 | 0xC0);
GlobalObject.AppendInHex(resultStr, value & 0x3F | 0x80);
}else if (value < 0xD800 || value > 0xDFFF){
GlobalObject.AppendInHex(resultStr, value >> 12 | 0xE0);
GlobalObject.AppendInHex(resultStr, value >> 6 & 0x3F | 0x80);
GlobalObject.AppendInHex(resultStr, value & 0x3F | 0x80);
}else{
if (value >= 0xDC00 && value <= 0xDFFF)
throw new JScriptException(JSError.URIEncodeError);
if (++i >= uriStr.Length)
throw new JScriptException(JSError.URIEncodeError);
int value1 = (int)uriStr[i];
if (value1 < 0xDC00 || value1 > 0xDFFF)
throw new JScriptException(JSError.URIEncodeError);
value = (value - 0xD800 << 10) + value1 + 0x2400;
GlobalObject.AppendInHex(resultStr, value >> 18 | 0xF0);
GlobalObject.AppendInHex(resultStr, value >> 12 & 0x3F | 0x80);
GlobalObject.AppendInHex(resultStr, value >> 6 & 0x3F | 0x80);
GlobalObject.AppendInHex(resultStr, value & 0x3F | 0x80);
}
}
}
return resultStr.ToString();
}
[JSFunctionAttribute(0, JSBuiltin.Global_encodeURI)]
public static String encodeURI(Object uri){
return GlobalObject.Encode(uri, URISetType.Reserved | URISetType.Unescaped);
}
[JSFunctionAttribute(0, JSBuiltin.Global_encodeURIComponent)]
public static String encodeURIComponent(Object uriComponent){
return GlobalObject.Encode(uriComponent, URISetType.Unescaped);
}
public static EnumeratorConstructor Enumerator{
get{
return EnumeratorConstructor.ob;
}
}
public static ErrorConstructor Error{
get{
return ErrorConstructor.ob;
}
}
[NotRecommended ("escape")]
[JSFunctionAttribute(0, JSBuiltin.Global_escape)]
public static String escape(Object @string){
String str = Convert.ToString(@string);
String hex = "0123456789ABCDEF";
int n = str.Length;
StringBuilder ustr = new StringBuilder(n*2);
char c; int d;
for (int k = -1; ++k < n; ustr.Append(c)){
c = str[k]; d = (int)c;
if ((int)'A' <= d && d <= (int)'Z')
continue;
if ((int)'a' <= d && d <= (int)'z')
continue;
if ((int)'0' <= d && d <= (int)'9')
continue;
if (c == '@' || c == '*' || c == '_' || c == '+' || c == '-' || c == '.' || c == '/')
continue;
ustr.Append('%');
if (d < 256){
ustr.Append(hex[d/16]);
c = hex[d%16];
}else{
ustr.Append('u');
ustr.Append(hex[(d>>12)%16]);
ustr.Append(hex[(d>>8)%16]);
ustr.Append(hex[(d>>4)%16]);
c = hex[d%16];
}
}
return ustr.ToString();
}
[JSFunctionAttribute(0, JSBuiltin.Global_eval)]
public static Object eval(Object x){
//The eval function is never called by JScript code because it is a special form that gets its own AST node.
//If this function is called, it is because of an illegal program.
throw new JScriptException(JSError.IllegalEval);
}
public static ErrorConstructor EvalError{
get{
return ErrorConstructor.evalOb;
}
}
public static Type @float{
get{
return Typeob.Single;
}
}
public static FunctionConstructor Function{
get{
return FunctionConstructor.ob;
}
}
[JSFunctionAttribute(0, JSBuiltin.Global_GetObject)]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public static Object GetObject(Object moniker, Object progId){
// GetObject is not supported for FEATURE_PAL.
throw new JScriptException(JSError.InvalidCall);
}
internal static int HexDigit(char c){
if (c >= '0' && c <= '9') return ((int)c) - ((int)'0');
if (c >= 'A' && c <= 'F') return 10 + ((int)c) - ((int)'A');
if (c >= 'a' && c <= 'f') return 10 + ((int)c) - ((int)'a');
return -1;
}
private static byte HexValue(char ch1, char ch2){
int d1, d2;
if ((d1 = HexDigit(ch1)) < 0
|| (d2 = HexDigit(ch2)) < 0)
throw new JScriptException(JSError.URIDecodeError);
return (byte)(d1 << 4 | d2);
}
public static Type @int{
get{
return Typeob.Int32;
}
}
private static bool InURISet(char ch, URISetType flags){
if ((flags & URISetType.Unescaped) != URISetType.None){
if (ch >= '0' && ch <= '9'
|| ch >= 'A' && ch <= 'Z'
|| ch >= 'a' && ch <= 'z')
return true;
switch (ch){
case '-': case '_': case '.':
case '!': case '~': case '*':
case '\'': case '(': case ')':
return true;
}
}
if ((flags & URISetType.Reserved) != URISetType.None){
switch (ch){
case ';': case '/': case '?':
case ':': case '@': case '&':
case '=': case '+': case '$':
case ',': case '#':
return true;
}
}
return false;
}
[JSFunctionAttribute(0, JSBuiltin.Global_isNaN)]
public static bool isNaN(Object num){
double number = Convert.ToNumber(num);
return number != number;
}
[JSFunctionAttribute(0, JSBuiltin.Global_isFinite)]
public static bool isFinite(double number){
return !(Double.IsInfinity(number) || Double.IsNaN(number));
}
public static Type @long{
get{
return Typeob.Int64;
}
}
public static MathObject Math{
get{
if (MathObject.ob == null)
MathObject.ob = new MathObject(ObjectPrototype.ob);
return MathObject.ob;
}
}
public static NumberConstructor Number{
get{
return NumberConstructor.ob;
}
}
public static ObjectConstructor Object{
get{
return ObjectConstructor.ob;
}
}
internal virtual ActiveXObjectConstructor originalActiveXObject{
get{
if (this.originalActiveXObjectField == null)
this.originalActiveXObjectField = ActiveXObjectConstructor.ob;
return this.originalActiveXObjectField;
}
}
internal virtual ArrayConstructor originalArray{
get{
if (this.originalArrayField == null)
this.originalArrayField = ArrayConstructor.ob;
return this.originalArrayField;
}
}
internal virtual BooleanConstructor originalBoolean{
get{
if (this.originalBooleanField == null)
this.originalBooleanField = BooleanConstructor.ob;
return this.originalBooleanField;
}
}
internal virtual DateConstructor originalDate{
get{
if (this.originalDateField == null)
this.originalDateField = DateConstructor.ob;
return this.originalDateField;
}
}
internal virtual EnumeratorConstructor originalEnumerator{
get{
if (this.originalEnumeratorField == null)
this.originalEnumeratorField = EnumeratorConstructor.ob;
return this.originalEnumeratorField;
}
}
internal virtual ErrorConstructor originalError{
get{
if (this.originalErrorField == null)
this.originalErrorField = ErrorConstructor.ob;
return this.originalErrorField;
}
}
internal virtual ErrorConstructor originalEvalError{
get{
if (this.originalEvalErrorField == null)
this.originalEvalErrorField = ErrorConstructor.evalOb;
return this.originalEvalErrorField;
}
}
internal virtual FunctionConstructor originalFunction{
get{
if (this.originalFunctionField == null)
this.originalFunctionField = FunctionConstructor.ob;
return this.originalFunctionField;
}
}
internal virtual NumberConstructor originalNumber{
get{
if (this.originalNumberField == null)
this.originalNumberField = NumberConstructor.ob;
return this.originalNumberField;
}
}
internal virtual ObjectConstructor originalObject{
get{
if (this.originalObjectField == null)
this.originalObjectField = ObjectConstructor.ob;
return this.originalObjectField;
}
}
internal virtual ObjectPrototype originalObjectPrototype{
get{
if (this.originalObjectPrototypeField == null)
this.originalObjectPrototypeField = ObjectPrototype.ob;
return this.originalObjectPrototypeField;
}
}
internal virtual ErrorConstructor originalRangeError{
get{
if (this.originalRangeErrorField == null)
this.originalRangeErrorField = ErrorConstructor.rangeOb;
return this.originalRangeErrorField;
}
}
internal virtual ErrorConstructor originalReferenceError{
get{
if (this.originalReferenceErrorField == null)
this.originalReferenceErrorField = ErrorConstructor.referenceOb;
return this.originalReferenceErrorField;
}
}
internal virtual RegExpConstructor originalRegExp{
get{
if (this.originalRegExpField == null)
this.originalRegExpField = RegExpConstructor.ob;
return this.originalRegExpField;
}
}
internal virtual StringConstructor originalString{
get{
if (this.originalStringField == null)
this.originalStringField = StringConstructor.ob;
return this.originalStringField;
}
}
internal virtual ErrorConstructor originalSyntaxError{
get{
if (this.originalSyntaxErrorField == null)
this.originalSyntaxErrorField = ErrorConstructor.syntaxOb;
return this.originalSyntaxErrorField;
}
}
internal virtual ErrorConstructor originalTypeError{
get{
if (this.originalTypeErrorField == null)
this.originalTypeErrorField = ErrorConstructor.typeOb;
return this.originalTypeErrorField;
}
}
internal virtual ErrorConstructor originalURIError{
get{
if (this.originalURIErrorField == null)
this.originalURIErrorField = ErrorConstructor.uriOb;
return this.originalURIErrorField;
}
}
internal virtual VBArrayConstructor originalVBArray{
get{
if (this.originalVBArrayField == null)
this.originalVBArrayField = VBArrayConstructor.ob;
return this.originalVBArrayField;
}
}
[JSFunctionAttribute(0, JSBuiltin.Global_parseFloat)]
public static double parseFloat(Object @string){
String str = Convert.ToString(@string);
return Convert.ToNumber(str, false, false, Missing.Value);
}
[JSFunctionAttribute(0, JSBuiltin.Global_parseInt)]
public static double parseInt(Object @string, Object radix){
String str = Convert.ToString(@string);
return Convert.ToNumber(str, true, true, radix);
}
public static ErrorConstructor RangeError{
get{
return ErrorConstructor.rangeOb;
}
}
public static ErrorConstructor ReferenceError{
get{
return ErrorConstructor.referenceOb;
}
}
public static RegExpConstructor RegExp{
get{
return RegExpConstructor.ob;
}
}
[JSFunctionAttribute(0, JSBuiltin.Global_ScriptEngine)]
public static String ScriptEngine(){
return "JScript";
}
[JSFunctionAttribute(0, JSBuiltin.Global_ScriptEngineBuildVersion)]
public static int ScriptEngineBuildVersion(){
return 0;
}
[JSFunctionAttribute(0, JSBuiltin.Global_ScriptEngineMajorVersion)]
public static int ScriptEngineMajorVersion(){
return 0;
}
[JSFunctionAttribute(0, JSBuiltin.Global_ScriptEngineMinorVersion)]
public static int ScriptEngineMinorVersion(){
return 0;
}
public static Type @sbyte{
get{
return Typeob.SByte;
}
}
public static Type @short{
get{
return Typeob.Int16;
}
}
public static StringConstructor String{
get{
return StringConstructor.ob;
}
}
public static ErrorConstructor SyntaxError{
get{
return ErrorConstructor.syntaxOb;
}
}
public static ErrorConstructor TypeError{
get{
return ErrorConstructor.typeOb;
}
}
[NotRecommended ("unescape")]
[JSFunctionAttribute(0, JSBuiltin.Global_unescape)]
public static String unescape(Object @string){
String str = Convert.ToString(@string);
int n = str.Length;
StringBuilder ustr = new StringBuilder(n);
char c; int d1, d2, d3, d4;
for (int k = -1; ++k < n; ustr.Append(c)){
c = str[k];
if (c == '%'){
if (k+5 < n && str[k+1] == 'u'
&& (d1 = HexDigit(str[k+2])) != -1
&& (d2 = HexDigit(str[k+3])) != -1
&& (d3 = HexDigit(str[k+4])) != -1
&& (d4 = HexDigit(str[k+5])) != -1){
c = (char)((d1<<12)+(d2<<8)+(d3<<4)+d4);
k += 5;
}else if (k+2 < n
&& (d1 = HexDigit(str[k+1])) != -1
&& (d2 = HexDigit(str[k+2])) != -1){
c = (char)((d1<<4)+d2);
k += 2;
}
}
}
return ustr.ToString();
}
public static ErrorConstructor URIError{
get{
return ErrorConstructor.uriOb;
}
}
private enum URISetType{ None = 0x0, Reserved = 0x1, Unescaped = 0x2 };
public static VBArrayConstructor VBArray{
get{
return VBArrayConstructor.ob;
}
}
public static Type @void{
get{
return Typeob.Void;
}
}
public static Type @uint{
get{
return Typeob.UInt32;
}
}
public static Type @ulong{
get{
return Typeob.UInt64;
}
}
public static Type @ushort{
get{
return Typeob.UInt16;
}
}
}
}
| |
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 AprZScorePerimetroCefalicoEdad class.
/// </summary>
[Serializable]
public partial class AprZScorePerimetroCefalicoEdadCollection : ActiveList<AprZScorePerimetroCefalicoEdad, AprZScorePerimetroCefalicoEdadCollection>
{
public AprZScorePerimetroCefalicoEdadCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprZScorePerimetroCefalicoEdadCollection</returns>
public AprZScorePerimetroCefalicoEdadCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprZScorePerimetroCefalicoEdad 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 APR_ZScorePerimetroCefalicoEdad table.
/// </summary>
[Serializable]
public partial class AprZScorePerimetroCefalicoEdad : ActiveRecord<AprZScorePerimetroCefalicoEdad>, IActiveRecord
{
#region .ctors and Default Settings
public AprZScorePerimetroCefalicoEdad()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprZScorePerimetroCefalicoEdad(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprZScorePerimetroCefalicoEdad(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprZScorePerimetroCefalicoEdad(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("APR_ZScorePerimetroCefalicoEdad", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "Sexo";
colvarSexo.DataType = DbType.Int32;
colvarSexo.MaxLength = 0;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = true;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
colvarSexo.DefaultSetting = @"";
colvarSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "Edad";
colvarEdad.DataType = DbType.Int32;
colvarEdad.MaxLength = 0;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = true;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
colvarEdad.DefaultSetting = @"";
colvarEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarSD4neg = new TableSchema.TableColumn(schema);
colvarSD4neg.ColumnName = "SD4neg";
colvarSD4neg.DataType = DbType.Decimal;
colvarSD4neg.MaxLength = 0;
colvarSD4neg.AutoIncrement = false;
colvarSD4neg.IsNullable = true;
colvarSD4neg.IsPrimaryKey = false;
colvarSD4neg.IsForeignKey = false;
colvarSD4neg.IsReadOnly = false;
colvarSD4neg.DefaultSetting = @"";
colvarSD4neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD4neg);
TableSchema.TableColumn colvarSD3neg = new TableSchema.TableColumn(schema);
colvarSD3neg.ColumnName = "SD3neg";
colvarSD3neg.DataType = DbType.Decimal;
colvarSD3neg.MaxLength = 0;
colvarSD3neg.AutoIncrement = false;
colvarSD3neg.IsNullable = true;
colvarSD3neg.IsPrimaryKey = false;
colvarSD3neg.IsForeignKey = false;
colvarSD3neg.IsReadOnly = false;
colvarSD3neg.DefaultSetting = @"";
colvarSD3neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD3neg);
TableSchema.TableColumn colvarSD2neg = new TableSchema.TableColumn(schema);
colvarSD2neg.ColumnName = "SD2neg";
colvarSD2neg.DataType = DbType.Decimal;
colvarSD2neg.MaxLength = 0;
colvarSD2neg.AutoIncrement = false;
colvarSD2neg.IsNullable = true;
colvarSD2neg.IsPrimaryKey = false;
colvarSD2neg.IsForeignKey = false;
colvarSD2neg.IsReadOnly = false;
colvarSD2neg.DefaultSetting = @"";
colvarSD2neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD2neg);
TableSchema.TableColumn colvarSD1neg = new TableSchema.TableColumn(schema);
colvarSD1neg.ColumnName = "SD1neg";
colvarSD1neg.DataType = DbType.Decimal;
colvarSD1neg.MaxLength = 0;
colvarSD1neg.AutoIncrement = false;
colvarSD1neg.IsNullable = true;
colvarSD1neg.IsPrimaryKey = false;
colvarSD1neg.IsForeignKey = false;
colvarSD1neg.IsReadOnly = false;
colvarSD1neg.DefaultSetting = @"";
colvarSD1neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD1neg);
TableSchema.TableColumn colvarSD0 = new TableSchema.TableColumn(schema);
colvarSD0.ColumnName = "SD0";
colvarSD0.DataType = DbType.Decimal;
colvarSD0.MaxLength = 0;
colvarSD0.AutoIncrement = false;
colvarSD0.IsNullable = true;
colvarSD0.IsPrimaryKey = false;
colvarSD0.IsForeignKey = false;
colvarSD0.IsReadOnly = false;
colvarSD0.DefaultSetting = @"";
colvarSD0.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD0);
TableSchema.TableColumn colvarSD1 = new TableSchema.TableColumn(schema);
colvarSD1.ColumnName = "SD1";
colvarSD1.DataType = DbType.Decimal;
colvarSD1.MaxLength = 0;
colvarSD1.AutoIncrement = false;
colvarSD1.IsNullable = true;
colvarSD1.IsPrimaryKey = false;
colvarSD1.IsForeignKey = false;
colvarSD1.IsReadOnly = false;
colvarSD1.DefaultSetting = @"";
colvarSD1.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD1);
TableSchema.TableColumn colvarSD2 = new TableSchema.TableColumn(schema);
colvarSD2.ColumnName = "SD2";
colvarSD2.DataType = DbType.Decimal;
colvarSD2.MaxLength = 0;
colvarSD2.AutoIncrement = false;
colvarSD2.IsNullable = true;
colvarSD2.IsPrimaryKey = false;
colvarSD2.IsForeignKey = false;
colvarSD2.IsReadOnly = false;
colvarSD2.DefaultSetting = @"";
colvarSD2.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD2);
TableSchema.TableColumn colvarSD3 = new TableSchema.TableColumn(schema);
colvarSD3.ColumnName = "SD3";
colvarSD3.DataType = DbType.Decimal;
colvarSD3.MaxLength = 0;
colvarSD3.AutoIncrement = false;
colvarSD3.IsNullable = true;
colvarSD3.IsPrimaryKey = false;
colvarSD3.IsForeignKey = false;
colvarSD3.IsReadOnly = false;
colvarSD3.DefaultSetting = @"";
colvarSD3.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD3);
TableSchema.TableColumn colvarSD4 = new TableSchema.TableColumn(schema);
colvarSD4.ColumnName = "SD4";
colvarSD4.DataType = DbType.Decimal;
colvarSD4.MaxLength = 0;
colvarSD4.AutoIncrement = false;
colvarSD4.IsNullable = true;
colvarSD4.IsPrimaryKey = false;
colvarSD4.IsForeignKey = false;
colvarSD4.IsReadOnly = false;
colvarSD4.DefaultSetting = @"";
colvarSD4.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD4);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_ZScorePerimetroCefalicoEdad",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public int? Sexo
{
get { return GetColumnValue<int?>(Columns.Sexo); }
set { SetColumnValue(Columns.Sexo, value); }
}
[XmlAttribute("Edad")]
[Bindable(true)]
public int? Edad
{
get { return GetColumnValue<int?>(Columns.Edad); }
set { SetColumnValue(Columns.Edad, value); }
}
[XmlAttribute("SD4neg")]
[Bindable(true)]
public decimal? SD4neg
{
get { return GetColumnValue<decimal?>(Columns.SD4neg); }
set { SetColumnValue(Columns.SD4neg, value); }
}
[XmlAttribute("SD3neg")]
[Bindable(true)]
public decimal? SD3neg
{
get { return GetColumnValue<decimal?>(Columns.SD3neg); }
set { SetColumnValue(Columns.SD3neg, value); }
}
[XmlAttribute("SD2neg")]
[Bindable(true)]
public decimal? SD2neg
{
get { return GetColumnValue<decimal?>(Columns.SD2neg); }
set { SetColumnValue(Columns.SD2neg, value); }
}
[XmlAttribute("SD1neg")]
[Bindable(true)]
public decimal? SD1neg
{
get { return GetColumnValue<decimal?>(Columns.SD1neg); }
set { SetColumnValue(Columns.SD1neg, value); }
}
[XmlAttribute("SD0")]
[Bindable(true)]
public decimal? SD0
{
get { return GetColumnValue<decimal?>(Columns.SD0); }
set { SetColumnValue(Columns.SD0, value); }
}
[XmlAttribute("SD1")]
[Bindable(true)]
public decimal? SD1
{
get { return GetColumnValue<decimal?>(Columns.SD1); }
set { SetColumnValue(Columns.SD1, value); }
}
[XmlAttribute("SD2")]
[Bindable(true)]
public decimal? SD2
{
get { return GetColumnValue<decimal?>(Columns.SD2); }
set { SetColumnValue(Columns.SD2, value); }
}
[XmlAttribute("SD3")]
[Bindable(true)]
public decimal? SD3
{
get { return GetColumnValue<decimal?>(Columns.SD3); }
set { SetColumnValue(Columns.SD3, value); }
}
[XmlAttribute("SD4")]
[Bindable(true)]
public decimal? SD4
{
get { return GetColumnValue<decimal?>(Columns.SD4); }
set { SetColumnValue(Columns.SD4, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int? varSexo,int? varEdad,decimal? varSD4neg,decimal? varSD3neg,decimal? varSD2neg,decimal? varSD1neg,decimal? varSD0,decimal? varSD1,decimal? varSD2,decimal? varSD3,decimal? varSD4)
{
AprZScorePerimetroCefalicoEdad item = new AprZScorePerimetroCefalicoEdad();
item.Sexo = varSexo;
item.Edad = varEdad;
item.SD4neg = varSD4neg;
item.SD3neg = varSD3neg;
item.SD2neg = varSD2neg;
item.SD1neg = varSD1neg;
item.SD0 = varSD0;
item.SD1 = varSD1;
item.SD2 = varSD2;
item.SD3 = varSD3;
item.SD4 = varSD4;
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 varId,int? varSexo,int? varEdad,decimal? varSD4neg,decimal? varSD3neg,decimal? varSD2neg,decimal? varSD1neg,decimal? varSD0,decimal? varSD1,decimal? varSD2,decimal? varSD3,decimal? varSD4)
{
AprZScorePerimetroCefalicoEdad item = new AprZScorePerimetroCefalicoEdad();
item.Id = varId;
item.Sexo = varSexo;
item.Edad = varEdad;
item.SD4neg = varSD4neg;
item.SD3neg = varSD3neg;
item.SD2neg = varSD2neg;
item.SD1neg = varSD1neg;
item.SD0 = varSD0;
item.SD1 = varSD1;
item.SD2 = varSD2;
item.SD3 = varSD3;
item.SD4 = varSD4;
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 IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn SexoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn EdadColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn SD4negColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn SD3negColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn SD2negColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn SD1negColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn SD0Column
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn SD1Column
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn SD2Column
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn SD3Column
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn SD4Column
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string Sexo = @"Sexo";
public static string Edad = @"Edad";
public static string SD4neg = @"SD4neg";
public static string SD3neg = @"SD3neg";
public static string SD2neg = @"SD2neg";
public static string SD1neg = @"SD1neg";
public static string SD0 = @"SD0";
public static string SD1 = @"SD1";
public static string SD2 = @"SD2";
public static string SD3 = @"SD3";
public static string SD4 = @"SD4";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("re", typeof(IronPython.Modules.PythonRegex))]
namespace IronPython.Modules {
/// <summary>
/// Python regular expression module.
/// </summary>
public static class PythonRegex {
private static CacheDict<PatternKey, RE_Pattern> _cachedPatterns = new CacheDict<PatternKey, RE_Pattern>(100);
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException("reerror", dict, "error", "re");
PythonCopyReg.GetDispatchTable(context.SharedContext)[DynamicHelpers.GetPythonTypeFromType(typeof(RE_Pattern))] = dict["_pickle"];
}
private static readonly Random r = new Random(DateTime.Now.Millisecond);
#region CONSTANTS
// short forms
public const int I = 0x02;
public const int L = 0x04;
public const int M = 0x08;
public const int S = 0x10;
public const int U = 0x20;
public const int X = 0x40;
// long forms
public const int IGNORECASE = 0x02;
public const int LOCALE = 0x04;
public const int MULTILINE = 0x08;
public const int DOTALL = 0x10;
public const int UNICODE = 0x20;
public const int VERBOSE = 0x40;
#endregion
#region Public API Surface
public static RE_Pattern compile(CodeContext/*!*/ context, object pattern, [DefaultParameterValue(0)]int flags) {
try {
return GetPattern(context, pattern, flags, true);
} catch (ArgumentException e) {
throw PythonExceptions.CreateThrowable(error(context), e.Message);
}
}
public const string engine = "cli reg ex";
public static string escape(string text) {
if (text == null) throw PythonOps.TypeError("text must not be None");
for (int i = 0; i < text.Length; i++) {
if (!Char.IsLetterOrDigit(text[i])) {
StringBuilder sb = new StringBuilder(text, 0, i, text.Length);
char ch = text[i];
do {
sb.Append('\\');
sb.Append(ch);
i++;
int last = i;
while (i < text.Length) {
ch = text[i];
if (!Char.IsLetterOrDigit(ch)) {
break;
}
i++;
}
sb.Append(text, last, i - last);
} while (i < text.Length);
return sb.ToString();
}
}
return text;
}
public static List findall(CodeContext/*!*/ context, object pattern, string @string, [DefaultParameterValue(0)]int flags) {
RE_Pattern pat = GetPattern(context, ValidatePattern(pattern), flags);
ValidateString(@string, "string");
MatchCollection mc = pat.FindAllWorker(context, @string, 0, @string.Length);
return FixFindAllMatch(pat, mc, null);
}
public static List findall(CodeContext context, object pattern, IList<byte> @string, [DefaultParameterValue(0)]int flags) {
RE_Pattern pat = GetPattern(context, ValidatePattern (pattern), flags);
ValidateString (@string, "string");
MatchCollection mc = pat.FindAllWorker(context, @string, 0, @string.Count);
return FixFindAllMatch (pat, mc, FindMaker(@string));
}
private static Func<string, object> FindMaker (object input) {
Func<string, object> maker = null;
if (input is ByteArray) {
maker = delegate (string x) { return new ByteArray (x.MakeByteArray ()); };
}
return maker;
}
private static List FixFindAllMatch(RE_Pattern pat, MatchCollection mc, Func<string, object> maker) {
object[] matches = new object[mc.Count];
int numgrps = pat._re.GetGroupNumbers().Length;
for (int i = 0; i < mc.Count; i++) {
if (numgrps > 2) { // CLR gives us a "bonus" group of 0 - the entire expression
// at this point we have more than one group in the pattern;
// need to return a list of tuples in this case
// for each match item in the matchcollection, create a tuple representing what was matched
// e.g. findall("(\d+)|(\w+)", "x = 99y") == [('', 'x'), ('99', ''), ('', 'y')]
// in the example above, ('', 'x') did not match (\d+) as indicated by '' but did
// match (\w+) as indicated by 'x' and so on...
int k = 0;
List<object> tpl = new List<object>();
foreach (Group g in mc[i].Groups) {
// here also the CLR gives us a "bonus" match as the first item which is the
// group that was actually matched in the tuple e.g. we get 'x', '', 'x' for
// the first match object...so we'll skip the first item when creating the
// tuple
if (k++ != 0) {
tpl.Add(maker != null ? maker(g.Value) : g.Value);
}
}
matches[i] = PythonTuple.Make(tpl);
} else if (numgrps == 2) {
// at this point we have exactly one group in the pattern (including the "bonus" one given
// by the CLR
// skip the first match since that contains the entire match and not the group match
// e.g. re.findall(r"(\w+)\s+fish\b", "green fish") will have "green fish" in the 0
// index and "green" as the (\w+) group match
matches[i] = maker != null ? maker(mc[i].Groups[1].Value) : mc[i].Groups[1].Value;
} else {
matches[i] = maker != null ? maker (mc[i].Value) : mc[i].Value;
}
}
return List.FromArrayNoCopy(matches);
}
public static object finditer(CodeContext/*!*/ context, object pattern, object @string, [DefaultParameterValue(0)]int flags) {
RE_Pattern pat = GetPattern(context, ValidatePattern(pattern), flags);
string str = ValidateString(@string, "string");
return MatchIterator(pat.FindAllWorker(context, str, 0, str.Length), pat, str);
}
public static RE_Match match(CodeContext/*!*/ context, object pattern, object @string, [DefaultParameterValue(0)]int flags) {
return GetPattern(context, ValidatePattern(pattern), flags).match(ValidateString(@string, "string"));
}
public static RE_Match search(CodeContext/*!*/ context, object pattern, object @string, [DefaultParameterValue(0)]int flags) {
return GetPattern(context, ValidatePattern(pattern), flags).search(ValidateString(@string, "string"));
}
[return: SequenceTypeInfo(typeof(string))]
public static List split(CodeContext/*!*/ context, object pattern, object @string, [DefaultParameterValue(0)]int maxsplit, [DefaultParameterValue(0)]int flags) {
return GetPattern(context, ValidatePattern(pattern), flags).split(ValidateString(@string, "string"), maxsplit);
}
public static string sub(CodeContext/*!*/ context, object pattern, object repl, object @string, [DefaultParameterValue(0)]int count, [DefaultParameterValue(0)]int flags) {
return GetPattern(context, ValidatePattern(pattern), flags).sub(context, repl, ValidateString(@string, "string"), count);
}
public static object subn(CodeContext/*!*/ context, object pattern, object repl, object @string, [DefaultParameterValue(0)]int count, [DefaultParameterValue(0)]int flags) {
return GetPattern(context, ValidatePattern(pattern), flags).subn(context, repl, ValidateString(@string, "string"), count);
}
public static void purge() {
_cachedPatterns = new CacheDict<PatternKey, RE_Pattern>(100);
}
#endregion
#region Public classes
/// <summary>
/// Compiled reg-ex pattern
/// </summary>
[PythonType]
public class RE_Pattern : IWeakReferenceable {
internal Regex _re;
private PythonDictionary _groups;
private readonly int _compileFlags;
private WeakRefTracker _weakRefTracker;
internal ParsedRegex _pre;
internal RE_Pattern(CodeContext/*!*/ context, object pattern, int flags=0, bool compiled=false) {
_pre = PreParseRegex(context, ValidatePatternAsString(pattern), (flags & VERBOSE) != 0);
try {
flags |= OptionToFlags(_pre.Options);
RegexOptions opts = FlagsToOption(flags);
this._re = new Regex(_pre.Pattern, opts | (compiled ? RegexOptions.Compiled : RegexOptions.None));
} catch (ArgumentException e) {
throw PythonExceptions.CreateThrowable(error(context), e.Message);
}
this._compileFlags = flags;
}
public RE_Match match(object text) {
string input = ValidateString(text, "text");
return RE_Match.makeMatch(_re.Match(input), this, input, 0, input.Length);
}
private static int FixPosition(string text, int position) {
if (position < 0) return 0;
if (position > text.Length) return text.Length;
return position;
}
public RE_Match match(object text, int pos) {
string input = ValidateString(text, "text");
pos = FixPosition(input, pos);
return RE_Match.makeMatch(_re.Match(input, pos), this, input, pos, input.Length);
}
public RE_Match match(object text, [DefaultParameterValue(0)]int pos, int endpos) {
string input = ValidateString(text, "text");
pos = FixPosition(input, pos);
endpos = FixPosition(input, endpos);
return RE_Match.makeMatch(
_re.Match(input.Substring(0, endpos), pos),
this,
input,
pos,
endpos);
}
public RE_Match search(object text) {
string input = ValidateString(text, "text");
return RE_Match.make(_re.Match(input), this, input);
}
public RE_Match search(object text, int pos) {
string input = ValidateString(text, "text");
if (pos < 0) pos = 0;
return RE_Match.make(_re.Match(input, pos), this, input);
}
public RE_Match search(object text, int pos, int endpos) {
string input = ValidateString(text, "text");
if (pos < 0) pos = 0;
if (endpos < pos) return null;
if (endpos < input.Length) input = input.Substring(0, endpos);
return RE_Match.make(_re.Match(input, pos), this, input);
}
public object findall(CodeContext/*!*/ context, string @string) {
return findall(context, @string, 0, null);
}
public object findall(CodeContext/*!*/ context, string @string, int pos) {
return findall(context, @string, pos, null);
}
public object findall(CodeContext/*!*/ context, object @string, int pos, object endpos) {
MatchCollection mc = FindAllWorker(context, ValidateString(@string, "text"), pos, endpos);
return FixFindAllMatch(this, mc, FindMaker(@string));
}
internal MatchCollection FindAllWorker(CodeContext/*!*/ context, string str, int pos, object endpos) {
string against = str;
if (endpos != null) {
int end = context.LanguageContext.ConvertToInt32(endpos);
against = against.Substring(0, Math.Max(end, 0));
}
return _re.Matches(against, pos);
}
internal MatchCollection FindAllWorker(CodeContext/*!*/ context, IList<byte> str, int pos, object endpos) {
string against = str.MakeString();
if (endpos != null) {
int end = context.LanguageContext.ConvertToInt32(endpos);
against = against.Substring(0, Math.Max(end, 0));
}
return _re.Matches(against, pos);
}
public object finditer(CodeContext/*!*/ context, object @string) {
string input = ValidateString(@string, "string");
return MatchIterator(FindAllWorker(context, input, 0, input.Length), this, input);
}
public object finditer(CodeContext/*!*/ context, object @string, int pos) {
string input = ValidateString(@string, "string");
return MatchIterator(FindAllWorker(context, input, pos, input.Length), this, input);
}
public object finditer(CodeContext/*!*/ context, object @string, int pos, int endpos) {
string input = ValidateString(@string, "string");
return MatchIterator(FindAllWorker(context, input, pos, endpos), this, input);
}
[return: SequenceTypeInfo(typeof(string))]
public List split(object @string, [DefaultParameterValue(0)]int maxsplit) {
List result = new List();
// fast path for negative maxSplit ( == "make no splits")
if (maxsplit < 0) {
result.AddNoLock(ValidateString(@string, "string"));
} else {
// iterate over all matches
string theStr = ValidateString(@string, "string");
MatchCollection matches = _re.Matches(theStr);
int lastPos = 0; // is either start of the string, or first position *after* the last match
int nSplits = 0; // how many splits have occurred?
foreach (Match m in matches) {
if (m.Length > 0) {
// add substring from lastPos to beginning of current match
result.AddNoLock(theStr.Substring(lastPos, m.Index - lastPos));
// if there are subgroups of the match, add their match or None
if (m.Groups.Count > 1)
for (int i = 1; i < m.Groups.Count; i++)
if (m.Groups[i].Success)
result.AddNoLock(m.Groups[i].Value);
else
result.AddNoLock(null);
// update lastPos, nSplits
lastPos = m.Index + m.Length;
nSplits++;
if (nSplits == maxsplit)
break;
}
}
// add tail following last match
result.AddNoLock(theStr.Substring(lastPos));
}
return result;
}
public string sub(CodeContext/*!*/ context, object repl, object @string, [DefaultParameterValue(0)]int count) {
if (repl == null) throw PythonOps.TypeError("NoneType is not valid repl");
// if 'count' is omitted or 0, all occurrences are replaced
if (count == 0) count = Int32.MaxValue;
string replacement = repl as string;
if (replacement == null) {
if (repl is ExtensibleString) {
replacement = ((ExtensibleString)repl).Value;
} else if (repl is Bytes) {
replacement = ((Bytes)repl).ToString();
}
}
int prevEnd = -1;
string input = ValidateString(@string, "string");
return _re.Replace(
input,
delegate(Match match) {
// from the docs: Empty matches for the pattern are replaced
// only when not adjacent to a previous match
if (string.IsNullOrEmpty(match.Value) && match.Index == prevEnd) {
return "";
};
prevEnd = match.Index + match.Length;
if (replacement != null) return UnescapeGroups(match, replacement);
return PythonCalls.Call(context, repl, RE_Match.make(match, this, input)) as string;
},
count);
}
public object subn(CodeContext/*!*/ context, object repl, object @string, [DefaultParameterValue(0)]int count) {
if (repl == null) throw PythonOps.TypeError("NoneType is not valid repl");
// if 'count' is omitted or 0, all occurrences are replaced
if (count == 0) count = Int32.MaxValue;
int totalCount = 0;
string res;
string replacement = repl as string;
if (replacement == null) {
if (repl is ExtensibleString) {
replacement = ((ExtensibleString)repl).Value;
} else if (repl is Bytes) {
replacement = ((Bytes)repl).ToString();
}
}
int prevEnd = -1;
string input = ValidateString(@string, "string");
res = _re.Replace(
input,
delegate(Match match) {
// from the docs: Empty matches for the pattern are replaced
// only when not adjacent to a previous match
if (string.IsNullOrEmpty(match.Value) && match.Index == prevEnd) {
return "";
};
prevEnd = match.Index + match.Length;
totalCount++;
if (replacement != null) return UnescapeGroups(match, replacement);
return PythonCalls.Call(context, repl, RE_Match.make(match, this, input)) as string;
},
count);
return PythonTuple.MakeTuple(res, totalCount);
}
public int flags {
get {
return _compileFlags;
}
}
public PythonDictionary groupindex {
get {
if (_groups == null) {
PythonDictionary d = new PythonDictionary();
string[] names = _re.GetGroupNames();
int[] nums = _re.GetGroupNumbers();
for (int i = 1; i < names.Length; i++) {
if (Char.IsDigit(names[i][0]) || names[i].StartsWith(_mangledNamedGroup)) {
// skip numeric names and our mangling for unnamed groups mixed w/ named groups.
continue;
}
d[names[i]] = nums[i];
}
_groups = d;
}
return _groups;
}
}
public int groups {
get {
return _re.GetGroupNumbers().Length - 1;
}
}
public string pattern {
get {
return _pre.UserPattern;
}
}
public override bool Equals(object obj) {
if (!(obj is RE_Pattern other)) {
return false;
}
return other.pattern == pattern && other.flags == flags;
}
public override int GetHashCode() {
return pattern.GetHashCode() ^ flags;
}
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _weakRefTracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_weakRefTracker = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
((IWeakReferenceable)this).SetWeakRef(value);
}
#endregion
}
public static PythonTuple _pickle(CodeContext/*!*/ context, RE_Pattern pattern) {
object scope = Importer.ImportModule(context, new PythonDictionary(), "re", false, 0);
if (scope is PythonModule && ((PythonModule)scope).__dict__.TryGetValue("compile", out object compile)) {
return PythonTuple.MakeTuple(compile, PythonTuple.MakeTuple(pattern.pattern, pattern.flags));
}
throw new InvalidOperationException("couldn't find compile method");
}
[PythonType]
public class RE_Match {
private RE_Pattern _pattern;
private Match _m;
private readonly string _text;
private int _lastindex = -1;
private readonly int _pos;
private readonly int _endPos;
#region Internal makers
internal static RE_Match make(Match m, RE_Pattern pattern, string input) {
if (m.Success) return new RE_Match(m, pattern, input, 0, input.Length);
return null;
}
internal static RE_Match make(Match m, RE_Pattern pattern, string input, int offset, int endpos) {
if (m.Success) return new RE_Match(m, pattern, input, offset, endpos);
return null;
}
internal static RE_Match makeMatch(Match m, RE_Pattern pattern, string input, int offset, int endpos) {
if (m.Success && m.Index == offset) return new RE_Match(m, pattern, input, offset, endpos);
return null;
}
#endregion
#region Public ctors
public RE_Match(Match m, RE_Pattern pattern, string text) {
_m = m;
_pattern = pattern;
_text = text;
}
public RE_Match(Match m, RE_Pattern pattern, string text, int pos, int endpos) {
_m = m;
_pattern = pattern;
_text = text;
_pos = pos;
_endPos = endpos;
}
#endregion
// public override bool __nonzero__() {
// return m.Success;
// }
#region Public API Surface
public int end() {
return _m.Index + _m.Length;
}
public int start() {
return _m.Index;
}
public int start(object group) {
int grpIndex = GetGroupIndex(group);
if (!_m.Groups[grpIndex].Success) {
return -1;
}
return _m.Groups[grpIndex].Index;
}
public int end(object group) {
int grpIndex = GetGroupIndex(group);
if (!_m.Groups[grpIndex].Success) {
return -1;
}
return _m.Groups[grpIndex].Index + _m.Groups[grpIndex].Length;
}
public object group(object index, params object[] additional) {
if (additional.Length == 0) {
return group(index);
}
object[] res = new object[additional.Length + 1];
res[0] = _m.Groups[GetGroupIndex(index)].Success ? _m.Groups[GetGroupIndex(index)].Value : null;
for (int i = 1; i < res.Length; i++) {
int grpIndex = GetGroupIndex(additional[i - 1]);
res[i] = _m.Groups[grpIndex].Success ? _m.Groups[grpIndex].Value : null;
}
return PythonTuple.MakeTuple(res);
}
public string group(object index) {
int pos = GetGroupIndex(index);
Group g = _m.Groups[pos];
return g.Success ? g.Value : null;
}
public string group() {
return group(0);
}
[return: SequenceTypeInfo(typeof(string))]
public PythonTuple groups() {
return groups(null);
}
public PythonTuple groups(object @default) {
object[] ret = new object[_m.Groups.Count - 1];
for (int i = 1; i < _m.Groups.Count; i++) {
if (!_m.Groups[i].Success) {
ret[i - 1] = @default;
} else {
ret[i - 1] = _m.Groups[i].Value;
}
}
return PythonTuple.MakeTuple(ret);
}
public string expand(object template) {
string strTmp = ValidateString(template, "template");
StringBuilder res = new StringBuilder();
for (int i = 0; i < strTmp.Length; i++) {
if (strTmp[i] != '\\') { res.Append(strTmp[i]); continue; }
if (++i == strTmp.Length) { res.Append(strTmp[i - 1]); continue; }
if (Char.IsDigit(strTmp[i])) {
AppendGroup(res, (int)(strTmp[i] - '0'));
} else if (strTmp[i] == 'g') {
if (++i == strTmp.Length) { res.Append("\\g"); return res.ToString(); }
if (strTmp[i] != '<') {
res.Append("\\g<"); continue;
} else { // '<'
StringBuilder name = new StringBuilder();
i++;
while (strTmp[i] != '>' && i < strTmp.Length) {
name.Append(strTmp[i++]);
}
AppendGroup(res, _pattern._re.GroupNumberFromName(name.ToString()));
}
} else {
switch (strTmp[i]) {
case 'n': res.Append('\n'); break;
case 'r': res.Append('\r'); break;
case 't': res.Append('\t'); break;
case '\\': res.Append('\\'); break;
}
}
}
return res.ToString();
}
[return: DictionaryTypeInfo(typeof(string), typeof(string))]
public PythonDictionary groupdict() {
return groupdict(null);
}
private static bool IsGroupNumber(string name) {
foreach (char c in name) {
if (!Char.IsNumber(c)) return false;
}
return true;
}
[return: DictionaryTypeInfo(typeof(string), typeof(string))]
public PythonDictionary groupdict([NotNull]string value) {
return groupdict((object)value);
}
[return: DictionaryTypeInfo(typeof(string), typeof(object))]
public PythonDictionary groupdict(object value) {
string[] groupNames = this._pattern._re.GetGroupNames();
Debug.Assert(groupNames.Length == this._m.Groups.Count);
PythonDictionary d = new PythonDictionary();
for (int i = 0; i < groupNames.Length; i++) {
if (IsGroupNumber(groupNames[i])) continue; // python doesn't report group numbers
if (_m.Groups[i].Captures.Count != 0) {
d[groupNames[i]] = _m.Groups[i].Value;
} else {
d[groupNames[i]] = value;
}
}
return d;
}
[return: SequenceTypeInfo(typeof(int))]
public PythonTuple span() {
return PythonTuple.MakeTuple(this.start(), this.end());
}
[return: SequenceTypeInfo(typeof(int))]
public PythonTuple span(object group) {
return PythonTuple.MakeTuple(this.start(group), this.end(group));
}
public int pos {
get {
return _pos;
}
}
public int endpos {
get {
return _endPos;
}
}
public string @string {
get {
return _text;
}
}
public PythonTuple regs {
get {
object[] res = new object[_m.Groups.Count];
for (int i = 0; i < res.Length; i++) {
res[i] = PythonTuple.MakeTuple(start(i), end(i));
}
return PythonTuple.MakeTuple(res);
}
}
public RE_Pattern re {
get {
return _pattern;
}
}
public object lastindex {
get {
// -1 : initial value of lastindex
// 0 : no match found
//other : the true lastindex
// Match.Groups contains "lower" level matched groups, which has to be removed
if (_lastindex == -1) {
int i = 1;
while (i < _m.Groups.Count) {
if (_m.Groups[i].Success) {
_lastindex = i;
int start = _m.Groups[i].Index;
int end = start + _m.Groups[i].Length;
i++;
// skip any group which fall into the range [start, end],
// no matter match succeed or fail
while (i < _m.Groups.Count && (_m.Groups[i].Index < end)) {
i++;
}
} else {
i++;
}
}
if (_lastindex == -1) {
_lastindex = 0;
}
}
if (_lastindex == 0) {
return null;
} else {
return _lastindex;
}
}
}
public string lastgroup {
get {
if (lastindex == null) return null;
// when group was not explicitly named, RegEx assigns the number as name
// This is different from C-Python, which returns None in such cases
return this._pattern._re.GroupNameFromNumber((int)lastindex);
}
}
#endregion
#region Private helper functions
private void AppendGroup(StringBuilder sb, int index) {
sb.Append(_m.Groups[index].Value);
}
private int GetGroupIndex(object group) {
if (!Converter.TryConvertToInt32(group, out int grpIndex)) {
grpIndex = _pattern._re.GroupNumberFromName(ValidateString(group, "group"));
}
if (grpIndex < 0 || grpIndex >= _m.Groups.Count) {
throw PythonOps.IndexError("no such group");
}
return grpIndex;
}
#endregion
}
#endregion
#region Private helper functions
private static RE_Pattern GetPattern(CodeContext/*!*/ context, object pattern, int flags) {
return GetPattern(context, pattern, flags, false);
}
private static RE_Pattern GetPattern(CodeContext/*!*/ context, object pattern, int flags, bool compiled) {
if (pattern is RE_Pattern res) {
return res;
}
string strPattern = ValidatePatternAsString(pattern);
PatternKey key = new PatternKey(strPattern, flags);
lock (_cachedPatterns) {
if (_cachedPatterns.TryGetValue(new PatternKey(strPattern, flags), out res)) {
if ( ! compiled || (res._re.Options & RegexOptions.Compiled) == RegexOptions.Compiled) {
return res;
}
}
res = new RE_Pattern(context, strPattern, flags, compiled);
_cachedPatterns[key] = res;
return res;
}
}
private static IEnumerator MatchIterator(MatchCollection matches, RE_Pattern pattern, string input) {
for (int i = 0; i < matches.Count; i++) {
yield return RE_Match.make(matches[i], pattern, input, 0, input.Length);
}
}
private static RegexOptions FlagsToOption(int flags) {
RegexOptions opts = RegexOptions.None;
if ((flags & (int)IGNORECASE) != 0) opts |= RegexOptions.IgnoreCase;
if ((flags & (int)MULTILINE) != 0) opts |= RegexOptions.Multiline;
if (((flags & (int)LOCALE)) == 0) opts &= (~RegexOptions.CultureInvariant);
if ((flags & (int)DOTALL) != 0) opts |= RegexOptions.Singleline;
if ((flags & (int)VERBOSE) != 0) opts |= RegexOptions.IgnorePatternWhitespace;
return opts;
}
private static int OptionToFlags(RegexOptions options) {
int flags = 0;
if ((options & RegexOptions.IgnoreCase) != 0) {
flags |= IGNORECASE;
}
if ((options & RegexOptions.Multiline) != 0) {
flags |= MULTILINE;
}
if ((options & RegexOptions.CultureInvariant) == 0) {
flags |= LOCALE;
}
if ((options & RegexOptions.Singleline) != 0) {
flags |= DOTALL;
}
if ((options & RegexOptions.IgnorePatternWhitespace) != 0) {
flags |= VERBOSE;
}
return flags;
}
internal class ParsedRegex {
public ParsedRegex(string pattern) {
this.UserPattern = pattern;
}
public string UserPattern;
public string Pattern;
public RegexOptions Options = RegexOptions.CultureInvariant;
}
private static readonly char[] _endOfLineChars = new[] { '\r', '\n' };
private static readonly char[] _preParsedChars = new[] { '(', '{', '[', ']', '#' };
private const string _mangledNamedGroup = "___PyRegexNameMangled";
/// <summary>
/// Preparses a regular expression text returning a ParsedRegex class
/// that can be used for further regular expressions.
/// </summary>
private static ParsedRegex PreParseRegex(CodeContext/*!*/ context, string pattern, bool verbose) {
ParsedRegex res = new ParsedRegex(pattern);
//string newPattern;
int cur = 0, nameIndex;
int curGroup = 0;
bool isCharList = false;
bool containsNamedGroup = false;
bool inComment = false;
int groupCount = 0;
var namedGroups = new Dictionary<string, int>();
for (; ; ) {
if (verbose && inComment) {
// read to end of line
inComment = false;
var idx = pattern.IndexOfAny(_endOfLineChars, cur);
if (idx < 0) break;
cur = idx;
}
nameIndex = pattern.IndexOfAny(_preParsedChars, cur);
if (nameIndex > 0 && pattern[nameIndex - 1] == '\\') {
int curIndex = nameIndex - 2;
int backslashCount = 1;
while (curIndex >= 0 && pattern[curIndex] == '\\') {
backslashCount++;
curIndex--;
}
// odd number of back slashes, this is an optional
// paren that we should ignore.
if ((backslashCount & 0x01) != 0) {
cur = ++nameIndex;
continue;
}
}
if (nameIndex == -1) break;
if (nameIndex == pattern.Length - 1) break;
switch (pattern[nameIndex]) {
case '{':
if (pattern[++nameIndex] == ',') {
// no beginning specified for the n-m quntifier, add the
// default 0 value.
pattern = pattern.Insert(nameIndex, "0");
}
break;
case '[':
nameIndex++;
isCharList = true;
break;
case ']':
nameIndex++;
isCharList = false;
break;
case '#':
if (verbose && !isCharList) {
inComment = true;
}
nameIndex++;
break;
case '(':
// make sure we're not dealing with [(]
if (!isCharList) {
groupCount++;
switch (pattern[++nameIndex]) {
case '?':
// extension syntax
if (nameIndex == pattern.Length - 1) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex");
switch (pattern[++nameIndex]) {
case 'P':
// named regex, .NET doesn't expect the P so we'll remove it;
// also, once we see a named group i.e. ?P then we need to start artificially
// naming all unnamed groups from then on---this is to get around the fact that
// the CLR RegEx support orders all the unnamed groups before all the named
// groups, even if the named groups are before the unnamed ones in the pattern;
// the artificial naming preserves the order of the groups and thus the order of
// the matches
if (nameIndex + 1 < pattern.Length && pattern[nameIndex + 1] == '=') {
// match whatever was previously matched by the named group
// remove the (?P=
pattern = pattern.Remove(nameIndex - 2, 4);
pattern = pattern.Insert(nameIndex - 2, "\\k<");
int tmpIndex = pattern.IndexOf(')', nameIndex);
if (tmpIndex == -1) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex");
pattern = pattern.Substring(0, tmpIndex) + ">" + pattern.Substring(tmpIndex + 1);
} else {
containsNamedGroup = true;
// we need to look and see if the named group was already seen and throw an error if it was
if(nameIndex + 1 < pattern.Length && pattern[nameIndex + 1] == '<') {
int tmpIndex = pattern.IndexOf('>', nameIndex);
if (tmpIndex == -1) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex");
var namedGroup = pattern.Substring(nameIndex + 2, tmpIndex - (nameIndex + 2));
if(namedGroups.ContainsKey(namedGroup)) {
throw PythonExceptions.CreateThrowable(error(context), $"redefinition of group name '{namedGroup}' as group {groupCount}; was group {namedGroups[namedGroup]}");
}
namedGroups[namedGroup] = groupCount;
}
pattern = pattern.Remove(nameIndex, 1);
}
break;
case 'i':
res.Options |= RegexOptions.IgnoreCase;
RemoveOption(ref pattern, ref nameIndex);
break;
case 'L':
res.Options &= ~(RegexOptions.CultureInvariant);
RemoveOption(ref pattern, ref nameIndex);
break;
case 'm': res.Options |= RegexOptions.Multiline;
RemoveOption(ref pattern, ref nameIndex);
break;
case 's': res.Options |= RegexOptions.Singleline;
RemoveOption(ref pattern, ref nameIndex);
break;
case 'u':
// specify unicode; not relevant and not valid under .NET as we're always unicode
// -- so the option needs to be removed
RemoveOption(ref pattern, ref nameIndex);
break;
case 'x': res.Options |= RegexOptions.IgnorePatternWhitespace;
RemoveOption(ref pattern, ref nameIndex);
break;
case ':': break; // non-capturing
case '=': break; // look ahead assertion
case '<': break; // positive look behind assertion
case '!': break; // negative look ahead assertion
case '#': break; // inline comment
case '(':
// conditional match alternation (?(id/name)yes-pattern|no-pattern)
// move past ?( so we don't preparse the name.
nameIndex++;
break;
default: throw PythonExceptions.CreateThrowable(error(context), "Unrecognized extension " + pattern[nameIndex]);
}
break;
default:
// just another group
curGroup++;
if (containsNamedGroup) {
// need to name this unnamed group
pattern = pattern.Insert(nameIndex, "?<" + _mangledNamedGroup + GetRandomString() + ">");
}
break;
}
} else {
nameIndex++;
}
break;
}
cur = nameIndex;
}
cur = 0;
for (; ; ) {
nameIndex = pattern.IndexOf('\\', cur);
if (nameIndex == -1 || nameIndex == pattern.Length - 1) break;
cur = ++nameIndex;
char curChar = pattern[cur];
switch (curChar) {
case 'x':
case 'u':
case 'a':
case 'b':
case 'e':
case 'f':
case 'k':
case 'n':
case 'r':
case 't':
case 'v':
case 'c':
case 's':
case 'W':
case 'w':
case 'p':
case 'P':
case 'S':
case 'd':
case 'D':
case 'A':
case 'B':
case '\\':
// known escape sequences, leave escaped.
break;
case 'Z':
// /Z matches "end of string" in Python, replace with /z which is the .NET equivalent
pattern = pattern.Remove(cur, 1).Insert(cur, "z");
break;
default:
System.Globalization.UnicodeCategory charClass = CharUnicodeInfo.GetUnicodeCategory(curChar);
switch (charClass) {
// recognized word characters, always unescape.
case System.Globalization.UnicodeCategory.ModifierLetter:
case System.Globalization.UnicodeCategory.LowercaseLetter:
case System.Globalization.UnicodeCategory.UppercaseLetter:
case System.Globalization.UnicodeCategory.TitlecaseLetter:
case System.Globalization.UnicodeCategory.OtherLetter:
case System.Globalization.UnicodeCategory.LetterNumber:
case System.Globalization.UnicodeCategory.OtherNumber:
case System.Globalization.UnicodeCategory.ConnectorPunctuation:
pattern = pattern.Remove(nameIndex - 1, 1);
cur--;
break;
case System.Globalization.UnicodeCategory.DecimalDigitNumber:
// actually don't want to unescape '\1', '\2' etc. which are references to groups
break;
}
break;
}
if (++cur >= pattern.Length) {
break;
}
}
res.Pattern = pattern;
return res;
}
private static void RemoveOption(ref string pattern, ref int nameIndex) {
if (pattern[nameIndex - 1] == '?' && nameIndex < (pattern.Length - 1) && pattern[nameIndex + 1] == ')') {
pattern = pattern.Remove(nameIndex - 2, 4);
nameIndex -= 2;
} else {
pattern = pattern.Remove(nameIndex, 1);
nameIndex -= 2;
}
}
private static string GetRandomString() {
return r.Next(Int32.MaxValue / 2, Int32.MaxValue).ToString();
}
private static string UnescapeGroups(Match m, string text) {
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\') {
StringBuilder sb = new StringBuilder(text, 0, i, text.Length);
do {
if (text[i] == '\\') {
i++;
if (i == text.Length) { sb.Append('\\'); break; }
switch (text[i]) {
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case '\\': sb.Append('\\'); break;
case '\'': sb.Append('\''); break;
case 'b': sb.Append('\b'); break;
case 'g':
// \g<#>, \g<name> need to be substituted by the groups they
// matched
if (text[i + 1] == '<') {
int anglebrkStart = i + 1;
int anglebrkEnd = text.IndexOf('>', i + 2);
if (anglebrkEnd != -1) {
// grab the # or 'name' of the group between '< >'
int lengrp = anglebrkEnd - (anglebrkStart + 1);
string grp = text.Substring(anglebrkStart + 1, lengrp);
Group g;
if (int.TryParse(grp, out int num)) {
g = m.Groups[num];
if (String.IsNullOrEmpty(g.Value)) {
throw PythonOps.IndexError("unknown group reference");
}
sb.Append(g.Value);
} else {
g = m.Groups[grp];
if (String.IsNullOrEmpty(g.Value)) {
throw PythonOps.IndexError("unknown group reference");
}
sb.Append(g.Value);
}
i = anglebrkEnd;
}
break;
}
sb.Append('\\');
sb.Append((char)text[i]);
break;
default:
if (Char.IsDigit(text[i]) && text[i] <= '7') {
int val = 0;
int digitCount = 0;
while (i < text.Length && Char.IsDigit(text[i]) && text[i] <= '7') {
digitCount++;
val += val * 8 + (text[i] - '0');
i++;
}
i--;
if (digitCount == 1 && val > 0 && val < m.Groups.Count) {
sb.Append(m.Groups[val].Value);
} else {
sb.Append((char)val);
}
} else {
sb.Append('\\');
sb.Append((char)text[i]);
}
break;
}
} else {
sb.Append(text[i]);
}
} while (++i < text.Length);
return sb.ToString();
}
}
return text;
}
private static object ValidatePattern(object pattern) {
if (pattern is string) return pattern as string;
if (pattern is ExtensibleString es) return es.Value;
if (pattern is Bytes bytes) {
return bytes.ToString();
}
if (pattern is RE_Pattern rep) return rep;
throw PythonOps.TypeError("pattern must be a string or compiled pattern");
}
private static string ValidatePatternAsString(object pattern) {
if (pattern is string) return pattern as string;
if (pattern is ExtensibleString es) return es.Value;
if (pattern is Bytes bytes) {
return bytes.ToString();
}
if (pattern is RE_Pattern rep) return rep._pre.UserPattern;
throw PythonOps.TypeError("pattern must be a string or compiled pattern");
}
private static string ValidateString(object str, string param) {
if (str is string) return str as string;
if (str is ExtensibleString es) return es.Value;
if (str is PythonBuffer buf) {
return buf.ToString();
}
if (str is Bytes bytes) {
return bytes.ToString();
}
if (str is ByteArray byteArray) {
return byteArray.MakeString();
}
if (str is ArrayModule.array array) {
return Bytes.Make(array.ToByteArray()).ToString();
}
#if FEATURE_MMAP
if (str is MmapModule.MmapDefault mmapFile) {
return mmapFile.GetSearchString();
}
#endif
throw PythonOps.TypeError($"expected string for parameter '{param}' but got '{PythonOps.GetPythonTypeName(str)}'");
}
private static PythonType error(CodeContext/*!*/ context) {
return (PythonType)context.LanguageContext.GetModuleState("reerror");
}
private class PatternKey : IEquatable<PatternKey> {
public string Pattern;
public int Flags;
public PatternKey(string pattern, int flags) {
Pattern = pattern;
Flags = flags;
}
public override bool Equals(object obj) {
if (obj is PatternKey key) {
return Equals(key);
}
return false;
}
public override int GetHashCode() {
return Pattern.GetHashCode() ^ Flags;
}
#region IEquatable<PatternKey> Members
public bool Equals(PatternKey other) {
return other.Pattern == Pattern && other.Flags == Flags;
}
#endregion
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// MemberResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Chat.V1.Service.Channel
{
public class MemberResource : Resource
{
private static Request BuildFetchRequest(FetchMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Fetch(FetchMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(FetchMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the member belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Fetch(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the member belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Create(CreateMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(CreateMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The unique ID of the channel the new member belongs to </param>
/// <param name="identity"> The `identity` value that identifies the new resource's User </param>
/// <param name="roleSid"> The SID of the Role to assign to the member </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Create(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The unique ID of the channel the new member belongs to </param>
/// <param name="identity"> The `identity` value that identifies the new resource's User </param>
/// <param name="roleSid"> The SID of the Role to assign to the member </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static ResourceSet<MemberResource> Read(ReadMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<MemberResource>.FromJson("members", response.Content);
return new ResourceSet<MemberResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(ReadMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<MemberResource>.FromJson("members", response.Content);
return new ResourceSet<MemberResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the member belongs to </param>
/// <param name="identity"> The `identity` value of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static ResourceSet<MemberResource> Read(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the member belongs to </param>
/// <param name="identity"> The `identity` value of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<MemberResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("members", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<MemberResource> NextPage(Page<MemberResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("members", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<MemberResource> PreviousPage(Page<MemberResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("members", response.Content);
}
private static Request BuildDeleteRequest(DeleteMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static bool Delete(DeleteMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the message to delete belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static bool Delete(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The unique ID of the channel the message to delete belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Update(UpdateMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(UpdateMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The unique ID of the channel the member to update belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="roleSid"> The SID of the Role to assign to the member </param>
/// <param name="lastConsumedMessageIndex"> The index of the last consumed Message for the Channel for the Member
/// </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Update(string pathServiceSid,
string pathChannelSid,
string pathSid,
string roleSid = null,
int? lastConsumedMessageIndex = null,
ITwilioRestClient client = null)
{
var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The unique ID of the channel the member to update belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="roleSid"> The SID of the Role to assign to the member </param>
/// <param name="lastConsumedMessageIndex"> The index of the last consumed Message for the Channel for the Member
/// </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
string roleSid = null,
int? lastConsumedMessageIndex = null,
ITwilioRestClient client = null)
{
var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a MemberResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> MemberResource object represented by the provided JSON </returns>
public static MemberResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<MemberResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The unique ID of the Channel for the member
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The SID of the Service that the resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The string that identifies the resource's User
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The SID of the Role assigned to the member
/// </summary>
[JsonProperty("role_sid")]
public string RoleSid { get; private set; }
/// <summary>
/// The index of the last Message that the Member has read within the Channel
/// </summary>
[JsonProperty("last_consumed_message_index")]
public int? LastConsumedMessageIndex { get; private set; }
/// <summary>
/// The ISO 8601 based timestamp string that represents the date-time of the last Message read event for the Member within the Channel
/// </summary>
[JsonProperty("last_consumption_timestamp")]
public DateTime? LastConsumptionTimestamp { get; private set; }
/// <summary>
/// The absolute URL of the Member resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private MemberResource()
{
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 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;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ConstraintExpression represents a compound constraint in the
/// process of being constructed from a series of syntactic elements.
///
/// Individual elements are appended to the expression as they are
/// reorganized. When a constraint is appended, it is returned as the
/// value of the operation so that modifiers may be applied. However,
/// any partially built expression is attached to the constraint for
/// later resolution. When an operator is appended, the partial
/// expression is returned. If it's a self-resolving operator, then
/// a ResolvableConstraintExpression is returned.
/// </summary>
public class ConstraintExpression
{
#region Instance Fields
/// <summary>
/// The ConstraintBuilder holding the elements recognized so far
/// </summary>
#pragma warning disable IDE1006
// ReSharper disable once InconsistentNaming
// Disregarding naming convention for back-compat
protected readonly ConstraintBuilder builder;
#pragma warning restore IDE1006
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintExpression"/> class.
/// </summary>
public ConstraintExpression() : this(new ConstraintBuilder())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintExpression"/>
/// class passing in a ConstraintBuilder, which may be pre-populated.
/// </summary>
/// <param name="builder">The builder.</param>
public ConstraintExpression(ConstraintBuilder builder)
{
Guard.ArgumentNotNull(builder, nameof(builder));
this.builder = builder;
}
#endregion
#region ToString()
/// <summary>
/// Returns a string representation of the expression as it
/// currently stands. This should only be used for testing,
/// since it has the side-effect of resolving the expression.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return builder.Resolve().ToString();
}
#endregion
#region Append Methods
/// <summary>
/// Appends an operator to the expression and returns the
/// resulting expression itself.
/// </summary>
public ConstraintExpression Append(ConstraintOperator op)
{
builder.Append(op);
return this;
}
/// <summary>
/// Appends a self-resolving operator to the expression and
/// returns a new ResolvableConstraintExpression.
/// </summary>
public ResolvableConstraintExpression Append(SelfResolvingOperator op)
{
builder.Append(op);
return new ResolvableConstraintExpression(builder);
}
/// <summary>
/// Appends a constraint to the expression and returns that
/// constraint, which is associated with the current state
/// of the expression being built. Note that the constraint
/// is not reduced at this time. For example, if there
/// is a NotOperator on the stack we don't reduce and
/// return a NotConstraint. The original constraint must
/// be returned because it may support modifiers that
/// are yet to be applied.
/// </summary>
public Constraint Append(Constraint constraint)
{
builder.Append(constraint);
return constraint;
}
#endregion
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return this.Append(new NotOperator()); }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return this.Append(new NotOperator()); }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return this.Append(new AllOperator()); }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return this.Append(new SomeOperator()); }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return this.Append(new NoneOperator()); }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public ItemsConstraintExpression Exactly(int expectedCount)
{
builder.Append(new ExactCountOperator(expectedCount));
return new ItemsConstraintExpression(builder);
}
#endregion
#region One
/// <summary>
/// Returns a <see cref="ItemsConstraintExpression"/>, which will
/// apply the following constraint to a collection of length one, succeeding
/// only if exactly one of them succeeds.
/// </summary>
public ItemsConstraintExpression One
{
get
{
builder.Append(new ExactCountOperator(1));
return new ItemsConstraintExpression(builder);
}
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return this.Append(new PropOperator(name));
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Property("Length"); }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Property("Count"); }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Property("Message"); }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Property("InnerException"); }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return this.Append(new AttributeOperator(expectedType));
}
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<TExpected>()
{
return Attribute(typeof(TExpected));
}
#endregion
#region With
/// <summary>
/// With is currently a NOP - reserved for future use.
/// </summary>
public ConstraintExpression With
{
get { return this.Append(new WithOperator()); }
}
#endregion
#region Matches
/// <summary>
/// Returns the constraint provided as an argument - used to allow custom
/// custom constraints to easily participate in the syntax.
/// </summary>
public Constraint Matches(IResolveConstraint constraint)
{
return this.Append((Constraint)constraint.Resolve());
}
/// <summary>
/// Returns the constraint provided as an argument - used to allow custom
/// custom constraints to easily participate in the syntax.
/// </summary>
public Constraint Matches<TActual>(Predicate<TActual> predicate)
{
return this.Append(new PredicateConstraint<TActual>(predicate));
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return (NullConstraint)this.Append(new NullConstraint()); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return (TrueConstraint)this.Append(new TrueConstraint()); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return (FalseConstraint)this.Append(new FalseConstraint()); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); }
}
#endregion
#region Zero
/// <summary>
/// Returns a constraint that tests if item is equal to zero
/// </summary>
public EqualConstraint Zero
{
get { return (EqualConstraint)this.Append(new EqualConstraint(0)); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return (NaNConstraint)this.Append(new NaNConstraint()); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return (EmptyConstraint)this.Append(new EmptyConstraint()); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); }
}
#endregion
#if SERIALIZATION
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); }
}
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in XML format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); }
}
#endif
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return (EqualConstraint)this.Append(new EqualConstraint(expected));
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return (SameAsConstraint)this.Append(new SameAsConstraint(expected));
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the supplied argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected));
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected));
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected));
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the supplied argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return (LessThanConstraint)this.Append(new LessThanConstraint(expected));
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected));
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected));
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<TExpected>()
{
return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(TExpected)));
}
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<TExpected>()
{
return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(TExpected)));
}
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<TExpected>()
{
return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(TExpected)));
}
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<TExpected>()
{
return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(TExpected)));
}
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected));
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected));
}
#endregion
#region SupersetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a superset of the collection supplied as an argument.
/// </summary>
public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
{
return (CollectionSupersetConstraint)this.Append(new CollectionSupersetConstraint(expected));
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); }
}
#endregion
#region Member
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Member(object expected)
{
return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected)));
}
#endregion
#region Contains
/// <summary>
/// <para>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </para>
/// <para>
/// To search for a substring instead of a collection element, use the
/// <see cref="Contains(string)"/> overload.
/// </para>
/// </summary>
public SomeItemsConstraint Contains(object expected)
{
return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected)));
}
/// <summary>
/// <para>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// </para>
/// <para>
/// To search for a collection element instead of a substring, use the
/// <see cref="Contains(object)"/> overload.
/// </para>
/// </summary>
public ContainsConstraint Contains(string expected)
{
return (ContainsConstraint)this.Append(new ContainsConstraint(expected));
}
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Contain(object expected)
{
return Contains(expected);
}
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contain(string expected)
{
return Contains(expected);
}
#endregion
#region DictionaryContains
/// <summary>
/// Returns a new DictionaryContainsKeyConstraint checking for the
/// presence of a particular key in the Dictionary key collection.
/// </summary>
/// <param name="expected">The key to be matched in the Dictionary key collection</param>
public DictionaryContainsKeyConstraint ContainKey(object expected)
{
return (DictionaryContainsKeyConstraint)this.Append(new DictionaryContainsKeyConstraint(expected));
}
/// <summary>
/// Returns a new DictionaryContainsValueConstraint checking for the
/// presence of a particular value in the Dictionary value collection.
/// </summary>
/// <param name="expected">The value to be matched in the Dictionary value collection</param>
public DictionaryContainsValueConstraint ContainValue(object expected)
{
return (DictionaryContainsValueConstraint)this.Append(new DictionaryContainsValueConstraint(expected));
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint StringContaining(string expected)
{
return (SubstringConstraint)this.Append(new SubstringConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint ContainsSubstring(string expected)
{
return (SubstringConstraint)this.Append(new SubstringConstraint(expected));
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartWith(string expected)
{
return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.StartWith or StartsWith")]
public StartsWithConstraint StringStarting(string expected)
{
return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndWith(string expected)
{
return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.EndWith or EndsWith")]
public EndsWithConstraint StringEnding(string expected)
{
return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
}
#endregion
#region Matches
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Match(string pattern)
{
return (RegexConstraint)this.Append(new RegexConstraint(pattern));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return (RegexConstraint)this.Append(new RegexConstraint(pattern));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Match or Matches")]
public RegexConstraint StringMatching(string pattern)
{
return (RegexConstraint)this.Append(new RegexConstraint(pattern));
}
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return (SamePathConstraint)this.Append(new SamePathConstraint(expected));
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the a subpath of the expected path after canonicalization.
/// </summary>
public SubPathConstraint SubPathOf(string expected)
{
return (SubPathConstraint)this.Append(new SubPathConstraint(expected));
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected));
}
#endregion
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// inclusively within a specified range.
/// </summary>
/// <param name="from">Inclusive beginning of the range.</param>
/// <param name="to">Inclusive end of the range.</param>
public RangeConstraint InRange(object from, object to)
{
return (RangeConstraint)this.Append(new RangeConstraint(from, to));
}
#endregion
#region Exist
/// <summary>
/// Returns a constraint that succeeds if the value
/// is a file or directory and it exists.
/// </summary>
public Constraint Exist
{
get { return Append(new FileOrDirectoryExistsConstraint()); }
}
#endregion
#region AnyOf
/// <summary>
/// Returns a constraint that tests if an item is equal to any of parameters
/// </summary>
/// <param name="expected">Expected values</param>
public AnyOfConstraint AnyOf(params object[] expected)
{
if (expected == null)
{
expected = new object[] { null };
}
return (AnyOfConstraint)this.Append(new AnyOfConstraint(expected));
}
#endregion
}
}
| |
// The MIT License
//
// Copyright (c) 2012-2015 Jordan E. Terrell
//
// 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.Linq;
using System.Text;
using NUnit.Framework;
using Rhino.Mocks;
namespace iSynaptic.Commons.Data
{
[TestFixture]
public class StandardExodataResolverTests
{
[SetUp]
public void BeforeTest()
{
Ioc.SetDependencyResolver(null);
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = false;
}
[Test]
public void Resolve_UsesIocToCreateSurrogates()
{
bool executed = false;
Ioc.SetDependencyResolver(new DependencyResolver(x => x
.ToMaybe()
.OfType<IDependencySymbol>()
.Where(y => typeof(BaseTestSubjectExodataSurrogate).IsAssignableFrom(y.DependencyType))
.Select(y => Activator.CreateInstance(y.DependencyType))
.OnValue(y => executed = true)));
var resolver = new StandardExodataResolver();
var value = resolver.TryResolve(StringExodata.MaxLength).For<TestSubject>(x => x.MiddleName);
Assert.AreEqual(74088, value);
Assert.IsTrue(executed);
}
[Test]
public void Resolve_WithModuleProvidedMatchingBinding_ReturnsValue()
{
var resolver = new StandardExodataResolver(new TestExodataBindingModule());
int value = resolver.TryResolve(StringExodata.MaxLength).Get();
Assert.AreEqual(42, value);
}
[Test]
public void TryResolve_AfterUnloadingModule_ReturnsNoValue()
{
var module = new TestExodataBindingModule();
var resolver = new StandardExodataResolver(module);
Maybe<int> value = resolver.TryResolve(StringExodata.MaxLength).TryGet();
Assert.IsTrue(value == 42);
resolver.UnloadModule(module);
value = resolver.TryResolve(StringExodata.MaxLength).TryGet();
Assert.IsTrue(value == Maybe<int>.NoValue);
}
[Test]
public void Resolve_WithAttributedProperty_ReturnsValue()
{
var resolver = new StandardExodataResolver();
var minLength = resolver.TryResolve(StringExodata.MinLength).For<TestSubject>(x => x.FirstName);
Assert.AreEqual(21, minLength);
var maxLength = resolver.TryResolve(StringExodata.MaxLength).For<TestSubject>(x => x.FirstName);
Assert.AreEqual(84, maxLength);
var description = resolver.TryResolve(CommonExodata.Description).For<TestSubject>(x => x.FirstName);
Assert.AreEqual("First Name", description);
}
[Test]
public void Resolve_WithAttributedField_ReturnsValue()
{
var resolver = new StandardExodataResolver();
var allExodata = resolver.TryResolve(StringExodata.All).For<TestSubject>(x => x.LastName);
Assert.AreEqual(7, allExodata.MinimumLength);
Assert.AreEqual(1764, allExodata.MaximumLength);
Assert.AreEqual("Last Name", allExodata.Description);
}
[Test]
public void Resolve_WithAttributedFieldForBaseExodataClass_ReturnsValue()
{
var resolver = new StandardExodataResolver();
var allExodata = resolver.TryResolve(CommonExodata.All).For<TestSubject>(x => x.LastName);
Assert.IsNotNull(allExodata);
Assert.AreEqual("Last Name", allExodata.Description);
}
[Test]
public void Resolve_WithSurrogate_ReturnsValue()
{
var resolver = new StandardExodataResolver();
var value = resolver.TryResolve(StringExodata.MaxLength).For<TestSubject>(x => x.MiddleName);
Assert.AreEqual(74088, value);
}
[Test]
public void Resolve_WithAttributedType_ReturnsValue()
{
var resolver = new StandardExodataResolver();
var value = resolver.TryResolve(CommonExodata.Description).For<TestSubject>();
Assert.AreEqual("Test Subject", value);
}
[Test]
public void Resolve_WithModuleThatOverridesAttributeExodata_ReturnsValue()
{
var resolver = new StandardExodataResolver(new TestExodataBindingModule());
var value = resolver.TryResolve(CommonExodata.Description).For<TestSubject>();
Assert.AreEqual("Overridden Description", value);
}
[Test]
public void Resolve_AgainstSubjectInstanceWithAttributedType_ReturnsValue()
{
var resolver = new StandardExodataResolver();
var subject = new TestSubject();
var value = resolver.TryResolve(CommonExodata.Description).For(subject);
Assert.AreEqual("Test Subject", value);
}
[Test]
public void Resolve_AgainstSpecificInstance_WorksCorrectly()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
var value = resolver.TryResolve(CommonExodata.Description).For(BaseTestSubjectExodataSurrogate.Subject);
Assert.AreEqual("Special Instance Description", value);
}
[Test]
public void Resolve_AgainstArbitraryInstance_YieldsAttributeExodata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = false;
var value = resolver.TryResolve(CommonExodata.Description).For(new TestSubject());
Assert.AreEqual("Test Subject", value);
}
[Test]
public void Resolve_AgainstArbitraryInstance_YieldsSurrogateExodata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
var value = resolver.TryResolve(CommonExodata.Description).For(new TestSubject());
Assert.AreEqual("Surrogate Description", value);
}
[Test]
public void Resolve_AgainstSpecificInstanceWhenPredicateReturnsFalse_YieldsAttributeExodata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = false;
var value = resolver.TryResolve(CommonExodata.Description).For(BaseTestSubjectExodataSurrogate.Subject);
Assert.AreEqual("Test Subject", value);
}
[Test]
public void Resolve_AgainstArbitraryDerivedInstance_YieldsSurrogateExodata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
var value = resolver.TryResolve(CommonExodata.Description).For(new DerivedTestSubject());
Assert.AreEqual("Surrogate Description", value);
}
[Test]
public void Resolve_WithDerivedInstance_YieldsMostDerivedBindingsExodata()
{
var resolver = new StandardExodataResolver();
resolver.Bind(CommonExodata.Description)
.For<DerivedTestSubject>()
.To("Derived Surrogate Description");
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
var value = resolver.TryResolve(CommonExodata.Description).For(new DerivedTestSubject());
Assert.AreEqual("Derived Surrogate Description", value);
}
[Test]
public void Resolve_WithSpecificInstanceAgainstMember_YieldsExodataSurrogateMetadata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
var value = resolver.TryResolve(CommonExodata.Description).For(BaseTestSubjectExodataSurrogate.Subject, x => x.FirstName);
Assert.AreEqual("Special Member Description", value);
}
[Test]
public void Resolve_WithSimpleStaticBinding_YieldsExodataSurrogateExodata()
{
var resolver = new StandardExodataResolver();
Assert.AreEqual("A string...", resolver.TryResolve(CommonExodata.Description).For<string>());
}
[Test]
public void Resolve_WithContext_YieldsContextualExodataSurrogateExodata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
Assert.AreEqual("Contextual Member Description", resolver.TryResolve(CommonExodata.Description).Given<string>().For<TestSubject>(x => x.FirstName));
}
[Test]
public void Resolve_WithSpecificContext_YieldsSpecificContextualExodataSurrogateExodata()
{
var resolver = new StandardExodataResolver();
BaseTestSubjectExodataSurrogate.ShouldYieldInstanceExodata = true;
Assert.AreEqual("Specific Contextual Member Description", resolver.TryResolve(CommonExodata.Description).Given("Context").For<TestSubject>(x => x.FirstName));
}
[Test]
public void Resolve_WithMultipleMembers_YieldsExodata()
{
var resolver = new StandardExodataResolver();
resolver.Bind(IntegerExodata.MinValue)
.For<DateTime>(x => x.Day, x => x.Month)
.To(42);
Assert.AreEqual(42, resolver.TryResolve(IntegerExodata.MinValue).For<DateTime>(x => x.Day));
Assert.AreEqual(42, resolver.TryResolve(IntegerExodata.MinValue).For<DateTime>(x => x.Month));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Imaging.MetafileHeader.cs
//
// Author: Everaldo Canuto
// eMail: [email protected]
// Dennis Hayes ([email protected])
//
// (C) 2002 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004, 2006 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.Drawing.Drawing2D;
using System.Runtime.InteropServices;
namespace System.Drawing.Imaging
{
[StructLayout(LayoutKind.Sequential, Pack = 2)]
internal struct EnhMetafileHeader
{
public int type;
public int size;
public Rectangle bounds;
public Rectangle frame;
public int signature;
public int version;
public int bytes;
public int records;
public short handles;
public short reserved;
public int description;
public int off_description;
public int palette_entires;
public Size device;
public Size millimeters;
}
// hack: keep public type as Sequential while making it possible to get the required union
[StructLayout(LayoutKind.Explicit)]
internal struct MonoMetafileHeader
{
[FieldOffset(0)]
public MetafileType type;
[FieldOffset(4)]
public int size;
[FieldOffset(8)]
public int version;
[FieldOffset(12)]
public int emf_plus_flags;
[FieldOffset(16)]
public float dpi_x;
[FieldOffset(20)]
public float dpi_y;
[FieldOffset(24)]
public int x;
[FieldOffset(28)]
public int y;
[FieldOffset(32)]
public int width;
[FieldOffset(36)]
public int height;
[FieldOffset(40)]
public WmfMetaHeader wmf_header;
[FieldOffset(40)]
public EnhMetafileHeader emf_header;
[FieldOffset(128)]
public int emfplus_header_size;
[FieldOffset(132)]
public int logical_dpi_x;
[FieldOffset(136)]
public int logical_dpi_y;
}
[StructLayout(LayoutKind.Sequential)]
public sealed class MetafileHeader
{
private MonoMetafileHeader header;
//constructor
internal MetafileHeader(IntPtr henhmetafile)
{
Marshal.PtrToStructure(henhmetafile, this);
}
// methods
public bool IsDisplay()
{
return false;
}
public bool IsEmf()
{
return (Type == MetafileType.Emf);
}
public bool IsEmfOrEmfPlus()
{
return (Type >= MetafileType.Emf);
}
public bool IsEmfPlus()
{
return (Type >= MetafileType.EmfPlusOnly);
}
public bool IsEmfPlusDual()
{
return (Type == MetafileType.EmfPlusDual);
}
public bool IsEmfPlusOnly()
{
return (Type == MetafileType.EmfPlusOnly);
}
public bool IsWmf()
{
return (Type <= MetafileType.WmfPlaceable);
}
public bool IsWmfPlaceable()
{
return (Type == MetafileType.WmfPlaceable);
}
// properties
public Rectangle Bounds
{
get
{
if (this.MetafileSize == 0)
{
// GDI+ compatibility;
return new Rectangle();
}
return new Rectangle(header.x, header.y, header.width, header.height);
}
}
public float DpiX
{
get { return header.dpi_x; }
}
public float DpiY
{
get { return header.dpi_y; }
}
public int EmfPlusHeaderSize
{
get { return header.emfplus_header_size; }
}
public int LogicalDpiX
{
get { return header.logical_dpi_x; }
}
public int LogicalDpiY
{
get { return header.logical_dpi_y; }
}
public int MetafileSize
{
get { return header.size; }
}
public MetafileType Type
{
get { return header.type; }
}
public int Version
{
get { return header.version; }
}
// note: this always returns a new instance (where we can change
// properties even if they don't seems to affect anything)
public MetaHeader WmfHeader
{
get
{
if (IsWmf())
return new MetaHeader(header.wmf_header);
throw new ArgumentException("WmfHeader only available on WMF files.");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Language.Extensions;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X
{
public class ModelDirectiveTest : RazorProjectEngineTestBase
{
protected override RazorLanguageVersion Version => RazorLanguageVersion.Version_2_1;
[Fact]
public void ModelDirective_GetModelType_GetsTypeFromFirstWellFormedDirective()
{
// Arrange
var codeDocument = CreateDocument(@"
@model Type1
@model Type2
@model
");
var engine = CreateRuntimeEngine();
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
var result = ModelDirective.GetModelType(irDocument);
// Assert
Assert.Equal("Type1", result);
}
[Fact]
public void ModelDirective_GetModelType_DefaultsToDynamic()
{
// Arrange
var codeDocument = CreateDocument(@" ");
var engine = CreateRuntimeEngine();
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
var result = ModelDirective.GetModelType(irDocument);
// Assert
Assert.Equal("dynamic", result);
}
[Fact]
public void ModelDirectivePass_Execute_ReplacesTModelInBaseType()
{
// Arrange
var codeDocument = CreateDocument(@"
@inherits BaseType<TModel>
@model Type1
");
var engine = CreateRuntimeEngine();
var pass = new ModelDirective.Pass()
{
Engine = engine,
};
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
var @class = FindClassNode(irDocument);
Assert.NotNull(@class);
Assert.Equal("BaseType<Type1>", @class.BaseType);
}
[Fact]
public void ModelDirectivePass_Execute_ReplacesTModelInBaseType_DifferentOrdering()
{
// Arrange
var codeDocument = CreateDocument(@"
@model Type1
@inherits BaseType<TModel>
@model Type2
");
var engine = CreateRuntimeEngine();
var pass = new ModelDirective.Pass()
{
Engine = engine,
};
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
var @class = FindClassNode(irDocument);
Assert.NotNull(@class);
Assert.Equal("BaseType<Type1>", @class.BaseType);
}
[Fact]
public void ModelDirectivePass_Execute_NoOpWithoutTModel()
{
// Arrange
var codeDocument = CreateDocument(@"
@inherits BaseType
@model Type1
");
var engine = CreateRuntimeEngine();
var pass = new ModelDirective.Pass()
{
Engine = engine,
};
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
var @class = FindClassNode(irDocument);
Assert.NotNull(@class);
Assert.Equal("BaseType", @class.BaseType);
}
[Fact]
public void ModelDirectivePass_Execute_ReplacesTModelInBaseType_DefaultDynamic()
{
// Arrange
var codeDocument = CreateDocument(@"
@inherits BaseType<TModel>
");
var engine = CreateRuntimeEngine();
var pass = new ModelDirective.Pass()
{
Engine = engine,
};
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
var @class = FindClassNode(irDocument);
Assert.NotNull(@class);
Assert.Equal("BaseType<dynamic>", @class.BaseType);
}
[Fact]
public void ModelDirectivePass_DesignTime_AddsTModelUsingDirective()
{
// Arrange
var codeDocument = CreateDocument(@"
@inherits BaseType<TModel>
");
var engine = CreateDesignTimeEngine();
var pass = new ModelDirective.Pass()
{
Engine = engine,
};
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
var @class = FindClassNode(irDocument);
Assert.NotNull(@class);
Assert.Equal("BaseType<dynamic>", @class.BaseType);
var @namespace = FindNamespaceNode(irDocument);
var usingNode = Assert.IsType<UsingDirectiveIntermediateNode>(@namespace.Children[0]);
Assert.Equal($"TModel = global::{typeof(object).FullName}", usingNode.Content);
}
[Fact]
public void ModelDirectivePass_DesignTime_WithModel_AddsTModelUsingDirective()
{
// Arrange
var codeDocument = CreateDocument(@"
@inherits BaseType<TModel>
@model SomeType
");
var engine = CreateDesignTimeEngine();
var pass = new ModelDirective.Pass()
{
Engine = engine,
};
var irDocument = CreateIRDocument(engine, codeDocument);
// Act
pass.Execute(codeDocument, irDocument);
// Assert
var @class = FindClassNode(irDocument);
Assert.NotNull(@class);
Assert.Equal("BaseType<SomeType>", @class.BaseType);
var @namespace = FindNamespaceNode(irDocument);
var usingNode = Assert.IsType<UsingDirectiveIntermediateNode>(@namespace.Children[0]);
Assert.Equal($"TModel = global::System.Object", usingNode.Content);
}
private RazorCodeDocument CreateDocument(string content)
{
var source = RazorSourceDocument.Create(content, "test.cshtml");
return RazorCodeDocument.Create(source);
}
private ClassDeclarationIntermediateNode FindClassNode(IntermediateNode node)
{
var visitor = new ClassNodeVisitor();
visitor.Visit(node);
return visitor.Node;
}
private NamespaceDeclarationIntermediateNode FindNamespaceNode(IntermediateNode node)
{
var visitor = new NamespaceNodeVisitor();
visitor.Visit(node);
return visitor.Node;
}
private RazorEngine CreateRuntimeEngine()
{
return CreateEngineCore();
}
private RazorEngine CreateDesignTimeEngine()
{
return CreateEngineCore(designTime: true);
}
private RazorEngine CreateEngineCore(bool designTime = false)
{
return CreateProjectEngine(b =>
{
// Notice we're not registering the ModelDirective.Pass here so we can run it on demand.
b.AddDirective(ModelDirective.Directive);
// There's some special interaction with the inherits directive
InheritsDirective.Register(b);
b.Features.Add(new DesignTimeOptionsFeature(designTime));
}).Engine;
}
private DocumentIntermediateNode CreateIRDocument(RazorEngine engine, RazorCodeDocument codeDocument)
{
for (var i = 0; i < engine.Phases.Count; i++)
{
var phase = engine.Phases[i];
phase.Execute(codeDocument);
if (phase is IRazorDocumentClassifierPhase)
{
break;
}
}
// InheritsDirectivePass needs to run before ModelDirective.
var pass = new InheritsDirectivePass()
{
Engine = engine
};
pass.Execute(codeDocument, codeDocument.GetDocumentIntermediateNode());
return codeDocument.GetDocumentIntermediateNode();
}
private string GetCSharpContent(IntermediateNode node)
{
var builder = new StringBuilder();
for (var i = 0; i < node.Children.Count; i++)
{
var child = node.Children[i] as IntermediateToken;
if (child.Kind == TokenKind.CSharp)
{
builder.Append(child.Content);
}
}
return builder.ToString();
}
private class ClassNodeVisitor : IntermediateNodeWalker
{
public ClassDeclarationIntermediateNode Node { get; set; }
public override void VisitClassDeclaration(ClassDeclarationIntermediateNode node)
{
Node = node;
}
}
private class NamespaceNodeVisitor : IntermediateNodeWalker
{
public NamespaceDeclarationIntermediateNode Node { get; set; }
public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateNode node)
{
Node = node;
}
}
private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature
{
private readonly bool _designTime;
public DesignTimeOptionsFeature(bool designTime)
{
_designTime = designTime;
}
public int Order { get; }
public RazorEngine Engine { get; set; }
public void Configure(RazorParserOptionsBuilder options)
{
options.SetDesignTime(_designTime);
}
public void Configure(RazorCodeGenerationOptionsBuilder options)
{
options.SetDesignTime(_designTime);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using NUnit.Framework;
using SuperSocket.Common;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Logging;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using SuperWebSocket;
using WebSocket4Net;
namespace WeblogNG.Test
{
[TestFixture()]
public class LoggerAPIConnectionWSTest
{
private static Random random = new Random();
private WebSocketServer webSocketServer;
private LinkedList<String> receivedMessages;
private AutoResetEvent socketOpenedEvent = new AutoResetEvent(false);
private AutoResetEvent socketClosedEvent = new AutoResetEvent(false);
private String serverHost = "localhost";
private int serverPort = 2424;
[TestFixtureSetUp]
public virtual void Setup()
{
RegisterUnhandledExceptionHandler ();
webSocketServer = new WebSocketServer();
webSocketServer.NewSessionConnected += new SessionHandler<WebSocketSession>(webSocketServer_NewSessionConnected);
webSocketServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(webSocketServer_NewMessageReceived);
webSocketServer.Setup(new ServerConfig
{
Port = serverPort,
Ip = "Any",
MaxConnectionNumber = 10,
Mode = SocketMode.Tcp,
Name = "WeblogNG Integration Testing Server",
LogAllSocketException = true,
}, logFactory: new ConsoleLogFactory());
}
//fails due to what appears to be an uncaught error in SuperSocket/WebSocket4Net
/// <summary>
/// Registers an unhandled exception handler that prints the exception. This is necessary because SuperSocket/WebSocket4Net
/// generates unhandled exceptions during the failure-handling tests.
/// </summary>
/// <example>
///System.Net.Sockets.Socket.SetSocketOption (optionLevel=System.Net.Sockets.SocketOptionLevel.Socket, optionName=System.Net.Sockets.SocketOptionName.KeepAlive, optionValue=true) in /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin/build-root/mono-3.2.5/mcs/class/System/System.Net.Sockets/Socket.cs:2091
///SuperSocket.ClientEngine.TcpClientSession.ProcessConnect (socket={System.Net.Sockets.Socket}, state=(null), e={System.Net.Sockets.SocketAsyncEventArgs}) in
///SuperSocket.ClientEngine.ConnectAsyncExtension.SocketConnectCompleted (sender={System.Net.Sockets.Socket}, e={System.Net.Sockets.SocketAsyncEventArgs}) in
///System.Net.Sockets.SocketAsyncEventArgs.OnCompleted (e={System.Net.Sockets.SocketAsyncEventArgs}) in /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin/build-root/mono-3.2.5/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs:177
///System.Net.Sockets.SocketAsyncEventArgs.ConnectCallback () in /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin/build-root/mono-3.2.5/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs:262
///System.Net.Sockets.SocketAsyncEventArgs.DispatcherCB (ares={System.Net.Sockets.Socket.SocketAsyncResult}) in /private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin/build-root/mono-3.2.5/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs:234
/// </example>
private void RegisterUnhandledExceptionHandler()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionUtilities.UnhandledExceptionHandler);
}
void webSocketServer_NewSessionConnected (WebSocketSession session)
{
Console.WriteLine ("New session connected to test server. {0}", session.ToString ());
session.Send ("v1.control");
}
void webSocketServer_NewMessageReceived(WebSocketSession session, String message)
{
this.receivedMessages.AddLast (message);
Console.WriteLine (String.Format("integration test server received new message: {0}", receivedMessages.Last.Value));
Console.WriteLine (String.Format ("integration test server has received {0} message(s)", receivedMessages.Count));
}
[SetUp]
public void SetUp()
{
StartServer ();
}
[TearDown]
public void TearDown()
{
StopServer ();
}
public void StartServer()
{
receivedMessages = new LinkedList<String> ();
webSocketServer.Start();
}
public void StopServer()
{
webSocketServer.Stop();
}
protected void webSocketClient_Opened(object sender, EventArgs e)
{
socketOpenedEvent.Set();
}
protected void webSocketClient_Closed(object sender, EventArgs e)
{
socketClosedEvent.Set();
}
[Test()]
public void should_be_configured_via_constructor_params()
{
String expectedKey = "key";
String expectedHost = "somehost:42";
String expectedUrl = "ws://" + expectedHost + "/log/ws";
LoggerAPIConnectionWS apiConn = new LoggerAPIConnectionWS (expectedHost, expectedKey);
Assert.AreEqual (expectedKey, apiConn.ApiKey);
Assert.AreEqual (expectedUrl, apiConn.ApiUrl);
Assert.IsNull (apiConn.WebSocket);
}
[Test()]
public void should_get_or_create_a_properly_configured_open_websocket()
{
String expectedKey = "key";
String expectedHost = string.Format("{0}:{1}", serverHost, serverPort);
LoggerAPIConnectionWS apiConn = new LoggerAPIConnectionWS (expectedHost, expectedKey);
Assert.IsNull (apiConn.WebSocket);
WebSocket client = apiConn.GetOrCreateOpenWebSocket ();
//verify users of GetOrCreateWebSocket should not have to manage the socket opening process
//clients should expect GetOrCreateWebSocket to block and return an open conn or throw an exception
//note: there are no waits between GetOrCreateWebSocket and the assertion that the socket is in an open state
Assert.AreEqual (WebSocketState.Open, client.State);
client.Closed += new EventHandler (webSocketClient_Closed);
client.Close();
if (!socketClosedEvent.WaitOne(1000))
Assert.Fail("Failed to close session ontime");
Assert.AreEqual(WebSocketState.Closed, client.State);
}
private LoggerAPIConnectionWS MakeAPIConnToTestServer()
{
String expectedKey = "key";
String expectedHost = string.Format("{0}:{1}", serverHost, serverPort);
LoggerAPIConnectionWS apiConn = new LoggerAPIConnectionWS (expectedHost, expectedKey);
return apiConn;
}
Logger MakeLogger(){
return new Logger (new MockFinishedMetricsFlusher());
}
private void WaitForMetricsToBeReceived()
{
Thread.Sleep (250);
}
private LinkedList<Timer> MakeTestTimers(String metricName, int numTimers)
{
Logger logger = MakeLogger ();
LinkedList<Timer> timers = new LinkedList<Timer> ();
for (int i = 0; i < numTimers; i++)
{
Timer t = new Timer (metricName, logger);
Thread.Sleep (random.Next(0, 25));
t.Stop ();
timers.AddLast (t);
}
return timers;
}
[Test()]
public void should_send_metrics_to_the_server()
{
LoggerAPIConnectionWS apiConn = MakeAPIConnToTestServer ();
LinkedList<Timer> timers = MakeTestTimers ("should_send_metrics_to_the_server", 50);
apiConn.sendMetrics (timers);
WaitForMetricsToBeReceived ();
Assert.AreEqual (timers.Count, this.receivedMessages.Count);
}
[Test()]
public void should_reconnect_to_server_when_connection_is_broken_for_short_duration()
{
LoggerAPIConnectionWS apiConn = MakeAPIConnToTestServer ();
LinkedList<Timer> timersBeforeFail = MakeTestTimers ("before-failure", 3);
apiConn.sendMetrics (timersBeforeFail);
WaitForMetricsToBeReceived ();
Assert.AreEqual (timersBeforeFail.Count, this.receivedMessages.Count);
//Simulate a short-duration connectivity problem, e.g.
// * network hiccup
// * restart of WeblogNG api
StopServer ();
Thread.Sleep (500);
StartServer ();
LinkedList<Timer> timersAfterFail = MakeTestTimers ("after-failure", 10);
apiConn.sendMetrics (timersAfterFail);
WaitForMetricsToBeReceived ();
Assert.AreEqual (timersAfterFail.Count, this.receivedMessages.Count);
}
[Test()]
public void should_throw_CannotSendMetricsException_when_SendMetrics_fails_after_initial_connect()
{
LoggerAPIConnectionWS apiConn = MakeAPIConnToTestServer ();
LinkedList<Timer> timersBeforeFail = MakeTestTimers ("before-failure", 3);
apiConn.sendMetrics (timersBeforeFail);
WaitForMetricsToBeReceived ();
Assert.AreEqual (timersBeforeFail.Count, this.receivedMessages.Count);
//Simulate a long-duration connectivity problem
StopServer ();
Thread.Sleep (100);
LinkedList<Timer> timersDuringFail = MakeTestTimers ("during-failure", 7);
try
{
Console.WriteLine("about to sendMetrics");
apiConn.sendMetrics(timersDuringFail);
Assert.Fail("expected sendMetrics to throw CannotSendMetricsException");
} catch (CannotSendMetricsException csm_e)
{
Assert.AreEqual(string.Format("Could not send metrics to {0}", apiConn.ApiUrl), csm_e.Message);
Assert.IsInstanceOfType(typeof(OpenConnectionTimeoutException), csm_e.InnerException);
}
}
[Test()]
public void should_throw_CannotSendMetricsException_when_metrics_cannot_be_sent_on_initial_connect()
{
LoggerAPIConnectionWS apiConn = MakeAPIConnToTestServer ();
StopServer ();
LinkedList<Timer> timersDuringFail = MakeTestTimers ("during-failure", 7);
try
{
Console.WriteLine("about to sendMetrics");
apiConn.sendMetrics(timersDuringFail);
Assert.Fail("expected sendMetrics to throw CannotSendMetricsException");
} catch (CannotSendMetricsException csm_e)
{
Assert.AreEqual(string.Format("Could not send metrics to {0}", apiConn.ApiUrl), csm_e.Message);
Assert.IsInstanceOfType(typeof(OpenConnectionTimeoutException), csm_e.InnerException);
}
}
[Test()]
public void on_error_api_conn_should_discard_websocket_and_reconnect_for_subsequent_metrics()
{
LoggerAPIConnectionWS apiConn = MakeAPIConnToTestServer ();
LinkedList<Timer> timersBeforeError = MakeTestTimers ("before-error", 3);
apiConn.sendMetrics (timersBeforeError);
WebSocket socketBeforeFailure = apiConn.WebSocket;
WaitForMetricsToBeReceived ();
apiConn.websocket_Error (new object (), new SuperSocket.ClientEngine.ErrorEventArgs (new Exception ("an error occurred")));
Assert.IsNull (apiConn.WebSocket);
LinkedList<Timer> timersAfterError = MakeTestTimers ("after-error", 10);
apiConn.sendMetrics (timersAfterError);
Assert.AreNotSame (socketBeforeFailure, apiConn.WebSocket);
WaitForMetricsToBeReceived ();
Assert.AreEqual (timersBeforeError.Count + timersAfterError.Count, this.receivedMessages.Count);
}
[Test()]
public void on_close_api_conn_should_discard_websocket_and_reconnect_for_subsequent_metrics()
{
LoggerAPIConnectionWS apiConn = MakeAPIConnToTestServer ();
LinkedList<Timer> timersBeforeClose = MakeTestTimers ("before-close", 3);
apiConn.sendMetrics (timersBeforeClose);
WebSocket socketBeforeFailure = apiConn.WebSocket;
WaitForMetricsToBeReceived ();
apiConn.websocket_Closed (new object (), new EventArgs());
Assert.IsNull (apiConn.WebSocket);
LinkedList<Timer> timersAfterClose = MakeTestTimers ("after-close", 2);
apiConn.sendMetrics (timersAfterClose);
Assert.AreNotSame (socketBeforeFailure, apiConn.WebSocket);
WaitForMetricsToBeReceived ();
Assert.AreEqual (timersBeforeClose.Count + timersAfterClose.Count, this.receivedMessages.Count);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Basic point graph.
* \ingroup graphs
* The point graph is the most basic graph structure, it consists of a number of interconnected points in space called nodes or waypoints.\n
* The point graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node.
* If #recursive is enabled, it will also search the child objects of the children recursively.
* It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large (#maxDistance)
* and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named #limits,
* is useful because usually an AI cannot climb very high, but linking nodes far away from each other,
* but on the same Y level should still be possible. #limits and #maxDistance are treated as being set to infinity if they are set to 0 (zero). \n
* Lastly it will check if there are any obstructions between the nodes using
* <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.\n
* One thing to think about when using raycasting is to either place the nodes a small
* distance above the ground in your scene or to make sure that the ground is not in the raycast \a mask to avoid the raycast from hitting the ground.\n
*
* Alternatively, a tag can be used to search for nodes.
* \see http://docs.unity3d.com/Manual/Tags.html
*
* For larger graphs, it can take quite some time to scan the graph with the default settings.
* If you have the pro version you can enable 'optimizeForSparseGraph' which will in most cases reduce the calculation times
* drastically. If your graph is essentially only in the XZ plane (note, not XY), you can enable #optimizeFor2D (called 'Optimize For XZ Plane' in the inspector).
*
* \note Does not support linecast because of obvious reasons.
*
* \shadowimage{pointgraph_graph.png}
* \shadowimage{pointgraph_inspector.png}
*
*/
[JsonOptIn]
public class PointGraph : NavGraph {
/** Childs of this transform are treated as nodes */
[JsonMember]
public Transform root;
/** If no #root is set, all nodes with the tag is used as nodes */
[JsonMember]
public string searchTag;
/** Max distance for a connection to be valid.
* The value 0 (zero) will be read as infinity and thus all nodes not restricted by
* other constraints will be added as connections.
*
* A negative value will disable any neighbours to be added.
* It will completely stop the connection processing to be done, so it can save you processing
* power if you don't these connections.
*/
[JsonMember]
public float maxDistance;
/** Max distance along the axis for a connection to be valid. 0 = infinity */
[JsonMember]
public Vector3 limits;
/** Use raycasts to check connections */
[JsonMember]
public bool raycast = true;
/** Use the 2D Physics API */
[JsonMember]
public bool use2DPhysics;
/** Use thick raycast */
[JsonMember]
public bool thickRaycast;
/** Thick raycast radius */
[JsonMember]
public float thickRaycastRadius = 1;
/** Recursively search for child nodes to the #root */
[JsonMember]
public bool recursive = true;
/** Layer mask to use for raycast */
[JsonMember]
public LayerMask mask;
/** All nodes in this graph.
* Note that only the first #nodeCount will be non-null.
*
* You can also use the GetNodes method to get all nodes.
*/
public PointNode[] nodes;
/** Number of nodes in this graph */
public int nodeCount { get; private set; }
public override int CountNodes () {
return nodeCount;
}
public override void GetNodes (GraphNodeDelegateCancelable del) {
if (nodes == null) return;
for (int i = 0; i < nodeCount && del(nodes[i]); i++) {}
}
public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearestForce(position, constraint);
}
public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) {
if (nodes == null) return new NNInfo();
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
float minDist = float.PositiveInfinity;
GraphNode minNode = null;
float minConstDist = float.PositiveInfinity;
GraphNode minConstNode = null;
for (int i = 0; i < nodeCount; i++) {
PointNode node = nodes[i];
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
minNode = node;
}
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable(node))) {
minConstDist = dist;
minConstNode = node;
}
}
var nnInfo = new NNInfo(minNode);
nnInfo.constrainedNode = minConstNode;
if (minConstNode != null) {
nnInfo.constClampedPosition = (Vector3)minConstNode.position;
} else if (minNode != null) {
nnInfo.constrainedNode = minNode;
nnInfo.constClampedPosition = (Vector3)minNode.position;
}
return nnInfo;
}
struct GetNearestHelper {
public Vector3 position;
public float minDist, minConstDist, maxDistSqr;
public PointNode minNode, minConstNode;
NNConstraint constraint;
Dictionary<Int3, PointNode> nodeLookup;
public GetNearestHelper(Vector3 position, float maxDistSqr, NNConstraint constraint, Dictionary<Int3, PointNode> nodeLookup) {
this.position = position;
this.maxDistSqr = maxDistSqr;
this.constraint = constraint;
this.nodeLookup = nodeLookup;
minDist = float.PositiveInfinity;
minConstDist = float.PositiveInfinity;
minNode = minConstNode = null;
}
public void Search (Int3 p) {
PointNode node;
if (nodeLookup.TryGetValue(p, out node)) {
while (node != null) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable(node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
}
}
/** Add a node to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \note This needs to be called when it is safe to update nodes, which is
* - when scanning
* - during a graph update
* - inside a callback registered using AstarPath.RegisterSafeUpdate
*/
public PointNode AddNode (Int3 position) {
return AddNode(new PointNode(active), position);
}
/** Add a node with the specified type to the graph at the specified position.
*
* \param node This must be a node created using T(AstarPath.active) right before the call to this method.
* The node parameter is only there because there is no new(AstarPath) constraint on
* generic type parameters.
* \param position The node will be set to this position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \note This needs to be called when it is safe to update nodes, which is
* - when scanning
* - during a graph update
* - inside a callback registered using AstarPath.RegisterSafeUpdate
*
* \see AstarPath.RegisterSafeUpdate
*/
public T AddNode<T>(T node, Int3 position) where T : PointNode {
if (nodes == null || nodeCount == nodes.Length) {
var nds = new PointNode[nodes != null ? System.Math.Max(nodes.Length+4, nodes.Length*2) : 4];
for (int i = 0; i < nodeCount; i++) nds[i] = nodes[i];
nodes = nds;
}
node.SetPosition(position);
node.GraphIndex = graphIndex;
node.Walkable = true;
nodes[nodeCount] = node;
nodeCount++;
AddToLookup(node);
return node;
}
/** Recursively counds children of a transform */
protected static int CountChildren (Transform tr) {
int c = 0;
foreach (Transform child in tr) {
c++;
c += CountChildren(child);
}
return c;
}
/** Recursively adds childrens of a transform as nodes */
protected void AddChildren (ref int c, Transform tr) {
foreach (Transform child in tr) {
nodes[c].SetPosition((Int3)child.position);
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
AddChildren(ref c, child);
}
}
/** Rebuilds the lookup structure for nodes.
*
* This is used when #optimizeForSparseGraph is enabled.
*
* You should call this method every time you move a node in the graph manually and
* you are using #optimizeForSparseGraph, otherwise pathfinding might not work correctly.
*
* \astarpro
*/
public void RebuildNodeLookup () {
// A* Pathfinding Project Pro Only
}
void AddToLookup (PointNode node) {
// A* Pathfinding Project Pro Only
}
public override void ScanInternal (OnScanStatus statusCallback) {
if (root == null) {
//If there is no root object, try to find nodes with the specified tag instead
GameObject[] gos = searchTag != null ? GameObject.FindGameObjectsWithTag(searchTag) : null;
if (gos == null) {
nodes = new PointNode[0];
nodeCount = 0;
return;
}
//Create and set up the found nodes
nodes = new PointNode[gos.Length];
nodeCount = nodes.Length;
for (int i = 0; i < nodes.Length; i++) nodes[i] = new PointNode(active);
for (int i = 0; i < gos.Length; i++) {
nodes[i].SetPosition((Int3)gos[i].transform.position);
nodes[i].Walkable = true;
nodes[i].gameObject = gos[i].gameObject;
}
} else {
//Search the root for children and create nodes for them
if (!recursive) {
nodes = new PointNode[root.childCount];
nodeCount = nodes.Length;
for (int i = 0; i < nodes.Length; i++) nodes[i] = new PointNode(active);
int c = 0;
foreach (Transform child in root) {
nodes[c].SetPosition((Int3)child.position);
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
}
} else {
nodes = new PointNode[CountChildren(root)];
nodeCount = nodes.Length;
for (int i = 0; i < nodes.Length; i++) nodes[i] = new PointNode(active);
//CreateNodes (CountChildren (root));
int startID = 0;
AddChildren(ref startID, root);
}
}
if (maxDistance >= 0) {
//To avoid too many allocations, these lists are reused for each node
var connections = new List<PointNode>(3);
var costs = new List<uint>(3);
//Loop through all nodes and add connections to other nodes
for (int i = 0; i < nodes.Length; i++) {
connections.Clear();
costs.Clear();
PointNode node = nodes[i];
// Only brute force is available in the free version
for (int j = 0; j < nodes.Length; j++) {
if (i == j) continue;
PointNode other = nodes[j];
float dist;
if (IsValidConnection(node, other, out dist)) {
connections.Add(other);
/** \todo Is this equal to .costMagnitude */
costs.Add((uint)Mathf.RoundToInt(dist*Int3.FloatPrecision));
}
}
node.connections = connections.ToArray();
node.connectionCosts = costs.ToArray();
}
}
}
/** Returns if the connection between \a a and \a b is valid.
* Checks for obstructions using raycasts (if enabled) and checks for height differences.\n
* As a bonus, it outputs the distance between the nodes too if the connection is valid
*/
public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) {
dist = 0;
if (!a.Walkable || !b.Walkable) return false;
var dir = (Vector3)(b.position-a.position);
if (
(!Mathf.Approximately(limits.x, 0) && Mathf.Abs(dir.x) > limits.x) ||
(!Mathf.Approximately(limits.y, 0) && Mathf.Abs(dir.y) > limits.y) ||
(!Mathf.Approximately(limits.z, 0) && Mathf.Abs(dir.z) > limits.z)) {
return false;
}
dist = dir.magnitude;
if (maxDistance == 0 || dist < maxDistance) {
if (raycast) {
var ray = new Ray((Vector3)a.position, dir);
var invertRay = new Ray((Vector3)b.position, -dir);
if (use2DPhysics) {
if (thickRaycast) {
return !Physics2D.CircleCast(ray.origin, thickRaycastRadius, ray.direction, dist, mask) && !Physics2D.CircleCast(invertRay.origin, thickRaycastRadius, invertRay.direction, dist, mask);
} else {
return !Physics2D.Linecast((Vector2)(Vector3)a.position, (Vector2)(Vector3)b.position, mask) && !Physics2D.Linecast((Vector2)(Vector3)b.position, (Vector2)(Vector3)a.position, mask);
}
} else {
if (thickRaycast) {
return !Physics.SphereCast(ray, thickRaycastRadius, dist, mask) && !Physics.SphereCast(invertRay, thickRaycastRadius, dist, mask);
} else {
return !Physics.Linecast((Vector3)a.position, (Vector3)b.position, mask) && !Physics.Linecast((Vector3)b.position, (Vector3)a.position, mask);
}
}
} else {
return true;
}
}
return false;
}
public override void PostDeserialization () {
RebuildNodeLookup();
}
public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) {
base.RelocateNodes(oldMatrix, newMatrix);
RebuildNodeLookup();
}
public override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) {
base.DeserializeSettingsCompatibility(ctx);
root = ctx.DeserializeUnityObject() as Transform;
searchTag = ctx.reader.ReadString();
maxDistance = ctx.reader.ReadSingle();
limits = ctx.DeserializeVector3();
raycast = ctx.reader.ReadBoolean();
use2DPhysics = ctx.reader.ReadBoolean();
thickRaycast = ctx.reader.ReadBoolean();
thickRaycastRadius = ctx.reader.ReadSingle();
recursive = ctx.reader.ReadBoolean();
ctx.reader.ReadBoolean(); // Deprecated field
mask = (LayerMask)ctx.reader.ReadInt32();
}
public override void SerializeExtraInfo (GraphSerializationContext ctx) {
// Serialize node data
if (nodes == null) ctx.writer.Write(-1);
// Length prefixed array of nodes
ctx.writer.Write(nodeCount);
for (int i = 0; i < nodeCount; i++) {
// -1 indicates a null field
if (nodes[i] == null) ctx.writer.Write(-1);
else {
ctx.writer.Write(0);
nodes[i].SerializeNode(ctx);
}
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
nodes = null;
return;
}
nodes = new PointNode[count];
nodeCount = count;
for (int i = 0; i < nodes.Length; i++) {
if (ctx.reader.ReadInt32() == -1) continue;
nodes[i] = new PointNode(active);
nodes[i].DeserializeNode(ctx);
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Microsoft.Reactive.Testing;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_Binding
{
[Fact]
public void Bind_Sets_Current_Value()
{
Class1 target = new Class1();
Class1 source = new Class1();
source.SetValue(Class1.FooProperty, "initial");
target.Bind(Class1.FooProperty, source.GetObservable(Class1.FooProperty));
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Bind_NonGeneric_Sets_Current_Value()
{
Class1 target = new Class1();
Class1 source = new Class1();
source.SetValue(Class1.FooProperty, "initial");
target.Bind((AvaloniaProperty)Class1.FooProperty, source.GetObservable(Class1.FooProperty));
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Bind_To_ValueType_Accepts_UnsetValue()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(5.6, target.GetValue(Class1.QuxProperty));
Assert.False(target.IsSet(Class1.QuxProperty));
}
[Fact]
public void OneTime_Binding_Ignores_UnsetValue()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, new TestOneTimeBinding(source));
source.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(5.6, target.GetValue(Class1.QuxProperty));
source.OnNext(6.7);
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void OneTime_Binding_Ignores_Binding_Errors()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, new TestOneTimeBinding(source));
source.OnNext(new BindingNotification(new Exception(), BindingErrorType.Error));
Assert.Equal(5.6, target.GetValue(Class1.QuxProperty));
source.OnNext(6.7);
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void Bind_Throws_Exception_For_Unregistered_Property()
{
Class1 target = new Class1();
Assert.Throws<ArgumentException>(() =>
{
target.Bind(Class2.BarProperty, Observable.Return("foo"));
});
}
[Fact]
public void Bind_Sets_Subsequent_Value()
{
Class1 target = new Class1();
Class1 source = new Class1();
source.SetValue(Class1.FooProperty, "initial");
target.Bind(Class1.FooProperty, source.GetObservable(Class1.FooProperty));
source.SetValue(Class1.FooProperty, "subsequent");
Assert.Equal("subsequent", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Bind_Ignores_Invalid_Value_Type()
{
Class1 target = new Class1();
target.Bind((AvaloniaProperty)Class1.FooProperty, Observable.Return((object)123));
Assert.Equal("foodefault", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Observable_Is_Unsubscribed_When_Subscription_Disposed()
{
var scheduler = new TestScheduler();
var source = scheduler.CreateColdObservable<object>();
var target = new Class1();
var subscription = target.Bind(Class1.FooProperty, source);
Assert.Equal(1, source.Subscriptions.Count);
Assert.Equal(Subscription.Infinite, source.Subscriptions[0].Unsubscribe);
subscription.Dispose();
Assert.Equal(1, source.Subscriptions.Count);
Assert.Equal(0, source.Subscriptions[0].Unsubscribe);
}
[Fact]
public void Two_Way_Separate_Binding_Works()
{
Class1 obj1 = new Class1();
Class1 obj2 = new Class1();
obj1.SetValue(Class1.FooProperty, "initial1");
obj2.SetValue(Class1.FooProperty, "initial2");
obj1.Bind(Class1.FooProperty, obj2.GetObservable(Class1.FooProperty));
obj2.Bind(Class1.FooProperty, obj1.GetObservable(Class1.FooProperty));
Assert.Equal("initial2", obj1.GetValue(Class1.FooProperty));
Assert.Equal("initial2", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "first");
Assert.Equal("first", obj1.GetValue(Class1.FooProperty));
Assert.Equal("first", obj2.GetValue(Class1.FooProperty));
obj2.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", obj1.GetValue(Class1.FooProperty));
Assert.Equal("second", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "third");
Assert.Equal("third", obj1.GetValue(Class1.FooProperty));
Assert.Equal("third", obj2.GetValue(Class1.FooProperty));
}
[Fact]
public void Two_Way_Binding_With_Priority_Works()
{
Class1 obj1 = new Class1();
Class1 obj2 = new Class1();
obj1.SetValue(Class1.FooProperty, "initial1", BindingPriority.Style);
obj2.SetValue(Class1.FooProperty, "initial2", BindingPriority.Style);
obj1.Bind(Class1.FooProperty, obj2.GetObservable(Class1.FooProperty), BindingPriority.Style);
obj2.Bind(Class1.FooProperty, obj1.GetObservable(Class1.FooProperty), BindingPriority.Style);
Assert.Equal("initial2", obj1.GetValue(Class1.FooProperty));
Assert.Equal("initial2", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "first", BindingPriority.Style);
Assert.Equal("first", obj1.GetValue(Class1.FooProperty));
Assert.Equal("first", obj2.GetValue(Class1.FooProperty));
obj2.SetValue(Class1.FooProperty, "second", BindingPriority.Style);
Assert.Equal("second", obj1.GetValue(Class1.FooProperty));
Assert.Equal("second", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "third", BindingPriority.Style);
Assert.Equal("third", obj1.GetValue(Class1.FooProperty));
Assert.Equal("third", obj2.GetValue(Class1.FooProperty));
}
[Fact]
public void Local_Binding_Overwrites_Local_Value()
{
var target = new Class1();
var binding = new Subject<string>();
target.Bind(Class1.FooProperty, binding);
binding.OnNext("first");
Assert.Equal("first", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", target.GetValue(Class1.FooProperty));
binding.OnNext("third");
Assert.Equal("third", target.GetValue(Class1.FooProperty));
}
[Fact]
public void StyleBinding_Overrides_Default_Value()
{
Class1 target = new Class1();
target.Bind(Class1.FooProperty, Single("stylevalue"), BindingPriority.Style);
Assert.Equal("stylevalue", target.GetValue(Class1.FooProperty));
}
[Fact]
public void this_Operator_Returns_Value_Property()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target[Class1.FooProperty]);
}
[Fact]
public void this_Operator_Sets_Value_Property()
{
Class1 target = new Class1();
target[Class1.FooProperty] = "newvalue";
Assert.Equal("newvalue", target.GetValue(Class1.FooProperty));
}
[Fact]
public void this_Operator_Doesnt_Accept_Observable()
{
Class1 target = new Class1();
Assert.Throws<ArgumentException>(() =>
{
target[Class1.FooProperty] = Observable.Return("newvalue");
});
}
[Fact]
public void this_Operator_Binds_One_Way()
{
Class1 target1 = new Class1();
Class2 target2 = new Class2();
IndexerDescriptor binding = Class2.BarProperty.Bind().WithMode(BindingMode.OneWay);
target1.SetValue(Class1.FooProperty, "first");
target2[binding] = target1[!Class1.FooProperty];
target1.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", target2.GetValue(Class2.BarProperty));
}
[Fact]
public void this_Operator_Binds_Two_Way()
{
Class1 target1 = new Class1();
Class1 target2 = new Class1();
target1.SetValue(Class1.FooProperty, "first");
target2[!Class1.FooProperty] = target1[!!Class1.FooProperty];
Assert.Equal("first", target2.GetValue(Class1.FooProperty));
target1.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", target2.GetValue(Class1.FooProperty));
target2.SetValue(Class1.FooProperty, "third");
Assert.Equal("third", target1.GetValue(Class1.FooProperty));
}
[Fact]
public void this_Operator_Binds_One_Time()
{
Class1 target1 = new Class1();
Class1 target2 = new Class1();
target1.SetValue(Class1.FooProperty, "first");
target2[!Class1.FooProperty] = target1[Class1.FooProperty.Bind().WithMode(BindingMode.OneTime)];
target1.SetValue(Class1.FooProperty, "second");
Assert.Equal("first", target2.GetValue(Class1.FooProperty));
}
[Fact]
public void BindingError_Does_Not_Cause_Target_Update()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error));
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void BindingNotification_With_FallbackValue_Causes_Target_Update()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error,
8.9));
Assert.Equal(8.9, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void Bind_Logs_Binding_Error()
{
var target = new Class1();
var source = new Subject<object>();
var called = false;
var expectedMessageTemplate = "Error in binding to {Target}.{Property}: {Message}";
LogCallback checkLogMessage = (level, area, src, mt, pv) =>
{
if (level == LogEventLevel.Error &&
area == LogArea.Binding &&
mt == expectedMessageTemplate)
{
called = true;
}
};
using (TestLogSink.Start(checkLogMessage))
{
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error));
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
Assert.True(called);
}
}
/// <summary>
/// Returns an observable that returns a single value but does not complete.
/// </summary>
/// <typeparam name="T">The type of the observable.</typeparam>
/// <param name="value">The value.</param>
/// <returns>The observable.</returns>
private IObservable<T> Single<T>(T value)
{
return Observable.Never<T>().StartWith(value);
}
private class Class1 : AvaloniaObject
{
public static readonly StyledProperty<string> FooProperty =
AvaloniaProperty.Register<Class1, string>("Foo", "foodefault");
public static readonly StyledProperty<double> QuxProperty =
AvaloniaProperty.Register<Class1, double>("Qux", 5.6);
}
private class Class2 : Class1
{
public static readonly StyledProperty<string> BarProperty =
AvaloniaProperty.Register<Class2, string>("Bar", "bardefault");
}
private class TestOneTimeBinding : IBinding
{
private IObservable<object> _source;
public TestOneTimeBinding(IObservable<object> source)
{
_source = source;
}
public InstancedBinding Initiate(
IAvaloniaObject target,
AvaloniaProperty targetProperty,
object anchor = null,
bool enableDataValidation = false)
{
return new InstancedBinding(_source, BindingMode.OneTime);
}
}
}
}
| |
/*
Copyright (c) 2007 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Reflection;
namespace Lidgren.Library.Network
{
[Flags]
public enum NetLogEntryTypes : int
{
None = 0,
Verbose = 1 << 0,
Debug = 1 << 1,
Info = 1 << 2,
Warning = 1 << 3,
Error = 1 << 4,
Break = 1 << 5,
Html = 1 << 6,
}
/// <summary>
/// An entry in the network log
/// </summary>
public sealed class NetLogEntry
{
public NetLogEntryTypes Type;
public long TimeMillis;
public string Where;
public string What;
}
/// <summary>
/// A class for capturing log feedback from the library
/// </summary>
public sealed class NetLog
{
private static Dictionary<NetLogEntryTypes, string> LogEntryTypeName;
private Queue<NetLogEntry> m_entries;
private Thread m_mainThread;
private string m_file, m_fileToUse;
private bool m_outputToFile;
/// <summary>
/// Specifies a filename to save log output to
/// </summary>
public string OutputFileName
{
get { return m_file; }
set { m_fileToUse = value; }
}
/// <summary>
/// Enables or disables log output to file
/// </summary>
public bool IsOutputToFileEnabled
{
get { return m_outputToFile; }
set { m_outputToFile = value; }
}
public event EventHandler<NetLogEventArgs> LogEvent;
public NetLogEntryTypes IgnoreTypes = NetLogEntryTypes.Verbose;
public NetLog()
{
m_entries = new Queue<NetLogEntry>();
m_mainThread = Thread.CurrentThread;
m_outputToFile = true;
LogEntryTypeName = new Dictionary<NetLogEntryTypes, string>();
LogEntryTypeName[NetLogEntryTypes.None] = "nnn";
LogEntryTypeName[NetLogEntryTypes.Verbose] = "vrb";
LogEntryTypeName[NetLogEntryTypes.Debug] = "dbg";
LogEntryTypeName[NetLogEntryTypes.Info] = "inf";
LogEntryTypeName[NetLogEntryTypes.Warning] = "wrn";
LogEntryTypeName[NetLogEntryTypes.Error] = "err";
LogEntryTypeName[NetLogEntryTypes.Break] = "brk";
LogEntryTypeName[NetLogEntryTypes.Html] = "htm";
}
private void MakeEntry(NetLogEntryTypes type, string str)
{
if ((type & IgnoreTypes) == type)
return;
if (type != NetLogEntryTypes.Break)
{
ConsoleColor wasColor = Console.ForegroundColor;
// TODO:
//Console.ForegroundColor = LogEntryTypeColors[(int)type];
Console.WriteLine(str);
Console.ForegroundColor = wasColor;
}
NetLogEntry entry = new NetLogEntry();
entry.TimeMillis = (long)(NetTime.Now * 1000.0);
entry.Type = type;
#if DEBUG
// get call stack
StackTrace trace = new StackTrace(2, true);
StackFrame frame = trace.GetFrame(0);
MethodBase method = frame.GetMethod();
entry.Where = method.Name + "() in " + method.DeclaringType.Name;
#else
entry.Where = "";
#endif
entry.What = str;
if (m_outputToFile)
m_entries.Enqueue(entry);
if (LogEvent != null)
{
NetLogEventArgs args = new NetLogEventArgs();
args.Entry = entry;
LogEvent(this, args);
}
if (Thread.CurrentThread == m_mainThread && m_entries.Count > 0)
Flush();
}
[Conditional("DEBUG")]
public void Verbose(string str) { MakeEntry(NetLogEntryTypes.Verbose, str); }
[Conditional("DEBUG")]
public void Debug(string str) { MakeEntry(NetLogEntryTypes.Debug, str); }
public void Info(string str) { MakeEntry(NetLogEntryTypes.Info, str); }
public void Warning(string str) { MakeEntry(NetLogEntryTypes.Warning, str); }
public void Error(string str) { MakeEntry(NetLogEntryTypes.Error, str); }
public void Break(string str) { MakeEntry(NetLogEntryTypes.Break, str); }
public void Html(string str) { MakeEntry(NetLogEntryTypes.Html, str); }
public void Flush()
{
if (m_fileToUse != m_file)
{
m_fileToUse = Path.GetFullPath(m_fileToUse);
m_file = m_fileToUse;
StreamWriter writer = new StreamWriter(m_file);
writer.Write(@"
<!DOCTYPE HTML PUBLIC \'-//W3C//DTD HTML 4.01 Transitional//EN\'>
<HTML>
<HEAD>
<TITLE>Log</TITLE>
<STYLE>
TD {
font-family: verdana;
font-size: 10px;
}
BODY {
font-family: verdana;
font-size: 10px;
line-height: 16px;
vertical-align: top;
}
H1 {
font-family: verdana;
font-size: 22px;
margin-left: 20px;
font-weight: bold;
}
.inf { color: #000000; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.suc { color: #008800; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.fai { color: #AA2200; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.dbg { color: #008800; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.vrb { color: #999999; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.wrn { font-weight: bold; color: #DD8800; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.err { font-weight: bold; color: #FF0000; border-bottom: 1px solid #CCCCCC; vertical-align: top; }
.brk { color: #FF0000; border-bottom: 1px solid #000000; vertical-align: top; }
.lbl { padding: 14px 4px 2px 22px; font-family: arial; font-size: 14px; font-weight: bold; color: #000000; background-color: #EEEEEE; border-top: 1px solid #000000; border-bottom: 1px solid #000000; }
U { text-align: right; text-decoration: none; width: 75px; margin-right: 6px; vertical-align: top; padding-right: 2px; }
Q { text-decoration: none; width: 275px; margin-left: 8px; margin-right: 6px; vertical-align: top; }
</STYLE>
</HEAD>
<BODY>
");
try
{
writer.WriteLine("\t\t<DIV CLASS=\"inf\">{0}</DIV>", System.Environment.CommandLine);
writer.WriteLine("\t\t<DIV CLASS=\"inf\">{0}\\{1} @ {2} ({3})</DIV>", System.Environment.UserDomainName, System.Environment.UserName, System.Environment.MachineName, System.Environment.OSVersion);
writer.WriteLine("\t\t<DIV CLASS=\"inf\">.NET Framework version: {0}</DIV>", System.Environment.Version);
writer.WriteLine("\t\t<DIV CLASS=\"inf\">Log started {0}</DIV>", DateTime.Now);
writer.WriteLine("\t\t<DIV CLASS=\"brk\"></DIV>");
}
finally { }
writer.Close();
}
while (m_entries.Count > 0)
{
NetLogEntry entry = m_entries.Dequeue();
if (m_file != null)
{
StringBuilder htmlBuilder = new StringBuilder(63);
htmlBuilder.AppendFormat("<DIV CLASS=\"{0}\">{1}", LogEntryTypeName[entry.Type], System.Environment.NewLine);
htmlBuilder.AppendFormat("<U>{0}</U>", entry.TimeMillis);
if (entry.Where == null)
{
htmlBuilder.AppendLine("<Q>-</Q>");
}
else
{
try
{
htmlBuilder.AppendFormat("<Q>{0}</Q>", entry.Where);
}
catch (Exception ex)
{
htmlBuilder.AppendFormat("<Q>{0}</Q>", ex.ToString());
}
}
htmlBuilder.Append(entry.What);
htmlBuilder.AppendLine("</DIV>");
File.AppendAllText(m_file, htmlBuilder.ToString(), Encoding.ASCII);
}
}
}
}
public sealed class NetLogEventArgs : System.EventArgs
{
public NetLogEntry Entry;
public override string ToString()
{
return Entry.What;
}
}
}
| |
// Copyright 2016 Tom Deseyn <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Tmds.DBus.Protocol;
namespace Tmds.DBus.CodeGen
{
internal class TypeDescription
{
private static readonly Type s_signalReturnType = typeof(Task<IDisposable>);
private static readonly Type s_idbusObjectType = typeof(IDBusObject);
private static readonly Type s_emptyActionType = typeof(Action);
private static readonly Type s_exceptionActionType = typeof(Action<Exception>);
private static readonly Type s_singleParameterActionType = typeof(Action<>);
private static readonly Type s_emptyTaskType = typeof(Task);
private static readonly Type s_parameterTaskType = typeof(Task<>);
private static readonly Type s_cancellationTokenType = typeof(CancellationToken);
private static readonly Type s_stringType = typeof(string);
private static readonly Type s_objectType = typeof(object);
private static readonly Signature s_propertiesChangedSignature = new Signature("a{sv}as");
private static readonly Signature s_getAllOutSignature = new Signature("a{sv}");
private static readonly Type[] s_mappedTypes = new[] { typeof(bool), typeof(byte), typeof(double), typeof(short), typeof(int),
typeof(long), typeof(ObjectPath), typeof(Signature), typeof(float), typeof(string), typeof(ushort), typeof(uint), typeof(ulong),
typeof(object), typeof(IDBusObject)};
public Type Type { get; }
private IList<InterfaceDescription> _interfaces;
public IList<InterfaceDescription> Interfaces { get { return _interfaces ?? Array.Empty<InterfaceDescription>(); } }
public static TypeDescription DescribeObject(Type type)
{
return Describe(type, isInterfaceType: false);
}
public static TypeDescription DescribeInterface(Type type)
{
return Describe(type, isInterfaceType : true);
}
private TypeDescription(Type type, IList<InterfaceDescription> interfaces)
{
Type = type;
_interfaces = interfaces;
}
private static TypeDescription Describe(Type type, bool isInterfaceType)
{
var interfaces = new List<InterfaceDescription>();
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsInterface != isInterfaceType)
{
if (isInterfaceType)
{
throw new ArgumentException($"Type '{type.FullName}' must be an interface type");
}
else
{
throw new ArgumentException($"Type '{type.FullName}' cannot be an interface type");
}
}
if ((type != s_idbusObjectType)
&& !typeInfo.ImplementedInterfaces.Contains(s_idbusObjectType))
{
throw new ArgumentException($"Type {type.FullName} does not implement {typeof(IDBusObject).FullName}");
}
if (!isInterfaceType)
{
var dbusInterfaces = from interf in typeInfo.ImplementedInterfaces
let interfAttribute = interf.GetTypeInfo().GetCustomAttribute<DBusInterfaceAttribute>(false)
where interfAttribute != null
select new { Type = interf, Attribute = interfAttribute };
foreach (var dbusInterf in dbusInterfaces)
{
AddInterfaceDescription(dbusInterf.Type, dbusInterf.Attribute, interfaces);
}
}
else if (type == s_idbusObjectType)
{}
else
{
var interfaceAttribute = typeInfo.GetCustomAttribute<DBusInterfaceAttribute>(false);
if (interfaceAttribute != null)
{
AddInterfaceDescription(type, interfaceAttribute, interfaces);
}
else
{
if (typeInfo.DeclaredMembers.Count() != 0)
{
throw new ArgumentException($"DBus object type {type.FullName} cannot implement methods. It must inherit one or more DBus interface types.");
}
}
var dbusInterfaces = from interf in typeInfo.ImplementedInterfaces
where interf != s_idbusObjectType
let interfAttribute = interf.GetTypeInfo().GetCustomAttribute<DBusInterfaceAttribute>(false)
select new { Type = interf, Attribute = interfAttribute };
foreach (var dbusInterf in dbusInterfaces)
{
AddInterfaceDescription(dbusInterf.Type, dbusInterf.Attribute, interfaces);
}
if (dbusInterfaces.Any(interf => interf.Attribute == null))
{
throw new ArgumentException($"DBus object type {type.FullName} inherits one or more interfaces which are not DBus interface types.");
}
if ((interfaces.Count == 0) && (!typeInfo.ImplementedInterfaces.Contains(s_idbusObjectType)))
{
throw new ArgumentException($"Type {type.FullName} does not inherit '{s_idbusObjectType.FullName}' or any interfaces with the {typeof(DBusInterfaceAttribute).FullName}.");
}
}
return new TypeDescription(type, interfaces);
}
private static void AddInterfaceDescription(Type type, DBusInterfaceAttribute interfaceAttribute, List<InterfaceDescription> interfaces)
{
if (interfaces.Any(interf => interf.Name == interfaceAttribute.Name))
{
throw new ArgumentException($"DBus interface {interfaceAttribute.Name} is inherited multiple times");
}
IList<MethodDescription> methods = null;
IList<SignalDescription> signals = null;
IList<PropertyDescription> properties = null;
MethodDescription propertyGetMethod = null;
MethodDescription propertySetMethod = null;
MethodDescription propertyGetAllMethod = null;
SignalDescription propertiesChangedSignal = null;
Type propertyType = interfaceAttribute.PropertyType;
Type elementType;
if (propertyType != null && ArgTypeInspector.InspectEnumerableType(propertyType, out elementType, isCompileTimeType: true) != ArgTypeInspector.EnumerableType.AttributeDictionary)
{
throw new ArgumentException($"Property type '{propertyType.FullName}' does not have the '{typeof(DictionaryAttribute).FullName}' attribute");
}
foreach (var member in type.GetMethods())
{
string memberName = member.ToString();
if (!member.Name.EndsWith("Async", StringComparison.Ordinal))
{
throw new ArgumentException($"{memberName} does not end with 'Async'");
}
var isSignal = member.Name.StartsWith("Watch", StringComparison.Ordinal);
if (isSignal)
{
if (member.ReturnType != s_signalReturnType)
{
throw new ArgumentException($"Signal {memberName} does not return 'Task<IDisposable>'");
}
var name = member.Name.Substring(5, member.Name.Length - 10);
if (name.Length == 0)
{
throw new ArgumentException($"Signal {memberName} has an empty name");
}
Signature? parameterSignature = null;
IList<ArgumentDescription> arguments = null;
var parameters = member.GetParameters();
var actionParameter = parameters.Length > 0 ? parameters[0] : null;
Type parameterType = null;
bool validActionParameter = false;
if (actionParameter != null)
{
if (actionParameter.ParameterType == s_exceptionActionType)
{
// actionParameter is missing
}
else if (actionParameter.ParameterType == s_emptyActionType)
{
validActionParameter = true;
}
else if (actionParameter.ParameterType.GetTypeInfo().IsGenericType
&& actionParameter.ParameterType.GetGenericTypeDefinition() == s_singleParameterActionType)
{
validActionParameter = true;
parameterType = actionParameter.ParameterType.GetGenericArguments()[0];
InspectParameterType(parameterType, actionParameter, out parameterSignature, out arguments);
}
}
if (parameters.Length > 0 && parameters[parameters.Length - 1].ParameterType == s_cancellationTokenType)
{
throw new NotSupportedException($"Signal {memberName} does not support cancellation. See https://github.com/tmds/Tmds.DBus/issues/15.");
}
var lastParameter = parameters.Length > 0 ? parameters[parameters.Length - 1] : null;
bool hasOnError = lastParameter?.ParameterType == s_exceptionActionType;
if (!validActionParameter || parameters.Length != 1 + (hasOnError ? 1 : 0))
{
throw new ArgumentException($"Signal {memberName} must accept an argument of Type 'Action'/'Action<>' and optional argument of Type 'Action<Exception>'");
}
var signal = new SignalDescription(member, name, actionParameter.ParameterType, parameterType, parameterSignature, arguments, hasOnError);
if (member.Name == interfaceAttribute.WatchPropertiesMethod)
{
if (propertiesChangedSignal != null)
{
throw new ArgumentException($"Multiple property changes signals are declared: {memberName}, {propertyGetMethod.MethodInfo.ToString()}");
}
propertiesChangedSignal = signal;
if (propertiesChangedSignal.SignalSignature != s_propertiesChangedSignature)
{
throw new ArgumentException($"PropertiesChanged signal {memberName} must accept an Action<T> where T is a struct with an IDictionary<string, object> and an string[] field");
}
}
else
{
signals = signals ?? new List<SignalDescription>();
signals.Add(signal);
}
}
else
{
var name = member.Name.Substring(0, member.Name.Length - 5);
if (name.Length == 0)
{
throw new ArgumentException($"DBus Method {memberName} has an empty name");
}
IList<ArgumentDescription> outArguments = null;
Signature? outSignature = null;
var taskParameter = member.ReturnType;
Type outType = null;
bool valid = false;
bool isGenericOut = false;
if (taskParameter != null)
{
if (taskParameter == s_emptyTaskType)
{
valid = true;
outType = null;
}
else if (taskParameter.GetTypeInfo().IsGenericType
&& taskParameter.GetGenericTypeDefinition() == s_parameterTaskType)
{
valid = true;
outType = taskParameter.GetGenericArguments()[0];
if (outType.IsGenericParameter)
{
outType = s_objectType;
isGenericOut = true;
}
InspectParameterType(outType, member.ReturnParameter, out outSignature, out outArguments);
}
}
if (!valid)
{
throw new ArgumentException($"DBus Method {memberName} does not return 'Task'/'Task<>'");
}
IList<ArgumentDescription> inArguments = null;
Signature? inSignature = null;
var parameters = member.GetParameters();
if (parameters.Length > 0 && parameters[parameters.Length - 1].ParameterType == s_cancellationTokenType)
{
throw new NotSupportedException($"DBus Method {memberName} does not support cancellation. See https://github.com/tmds/Tmds.DBus/issues/15.");
}
for (int i = 0; i < parameters.Length; i++)
{
var param = parameters[i];
var parameterType = param.ParameterType;
var paramSignature = Signature.GetSig(parameterType, isCompileTimeType: true);
if (inSignature == null)
{
inSignature = paramSignature;
}
else
{
inSignature = Signature.Concat(inSignature.Value, paramSignature);
}
inArguments = inArguments ?? new List<ArgumentDescription>();
var argumentAttribute = param.GetCustomAttribute<ArgumentAttribute>(false);
var argName = argumentAttribute != null ? argumentAttribute.Name : param.Name;
inArguments.Add(new ArgumentDescription(argName, paramSignature, parameterType));
}
var methodDescription = new MethodDescription(member, name, inArguments, inSignature, outType, isGenericOut, outSignature, outArguments);
if (member.Name == interfaceAttribute.GetPropertyMethod)
{
if (propertyGetMethod != null)
{
throw new ArgumentException($"Multiple property Get methods are declared: {memberName}, {propertyGetMethod.MethodInfo.ToString()}");
}
propertyGetMethod = methodDescription;
if ((propertyGetMethod.InSignature != Signature.StringSig) ||
(propertyGetMethod.OutSignature != Signature.VariantSig))
{
throw new ArgumentException($"Property Get method {memberName} must accept a 'string' parameter and return 'Task<object>'");
}
}
else if (member.Name == interfaceAttribute.GetAllPropertiesMethod)
{
if (propertyGetAllMethod != null)
{
throw new ArgumentException($"Multiple property GetAll are declared: {memberName}, {propertyGetAllMethod.MethodInfo.ToString()}");
}
propertyGetAllMethod = methodDescription;
if ((propertyGetAllMethod.InArguments.Count != 0) ||
(propertyGetAllMethod.OutSignature != s_getAllOutSignature))
{
throw new ArgumentException($"Property GetAll method {memberName} must accept no parameters and return 'Task<IDictionary<string, object>>'");
}
if (propertyType == null)
{
if (ArgTypeInspector.InspectEnumerableType(methodDescription.OutType, out elementType, isCompileTimeType: true) == ArgTypeInspector.EnumerableType.AttributeDictionary)
{
propertyType = methodDescription.OutType;
}
}
}
else if (member.Name == interfaceAttribute.SetPropertyMethod)
{
if (propertySetMethod != null)
{
throw new ArgumentException($"Multiple property Set are declared: {memberName}, {propertySetMethod.MethodInfo.ToString()}");
}
propertySetMethod = methodDescription;
if ((propertySetMethod.InArguments?.Count != 2 || propertySetMethod.InArguments[0].Type != s_stringType || propertySetMethod.InArguments[1].Type != s_objectType) ||
(propertySetMethod.OutArguments.Count != 0))
{
throw new ArgumentException($"Property Set method {memberName} must accept a 'string' and 'object' parameter and return 'Task'");
}
}
else
{
methods = methods ?? new List<MethodDescription>();
methods.Add(methodDescription);
}
}
}
if (propertyType != null)
{
var fields = propertyType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach(var field in fields)
{
string propertyName;
Type fieldType;
PropertyTypeInspector.InspectField(field, out propertyName, out fieldType);
var propertySignature = Signature.GetSig(fieldType, isCompileTimeType: true);
var propertyAccess = field.GetCustomAttribute<PropertyAttribute>()?.Access ?? PropertyAccess.ReadWrite;
var description = new PropertyDescription(propertyName, propertySignature, propertyAccess);
properties = properties ?? new List<PropertyDescription>();
properties.Add(description);
}
}
interfaces.Add(new InterfaceDescription(type, interfaceAttribute.Name, methods, signals, properties,
propertyGetMethod, propertyGetAllMethod, propertySetMethod, propertiesChangedSignal));
}
private static void InspectParameterType(Type parameterType, ParameterInfo parameter, out Signature? signature, out IList<ArgumentDescription> arguments)
{
var argumentAttribute = parameter.GetCustomAttribute<ArgumentAttribute>(false);
bool isValueTuple;
arguments = new List<ArgumentDescription>();
if (argumentAttribute != null)
{
signature = Signature.GetSig(parameterType, isCompileTimeType: true);
arguments.Add(new ArgumentDescription(argumentAttribute.Name, signature.Value, parameterType));
}
else if (IsStructType(parameterType, out isValueTuple))
{
signature = null;
var fields = ArgTypeInspector.GetStructFields(parameterType, isValueTuple);
IList<string> tupleElementNames = null;
if (isValueTuple)
{
var tupleElementNamesAttribute = parameter.GetCustomAttribute<TupleElementNamesAttribute>(false);
if (tupleElementNamesAttribute != null)
{
tupleElementNames = tupleElementNamesAttribute.TransformNames;
}
}
int nameIdx = 0;
for (int i = 0; i < fields.Length;)
{
var field = fields[i];
var fieldType = field.FieldType;
if (i == 7 && isValueTuple)
{
fields = ArgTypeInspector.GetStructFields(fieldType, isValueTuple);
i = 0;
}
else
{
var argumentSignature = Signature.GetSig(fieldType, isCompileTimeType: true);
var name = tupleElementNames != null && tupleElementNames.Count > nameIdx ? tupleElementNames[nameIdx] : field.Name;
arguments.Add(new ArgumentDescription(name, argumentSignature, fieldType));
if (signature == null)
{
signature = argumentSignature;
}
else
{
signature = Signature.Concat(signature.Value, argumentSignature);
}
i++;
nameIdx++;
}
}
}
else
{
signature = Signature.GetSig(parameterType, isCompileTimeType: true);
arguments.Add(new ArgumentDescription("value", signature.Value, parameterType));
}
}
private static bool IsStructType(Type type, out bool isValueTuple)
{
isValueTuple = false;
if (type.GetTypeInfo().IsEnum)
{
return false;
}
if (s_mappedTypes.Contains(type))
{
return false;
}
if (ArgTypeInspector.IsDBusObjectType(type, isCompileTimeType: true))
{
return false;
}
Type elementType;
if (ArgTypeInspector.InspectEnumerableType(type, out elementType, isCompileTimeType: true)
!= ArgTypeInspector.EnumerableType.NotEnumerable)
{
return false;
}
return ArgTypeInspector.IsStructType(type, out isValueTuple);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using GitTfs.Core;
using GitTfs.Core.TfsInterop;
using GitTfs.Util;
using Microsoft.TeamFoundation.VersionControl.Common;
namespace GitTfs.VsCommon
{
public class WrapperForVersionControlServer : WrapperFor<VersionControlServer>, IVersionControlServer
{
private readonly TfsApiBridge _bridge;
private readonly VersionControlServer _versionControlServer;
public WrapperForVersionControlServer(TfsApiBridge bridge, VersionControlServer versionControlServer) : base(versionControlServer)
{
_bridge = bridge;
_versionControlServer = versionControlServer;
}
public IItem GetItem(int itemId, int changesetNumber)
{
return _bridge.Wrap<WrapperForItem, Item>(_versionControlServer.GetItem(itemId, changesetNumber));
}
public IItem GetItem(string itemPath, int changesetNumber)
{
return _bridge.Wrap<WrapperForItem, Item>(_versionControlServer.GetItem(itemPath, new ChangesetVersionSpec(changesetNumber)));
}
public IItem[] GetItems(string itemPath, int changesetNumber, TfsRecursionType recursionType)
{
var itemSet = _versionControlServer.GetItems(
new ItemSpec(itemPath, _bridge.Convert<RecursionType>(recursionType), 0),
new ChangesetVersionSpec(changesetNumber),
DeletedState.NonDeleted,
ItemType.Any,
// do not load the loading info
false);
return _bridge.Wrap<WrapperForItem, Item>(itemSet.Items);
}
public IEnumerable<IChangeset> QueryHistory(string path, int version, int deletionId,
TfsRecursionType recursion, string user, int versionFrom, int versionTo, int maxCount,
bool includeChanges, bool slotMode, bool includeDownloadInfo)
{
var history = _versionControlServer.QueryHistory(path, new ChangesetVersionSpec(version), deletionId,
_bridge.Convert<RecursionType>(recursion), user, new ChangesetVersionSpec(versionFrom),
new ChangesetVersionSpec(versionTo), maxCount, includeChanges, slotMode,
includeDownloadInfo);
return _bridge.Wrap<WrapperForChangeset, Changeset>(history);
}
}
public class WrapperForChangeset : WrapperFor<Changeset>, IChangeset
{
private readonly TfsApiBridge _bridge;
private readonly Changeset _changeset;
public WrapperForChangeset(TfsApiBridge bridge, Changeset changeset) : base(changeset)
{
_bridge = bridge;
_changeset = changeset;
}
public IChange[] Changes
{
get { return _bridge.Wrap<WrapperForChange, Change>(_changeset.Changes); }
}
public string Committer
{
get
{
var committer = _changeset.Committer;
var owner = _changeset.Owner;
// Sometimes TFS itself commits the changeset
if (owner != committer)
return owner;
return committer;
}
}
public DateTime CreationDate
{
get { return _changeset.CreationDate; }
}
public string Comment
{
get { return _changeset.Comment; }
}
public int ChangesetId
{
get { return _changeset.ChangesetId; }
}
public IVersionControlServer VersionControlServer
{
get { return _bridge.Wrap<WrapperForVersionControlServer, VersionControlServer>(_changeset.VersionControlServer); }
}
public void Get(ITfsWorkspace workspace, IEnumerable<IChange> changes, Action<Exception> ignorableErrorHandler)
{
workspace.Get(ChangesetId, changes);
}
}
public class WrapperForChange : WrapperFor<Change>, IChange
{
private readonly TfsApiBridge _bridge;
private readonly Change _change;
public WrapperForChange(TfsApiBridge bridge, Change change) : base(change)
{
_bridge = bridge;
_change = change;
}
public TfsChangeType ChangeType
{
get { return _bridge.Convert<TfsChangeType>(_change.ChangeType); }
}
public IItem Item
{
get { return _bridge.Wrap<WrapperForItem, Item>(_change.Item); }
}
}
public class WrapperForItem : WrapperFor<Item>, IItem
{
private readonly IItemDownloadStrategy _downloadStrategy;
private readonly TfsApiBridge _bridge;
private readonly Item _item;
public WrapperForItem(IItemDownloadStrategy downloadStrategy, TfsApiBridge bridge, Item item) : base(item)
{
_downloadStrategy = downloadStrategy;
_bridge = bridge;
_item = item;
}
public IVersionControlServer VersionControlServer
{
get { return _bridge.Wrap<WrapperForVersionControlServer, VersionControlServer>(_item.VersionControlServer); }
}
public int ChangesetId
{
get { return _item.ChangesetId; }
}
public string ServerItem
{
get { return _item.ServerItem; }
}
public int DeletionId
{
get { return _item.DeletionId; }
}
public TfsItemType ItemType
{
get { return _bridge.Convert<TfsItemType>(_item.ItemType); }
}
public int ItemId
{
get { return _item.ItemId; }
}
public long ContentLength
{
get { return _item.ContentLength; }
}
public TemporaryFile DownloadFile()
{
return _downloadStrategy.DownloadFile(this);
}
}
public class WrapperForIdentity : WrapperFor<Identity>, IIdentity
{
private readonly Identity _identity;
public WrapperForIdentity(Identity identity) : base(identity)
{
Debug.Assert(identity != null, "wrapped property must not be null.");
_identity = identity;
}
public string MailAddress
{
get { return _identity.MailAddress; }
}
public string DisplayName
{
get { return _identity.DisplayName; }
}
}
public class WrapperForShelveset : WrapperFor<Shelveset>, IShelveset
{
private readonly Shelveset _shelveset;
private readonly TfsApiBridge _bridge;
public WrapperForShelveset(TfsApiBridge bridge, Shelveset shelveset) : base(shelveset)
{
_shelveset = shelveset;
_bridge = bridge;
}
public string Comment
{
get { return _shelveset.Comment; }
set { _shelveset.Comment = value; }
}
public IWorkItemCheckinInfo[] WorkItemInfo
{
get { return _bridge.Wrap<WrapperForWorkItemCheckinInfo, WorkItemCheckinInfo>(_shelveset.WorkItemInfo); }
set { _shelveset.WorkItemInfo = _bridge.Unwrap<WorkItemCheckinInfo>(value); }
}
}
public class WrapperForWorkItemCheckinInfo : WrapperFor<WorkItemCheckinInfo>, IWorkItemCheckinInfo
{
public WrapperForWorkItemCheckinInfo(WorkItemCheckinInfo workItemCheckinInfo) : base(workItemCheckinInfo)
{
}
}
public class WrapperForWorkItemCheckedInfo : WrapperFor<WorkItemCheckedInfo>, IWorkItemCheckedInfo
{
public WrapperForWorkItemCheckedInfo(WorkItemCheckedInfo workItemCheckinInfo)
: base(workItemCheckinInfo)
{
}
}
public class WrapperForPendingChange : WrapperFor<PendingChange>, IPendingChange
{
public WrapperForPendingChange(PendingChange pendingChange) : base(pendingChange)
{
}
}
public class WrapperForCheckinNote : WrapperFor<CheckinNote>, ICheckinNote
{
public WrapperForCheckinNote(CheckinNote checkiNote) : base(checkiNote)
{
}
}
public class WrapperForCheckinEvaluationResult : WrapperFor<CheckinEvaluationResult>, ICheckinEvaluationResult
{
private readonly TfsApiBridge _bridge;
private readonly CheckinEvaluationResult _result;
public WrapperForCheckinEvaluationResult(TfsApiBridge bridge, CheckinEvaluationResult result) : base(result)
{
_bridge = bridge;
_result = result;
}
public ICheckinConflict[] Conflicts
{
get { return _bridge.Wrap<WrapperForCheckinConflict, CheckinConflict>(_result.Conflicts); }
}
public ICheckinNoteFailure[] NoteFailures
{
get { return _bridge.Wrap<WrapperForCheckinNoteFailure, CheckinNoteFailure>(_result.NoteFailures); }
}
public IPolicyFailure[] PolicyFailures
{
get { return _bridge.Wrap<WrapperForPolicyFailure, PolicyFailure>(_result.PolicyFailures); }
}
public Exception PolicyEvaluationException
{
get { return _result.PolicyEvaluationException; }
}
}
public class WrapperForCheckinConflict : WrapperFor<CheckinConflict>, ICheckinConflict
{
private readonly CheckinConflict _conflict;
public WrapperForCheckinConflict(CheckinConflict conflict) : base(conflict)
{
_conflict = conflict;
}
public string ServerItem
{
get { return _conflict.ServerItem; }
}
public string Message
{
get { return _conflict.Message; }
}
public bool Resolvable
{
get { return _conflict.Resolvable; }
}
}
public class WrapperForCheckinNoteFailure : WrapperFor<CheckinNoteFailure>, ICheckinNoteFailure
{
private readonly TfsApiBridge _bridge;
private readonly CheckinNoteFailure _failure;
public WrapperForCheckinNoteFailure(TfsApiBridge bridge, CheckinNoteFailure failure) : base(failure)
{
_bridge = bridge;
_failure = failure;
}
public ICheckinNoteFieldDefinition Definition
{
get { return _bridge.Wrap<WrapperForCheckinNoteFieldDefinition, CheckinNoteFieldDefinition>(_failure.Definition); }
}
public string Message
{
get { return _failure.Message; }
}
}
public class WrapperForCheckinNoteFieldDefinition : WrapperFor<CheckinNoteFieldDefinition>, ICheckinNoteFieldDefinition
{
private readonly CheckinNoteFieldDefinition _fieldDefinition;
public WrapperForCheckinNoteFieldDefinition(CheckinNoteFieldDefinition fieldDefinition) : base(fieldDefinition)
{
_fieldDefinition = fieldDefinition;
}
public string ServerItem
{
get { return _fieldDefinition.ServerItem; }
}
public string Name
{
get { return _fieldDefinition.Name; }
}
public bool Required
{
get { return _fieldDefinition.Required; }
}
public int DisplayOrder
{
get { return _fieldDefinition.DisplayOrder; }
}
}
public class WrapperForPolicyFailure : WrapperFor<PolicyFailure>, IPolicyFailure
{
private readonly PolicyFailure _failure;
public WrapperForPolicyFailure(PolicyFailure failure) : base(failure)
{
_failure = failure;
}
public string Message
{
get { return _failure.Message; }
}
}
public class WrapperForWorkspace : WrapperFor<Workspace>, IWorkspace
{
private readonly TfsApiBridge _bridge;
private readonly Workspace _workspace;
public WrapperForWorkspace(TfsApiBridge bridge, Workspace workspace) : base(workspace)
{
_bridge = bridge;
_workspace = workspace;
}
public IPendingChange[] GetPendingChanges()
{
return _bridge.Wrap<WrapperForPendingChange, PendingChange>(_workspace.GetPendingChanges());
}
public void Shelve(IShelveset shelveset, IPendingChange[] changes, TfsShelvingOptions options)
{
_workspace.Shelve(_bridge.Unwrap<Shelveset>(shelveset), _bridge.Unwrap<PendingChange>(changes), _bridge.Convert<ShelvingOptions>(options));
}
private PolicyOverrideInfo ToTfs(TfsPolicyOverrideInfo policyOverrideInfo)
{
if (policyOverrideInfo == null)
return null;
return new PolicyOverrideInfo(policyOverrideInfo.Comment,
_bridge.Unwrap<PolicyFailure>(policyOverrideInfo.Failures));
}
public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes,
string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges)
{
return _bridge.Wrap<WrapperForCheckinEvaluationResult, CheckinEvaluationResult>(_workspace.EvaluateCheckin(
_bridge.Convert<CheckinEvaluationOptions>(options),
_bridge.Unwrap<PendingChange>(allChanges),
_bridge.Unwrap<PendingChange>(changes),
comment,
_bridge.Unwrap<CheckinNote>(checkinNote),
_bridge.Unwrap<WorkItemCheckinInfo>(workItemChanges)));
}
public int PendAdd(string path)
{
return _workspace.PendAdd(path);
}
public int PendEdit(string path)
{
return _workspace.PendEdit(new string[] { path }, RecursionType.None, null, LockLevel.Unchanged, false, PendChangesOptions.ForceCheckOutLocalVersion);
}
public int PendDelete(string path)
{
return _workspace.PendDelete(path);
}
public int PendRename(string pathFrom, string pathTo)
{
FileInfo info = new FileInfo(pathTo);
if (info.Exists)
info.Delete();
return _workspace.PendRename(pathFrom, pathTo);
}
private void DoUntilNoFailures(Func<GetStatus> get)
{
Retry.DoWhile(() => get().NumFailures != 0);
}
public void ForceGetFile(string path, int changeset)
{
var item = new ItemSpec(path, RecursionType.None);
DoUntilNoFailures(() => _workspace.Get(new GetRequest(item, changeset), GetOptions.Overwrite | GetOptions.GetAll));
}
public void GetSpecificVersion(int changeset)
{
Retry.Do(() => DoUntilNoFailures(() => _workspace.Get(new ChangesetVersionSpec(changeset), GetOptions.Overwrite | GetOptions.GetAll)));
}
public void GetSpecificVersion(int changesetId, IEnumerable<IItem> items)
{
var version = new ChangesetVersionSpec(changesetId);
GetRequests(items.Select(e => new GetRequest(new ItemSpec(e.ServerItem, RecursionType.Full), version)));
}
public void GetSpecificVersion(IChangeset changeset)
{
GetSpecificVersion(changeset.ChangesetId, changeset.Changes);
}
public void GetSpecificVersion(int changesetId, IEnumerable<IChange> changes)
{
GetRequests(changes.Select(change => new GetRequest(new ItemSpec(change.Item.ServerItem, RecursionType.None, change.Item.DeletionId), changesetId)));
}
public string GetLocalItemForServerItem(string serverItem)
{
return _workspace.GetLocalItemForServerItem(serverItem);
}
public string GetServerItemForLocalItem(string localItem)
{
return _workspace.GetServerItemForLocalItem(localItem);
}
public string OwnerName
{
get { return _workspace.OwnerName; }
}
public void Merge(string sourceTfsPath, string targetTfsPath)
{
var status = _workspace.Merge(sourceTfsPath, targetTfsPath, null, null, LockLevel.None, RecursionType.Full,
MergeOptions.AlwaysAcceptMine);
var conflicts = _workspace.QueryConflicts(null, true);
foreach (var conflict in conflicts)
{
conflict.Resolution = Resolution.AcceptYours;
_workspace.ResolveConflict(conflict);
}
}
public int Checkin(IPendingChange[] changes, string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges,
TfsPolicyOverrideInfo policyOverrideInfo, bool overrideGatedCheckIn)
{
var checkinParameters = new WorkspaceCheckInParameters(_bridge.Unwrap<PendingChange>(changes), comment)
{
CheckinNotes = _bridge.Unwrap<CheckinNote>(checkinNote),
AssociatedWorkItems = _bridge.Unwrap<WorkItemCheckinInfo>(workItemChanges),
PolicyOverride = ToTfs(policyOverrideInfo),
OverrideGatedCheckIn = overrideGatedCheckIn
};
if (author != null)
checkinParameters.Author = author;
try
{
return _workspace.CheckIn(checkinParameters);
}
catch (GatedCheckinException gatedException)
{
throw new GitTfsGatedCheckinException(gatedException.ShelvesetName, gatedException.AffectedBuildDefinitions, gatedException.CheckInTicket);
}
}
public void GetRequests(IEnumerable<GetRequest> source, int batchSize = 20)
{
source.ToBatch(batchSize).DoParallel(batch =>
{
var items = batch;
Retry.Do(() =>
{
while (items.Length > 0)
{
var status = _workspace.Get(items.ToArray(), GetOptions.Overwrite | GetOptions.GetAll);
if (status.NumFailures == 0)
{
break;
}
items = status.GetFailures().Join(items, e => e.ServerItem, e => e.ItemSpec.Item, (failure, request) => request).ToArray();
}
});
});
}
}
public class WrapperForBranchObject : WrapperFor<BranchObject>, IBranchObject
{
private readonly BranchObject _branch;
public WrapperForBranchObject(BranchObject branch)
: base(branch)
{
_branch = branch;
}
public string Path
{
get { return _branch.Properties.RootItem.Item; }
}
public bool IsRoot
{
get { return _branch.Properties.ParentBranch == null; }
}
public string ParentPath
{
get { return _branch.Properties.ParentBranch.Item; }
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.UserModel
{
using System;
using System.IO;
using TestCases.HSSF;
using NPOI.SS.Util;
using NPOI.Util;
using NPOI.HSSF.UserModel;
using NUnit.Framework;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.PTG;
using NPOI.HSSF.Model;
using NPOI.SS.Formula;
/**
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Avik Sengupta
*/
[TestFixture]
public class TestFormulas
{
public TestFormulas()
{
}
private static HSSFWorkbook OpenSample(String sampleFileName)
{
return HSSFTestDataSamples.OpenSampleWorkbook(sampleFileName);
}
/**
* Add 1+1 -- WHoohoo!
*/
[Test]
public void TestBasicAddIntegers()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
//get our minimum values
r = s.CreateRow(1);
c = r.CreateCell(1);
c.CellFormula = (1 + "+" + 1);
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(1);
c = r.GetCell(1);
Assert.IsTrue("1+1".Equals(c.CellFormula), "Formula is as expected");
}
/**
* Add various integers
*/
[Test]
public void TestAddIntegers()
{
BinomialOperator("+");
}
/**
* Multiply various integers
*/
[Test]
public void TestMultplyIntegers()
{
BinomialOperator("*");
}
/**
* Subtract various integers
*/
[Test]
public void TestSubtractIntegers()
{
BinomialOperator("-");
}
/**
* Subtract various integers
*/
[Test]
public void TestDivideIntegers()
{
BinomialOperator("/");
}
/**
* Exponentialize various integers;
*/
[Test]
public void TestPowerIntegers()
{
BinomialOperator("^");
}
/**
* Concatenate two numbers 1&2 = 12
*/
[Test]
public void TestConcatIntegers()
{
BinomialOperator("&");
}
/**
* Tests 1*2+3*4
*/
[Test]
public void TestOrderOfOperationsMultiply()
{
OrderTest("1*2+3*4");
}
/**
* Tests 1*2+3^4
*/
[Test]
public void TestOrderOfOperationsPower()
{
OrderTest("1*2+3^4");
}
/**
* Tests that parenthesis are obeyed
*/
[Test]
public void TestParenthesis()
{
OrderTest("(1*3)+2+(1+2)*(3^4)^5");
}
[Test]
public void TestReferencesOpr()
{
String[] operation = new String[] {
"+", "-", "*", "/", "^", "&"
};
for (int k = 0; k < operation.Length; k++)
{
OperationRefTest(operation[k]);
}
}
/**
* Tests creating a file with floating point in a formula.
*
*/
[Test]
public void TestFloat()
{
// This Test depends on the american culture.
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
floatTest("*");
floatTest("/");
}
private static void floatTest(String operator1)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
//get our minimum values
r = s.CreateRow(0);
c = r.CreateCell(1);
c.CellFormula = ("" + float.MinValue + operator1 + float.MinValue);
for (int x = 1; x < short.MaxValue && x > 0; x = (short)(x * 2))
{
r = s.CreateRow(x);
for (int y = 1; y < 256 && y > 0; y = (short)(y + 2))
{
c = r.CreateCell(y);
c.CellFormula = ("" + x + "." + y + operator1 + y + "." + x);
}
}
if (s.LastRowNum < short.MaxValue)
{
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellFormula = ("" + float.MaxValue + operator1 + float.MaxValue);
}
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
floatVerify(operator1, wb);
}
private static void floatVerify(String operator1, HSSFWorkbook wb)
{
NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0);
// don't know how to Check correct result .. for the moment, we just verify that the file can be read.
for (int x = 1; x < short.MaxValue && x > 0; x = (short)(x * 2))
{
IRow r = s.GetRow(x);
for (int y = 1; y < 256 && y > 0; y = (short)(y + 2))
{
ICell c = r.GetCell(y);
Assert.IsTrue(c.CellFormula != null, "got a formula");
Assert.IsTrue(
("" + x + "." + y + operator1 + y + "." + x).Equals(c.CellFormula),
"loop Formula is as expected " + x + "." + y + operator1 + y + "." + x + "!=" + c.CellFormula);
}
}
}
[Test]
public void TestAreaSum()
{
AreaFunctionTest("SUM");
}
[Test]
public void TestAreaAverage()
{
AreaFunctionTest("AVERAGE");
}
[Test]
public void TestRefArraySum()
{
RefArrayFunctionTest("SUM");
}
[Test]
public void TestAreaArraySum()
{
RefAreaArrayFunctionTest("SUM");
}
private static void OperationRefTest(String operator1)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
//get our minimum values
r = s.CreateRow(0);
c = r.CreateCell(1);
c.CellFormula = ("A2" + operator1 + "A3");
for (int x = 1; x < short.MaxValue && x > 0; x = (short)(x * 2))
{
r = s.CreateRow(x);
for (int y = 1; y < 256 && y > 0; y++)
{
String ref1 = null;
String ref2 = null;
short refx1 = 0;
short refy1 = 0;
short refx2 = 0;
short refy2 = 0;
if (x + 50 < short.MaxValue)
{
refx1 = (short)(x + 50);
refx2 = (short)(x + 46);
}
else
{
refx1 = (short)(x - 4);
refx2 = (short)(x - 3);
}
if (y + 50 < 255)
{
refy1 = (short)(y + 50);
refy2 = (short)(y + 49);
}
else
{
refy1 = (short)(y - 4);
refy2 = (short)(y - 3);
}
c = r.GetCell(y);
CellReference cr = new CellReference(refx1, refy1, false, false);
ref1 = cr.FormatAsString();
cr = new CellReference(refx2, refy2, false, false);
ref2 = cr.FormatAsString();
c = r.CreateCell(y);
c.CellFormula = ("" + ref1 + operator1 + ref2);
}
}
//make sure we do the maximum value of the Int operator
if (s.LastRowNum < short.MaxValue)
{
r = s.GetRow(0);
c = r.CreateCell(0);
c.CellFormula = ("" + "B1" + operator1 + "IV255");
}
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
OperationalRefVerify(operator1, wb);
}
/**
* Opens the sheet we wrote out by BinomialOperator and makes sure the formulas
* all Match what we expect (x operator y)
*/
private static void OperationalRefVerify(String operator1, HSSFWorkbook wb)
{
NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0);
IRow r = null;
ICell c = null;
//get our minimum values
r = s.GetRow(0);
c = r.GetCell(1);
//get our minimum values
Assert.IsTrue(("A2" + operator1 + "A3").Equals(c.CellFormula), "minval Formula is as expected A2" + operator1 + "A3 != " + c.CellFormula);
for (int x = 1; x < short.MaxValue && x > 0; x = (short)(x * 2))
{
r = s.GetRow(x);
for (int y = 1; y < 256 && y > 0; y++)
{
int refx1;
int refy1;
int refx2;
int refy2;
if (x + 50 < short.MaxValue)
{
refx1 = x + 50;
refx2 = x + 46;
}
else
{
refx1 = x - 4;
refx2 = x - 3;
}
if (y + 50 < 255)
{
refy1 = y + 50;
refy2 = y + 49;
}
else
{
refy1 = y - 4;
refy2 = y - 3;
}
c = r.GetCell(y);
CellReference cr = new CellReference(refx1, refy1, false, false);
String ref1 = cr.FormatAsString();
ref1 = cr.FormatAsString();
cr = new CellReference(refx2, refy2, false, false);
String ref2 = cr.FormatAsString();
Assert.IsTrue((
("" + ref1 + operator1 + ref2).Equals(c.CellFormula)
), "loop Formula is as expected " + ref1 + operator1 + ref2 + "!=" + c.CellFormula
);
}
}
//Test our maximum values
r = s.GetRow(0);
c = r.GetCell(0);
Assert.AreEqual("B1" + operator1 + "IV255", c.CellFormula);
}
/**
* Tests Order wrting out == Order writing in for a given formula
*/
private static void OrderTest(String formula)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
//get our minimum values
r = s.CreateRow(0);
c = r.CreateCell(1);
c.CellFormula = (formula);
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
//get our minimum values
r = s.GetRow(0);
c = r.GetCell(1);
Assert.IsTrue(formula.Equals(c.CellFormula), "minval Formula is as expected"
);
}
/**
* All multi-binomial operator Tests use this to Create a worksheet with a
* huge set of x operator y formulas. Next we call BinomialVerify and verify
* that they are all how we expect.
*/
private static void BinomialOperator(String operator1)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
//get our minimum values
r = s.CreateRow(0);
c = r.CreateCell(1);
c.CellFormula = (1 + operator1 + 1);
for (int x = 1; x < short.MaxValue && x > 0; x = (short)(x * 2))
{
r = s.CreateRow(x);
for (int y = 1; y < 256 && y > 0; y++)
{
c = r.CreateCell(y);
c.CellFormula = ("" + x + operator1 + y);
}
}
//make sure we do the maximum value of the Int operator
if (s.LastRowNum < short.MaxValue)
{
r = s.GetRow(0);
c = r.CreateCell(0);
c.CellFormula = ("" + short.MaxValue + operator1 + short.MaxValue);
}
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
BinomialVerify(operator1, wb);
}
/**
* Opens the sheet we wrote out by BinomialOperator and makes sure the formulas
* all Match what we expect (x operator y)
*/
private static void BinomialVerify(String operator1, HSSFWorkbook wb)
{
NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0);
IRow r = null;
ICell c = null;
//get our minimum values
r = s.GetRow(0);
c = r.GetCell(1);
Assert.IsTrue(("1" + operator1 + "1").Equals(c.CellFormula),
"minval Formula is as expected 1" + operator1 + "1 != " + c.CellFormula);
for (int x = 1; x < short.MaxValue && x > 0; x = (short)(x * 2))
{
r = s.GetRow(x);
for (int y = 1; y < 256 && y > 0; y++)
{
c = r.GetCell(y);
Assert.IsTrue(("" + x + operator1 + y).Equals(c.CellFormula),
"loop Formula is as expected " + x + operator1 + y + "!=" + c.CellFormula
);
}
}
//Test our maximum values
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue(
("" + short.MaxValue + operator1 + short.MaxValue).Equals(c.CellFormula), "maxval Formula is as expected"
);
}
/**
* Writes a function then Tests to see if its correct
*/
public static void AreaFunctionTest(String function)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellFormula = (function + "(A2:A3)");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue((function + "(A2:A3)").Equals((function + "(A2:A3)")), "function =" + function + "(A2:A3)"
);
}
/**
* Writes a function then Tests to see if its correct
*/
public void RefArrayFunctionTest(String function)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellFormula = (function + "(A2,A3)");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue((function + "(A2,A3)").Equals(c.CellFormula), "function =" + function + "(A2,A3)"
);
}
/**
* Writes a function then Tests to see if its correct
*
*/
public void RefAreaArrayFunctionTest(String function)
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellFormula = (function + "(A2:A4,B2:B4)");
c = r.CreateCell(1);
c.CellFormula = (function + "($A$2:$A4,B$2:B4)");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue(
(function + "(A2:A4,B2:B4)").Equals(c.CellFormula), "function =" + function + "(A2:A4,B2:B4)"
);
c = r.GetCell(1);
Assert.IsTrue((function + "($A$2:$A4,B$2:B4)").Equals(c.CellFormula),
"function =" + function + "($A$2:$A4,B$2:B4)"
);
}
[Test]
public void TestAbsRefs()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r;
ICell c;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellFormula = ("A3+A2");
c = r.CreateCell(1);
c.CellFormula = ("$A3+$A2");
c = r.CreateCell(2);
c.CellFormula = ("A$3+A$2");
c = r.CreateCell(3);
c.CellFormula = ("$A$3+$A$2");
c = r.CreateCell(4);
c.CellFormula = ("SUM($A$3,$A$2)");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue(("A3+A2").Equals(c.CellFormula), "A3+A2");
c = r.GetCell(1);
Assert.IsTrue(("$A3+$A2").Equals(c.CellFormula), "$A3+$A2");
c = r.GetCell(2);
Assert.IsTrue(("A$3+A$2").Equals(c.CellFormula), "A$3+A$2");
c = r.GetCell(3);
Assert.IsTrue(("$A$3+$A$2").Equals(c.CellFormula), "$A$3+$A$2");
c = r.GetCell(4);
Assert.IsTrue(("SUM($A$3,$A$2)").Equals(c.CellFormula), "SUM($A$3,$A$2)");
}
[Test]
public void TestSheetFunctions()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet("A");
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(0); c.SetCellValue(1);
c = r.CreateCell(1); c.SetCellValue(2);
s = wb.CreateSheet("B");
r = s.CreateRow(0);
c = r.CreateCell(0); c.CellFormula = ("AVERAGE(A!A1:B1)");
c = r.CreateCell(1); c.CellFormula = ("A!A1+A!B1");
c = r.CreateCell(2); c.CellFormula = ("A!$A$1+A!$B1");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheet("B");
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue(("AVERAGE(A!A1:B1)").Equals(c.CellFormula), "expected: AVERAGE(A!A1:B1) got: " + c.CellFormula);
c = r.GetCell(1);
Assert.IsTrue(("A!A1+A!B1").Equals(c.CellFormula), "expected: A!A1+A!B1 got: " + c.CellFormula);
}
[Test]
public void TestRVAoperands()
{
string tmpfile = TempFile.GetTempFilePath("TestFormulaRVA", ".xls");
FileStream out1 = new FileStream(tmpfile, FileMode.Create);
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellFormula = ("A3+A2");
c = r.CreateCell(1);
c.CellFormula = ("AVERAGE(A3,A2)");
c = r.CreateCell(2);
c.CellFormula = ("ROW(A3)");
c = r.CreateCell(3);
c.CellFormula = ("AVERAGE(A2:A3)");
c = r.CreateCell(4);
c.CellFormula = ("POWER(A2,A3)");
c = r.CreateCell(5);
c.CellFormula = ("SIN(A2)");
c = r.CreateCell(6);
c.CellFormula = ("SUM(A2:A3)");
c = r.CreateCell(7);
c.CellFormula = ("SUM(A2,A3)");
r = s.CreateRow(1); c = r.CreateCell(0); c.SetCellValue(2.0);
r = s.CreateRow(2); c = r.CreateCell(0); c.SetCellValue(3.0);
wb.Write(out1);
out1.Close();
Assert.IsTrue(File.Exists(tmpfile), "file exists");
}
[Test]
public void TestStringFormulas()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet("A");
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(1); c.CellFormula = ("UPPER(\"abc\")");
c = r.CreateCell(2); c.CellFormula = ("LOWER(\"ABC\")");
c = r.CreateCell(3); c.CellFormula = ("CONCATENATE(\" my \",\" name \")");
HSSFTestDataSamples.WriteOutAndReadBack(wb);
wb = OpenSample("StringFormulas.xls");
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.AreEqual("UPPER(\"xyz\")", c.CellFormula);
}
[Test]
public void TestLogicalFormulas()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet("A");
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(1); c.CellFormula = ("IF(A1<A2,B1,B2)");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(1);
Assert.AreEqual("IF(A1<A2,B1,B2)", c.CellFormula, "Formula in cell 1 ");
}
[Test]
public void TestDateFormulas()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet("TestSheet1");
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(0);
NPOI.SS.UserModel.ICellStyle cellStyle = wb.CreateCellStyle();
cellStyle.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy h:mm"));
c.SetCellValue(new DateTime());
c.CellStyle = (cellStyle);
// Assert.AreEqual("Checking hour = " + hour, date.GetTime().GetTime(),
// NPOI.SS.UserModel.DateUtil.GetJavaDate(excelDate).GetTime());
for (int k = 1; k < 100; k++)
{
r = s.CreateRow(k);
c = r.CreateCell(0);
c.CellFormula = ("A" + (k) + "+1");
c.CellStyle = cellStyle;
}
HSSFTestDataSamples.WriteOutAndReadBack(wb);
}
[Test]
public void TestIfFormulas()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet("TestSheet1");
IRow r = null;
ICell c = null;
r = s.CreateRow(0);
c = r.CreateCell(1); c.SetCellValue(1);
c = r.CreateCell(2); c.SetCellValue(2);
c = r.CreateCell(3); c.CellFormula = ("MAX(A1:B1)");
c = r.CreateCell(4); c.CellFormula = ("IF(A1=D1,\"A1\",\"B1\")");
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(4);
Assert.IsTrue(("IF(A1=D1,\"A1\",\"B1\")").Equals(c.CellFormula), "expected: IF(A1=D1,\"A1\",\"B1\") got " + c.CellFormula);
wb = OpenSample("IfFormulaTest.xls");
s = wb.GetSheetAt(0);
r = s.GetRow(3);
c = r.GetCell(0);
Assert.IsTrue(("IF(A3=A1,\"A1\",\"A2\")").Equals(c.CellFormula), "expected: IF(A3=A1,\"A1\",\"A2\") got " + c.CellFormula);
//c = r.GetCell((short)1);
//Assert.IsTrue("expected: A!A1+A!B1 got: "+c.CellFormula, ("A!A1+A!B1").Equals(c.CellFormula));
wb = new HSSFWorkbook();
s = wb.CreateSheet("TestSheet1");
r = null;
c = null;
r = s.CreateRow(0);
c = r.CreateCell(0); c.CellFormula = ("IF(1=1,0,1)");
HSSFTestDataSamples.WriteOutAndReadBack(wb);
wb = new HSSFWorkbook();
s = wb.CreateSheet("TestSheet1");
r = null;
c = null;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.SetCellValue(1);
c = r.CreateCell(1);
c.SetCellValue(3);
ICell formulaCell = r.CreateCell(3);
r = s.CreateRow(1);
c = r.CreateCell(0);
c.SetCellValue(3);
c = r.CreateCell(1);
c.SetCellValue(7);
formulaCell.CellFormula = ("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))");
HSSFTestDataSamples.WriteOutAndReadBack(wb);
}
[Test]
public void TestSumIf()
{
String function = "SUMIF(A1:A5,\">4000\",B1:B5)";
HSSFWorkbook wb = OpenSample("sumifformula.xls");
NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0);
IRow r = s.GetRow(0);
ICell c = r.GetCell(2);
Assert.AreEqual(function, c.CellFormula);
wb = new HSSFWorkbook();
s = wb.CreateSheet();
r = s.CreateRow(0);
c = r.CreateCell(0); c.SetCellValue(1000);
c = r.CreateCell(1); c.SetCellValue(1);
r = s.CreateRow(1);
c = r.CreateCell(0); c.SetCellValue(2000);
c = r.CreateCell(1); c.SetCellValue(2);
r = s.CreateRow(2);
c = r.CreateCell(0); c.SetCellValue(3000);
c = r.CreateCell(1); c.SetCellValue(3);
r = s.CreateRow(3);
c = r.CreateCell(0); c.SetCellValue(4000);
c = r.CreateCell(1); c.SetCellValue(4);
r = s.CreateRow(4);
c = r.CreateCell(0); c.SetCellValue(5000);
c = r.CreateCell(1); c.SetCellValue(5);
r = s.GetRow(0);
c = r.CreateCell(2); c.CellFormula = (function);
HSSFTestDataSamples.WriteOutAndReadBack(wb);
}
[Test]
public void TestSquareMacro()
{
HSSFWorkbook w = OpenSample("SquareMacro.xls");
NPOI.SS.UserModel.ISheet s0 = w.GetSheetAt(0);
IRow[] r = { s0.GetRow(0), s0.GetRow(1) };
ICell a1 = r[0].GetCell(0);
Assert.AreEqual("square(1)", a1.CellFormula);
Assert.AreEqual(1d, a1.NumericCellValue, 1e-9);
ICell a2 = r[1].GetCell(0);
Assert.AreEqual("square(2)", a2.CellFormula);
Assert.AreEqual(4d, a2.NumericCellValue, 1e-9);
ICell b1 = r[0].GetCell(1);
Assert.AreEqual("IF(TRUE,square(1))", b1.CellFormula);
Assert.AreEqual(1d, b1.NumericCellValue, 1e-9);
ICell b2 = r[1].GetCell(1);
Assert.AreEqual("IF(TRUE,square(2))", b2.CellFormula);
Assert.AreEqual(4d, b2.NumericCellValue, 1e-9);
ICell c1 = r[0].GetCell(2);
Assert.AreEqual("square(square(1))", c1.CellFormula);
Assert.AreEqual(1d, c1.NumericCellValue, 1e-9);
ICell c2 = r[1].GetCell(2);
Assert.AreEqual("square(square(2))", c2.CellFormula);
Assert.AreEqual(16d, c2.NumericCellValue, 1e-9);
ICell d1 = r[0].GetCell(3);
Assert.AreEqual("square(one())", d1.CellFormula);
Assert.AreEqual(1d, d1.NumericCellValue, 1e-9);
ICell d2 = r[1].GetCell(3);
Assert.AreEqual("square(two())", d2.CellFormula);
Assert.AreEqual(4d, d2.NumericCellValue, 1e-9);
}
[Test]
public void TestStringFormulaRead()
{
HSSFWorkbook w = OpenSample("StringFormulas.xls");
ICell c = w.GetSheetAt(0).GetRow(0).GetCell(0);
Assert.AreEqual("XYZ", c.RichStringCellValue.String, "String Cell value");
}
/** Test for bug 34021*/
[Test]
public void TestComplexSheetRefs()
{
HSSFWorkbook sb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s1 = sb.CreateSheet("Sheet a.1");
NPOI.SS.UserModel.ISheet s2 = sb.CreateSheet("Sheet.A");
s2.CreateRow(1).CreateCell(2).CellFormula = ("'Sheet a.1'!A1");
s1.CreateRow(1).CreateCell(2).CellFormula = ("'Sheet.A'!A1");
string tmpfile = TempFile.GetTempFilePath("TestComplexSheetRefs", ".xls");
FileStream fs = new FileStream(tmpfile, FileMode.Create);
sb.Write(fs);
fs.Close();
}
/** Unknown Ptg 3C*/
[Test]
public void Test27272_1()
{
HSSFWorkbook wb = OpenSample("27272_1.xls");
wb.GetSheetAt(0);
Assert.AreEqual("Compliance!#REF!", wb.GetNameAt(0).RefersToFormula, "Reference for named range ");
string tmpfile = TempFile.GetTempFilePath("bug27272_1", ".xls");
FileStream fs = new FileStream(tmpfile, FileMode.OpenOrCreate);
wb.Write(fs);
fs.Close();
Console.WriteLine("Open " + Path.GetFullPath(tmpfile) + " in Excel");
}
/** Unknown Ptg 3D*/
[Test]
public void Test27272_2()
{
HSSFWorkbook wb = OpenSample("27272_2.xls");
Assert.AreEqual("LOAD.POD_HISTORIES!#REF!", wb.GetNameAt(0).RefersToFormula, "Reference for named range ");
string tmpfile = TempFile.GetTempFilePath("bug27272_2", ".xls");
FileStream fs = new FileStream(tmpfile, FileMode.OpenOrCreate);
wb.Write(fs);
Console.WriteLine("Open " + Path.GetFullPath(tmpfile) + " in Excel");
}
/** MissingArgPtg */
[Test]
public void TestMissingArgPtg()
{
HSSFWorkbook wb = new HSSFWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(4).CreateCell(0);
cell.CellFormula = ("IF(A1=\"A\",1,)");
}
[Test]
public void TestSharedFormula()
{
HSSFWorkbook wb = OpenSample("SharedFormulaTest.xls");
Assert.AreEqual("A$1*2", wb.GetSheetAt(0).GetRow(1).GetCell(1).ToString());
Assert.AreEqual("$A11*2", wb.GetSheetAt(0).GetRow(11).GetCell(1).ToString());
Assert.AreEqual("DZ2*2", wb.GetSheetAt(0).GetRow(1).GetCell(128).ToString());
Assert.AreEqual("B32770*2", wb.GetSheetAt(0).GetRow(32768).GetCell(1).ToString());
}
/**
* Test creation / evaluation of formulas with sheet-level names
*/
[Test]
public void TestSheetLevelFormulas()
{
HSSFWorkbook wb = new HSSFWorkbook();
IRow row;
ISheet sh1 = wb.CreateSheet("Sheet1");
IName nm1 = wb.CreateName();
nm1.NameName = ("sales_1");
nm1.SheetIndex = (0);
nm1.RefersToFormula = ("Sheet1!$A$1");
row = sh1.CreateRow(0);
row.CreateCell(0).SetCellValue(3);
row.CreateCell(1).SetCellFormula("sales_1");
row.CreateCell(2).SetCellFormula("sales_1*2");
ISheet sh2 = wb.CreateSheet("Sheet2");
IName nm2 = wb.CreateName();
nm2.NameName = ("sales_1");
nm2.SheetIndex = (1);
nm2.RefersToFormula = ("Sheet2!$A$1");
row = sh2.CreateRow(0);
row.CreateCell(0).SetCellValue(5);
row.CreateCell(1).SetCellFormula("sales_1");
row.CreateCell(2).SetCellFormula("sales_1*3");
//check that NamePtg refers to the correct NameRecord
Ptg[] ptgs1 = HSSFFormulaParser.Parse("sales_1", wb, FormulaType.Cell, 0);
NamePtg nPtg1 = (NamePtg)ptgs1[0];
Assert.AreSame(nm1, wb.GetNameAt(nPtg1.Index));
Ptg[] ptgs2 = HSSFFormulaParser.Parse("sales_1", wb, FormulaType.Cell, 1);
NamePtg nPtg2 = (NamePtg)ptgs2[0];
Assert.AreSame(nm2, wb.GetNameAt(nPtg2.Index));
//check that the formula evaluator returns the correct result
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
Assert.AreEqual(3.0, evaluator.Evaluate(sh1.GetRow(0).GetCell(1)).NumberValue, 0.0);
Assert.AreEqual(6.0, evaluator.Evaluate(sh1.GetRow(0).GetCell(2)).NumberValue, 0.0);
Assert.AreEqual(5.0, evaluator.Evaluate(sh2.GetRow(0).GetCell(1)).NumberValue, 0.0);
Assert.AreEqual(15.0, evaluator.Evaluate(sh2.GetRow(0).GetCell(2)).NumberValue, 0.0);
}
/**
* Verify that FormulaParser handles defined names beginning with underscores,
* see Bug #49640
*/
[Test]
public void TestFormulasWithUnderscore()
{
HSSFWorkbook wb = new HSSFWorkbook();
IName nm1 = wb.CreateName();
nm1.NameName = ("_score1");
nm1.RefersToFormula = ("A1");
IName nm2 = wb.CreateName();
nm2.NameName = ("_score2");
nm2.RefersToFormula = ("A2");
ISheet sheet = wb.CreateSheet();
ICell cell = sheet.CreateRow(0).CreateCell(2);
cell.CellFormula = ("_score1*SUM(_score1+_score2)");
Assert.AreEqual("_score1*SUM(_score1+_score2)", cell.CellFormula);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Entities;
using Abp.MultiTenancy;
using Abp.Reflection.Extensions;
namespace Abp.Domain.Repositories
{
/// <summary>
/// Base class to implement <see cref="IRepository{TEntity,TPrimaryKey}"/>.
/// It implements some methods in most simple way.
/// </summary>
/// <typeparam name="TEntity">Type of the Entity for this repository</typeparam>
/// <typeparam name="TPrimaryKey">Primary key of the entity</typeparam>
public abstract class AbpRepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
/// <summary>
/// The multi tenancy side
/// </summary>
public static MultiTenancySides? MultiTenancySide { get; private set; }
public IIocResolver IocResolver { get; set; }
static AbpRepositoryBase()
{
var attr = typeof (TEntity).GetSingleAttributeOfTypeOrBaseTypesOrNull<MultiTenancySideAttribute>();
if (attr != null)
{
MultiTenancySide = attr.Side;
}
}
public abstract IQueryable<TEntity> GetAll();
public virtual List<TEntity> GetAllList()
{
return GetAll().ToList();
}
public virtual Task<List<TEntity>> GetAllListAsync()
{
return Task.FromResult(GetAllList());
}
public virtual List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Where(predicate).ToList();
}
public virtual Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(GetAllList(predicate));
}
public virtual T Query<T>(Func<IQueryable<TEntity>, T> queryMethod)
{
return queryMethod(GetAll());
}
public virtual TEntity Get(TPrimaryKey id)
{
var entity = FirstOrDefault(id);
if (entity == null)
{
throw new AbpException("There is no such an entity with given primary key. Entity type: " + typeof(TEntity).FullName + ", primary key: " + id);
}
return entity;
}
public virtual async Task<TEntity> GetAsync(TPrimaryKey id)
{
var entity = await FirstOrDefaultAsync(id);
if (entity == null)
{
throw new AbpException("There is no such an entity with given primary key. Entity type: " + typeof(TEntity).FullName + ", primary key: " + id);
}
return entity;
}
public virtual TEntity Single(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Single(predicate);
}
public virtual Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(Single(predicate));
}
public virtual TEntity FirstOrDefault(TPrimaryKey id)
{
return GetAll().FirstOrDefault(CreateEqualityExpressionForId(id));
}
public virtual Task<TEntity> FirstOrDefaultAsync(TPrimaryKey id)
{
return Task.FromResult(FirstOrDefault(id));
}
public virtual TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().FirstOrDefault(predicate);
}
public virtual Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(FirstOrDefault(predicate));
}
public virtual TEntity Load(TPrimaryKey id)
{
return Get(id);
}
public abstract TEntity Insert(TEntity entity);
public virtual Task<TEntity> InsertAsync(TEntity entity)
{
return Task.FromResult(Insert(entity));
}
public virtual TPrimaryKey InsertAndGetId(TEntity entity)
{
return Insert(entity).Id;
}
public virtual Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity)
{
return Task.FromResult(InsertAndGetId(entity));
}
public virtual TEntity InsertOrUpdate(TEntity entity)
{
return entity.IsTransient()
? Insert(entity)
: Update(entity);
}
public virtual async Task<TEntity> InsertOrUpdateAsync(TEntity entity)
{
return entity.IsTransient()
? await InsertAsync(entity)
: await UpdateAsync(entity);
}
public virtual TPrimaryKey InsertOrUpdateAndGetId(TEntity entity)
{
return InsertOrUpdate(entity).Id;
}
public virtual Task<TPrimaryKey> InsertOrUpdateAndGetIdAsync(TEntity entity)
{
return Task.FromResult(InsertOrUpdateAndGetId(entity));
}
public abstract TEntity Update(TEntity entity);
public virtual Task<TEntity> UpdateAsync(TEntity entity)
{
return Task.FromResult(Update(entity));
}
public virtual TEntity Update(TPrimaryKey id, Action<TEntity> updateAction)
{
var entity = Get(id);
updateAction(entity);
return entity;
}
public virtual async Task<TEntity> UpdateAsync(TPrimaryKey id, Func<TEntity, Task> updateAction)
{
var entity = await GetAsync(id);
await updateAction(entity);
return entity;
}
public abstract void Delete(TEntity entity);
public virtual Task DeleteAsync(TEntity entity)
{
Delete(entity);
return Task.FromResult(0);
}
public abstract void Delete(TPrimaryKey id);
public virtual Task DeleteAsync(TPrimaryKey id)
{
Delete(id);
return Task.FromResult(0);
}
public virtual void Delete(Expression<Func<TEntity, bool>> predicate)
{
foreach (var entity in GetAll().Where(predicate).ToList())
{
Delete(entity);
}
}
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate)
{
Delete(predicate);
}
public virtual int Count()
{
return GetAll().Count();
}
public virtual Task<int> CountAsync()
{
return Task.FromResult(Count());
}
public virtual int Count(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Where(predicate).Count();
}
public virtual Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(Count(predicate));
}
public virtual long LongCount()
{
return GetAll().LongCount();
}
public virtual Task<long> LongCountAsync()
{
return Task.FromResult(LongCount());
}
public virtual long LongCount(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Where(predicate).LongCount();
}
public virtual Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(LongCount(predicate));
}
protected static Expression<Func<TEntity, bool>> CreateEqualityExpressionForId(TPrimaryKey id)
{
var lambdaParam = Expression.Parameter(typeof(TEntity));
var lambdaBody = Expression.Equal(
Expression.PropertyOrField(lambdaParam, "Id"),
Expression.Constant(id, typeof(TPrimaryKey))
);
return Expression.Lambda<Func<TEntity, bool>>(lambdaBody, lambdaParam);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using /*<com>*/Finegamedesign.Utils/*<DataUtil>*/;
namespace Monster
{
/**
* Portable. Independent of platform.
*/
public class MonsterModel
{
internal ArrayList cityNames;
internal int level = 1;
internal int length;
internal Dictionary<string, dynamic> changes;
internal int population;
internal int health;
internal Dictionary<string, dynamic> represents;
internal int result = 0;
internal int resultNow = 0;
internal int selectCount = 0;
internal int selected = 0;
internal ArrayList gridClassNames = new ArrayList(){
null, "City", "Forest"}
;
private int vacancy;
private int cellWidth;
private int cellHeight;
private int width;
private int height;
private int widthInCells;
private int heightInCells;
private float period = 2.0f;
private float accumulated = 0.0f;
private ArrayList grid = new ArrayList(){
}
;
private ArrayList gridPreviously = new ArrayList(){
}
;
public MonsterModel()
{
}
internal void Restart()
{
resultNow = 0;
result = 0;
periodBase = 120.0f;
period = 2.0f;
level = 1;
selectCount = 0;
ClearGrid(2);
RandomlyPlace(grid);
}
private void InitGrid(ArrayList grid, int cellWidth, int cellHeight)
{
this.cellWidth = Mathf.Ceil(cellWidth);
float isometricHeightMultiplier = 0.5f;
// 0.5;
// 1.0;
cellHeight = Mathf.Ceil(cellHeight * isometricHeightMultiplier);
this.cellHeight = cellHeight;
widthInCells = Mathf.Floor(width / cellWidth);
heightInCells = Mathf.Floor(height / cellHeight);
ClearGrid(0);
gridPreviously = DataUtil.CloneList(grid);
}
private ArrayList ToGrid(Dictionary<string, dynamic> represents, ArrayList cityNames)
{
width = Mathf.Ceil(represents.spawnArea.width);
height = Mathf.Ceil(represents.spawnArea.height);
for (int c = 0; c < DataUtil.Length(cityNames); c++)
{
string name = cityNames[c];
var child = represents.spawnArea[name];
if (0 == DataUtil.Length(grid)) {
InitGrid(grid, child.width, child.height);
}
int column = Mathf.Floor(child.x / cellWidth);
int row = Mathf.Floor(child.y / cellHeight);
grid[row * widthInCells + column] = 1;
}
length = DataUtil.Length(grid);
// trace(grid);
return grid;
}
internal void Represent(Dictionary<string, dynamic> represents)
{
this.represents = represents;
cityNames = Model.Keys(represents.spawnArea, "city");
grid = ToGrid(represents, cityNames);
Restart();
if (Count(grid, 1) <= 0)
{
RandomlyPlace(grid);
}
}
/**
*
Torri expects isometric grid.
Represent grid with offsets:
Expand: Neighbor is up and down, up-left and down-left (if even), up-right, down-right (if odd).
Layout each odd indexed row with an offset right.
2 2 2
1 1 3
2 0 2
1 1 3
*/
private void ExpandIsometric(ArrayList grid, int row, int column, ArrayList gridNext)
{
int index = (row) * widthInCells + column;
int cell = grid[index];
if (1 == cell)
{
int offset = row % 2;
int columnOffset = offset == 0 ? -1 : 1;
if (0 < row)
{
int up = (row-1) * widthInCells + column;
if (0 <= up)
{
gridNext[up] = 1;
if (0 <= column + columnOffset)
{
gridNext[up + columnOffset] = 1;
}
}
}
if (row < heightInCells - 1)
{
int down = (row+1) * widthInCells + column;
if (down < length)
{
gridNext[down] = 1;
if (column + columnOffset < widthInCells - 1)
{
gridNext[down + columnOffset] = 1;
}
}
}
}
}
private void ExpandTopDown(ArrayList grid, int row, int column, ArrayList gridNext)
{
int index = (row) * widthInCells + column;
int cell = grid[index];
if (1 == cell)
{
if (0 < row)
{
gridNext[(row-1) * widthInCells + column] = 1;
}
if (0 < column)
{
gridNext[(row) * widthInCells + column - 1] = 1;
}
if (row < heightInCells - 1)
{
gridNext[(row+1) * widthInCells + column] = 1;
}
if (column < widthInCells - 1)
{
gridNext[(row) * widthInCells + column + 1] = 1;
}
}
}
private ArrayList Grow(ArrayList grid)
{
// trace("grow: " + grid);
ArrayList gridNext = DataUtil.CloneList(grid);
for (int row = 0; row < heightInCells; row++)
{
for (int column = 0; column < widthInCells; column++)
{
ExpandIsometric(grid, row, column, gridNext);
}
}
return gridNext;
}
private float OffsetWidth(int row)
{
return (row % 2) * cellWidth * 0.5f;
}
private Dictionary<string, dynamic> Change(ArrayList gridPreviously, ArrayList grid)
{
Dictionary<string, dynamic> changes = new Dictionary<string, dynamic>(){
}
;
int count = 0;
for (int row = 0; row < heightInCells; row++)
{
for (int column = 0; column < widthInCells; column++)
{
int index = row * widthInCells + column;
if (grid[index] != gridPreviously[index]) {
if (null == changes.spawnArea)
{
changes.spawnArea = new Dictionary<string, dynamic>(){
}
;
}
for (int g = 1; g < DataUtil.Length(gridClassNames); g++)
{
string className = gridClassNames[g];
bool isChanged = g == grid[index] || g == gridPreviously[index];
if (isChanged)
{
string name = className + "_" + row + "_" + column;
count++;
if (g == grid[index])
{
changes.spawnArea[name] = new Dictionary<string, dynamic>(){
{
"x", cellWidth * column + cellWidth * 0.5f + OffsetWidth(row)}
,
{
"y", cellHeight * row + cellHeight * 0.5f}
,
{
"visible", true}
}
;
}
else
{
changes.spawnArea[name] = new Dictionary<string, dynamic>(){
{
"visible", false}
}
;
}
}
}
}
}
}
return changes;
}
internal void Update(float deltaSeconds)
{
accumulated += deltaSeconds;
population = Count(grid, 1);
health = Count(grid, 2);
vacancy = DataUtil.Length(grid) - population;
Win();
if (period <= accumulated)
{
accumulated = 0;
if (1 <= selectCount)
{
grid = Grow(grid);
if (population <= 2)
{
if (population <= 0)
{
level++;
}
RandomlyPlace(grid);
}
}
period = UpdatePeriod(population, vacancy);
}
changes = Change(gridPreviously, grid);
cityNames = Model.Keys(changes.spawnArea, "city");
gridPreviously = DataUtil.CloneList(grid);
}
private int Count(ArrayList counts, int value)
{
int sum = 0;
for (int c = 0; c < DataUtil.Length(counts); c++)
{
if (object.ReferenceEquals(value, counts[c]))
{
sum += 1;
}
}
return sum;
}
private float startingPlaces = 2;
// 2;
/**
* Slow to keep trying if there were lot of starting places, but there aren't.
*/
private void RandomlyPlace(ArrayList grid)
{
int attemptMax = 128;
for (int attempt = 0; Count(grid, 1) < startingPlaces && attempt < attemptMax; attempt++)
{
int index = Mathf.Floor((Random.value % 1.0f) * (DataUtil.Length(grid) - 4)) + 2;
grid[index] = 1;
}
// startingPlaces += 0.125;
// 0.25;
}
// 120.0;
// 90.0;
// 80.0;
// 60.0;
// 40.0;
// 20.0;
private float periodBase = 120.0f;
private float UpdatePeriod(int population, int vacancy)
{
float period = 999999.0f;
if (population <= 0)
{
periodBase = Mathf.Max(3, periodBase * 0.95f);
period = 2.0f + 3.0f / level;
accumulated = 0;
// periodBase * 0.05;
}
else if (1 <= vacancy)
{
float ratio = Mathf.Pow(population, 0.325f) / DataUtil.Length(grid);
float exponent = 1.0f;
// 0.75;
// 0.25;
// 1.0;
// 0.25;
float power = Mathf.Pow(ratio, exponent);
period = power * periodBase;
}
return period;
}
private int Win()
{
resultNow = result == 0 ? 0 : result;
if (vacancy <= 0 || health <= 0)
{
result = -1;
}
else if (population <= 0)
{
result = 1;
}
else
{
result = 0;
}
resultNow = resultNow == 0 ? result : 0;
return resultNow;
}
internal bool Select(string name)
{
ArrayList parts = DataUtil.Split(name, "_");
int row = int.Parse(parts[1]);
int column = int.Parse(parts[2]);
int result = SelectCell(row, column);
population = Count(grid, 1);
bool isExplosion = object.ReferenceEquals(1, result);
if (isExplosion && 0 <= population)
{
vacancy = DataUtil.Length(grid) - population;
period = UpdatePeriod(population, vacancy);
}
return isExplosion;
}
internal int SelectCell(int row, int column)
{
int index = row * widthInCells + column;
int was = grid[index];
if (!object.ReferenceEquals(0, was))
{
if (1 == was)
{
selectCount++;
}
grid[index] = 0;
}
// trace("select: " + grid);
return was;
}
internal void ClearGrid(int value)
{
DataUtil.Clear(grid);
for (int row = 0; row < heightInCells; row++)
{
for (int column = 0; column < widthInCells; column++)
{
grid.Add(value);
}
}
}
}
}
| |
using Simple.Web.Helpers;
namespace Simple.Web.Razor
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
internal class RazorViews
{
private const string FileExtension = "cshtml";
private const string DefaultViewPath = "Views";
private const string AppSettings_CacheEnabled = "ViewCache:Enabled";
private const string AppSettings_Path = "ViewPath:Value";
private const string AppSettings_RecursiveDiscovery = "ViewRecursiveDiscovery:Enabled";
private static readonly object LockObject = new object();
private static volatile bool _initialized;
private static readonly Dictionary<string, Func<Type>> TypeCache = new Dictionary<string, Func<Type>>();
private static readonly Dictionary<string, string> ViewPathCache = new Dictionary<string, string>();
private static readonly Dictionary<Tuple<string, string>, string> HandlerAndModelTypeCache = new Dictionary<Tuple<string, string>, string>();
private static readonly Dictionary<string, string> HandlerTypeCache = new Dictionary<string, string>();
private static readonly Dictionary<string, string> ModelTypeCache = new Dictionary<string, string>();
private static readonly HashSet<Tuple<string, string>> AmbiguousHandlerAndModelTypes = new HashSet<Tuple<string, string>>();
private static readonly HashSet<string> AmbiguousHandlerTypes = new HashSet<string>();
private static readonly HashSet<string> AmbiguousModelTypes = new HashSet<string>();
private static readonly RazorTypeBuilder RazorTypeBuilder = new RazorTypeBuilder();
private static readonly string AppRoot = AssemblyAppRoot(typeof(RazorViews).Assembly.GetPath());
private static readonly bool IsCacheEnabled = ParseBooleanAppSettings(AppSettings_CacheEnabled);
private static readonly Func<string, string> FileTokenizer = file =>
Path.Combine(
file.StartsWith("~/") ? Path.GetDirectoryName(file.Substring(2)) : Path.GetDirectoryName(file).Replace(AppRoot + Path.DirectorySeparatorChar, ""),
Path.GetFileNameWithoutExtension(file));
private static readonly Func<string, string> FileFormatter =
prefix => string.Format("{0}.{1}", prefix, FileExtension);
public static string AssemblyAppRoot(string typePath)
{
return Path.GetDirectoryName(typePath).Regex(@"(\\|/)bin(\\|/)?([Dd]ebug|[Rr]elease)?$", string.Empty);
}
public static void Initialize()
{
ClearCaches();
string searchPath = ParseStringAppSettings(AppSettings_Path, DefaultViewPath).Trim('/', '\\');
bool recursiveDiscovery = ParseBooleanAppSettings(AppSettings_RecursiveDiscovery);
var viewsDirectory = Path.Combine(AppRoot, searchPath);
if (!Directory.Exists(viewsDirectory))
{
return;
}
FindViews(viewsDirectory, recursiveDiscovery);
}
private static void FindViews(string directory, bool recurse = true)
{
foreach (var file in Directory.GetFiles(directory, FileFormatter("*")))
{
GenerateViewType(file);
}
if (recurse)
{
foreach (
var subDirectory in Directory.GetDirectories(directory).Select(sub => Path.Combine(directory, sub)))
{
FindViews(subDirectory);
}
}
}
private static Type GenerateViewType(string pathname)
{
using (var reader = new StreamReader(pathname))
{
try
{
var type = RazorTypeBuilder.CreateType(reader);
if (TypeCache.ContainsKey(type.FullName))
{
throw new ArgumentException(
String.Format("Duplicate generated type '{0}' is not permitted", type.FullName), pathname);
}
CachePageType(type, pathname);
return type;
}
catch (RazorCompilerException ex)
{
Debug.WriteLine("*** View compile failed for " + pathname + ": " + ex.Message);
Trace.TraceError(ex.Message);
}
}
return null;
}
private static void CachePageType(Type type, string file)
{
var token = FileTokenizer(file);
TypeCache.Add(type.FullName, () => RuntimeTypeCheck(type));
if (ViewPathCache.ContainsKey(token))
{
if (!IsCacheEnabled)
{
ClearCaches(ViewPathCache[token]);
ViewPathCache[token] = type.FullName;
}
else
{
throw new ArgumentException(
string.Format("Unable to add duplicate view type for '{0}'.", file), "file");
}
}
else
{
ViewPathCache.Add(token, type.FullName);
}
if (!CacheViewTypeByHandlerAndModelType(type))
{
CacheViewTypeByModelType(type);
CacheViewTypeByHandlerType(type);
}
}
private static void CacheViewTypeByModelType(Type type)
{
var baseType = type.BaseType;
if (!IsGeneric(baseType, typeof(SimpleTemplateModelBase<>), typeof(SimpleTemplateHandlerModelBase<,>))) return;
int modelTypeIndex = baseType.GetGenericArguments().Length - 1;
var modelType = baseType.GetGenericArguments()[modelTypeIndex];
if (AmbiguousModelTypes.Contains(modelType.FullName)) return;
if (ModelTypeCache.ContainsKey(modelType.FullName))
{
AmbiguousModelTypes.Add(modelType.FullName);
ModelTypeCache.Remove(modelType.FullName);
}
else
{
ModelTypeCache.Add(modelType.FullName, type.FullName);
}
}
private static void CacheViewTypeByHandlerType(Type type)
{
var baseType = type.BaseType;
if (!IsGeneric(baseType, typeof(SimpleTemplateHandlerBase<>), typeof(SimpleTemplateHandlerModelBase<,>))) return;
var handlerType = baseType.GetGenericArguments()[0];
if (AmbiguousModelTypes.Contains(handlerType.FullName)) return;
if (HandlerTypeCache.ContainsKey(handlerType.FullName))
{
AmbiguousHandlerTypes.Add(handlerType.FullName);
HandlerTypeCache.Remove(handlerType.FullName);
}
else
{
HandlerTypeCache.Add(handlerType.FullName, type.FullName);
}
}
private static bool CacheViewTypeByHandlerAndModelType(Type type)
{
var baseType = type.BaseType;
if (!IsGeneric(baseType, typeof(SimpleTemplateHandlerModelBase<,>))) return false;
var genericArgs = baseType.GetGenericArguments();
var key = Tuple.Create(genericArgs[0].FullName, genericArgs[1].FullName);
if (AmbiguousHandlerAndModelTypes.Contains(key)) return false;
if (HandlerAndModelTypeCache.ContainsKey(key))
{
AmbiguousHandlerAndModelTypes.Add(key);
HandlerAndModelTypeCache.Remove(key);
}
else
{
HandlerAndModelTypeCache.Add(key, type.FullName);
}
return true;
}
private static bool IsGeneric(Type baseType, params Type[] validTypes)
{
if (baseType == null) return false;
if (!baseType.IsGenericType) return false;
var genericType = baseType.GetGenericTypeDefinition();
return validTypes.Contains(genericType);
}
public Type GetViewType(Type handlerType, Type modelType)
{
InitializeIfNot();
Type type;
if (TryGetCombinedType(handlerType, modelType, out type)) return type;
if (TryGetHandlerType(handlerType, modelType, out type)) return type;
if (handlerType != null)
{
if (TryGetHandlerType(handlerType.GetInterfaces(), out type)) return type;
}
if (TryGetModelType(handlerType, modelType, out type)) return type;
if (modelType != null)
{
if (TryGetModelType(modelType.GetInterfaces(), out type)) return type;
}
throw new ViewNotFoundException(handlerType, modelType);
}
private static bool TryGetModelType(Type handlerType, Type modelType, out Type type)
{
if (modelType == null)
{
type = null;
return false;
}
if (AmbiguousModelTypes.Contains(modelType.FullName))
{
throw new AmbiguousViewException(handlerType, modelType);
}
if (ModelTypeCache.ContainsKey(modelType.FullName))
{
type = TypeCache[ModelTypeCache[modelType.FullName]].Invoke();
return true;
}
return TryGetModelType(handlerType, modelType.BaseType, out type);
}
private static bool TryGetModelType(Type[] modelTypeInterfaces, out Type type)
{
if (modelTypeInterfaces == null || modelTypeInterfaces.Length == 0)
{
type = null;
return false;
}
var q = from @interface in modelTypeInterfaces
where ModelTypeCache.ContainsKey(@interface.FullName)
select ModelTypeCache[@interface.FullName];
var list = q.ToList();
if (list.Count == 1)
{
type = TypeCache[list[0]].Invoke();
return true;
}
type = null;
return false;
}
private static bool TryGetHandlerType(Type handlerType, Type modelType, out Type type)
{
if (handlerType == null)
{
type = null;
return false;
}
if (AmbiguousHandlerTypes.Contains(handlerType.FullName))
{
throw new AmbiguousViewException(handlerType, modelType);
}
if (HandlerTypeCache.ContainsKey(handlerType.FullName))
{
{
type = TypeCache[HandlerTypeCache[handlerType.FullName]].Invoke();
return true;
}
}
return TryGetHandlerType(handlerType.BaseType, modelType, out type);
}
private static bool TryGetHandlerType(Type[] handlerTypeInterfaces, out Type type)
{
if (handlerTypeInterfaces == null || handlerTypeInterfaces.Length == 0)
{
type = null;
return false;
}
var q = from @interface in handlerTypeInterfaces
where HandlerTypeCache.ContainsKey(@interface.FullName)
select HandlerTypeCache[@interface.FullName];
var list = q.ToList();
if (list.Count == 1)
{
type = TypeCache[list[0]].Invoke();
return true;
}
type = null;
return false;
}
private static bool TryGetCombinedType(Type handlerType, Type modelType, out Type type)
{
if (handlerType != null && modelType != null)
{
var key = Tuple.Create(handlerType.FullName, modelType.FullName);
if (AmbiguousHandlerAndModelTypes.Contains(key))
{
throw new AmbiguousViewException(handlerType, modelType);
}
if (HandlerAndModelTypeCache.ContainsKey(key))
{
type = TypeCache[HandlerAndModelTypeCache[key]].Invoke();
return true;
}
if (handlerType.BaseType != null)
{
if (TryGetCombinedType(handlerType.BaseType, modelType, out type)) return true;
}
if (modelType.BaseType != null)
{
if (TryGetCombinedType(handlerType, modelType.BaseType, out type)) return true;
}
}
type = null;
return false;
}
private static void InitializeIfNot()
{
if (!_initialized)
{
lock (LockObject)
{
if (!_initialized)
{
Initialize();
_initialized = true;
}
}
}
}
public Type GetViewType(string viewPath)
{
if (viewPath == null) throw new ArgumentNullException("viewPath");
InitializeIfNot();
var key = FileTokenizer(viewPath);
if (!ViewPathCache.ContainsKey(key))
{
return GenerateViewType(FileFormatter(key));
}
return TypeCache[ViewPathCache[key]].Invoke();
}
private static void ClearTypesIn(IDictionary<string, string> dictionary, string typeName = null)
{
if (String.IsNullOrWhiteSpace(typeName))
{
dictionary.Clear();
}
else
{
KeyValuePair<string, string>? pair = dictionary.FirstOrDefault(x => x.Value.Equals(typeName));
if (pair != null && pair.Value.Key != null)
dictionary.Remove(pair.Value.Key);
}
}
private static void ClearTypesIn(IDictionary<Tuple<string, string>, string> dictionary, string typeName = null)
{
if (String.IsNullOrWhiteSpace(typeName))
{
dictionary.Clear();
}
else
{
KeyValuePair<Tuple<string, string>, string>? pair = HandlerAndModelTypeCache.FirstOrDefault(x => x.Value.Equals(typeName));
if (pair != null && pair.Value.Key != null)
HandlerAndModelTypeCache.Remove(pair.Value.Key);
}
}
private static void ClearCaches(string typeName = null)
{
ClearTypesIn(ViewPathCache, typeName);
ClearTypesIn(ModelTypeCache, typeName);
ClearTypesIn(ViewPathCache, typeName);
ClearTypesIn(ModelTypeCache, typeName);
ClearTypesIn(HandlerTypeCache, typeName);
ClearTypesIn(HandlerAndModelTypeCache, typeName);
AmbiguousModelTypes.RemoveWhere(x => typeName == null || x.Equals(typeName));
AmbiguousHandlerTypes.RemoveWhere(x => typeName == null || x.Equals(typeName));
AmbiguousHandlerAndModelTypes.RemoveWhere(x => typeName == null || x.Equals(typeName));
if (typeName == null)
TypeCache.Clear();
else
TypeCache.Remove(typeName);
}
private static Type RuntimeTypeCheck(Type type)
{
if (!IsCacheEnabled)
{
return
GenerateViewType(
Path.Combine(AppRoot, FileFormatter(ViewPathCache.FirstOrDefault(p => p.Value.Equals(type.FullName)).Key)));
}
return type;
}
private static string ParseStringAppSettings(string key, string defaultValue)
{
var value = ConfigurationManager.AppSettings[key];
if (String.IsNullOrWhiteSpace(value))
{
if (String.IsNullOrWhiteSpace(defaultValue))
{
throw new ConfigurationErrorsException(
string.Format("Invalid configuration value for appSetting '{0}'", key));
}
return defaultValue;
}
return value;
}
private static bool ParseBooleanAppSettings(string key)
{
var value = ConfigurationManager.AppSettings[key];
if (string.IsNullOrWhiteSpace(value)) return true;
bool isEnabled;
if (!bool.TryParse(value, out isEnabled))
{
throw new ConfigurationErrorsException(
string.Format("Invalid configuration value for appSetting '{0}'", key));
}
return isEnabled;
}
}
internal static class RegexEx
{
public static string Regex(this string target, string pattern, string replaceWith)
{
return new Regex(pattern).Replace(target, replaceWith);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VStation class.
/// </summary>
[Serializable]
public partial class VStationCollection : ReadOnlyList<VStation, VStationCollection>
{
public VStationCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vStation view.
/// </summary>
[Serializable]
public partial class VStation : ReadOnlyRecord<VStation>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
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("vStation", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Guid;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = false;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema);
colvarCode.ColumnName = "Code";
colvarCode.DataType = DbType.AnsiString;
colvarCode.MaxLength = 50;
colvarCode.AutoIncrement = false;
colvarCode.IsNullable = false;
colvarCode.IsPrimaryKey = false;
colvarCode.IsForeignKey = false;
colvarCode.IsReadOnly = false;
schema.Columns.Add(colvarCode);
TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema);
colvarName.ColumnName = "Name";
colvarName.DataType = DbType.AnsiString;
colvarName.MaxLength = 150;
colvarName.AutoIncrement = false;
colvarName.IsNullable = false;
colvarName.IsPrimaryKey = false;
colvarName.IsForeignKey = false;
colvarName.IsReadOnly = false;
schema.Columns.Add(colvarName);
TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema);
colvarDescription.ColumnName = "Description";
colvarDescription.DataType = DbType.AnsiString;
colvarDescription.MaxLength = 5000;
colvarDescription.AutoIncrement = false;
colvarDescription.IsNullable = true;
colvarDescription.IsPrimaryKey = false;
colvarDescription.IsForeignKey = false;
colvarDescription.IsReadOnly = false;
schema.Columns.Add(colvarDescription);
TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema);
colvarUrl.ColumnName = "Url";
colvarUrl.DataType = DbType.AnsiString;
colvarUrl.MaxLength = 250;
colvarUrl.AutoIncrement = false;
colvarUrl.IsNullable = true;
colvarUrl.IsPrimaryKey = false;
colvarUrl.IsForeignKey = false;
colvarUrl.IsReadOnly = false;
schema.Columns.Add(colvarUrl);
TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema);
colvarLatitude.ColumnName = "Latitude";
colvarLatitude.DataType = DbType.Double;
colvarLatitude.MaxLength = 0;
colvarLatitude.AutoIncrement = false;
colvarLatitude.IsNullable = true;
colvarLatitude.IsPrimaryKey = false;
colvarLatitude.IsForeignKey = false;
colvarLatitude.IsReadOnly = false;
schema.Columns.Add(colvarLatitude);
TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema);
colvarLongitude.ColumnName = "Longitude";
colvarLongitude.DataType = DbType.Double;
colvarLongitude.MaxLength = 0;
colvarLongitude.AutoIncrement = false;
colvarLongitude.IsNullable = true;
colvarLongitude.IsPrimaryKey = false;
colvarLongitude.IsForeignKey = false;
colvarLongitude.IsReadOnly = false;
schema.Columns.Add(colvarLongitude);
TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema);
colvarElevation.ColumnName = "Elevation";
colvarElevation.DataType = DbType.Double;
colvarElevation.MaxLength = 0;
colvarElevation.AutoIncrement = false;
colvarElevation.IsNullable = true;
colvarElevation.IsPrimaryKey = false;
colvarElevation.IsForeignKey = false;
colvarElevation.IsReadOnly = false;
schema.Columns.Add(colvarElevation);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarSiteID = new TableSchema.TableColumn(schema);
colvarSiteID.ColumnName = "SiteID";
colvarSiteID.DataType = DbType.Guid;
colvarSiteID.MaxLength = 0;
colvarSiteID.AutoIncrement = false;
colvarSiteID.IsNullable = false;
colvarSiteID.IsPrimaryKey = false;
colvarSiteID.IsForeignKey = false;
colvarSiteID.IsReadOnly = false;
schema.Columns.Add(colvarSiteID);
TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema);
colvarStartDate.ColumnName = "StartDate";
colvarStartDate.DataType = DbType.Date;
colvarStartDate.MaxLength = 0;
colvarStartDate.AutoIncrement = false;
colvarStartDate.IsNullable = true;
colvarStartDate.IsPrimaryKey = false;
colvarStartDate.IsForeignKey = false;
colvarStartDate.IsReadOnly = false;
schema.Columns.Add(colvarStartDate);
TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema);
colvarEndDate.ColumnName = "EndDate";
colvarEndDate.DataType = DbType.Date;
colvarEndDate.MaxLength = 0;
colvarEndDate.AutoIncrement = false;
colvarEndDate.IsNullable = true;
colvarEndDate.IsPrimaryKey = false;
colvarEndDate.IsForeignKey = false;
colvarEndDate.IsReadOnly = false;
schema.Columns.Add(colvarEndDate);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema);
colvarRowVersion.ColumnName = "RowVersion";
colvarRowVersion.DataType = DbType.Binary;
colvarRowVersion.MaxLength = 0;
colvarRowVersion.AutoIncrement = false;
colvarRowVersion.IsNullable = false;
colvarRowVersion.IsPrimaryKey = false;
colvarRowVersion.IsForeignKey = false;
colvarRowVersion.IsReadOnly = true;
schema.Columns.Add(colvarRowVersion);
TableSchema.TableColumn colvarSiteCode = new TableSchema.TableColumn(schema);
colvarSiteCode.ColumnName = "SiteCode";
colvarSiteCode.DataType = DbType.AnsiString;
colvarSiteCode.MaxLength = 50;
colvarSiteCode.AutoIncrement = false;
colvarSiteCode.IsNullable = false;
colvarSiteCode.IsPrimaryKey = false;
colvarSiteCode.IsForeignKey = false;
colvarSiteCode.IsReadOnly = false;
schema.Columns.Add(colvarSiteCode);
TableSchema.TableColumn colvarSiteName = new TableSchema.TableColumn(schema);
colvarSiteName.ColumnName = "SiteName";
colvarSiteName.DataType = DbType.AnsiString;
colvarSiteName.MaxLength = 150;
colvarSiteName.AutoIncrement = false;
colvarSiteName.IsNullable = false;
colvarSiteName.IsPrimaryKey = false;
colvarSiteName.IsForeignKey = false;
colvarSiteName.IsReadOnly = false;
schema.Columns.Add(colvarSiteName);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vStation",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VStation()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VStation(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VStation(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VStation(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public Guid Id
{
get
{
return GetColumnValue<Guid>("ID");
}
set
{
SetColumnValue("ID", value);
}
}
[XmlAttribute("Code")]
[Bindable(true)]
public string Code
{
get
{
return GetColumnValue<string>("Code");
}
set
{
SetColumnValue("Code", value);
}
}
[XmlAttribute("Name")]
[Bindable(true)]
public string Name
{
get
{
return GetColumnValue<string>("Name");
}
set
{
SetColumnValue("Name", value);
}
}
[XmlAttribute("Description")]
[Bindable(true)]
public string Description
{
get
{
return GetColumnValue<string>("Description");
}
set
{
SetColumnValue("Description", value);
}
}
[XmlAttribute("Url")]
[Bindable(true)]
public string Url
{
get
{
return GetColumnValue<string>("Url");
}
set
{
SetColumnValue("Url", value);
}
}
[XmlAttribute("Latitude")]
[Bindable(true)]
public double? Latitude
{
get
{
return GetColumnValue<double?>("Latitude");
}
set
{
SetColumnValue("Latitude", value);
}
}
[XmlAttribute("Longitude")]
[Bindable(true)]
public double? Longitude
{
get
{
return GetColumnValue<double?>("Longitude");
}
set
{
SetColumnValue("Longitude", value);
}
}
[XmlAttribute("Elevation")]
[Bindable(true)]
public double? Elevation
{
get
{
return GetColumnValue<double?>("Elevation");
}
set
{
SetColumnValue("Elevation", value);
}
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("SiteID")]
[Bindable(true)]
public Guid SiteID
{
get
{
return GetColumnValue<Guid>("SiteID");
}
set
{
SetColumnValue("SiteID", value);
}
}
[XmlAttribute("StartDate")]
[Bindable(true)]
public DateTime? StartDate
{
get
{
return GetColumnValue<DateTime?>("StartDate");
}
set
{
SetColumnValue("StartDate", value);
}
}
[XmlAttribute("EndDate")]
[Bindable(true)]
public DateTime? EndDate
{
get
{
return GetColumnValue<DateTime?>("EndDate");
}
set
{
SetColumnValue("EndDate", value);
}
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get
{
return GetColumnValue<DateTime?>("AddedAt");
}
set
{
SetColumnValue("AddedAt", value);
}
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get
{
return GetColumnValue<DateTime?>("UpdatedAt");
}
set
{
SetColumnValue("UpdatedAt", value);
}
}
[XmlAttribute("RowVersion")]
[Bindable(true)]
public byte[] RowVersion
{
get
{
return GetColumnValue<byte[]>("RowVersion");
}
set
{
SetColumnValue("RowVersion", value);
}
}
[XmlAttribute("SiteCode")]
[Bindable(true)]
public string SiteCode
{
get
{
return GetColumnValue<string>("SiteCode");
}
set
{
SetColumnValue("SiteCode", value);
}
}
[XmlAttribute("SiteName")]
[Bindable(true)]
public string SiteName
{
get
{
return GetColumnValue<string>("SiteName");
}
set
{
SetColumnValue("SiteName", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string Code = @"Code";
public static string Name = @"Name";
public static string Description = @"Description";
public static string Url = @"Url";
public static string Latitude = @"Latitude";
public static string Longitude = @"Longitude";
public static string Elevation = @"Elevation";
public static string UserId = @"UserId";
public static string SiteID = @"SiteID";
public static string StartDate = @"StartDate";
public static string EndDate = @"EndDate";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string RowVersion = @"RowVersion";
public static string SiteCode = @"SiteCode";
public static string SiteName = @"SiteName";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter
{
private void WriteMethodDefinition(IMethodDefinition method)
{
if (method.IsPropertyOrEventAccessor())
return;
WriteMethodPseudoCustomAttributes(method);
WriteAttributes(method.Attributes);
WriteAttributes(method.SecurityAttributes);
if (method.IsDestructor())
{
// If platformNotSupportedExceptionMessage is != null we're generating a dummy assembly which means we don't need a destructor at all.
if(_platformNotSupportedExceptionMessage == null)
WriteDestructor(method);
return;
}
string name = method.GetMethodName();
if (!method.ContainingTypeDefinition.IsInterface)
{
if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility);
WriteMethodModifiers(method);
}
WriteInterfaceMethodModifiers(method);
WriteMethodDefinitionSignature(method, name);
WriteMethodBody(method);
}
private void WriteDestructor(IMethodDefinition method)
{
WriteSymbol("~");
WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name);
WriteSymbol("(");
WriteSymbol(")", false);
WriteEmptyBody();
}
private void WriteTypeName(ITypeReference type, ITypeReference containingType, bool isDynamic = false)
{
var useKeywords = containingType.GetTypeName() != type.GetTypeName();
WriteTypeName(type, isDynamic: isDynamic, useTypeKeywords: useKeywords);
}
private void WriteMethodDefinitionSignature(IMethodDefinition method, string name)
{
bool isOperator = method.IsConversionOperator();
if (!isOperator && !method.IsConstructor)
{
WriteAttributes(method.ReturnValueAttributes, true);
if (method.ReturnValueIsByRef)
{
WriteKeyword("ref");
if (method.ReturnValueAttributes.HasIsReadOnlyAttribute())
WriteKeyword("readonly");
}
// We are ignoring custom modifiers right now, we might need to add them later.
WriteTypeName(method.Type, method.ContainingType, isDynamic: IsDynamic(method.ReturnValueAttributes));
}
if (method.IsExplicitInterfaceMethod() && _forCompilationIncludeGlobalprefix)
Write("global::");
WriteIdentifier(name);
if (isOperator)
{
WriteSpace();
WriteTypeName(method.Type, method.ContainingType);
}
Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances");
if (method.IsGeneric)
WriteGenericParameters(method.GenericParameters);
WriteParameters(method.Parameters, method.ContainingType, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments);
if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod())
WriteGenericContraints(method.GenericParameters);
}
private void WriteParameters(IEnumerable<IParameterDefinition> parameters, ITypeReference containingType, bool property = false, bool extensionMethod = false, bool acceptsExtraArguments = false)
{
string start = property ? "[" : "(";
string end = property ? "]" : ")";
WriteSymbol(start);
_writer.WriteList(parameters, p =>
{
WriteParameter(p, containingType, extensionMethod);
extensionMethod = false;
});
if (acceptsExtraArguments)
{
if (parameters.Any())
_writer.WriteSymbol(",");
_writer.WriteSpace();
_writer.Write("__arglist");
}
WriteSymbol(end);
}
private void WriteParameter(IParameterDefinition parameter, ITypeReference containingType, bool extensionMethod)
{
WriteAttributes(parameter.Attributes, true);
if (extensionMethod)
WriteKeyword("this");
if (parameter.IsParameterArray)
WriteKeyword("params");
if (parameter.IsOut && !parameter.IsIn && parameter.IsByReference)
{
WriteKeyword("out");
}
else
{
// For In/Out we should not emit them until we find a scenario that is needs thems.
//if (parameter.IsIn)
// WriteFakeAttribute("System.Runtime.InteropServices.In", writeInline: true);
//if (parameter.IsOut)
// WriteFakeAttribute("System.Runtime.InteropServices.Out", writeInline: true);
if (parameter.IsByReference)
{
if (parameter.Attributes.HasIsReadOnlyAttribute())
{
WriteKeyword("in");
}
else
{
WriteKeyword("ref");
}
}
}
WriteTypeName(parameter.Type, containingType, isDynamic: IsDynamic(parameter.Attributes));
WriteIdentifier(parameter.Name);
if (parameter.IsOptional && parameter.HasDefaultValue)
{
WriteSymbol(" = ");
WriteMetadataConstant(parameter.DefaultValue, parameter.Type);
}
}
private void WriteInterfaceMethodModifiers(IMethodDefinition method)
{
if (method.GetHiddenBaseMethod(_filter) != Dummy.Method)
WriteKeyword("new");
}
private void WriteMethodModifiers(IMethodDefinition method)
{
if (method.IsMethodUnsafe())
WriteKeyword("unsafe");
if (method.IsStatic)
WriteKeyword("static");
if (method.IsPlatformInvoke)
WriteKeyword("extern");
if (method.IsVirtual)
{
if (method.IsNewSlot)
{
if (method.IsAbstract)
WriteKeyword("abstract");
else if (!method.IsSealed) // non-virtual interfaces implementations are sealed virtual newslots
WriteKeyword("virtual");
}
else
{
if (method.IsAbstract)
WriteKeyword("abstract");
else if (method.IsSealed)
WriteKeyword("sealed");
WriteKeyword("override");
}
}
}
private void WriteMethodBody(IMethodDefinition method)
{
if (method.IsAbstract || !_forCompilation || method.IsPlatformInvoke)
{
WriteSymbol(";");
return;
}
if (method.IsConstructor)
WriteBaseConstructorCall(method.ContainingTypeDefinition);
// Write Dummy Body
WriteSpace();
WriteSymbol("{", true);
if (_platformNotSupportedExceptionMessage != null && !method.IsDispose())
{
Write("throw new ");
if (_forCompilationIncludeGlobalprefix)
Write("global::");
if(_platformNotSupportedExceptionMessage.Length == 0)
Write("System.PlatformNotSupportedException();");
else if(_platformNotSupportedExceptionMessage.StartsWith("SR."))
Write($"System.PlatformNotSupportedException(System.{_platformNotSupportedExceptionMessage}); ");
else
Write($"System.PlatformNotSupportedException(\"{_platformNotSupportedExceptionMessage}\"); ");
}
else if (NeedsMethodBodyForCompilation(method))
{
Write("throw null; ");
}
WriteSymbol("}");
}
private bool NeedsMethodBodyForCompilation(IMethodDefinition method)
{
// Structs cannot have empty constructors so we need a body
if (method.ContainingTypeDefinition.IsValueType && method.IsConstructor)
return true;
// Compiler requires out parameters to be initialized
if (method.Parameters.Any(p => p.IsOut))
return true;
// For non-void returning methods we need a body.
if (!TypeHelper.TypesAreEquivalent(method.Type, method.ContainingTypeDefinition.PlatformType.SystemVoid))
return true;
return false;
}
private void WritePrivateConstructor(ITypeDefinition type)
{
if (!_forCompilation ||
type.IsInterface ||
type.IsEnum ||
type.IsDelegate ||
type.IsValueType ||
type.IsStatic)
return;
WriteVisibility(TypeMemberVisibility.Assembly);
WriteIdentifier(((INamedEntity)type).Name);
WriteSymbol("(");
WriteSymbol(")");
WriteBaseConstructorCall(type);
WriteEmptyBody();
}
private void WriteBaseConstructorCall(ITypeDefinition type)
{
if (!_forCompilation)
return;
ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull();
if (baseType == null)
return;
var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m) && !m.Attributes.Any(a => a.IsObsoleteWithUsageTreatedAsCompilationError()));
var defaultCtor = ctors.Where(c => c.ParameterCount == 0);
// Don't need a base call if we have a default constructor
if (defaultCtor.Any())
return;
var ctor = ctors.FirstOrDefault();
if (ctor == null)
return;
WriteSpace();
WriteSymbol(":", true);
WriteKeyword("base");
WriteSymbol("(");
_writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type));
WriteSymbol(")");
}
private void WriteEmptyBody()
{
if (!_forCompilation)
{
WriteSymbol(";");
}
else
{
WriteSpace();
WriteSymbol("{", true);
WriteSymbol("}");
}
}
private void WriteDefaultOf(ITypeReference type)
{
WriteKeyword("default", true);
WriteSymbol("(");
WriteTypeName(type, true);
WriteSymbol(")");
}
public static IDefinition GetDummyConstructor(ITypeDefinition type)
{
return new DummyInternalConstructor() { ContainingType = type };
}
private class DummyInternalConstructor : IDefinition
{
public ITypeDefinition ContainingType { get; set; }
public IEnumerable<ICustomAttribute> Attributes
{
get { throw new System.NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
public IEnumerable<ILocation> Locations
{
get { throw new System.NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
}
}
}
| |
namespace Stripe
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Stripe.Infrastructure;
/// <summary>Abstract base class for all services.</summary>
/// <typeparam name="TEntityReturned">
/// The type of <see cref="IStripeEntity"/> that this service returns.
/// </typeparam>
public abstract class Service<TEntityReturned>
where TEntityReturned : IStripeEntity
{
private IStripeClient client;
/// <summary>
/// Initializes a new instance of the <see cref="Service{EntityReturned}"/> class.
/// </summary>
protected Service()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Service{EntityReturned}"/> class with a
/// custom <see cref="IStripeClient"/>.
/// </summary>
/// <param name="client">The client used by the service to send requests.</param>
protected Service(IStripeClient client)
{
this.client = client;
}
public abstract string BasePath { get; }
public virtual string BaseUrl => this.Client.ApiBase;
/// <summary>
/// Gets or sets the client used by this service to send requests. If no client was set when the
/// service instance was created, then the default client in
/// <see cref="StripeConfiguration.StripeClient"/> is used instead.
/// </summary>
/// <remarks>
/// Setting the client at runtime may not be thread-safe.
/// If you wish to use a custom client, it is recommended that you pass it to the service's constructor and not change it during the service's lifetime.
/// </remarks>
public IStripeClient Client
{
get => this.client ?? StripeConfiguration.StripeClient;
set => this.client = value;
}
protected TEntityReturned CreateEntity(BaseOptions options, RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Post,
this.ClassUrl(),
options,
requestOptions);
}
protected Task<TEntityReturned> CreateEntityAsync(
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Post,
this.ClassUrl(),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned DeleteEntity(
string id,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Delete,
this.InstanceUrl(id),
options,
requestOptions);
}
protected Task<TEntityReturned> DeleteEntityAsync(
string id,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Delete,
this.InstanceUrl(id),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned GetEntity(
string id,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Get,
this.InstanceUrl(id),
options,
requestOptions);
}
protected Task<TEntityReturned> GetEntityAsync(
string id,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Get,
this.InstanceUrl(id),
options,
requestOptions,
cancellationToken);
}
protected StripeList<TEntityReturned> ListEntities(
ListOptions options,
RequestOptions requestOptions)
{
return this.Request<StripeList<TEntityReturned>>(
HttpMethod.Get,
this.ClassUrl(),
options,
requestOptions);
}
protected Task<StripeList<TEntityReturned>> ListEntitiesAsync(
ListOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync<StripeList<TEntityReturned>>(
HttpMethod.Get,
this.ClassUrl(),
options,
requestOptions,
cancellationToken);
}
protected IEnumerable<TEntityReturned> ListEntitiesAutoPaging(
ListOptions options,
RequestOptions requestOptions)
{
return this.ListRequestAutoPaging<TEntityReturned>(
this.ClassUrl(),
options,
requestOptions);
}
protected IAsyncEnumerable<TEntityReturned> ListEntitiesAutoPagingAsync(
ListOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.ListRequestAutoPagingAsync<TEntityReturned>(
this.ClassUrl(),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned UpdateEntity(
string id,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request(
HttpMethod.Post,
this.InstanceUrl(id),
options,
requestOptions);
}
protected Task<TEntityReturned> UpdateEntityAsync(
string id,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken)
{
return this.RequestAsync(
HttpMethod.Post,
this.InstanceUrl(id),
options,
requestOptions,
cancellationToken);
}
protected TEntityReturned Request(
HttpMethod method,
string path,
BaseOptions options,
RequestOptions requestOptions)
{
return this.Request<TEntityReturned>(
method,
path,
options,
requestOptions);
}
protected Task<TEntityReturned> RequestAsync(
HttpMethod method,
string path,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken = default)
{
return this.RequestAsync<TEntityReturned>(
method,
path,
options,
requestOptions,
cancellationToken);
}
protected T Request<T>(
HttpMethod method,
string path,
BaseOptions options,
RequestOptions requestOptions)
where T : IStripeEntity
{
return this.RequestAsync<T>(method, path, options, requestOptions)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
protected Stream RequestStreaming(
HttpMethod method,
string path,
BaseOptions options,
RequestOptions requestOptions)
{
return this.RequestStreamingAsync(method, path, options, requestOptions)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
protected async Task<T> RequestAsync<T>(
HttpMethod method,
string path,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken = default)
where T : IStripeEntity
{
requestOptions = this.SetupRequestOptions(requestOptions);
return await this.Client.RequestAsync<T>(
method,
path,
options,
requestOptions,
cancellationToken).ConfigureAwait(false);
}
protected async Task<Stream> RequestStreamingAsync(
HttpMethod method,
string path,
BaseOptions options,
RequestOptions requestOptions,
CancellationToken cancellationToken = default)
{
requestOptions = this.SetupRequestOptions(requestOptions);
var stream = await this.Client.RequestStreamingAsync(
method,
path,
options,
requestOptions,
cancellationToken)
.ConfigureAwait(false);
return stream;
}
protected IEnumerable<T> ListRequestAutoPaging<T>(
string url,
ListOptions options,
RequestOptions requestOptions)
where T : IStripeEntity
{
#if NET461
return
this.ListRequestAutoPagingSync<T>(url, options, requestOptions);
#else
return AsyncUtils.ToEnumerable(
this.ListRequestAutoPagingAsync<T>(url, options, requestOptions));
#endif
}
#if NET461
protected IEnumerable<T> ListRequestAutoPagingSync<T>(
string url,
ListOptions options,
RequestOptions requestOptions)
where T : IStripeEntity
{
var page = this.Request<StripeList<T>>(
HttpMethod.Get,
url,
options,
requestOptions);
options = options ?? new ListOptions();
bool iterateBackward = false;
// Backward iterating activates if we have an `EndingBefore`
// constraint and not a `StartingAfter` constraint
if (!string.IsNullOrEmpty(options.EndingBefore) && string.IsNullOrEmpty(options.StartingAfter))
{
iterateBackward = true;
}
while (true)
{
if (iterateBackward)
{
page.Reverse();
}
string itemId = null;
foreach (var item in page)
{
// Elements in `StripeList` instances are decoded by `StripeObjectConverter`,
// which returns `null` for objects it doesn't know how to decode.
// When auto-paginating, we simply ignore these null elements but still return
// other elements.
if (item == null)
{
continue;
}
itemId = ((IHasId)item).Id;
yield return item;
}
if (!page.HasMore || string.IsNullOrEmpty(itemId))
{
break;
}
if (iterateBackward)
{
options.EndingBefore = itemId;
}
else
{
options.StartingAfter = itemId;
}
page = this.Request<StripeList<T>>(
HttpMethod.Get,
url,
options,
requestOptions);
}
}
#endif
protected async IAsyncEnumerable<T> ListRequestAutoPagingAsync<T>(
string url,
ListOptions options,
RequestOptions requestOptions,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
where T : IStripeEntity
{
var page = await this.RequestAsync<StripeList<T>>(
HttpMethod.Get,
url,
options,
requestOptions,
cancellationToken);
options = options ?? new ListOptions();
bool iterateBackward = false;
// Backward iterating activates if we have an `EndingBefore`
// constraint and not a `StartingAfter` constraint
if (!string.IsNullOrEmpty(options.EndingBefore) && string.IsNullOrEmpty(options.StartingAfter))
{
iterateBackward = true;
}
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
if (iterateBackward)
{
page.Reverse();
}
string itemId = null;
foreach (var item in page)
{
cancellationToken.ThrowIfCancellationRequested();
// Elements in `StripeList` instances are decoded by `StripeObjectConverter`,
// which returns `null` for objects it doesn't know how to decode.
// When auto-paginating, we simply ignore these null elements but still return
// other elements.
if (item == null)
{
continue;
}
itemId = ((IHasId)item).Id;
yield return item;
}
if (!page.HasMore || string.IsNullOrEmpty(itemId))
{
break;
}
if (iterateBackward)
{
options.EndingBefore = itemId;
}
else
{
options.StartingAfter = itemId;
}
page = await this.RequestAsync<StripeList<T>>(
HttpMethod.Get,
url,
options,
requestOptions,
cancellationToken);
}
}
protected RequestOptions SetupRequestOptions(RequestOptions requestOptions)
{
if (requestOptions == null)
{
requestOptions = new RequestOptions();
}
requestOptions.BaseUrl = requestOptions.BaseUrl ?? this.BaseUrl;
return requestOptions;
}
protected virtual string ClassUrl()
{
return this.BasePath;
}
protected virtual string InstanceUrl(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentException(
"The resource ID cannot be null or whitespace.",
nameof(id));
}
return $"{this.ClassUrl()}/{WebUtility.UrlEncode(id)}";
}
private static bool IsStripeList<T>()
{
var typeInfo = typeof(T).GetTypeInfo();
return typeInfo.IsGenericType
&& typeInfo.GetGenericTypeDefinition() == typeof(StripeList<>);
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The <see cref="CloudJobSchedule.JobSpecification"/> of a <see cref="CloudJobSchedule"/>.
/// </summary>
public partial class JobSpecification : ITransportObjectProvider<Models.JobSpecification>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty;
public readonly PropertyAccessor<JobConstraints> ConstraintsProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty;
public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty;
public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty;
public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty;
public readonly PropertyAccessor<PoolInformation> PoolInformationProperty;
public readonly PropertyAccessor<int?> PriorityProperty;
public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(CommonEnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>(nameof(JobManagerTask), BindingAccess.Read | BindingAccess.Write);
this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>(nameof(JobPreparationTask), BindingAccess.Read | BindingAccess.Write);
this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>(nameof(JobReleaseTask), BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>(nameof(OnAllTasksComplete), BindingAccess.Read | BindingAccess.Write);
this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>(nameof(OnTaskFailure), BindingAccess.Read | BindingAccess.Write);
this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>(nameof(PoolInformation), BindingAccess.Read | BindingAccess.Write);
this.PriorityProperty = this.CreatePropertyAccessor<int?>(nameof(Priority), BindingAccess.Read | BindingAccess.Write);
this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>(nameof(UsesTaskDependencies), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.JobSpecification protocolObject) : base(BindingState.Bound)
{
this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.CommonEnvironmentSettings),
nameof(CommonEnvironmentSettings),
BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)),
nameof(Constraints),
BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read | BindingAccess.Write);
this.JobManagerTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o)),
nameof(JobManagerTask),
BindingAccess.Read | BindingAccess.Write);
this.JobPreparationTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o)),
nameof(JobPreparationTask),
BindingAccess.Read | BindingAccess.Write);
this.JobReleaseTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o)),
nameof(JobReleaseTask),
BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete),
nameof(OnAllTasksComplete),
BindingAccess.Read | BindingAccess.Write);
this.OnTaskFailureProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure),
nameof(OnTaskFailure),
BindingAccess.Read | BindingAccess.Write);
this.PoolInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)),
nameof(PoolInformation),
BindingAccess.Read | BindingAccess.Write);
this.PriorityProperty = this.CreatePropertyAccessor(
protocolObject.Priority,
nameof(Priority),
BindingAccess.Read | BindingAccess.Write);
this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor(
protocolObject.UsesTaskDependencies,
nameof(UsesTaskDependencies),
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JobSpecification"/> class.
/// </summary>
/// <param name='poolInformation'>The pool on which the Batch service runs the tasks of jobs created via this <see cref="JobSpecification"/>.</param>
public JobSpecification(
PoolInformation poolInformation)
{
this.propertyContainer = new PropertyContainer();
this.PoolInformation = poolInformation;
}
internal JobSpecification(Models.JobSpecification protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region JobSpecification
/// <summary>
/// Gets or sets a list of common environment variable settings.
/// </summary>
/// <remarks>
/// These environment variables are set for all tasks in jobs created under this <see cref="CloudJobSchedule"/> (including
/// the Job Manager, Job Preparation and Job Release tasks).
/// </remarks>
public IList<EnvironmentSetting> CommonEnvironmentSettings
{
get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the execution constraints for jobs created via this <see cref="JobSpecification"/>.
/// </summary>
public JobConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a display name for all jobs created via this <see cref="JobSpecification"/>.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets details of a Job Manager task to be launched when a job is created via this <see cref="JobSpecification"/>.
/// </summary>
public JobManagerTask JobManagerTask
{
get { return this.propertyContainer.JobManagerTaskProperty.Value; }
set { this.propertyContainer.JobManagerTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets the Job Preparation task for jobs created via this <see cref="JobSpecification"/>.
/// </summary>
/// <remarks>
/// The Batch service will run the Job Preparation task on a compute node before starting any tasks of that job on
/// that compute node.
/// </remarks>
public JobPreparationTask JobPreparationTask
{
get { return this.propertyContainer.JobPreparationTaskProperty.Value; }
set { this.propertyContainer.JobPreparationTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets the Job Release task for jobs created via this <see cref="JobSpecification"/>.
/// </summary>
/// <remarks>
/// The Batch service runs the Job Release task when the job ends, on each compute node where any task of the job
/// has run.
/// </remarks>
public JobReleaseTask JobReleaseTask
{
get { return this.propertyContainer.JobReleaseTaskProperty.Value; }
set { this.propertyContainer.JobReleaseTaskProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with jobs created via this <see cref="JobSpecification"/>
/// as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/>
/// state.
/// </summary>
public Common.OnAllTasksComplete? OnAllTasksComplete
{
get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; }
set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; }
}
/// <summary>
/// Gets or sets the action the Batch service should take when any task in the job fails.
/// </summary>
/// <remarks>
/// A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count,
/// or if it had a scheduling error.
/// </remarks>
public Common.OnTaskFailure? OnTaskFailure
{
get { return this.propertyContainer.OnTaskFailureProperty.Value; }
set { this.propertyContainer.OnTaskFailureProperty.Value = value; }
}
/// <summary>
/// Gets or sets the pool on which the Batch service runs the tasks of jobs created via this <see cref="JobSpecification"/>.
/// </summary>
public PoolInformation PoolInformation
{
get { return this.propertyContainer.PoolInformationProperty.Value; }
set { this.propertyContainer.PoolInformationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the priority of jobs created via this <see cref="JobSpecification"/>.
/// </summary>
/// <remarks>
/// Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being the highest
/// priority.
/// </remarks>
public int? Priority
{
get { return this.propertyContainer.PriorityProperty.Value; }
set { this.propertyContainer.PriorityProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether tasks in jobs created under this <see cref="CloudJobSchedule"/> can define dependencies
/// on each other.
/// </summary>
/// <remarks>
/// The default value is false.
/// </remarks>
public bool? UsesTaskDependencies
{
get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; }
set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; }
}
#endregion // JobSpecification
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobSpecification ITransportObjectProvider<Models.JobSpecification>.GetTransportObject()
{
Models.JobSpecification result = new Models.JobSpecification()
{
CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings),
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()),
JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()),
JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()),
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete),
OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure),
PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()),
Priority = this.Priority,
UsesTaskDependencies = this.UsesTaskDependencies,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
/*
* Muhimbi PDF
*
* Convert, Merge, Watermark, Secure and OCR files.
*
* OpenAPI spec version: 9.15
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Muhimbi.PDF.Online.Client.Model
{
/// <summary>
/// Parameters for CopyMetadata operation
/// </summary>
[DataContract]
public partial class CopyMetadataData : IEquatable<CopyMetadataData>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CopyMetadataData" /> class.
/// </summary>
[JsonConstructorAttribute]
protected CopyMetadataData() { }
/// <summary>
/// Initializes a new instance of the <see cref="CopyMetadataData" /> class.
/// </summary>
/// <param name="SiteUrl">SharePoint site url (example: http://contoso.sharepoint.com/sites/mysite) (required).</param>
/// <param name="SourceFileUrl">Path to the source file (required).</param>
/// <param name="DestinationFileUrl">Path to the destination file (required).</param>
/// <param name="Username">User name to log in to the SharePoint site.</param>
/// <param name="Password">Password to log in to the SharePoint site.</param>
/// <param name="CopyFields">Optional comma separated list of fields.</param>
/// <param name="ContentType">Optional content type for the destination file.</param>
/// <param name="FailOnError">Fail on error (default to true).</param>
public CopyMetadataData(string SiteUrl = default(string), string SourceFileUrl = default(string), string DestinationFileUrl = default(string), string Username = default(string), string Password = default(string), string CopyFields = default(string), string ContentType = default(string), bool? FailOnError = true)
{
// to ensure "SiteUrl" is required (not null)
if (SiteUrl == null)
{
throw new InvalidDataException("SiteUrl is a required property for CopyMetadataData and cannot be null");
}
else
{
this.SiteUrl = SiteUrl;
}
// to ensure "SourceFileUrl" is required (not null)
if (SourceFileUrl == null)
{
throw new InvalidDataException("SourceFileUrl is a required property for CopyMetadataData and cannot be null");
}
else
{
this.SourceFileUrl = SourceFileUrl;
}
// to ensure "DestinationFileUrl" is required (not null)
if (DestinationFileUrl == null)
{
throw new InvalidDataException("DestinationFileUrl is a required property for CopyMetadataData and cannot be null");
}
else
{
this.DestinationFileUrl = DestinationFileUrl;
}
this.Username = Username;
this.Password = Password;
this.CopyFields = CopyFields;
this.ContentType = ContentType;
// use default value if no "FailOnError" provided
if (FailOnError == null)
{
this.FailOnError = true;
}
else
{
this.FailOnError = FailOnError;
}
}
/// <summary>
/// SharePoint site url (example: http://contoso.sharepoint.com/sites/mysite)
/// </summary>
/// <value>SharePoint site url (example: http://contoso.sharepoint.com/sites/mysite)</value>
[DataMember(Name="site_url", EmitDefaultValue=false)]
public string SiteUrl { get; set; }
/// <summary>
/// Path to the source file
/// </summary>
/// <value>Path to the source file</value>
[DataMember(Name="source_file_url", EmitDefaultValue=false)]
public string SourceFileUrl { get; set; }
/// <summary>
/// Path to the destination file
/// </summary>
/// <value>Path to the destination file</value>
[DataMember(Name="destination_file_url", EmitDefaultValue=false)]
public string DestinationFileUrl { get; set; }
/// <summary>
/// User name to log in to the SharePoint site
/// </summary>
/// <value>User name to log in to the SharePoint site</value>
[DataMember(Name="username", EmitDefaultValue=false)]
public string Username { get; set; }
/// <summary>
/// Password to log in to the SharePoint site
/// </summary>
/// <value>Password to log in to the SharePoint site</value>
[DataMember(Name="password", EmitDefaultValue=false)]
public string Password { get; set; }
/// <summary>
/// Optional comma separated list of fields
/// </summary>
/// <value>Optional comma separated list of fields</value>
[DataMember(Name="copy_fields", EmitDefaultValue=false)]
public string CopyFields { get; set; }
/// <summary>
/// Optional content type for the destination file
/// </summary>
/// <value>Optional content type for the destination file</value>
[DataMember(Name="content_type", EmitDefaultValue=false)]
public string ContentType { get; set; }
/// <summary>
/// Fail on error
/// </summary>
/// <value>Fail on error</value>
[DataMember(Name="fail_on_error", EmitDefaultValue=false)]
public bool? FailOnError { 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 CopyMetadataData {\n");
sb.Append(" SiteUrl: ").Append(SiteUrl).Append("\n");
sb.Append(" SourceFileUrl: ").Append(SourceFileUrl).Append("\n");
sb.Append(" DestinationFileUrl: ").Append(DestinationFileUrl).Append("\n");
sb.Append(" Username: ").Append(Username).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" CopyFields: ").Append(CopyFields).Append("\n");
sb.Append(" ContentType: ").Append(ContentType).Append("\n");
sb.Append(" FailOnError: ").Append(FailOnError).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)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CopyMetadataData);
}
/// <summary>
/// Returns true if CopyMetadataData instances are equal
/// </summary>
/// <param name="other">Instance of CopyMetadataData to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CopyMetadataData other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.SiteUrl == other.SiteUrl ||
this.SiteUrl != null &&
this.SiteUrl.Equals(other.SiteUrl)
) &&
(
this.SourceFileUrl == other.SourceFileUrl ||
this.SourceFileUrl != null &&
this.SourceFileUrl.Equals(other.SourceFileUrl)
) &&
(
this.DestinationFileUrl == other.DestinationFileUrl ||
this.DestinationFileUrl != null &&
this.DestinationFileUrl.Equals(other.DestinationFileUrl)
) &&
(
this.Username == other.Username ||
this.Username != null &&
this.Username.Equals(other.Username)
) &&
(
this.Password == other.Password ||
this.Password != null &&
this.Password.Equals(other.Password)
) &&
(
this.CopyFields == other.CopyFields ||
this.CopyFields != null &&
this.CopyFields.Equals(other.CopyFields)
) &&
(
this.ContentType == other.ContentType ||
this.ContentType != null &&
this.ContentType.Equals(other.ContentType)
) &&
(
this.FailOnError == other.FailOnError ||
this.FailOnError != null &&
this.FailOnError.Equals(other.FailOnError)
);
}
/// <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 etc, of course :)
if (this.SiteUrl != null)
hash = hash * 59 + this.SiteUrl.GetHashCode();
if (this.SourceFileUrl != null)
hash = hash * 59 + this.SourceFileUrl.GetHashCode();
if (this.DestinationFileUrl != null)
hash = hash * 59 + this.DestinationFileUrl.GetHashCode();
if (this.Username != null)
hash = hash * 59 + this.Username.GetHashCode();
if (this.Password != null)
hash = hash * 59 + this.Password.GetHashCode();
if (this.CopyFields != null)
hash = hash * 59 + this.CopyFields.GetHashCode();
if (this.ContentType != null)
hash = hash * 59 + this.ContentType.GetHashCode();
if (this.FailOnError != null)
hash = hash * 59 + this.FailOnError.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using DotVVM.Framework.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Compilation.Javascript;
using DotVVM.Framework.Compilation.Javascript.Ast;
using DotVVM.Framework.Binding.Properties;
using DotVVM.Framework.Compilation.ControlTree;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using System.Diagnostics.CodeAnalysis;
using DotVVM.Framework.Utils;
using DotVVM.Framework.Compilation.Binding;
using DotVVM.Framework.Compilation;
using DotVVM.Framework.Runtime;
namespace DotVVM.Framework.Binding
{
public static partial class BindingHelper
{
[return: MaybeNull]
public static T GetProperty<T>(this IBinding binding, ErrorHandlingMode errorMode = ErrorHandlingMode.ThrowException) => (T)binding.GetProperty(typeof(T), errorMode)!;
public static T GetProperty<T>(this IBinding binding) => GetProperty<T>(binding, ErrorHandlingMode.ThrowException)!;
[Obsolete]
public static string GetKnockoutBindingExpression(this IValueBinding binding) =>
JavascriptTranslator.FormatKnockoutScript(binding.KnockoutExpression);
/// <summary>
/// Gets the javascript translation of the binding adjusted to the `currentControl`s DataContext
/// </summary>
public static string GetKnockoutBindingExpression(this IValueBinding binding, DotvvmBindableObject currentControl, bool unwrapped = false) =>
(unwrapped ? binding.UnwrappedKnockoutExpression : binding.KnockoutExpression)
.FormatKnockoutScript(currentControl, binding);
/// <summary>
/// Gets the javascript translation of the binding adjusted to the `currentControl`s DataContext, returned value is ParametrizedCode, so it can be further adjusted
/// </summary>
public static ParametrizedCode GetParametrizedKnockoutExpression(this IValueBinding binding, DotvvmBindableObject currentControl, bool unwrapped = false) =>
JavascriptTranslator.AdjustKnockoutScriptContext(unwrapped ? binding.UnwrappedKnockoutExpression : binding.KnockoutExpression, dataContextLevel: FindDataContextTarget(binding, currentControl).stepsUp);
/// <summary>
/// Adjusts the knockout expression to `currentControl`s DataContext like it was translated in `currentBinding`s context
/// </summary>
public static string FormatKnockoutScript(this ParametrizedCode code, DotvvmBindableObject currentControl, IBinding currentBinding) =>
JavascriptTranslator.FormatKnockoutScript(code, dataContextLevel: FindDataContextTarget(currentBinding, currentControl).stepsUp);
/// <summary>
/// Adjusts the knockout expression to `currentControl`s DataContext like it was translated in `currentBinding`s context
/// </summary>
public static string FormatKnockoutScript(this ParametrizedCode code, DotvvmBindableObject currentControl, IBinding currentBinding, int additionalDataContextSteps) =>
JavascriptTranslator.FormatKnockoutScript(code, dataContextLevel: FindDataContextTarget(currentBinding, currentControl).stepsUp + additionalDataContextSteps);
/// <summary>
/// Gets Internal.PathFragmentProperty or DataContext.KnockoutExpression. Returns null if none of these is set.
/// </summary>
public static string? GetDataContextPathFragment(this DotvvmBindableObject currentControl) =>
(string?)currentControl.GetValue(Internal.PathFragmentProperty, inherit: false) ??
(currentControl.GetBinding(DotvvmBindableObject.DataContextProperty, inherit: false) is IValueBinding binding ?
binding.GetProperty<SimplePathExpressionBindingProperty>()
.Code.FormatKnockoutScript(currentControl, binding) :
null);
// PERF: maybe safe last GetValue's target/binding to ThreadLocal variable, so the path does not have to be traversed twice
/// <summary>
/// Finds expected context control of the `binding` and returns (parent index of the correct DataContext, control in the correct context)
/// </summary>
public static (int stepsUp, DotvvmBindableObject target) FindDataContextTarget(this IBinding binding, DotvvmBindableObject control)
{
if (control == null) throw new ArgumentNullException(nameof(control), $"Cannot evaluate binding without any dataContext.");
var bindingContext = binding.DataContext;
return FindDataContextTarget(control, bindingContext, binding);
}
internal static (int stepsUp, DotvvmBindableObject target) FindDataContextTarget(DotvvmBindableObject control, DataContextStack? bindingContext, object? contextObject)
{
var controlContext = control.GetDataContextType();
if (bindingContext == null || controlContext == null || controlContext.Equals(bindingContext)) return (0, control);
var changes = 0;
foreach (var a in control.GetAllAncestors(includingThis: true))
{
if (bindingContext.Equals(a.GetDataContextType(inherit: false)))
return (changes, a);
if (a.properties.Contains(DotvvmBindableObject.DataContextProperty)) changes++;
}
throw new InvalidDataContextTypeException(control, contextObject, controlContext, bindingContext);
}
/// <summary>
/// Prepares DataContext hierarchy argument and executes update delegate.
/// </summary>
public static void ExecUpdateDelegate(this BindingUpdateDelegate func, DotvvmBindableObject contextControl, object? value)
{
var dataContexts = GetDataContexts(contextControl);
//var control = contextControl.GetClosestControlBindingTarget();
func(dataContexts.ToArray(), contextControl, value);
}
/// <summary>
/// Prepares DataContext hierarchy argument and executes update delegate.
/// </summary>
public static void ExecUpdateDelegate<T>(this BindingUpdateDelegate<T> func, DotvvmBindableObject contextControl, T value)
{
var dataContexts = GetDataContexts(contextControl);
//var control = contextControl.GetClosestControlBindingTarget();
func(dataContexts.ToArray(), contextControl, value);
}
/// <summary>
/// Prepares DataContext hierarchy argument and executes update delegate.
/// </summary>
public static object? ExecDelegate(this BindingDelegate func, DotvvmBindableObject contextControl)
{
var dataContexts = GetDataContexts(contextControl);
return func(dataContexts.ToArray(), contextControl);
}
/// <summary>
/// Prepares DataContext hierarchy argument and executes update delegate.
/// </summary>
public static T ExecDelegate<T>(this BindingDelegate<T> func, DotvvmBindableObject contextControl)
{
var dataContexts = GetDataContexts(contextControl);
return func(dataContexts.ToArray(), contextControl);
}
/// <summary>
/// Gets all data context on the path to root. Maximum count can be specified by `count`
/// </summary>
public static IEnumerable<object?> GetDataContexts(this DotvvmBindableObject contextControl, int count = -1)
{
DotvvmBindableObject? c = contextControl;
while (c != null)
{
// PERF: O(h^2) because GetValue calls another GetDataContexts
if (c.IsPropertySet(DotvvmBindableObject.DataContextProperty, inherit: false))
{
yield return c.GetValue(DotvvmBindableObject.DataContextProperty);
count--;
}
if (count == 0) yield break;
c = c.Parent;
}
}
/// <summary>
/// Finds expected DataContext target in control.Ancestors() and evaluates the `binding.BindingDelegate`.
/// </summary>
public static object? Evaluate(this IStaticValueBinding binding, DotvvmBindableObject control)
{
return ExecDelegate(
binding.BindingDelegate,
FindDataContextTarget(binding, control).target);
}
/// <summary>
/// Finds expected DataContext target in control.Ancestors() and evaluates the `binding.BindingDelegate`.
/// </summary>
public static T Evaluate<T>(this IStaticValueBinding<T> binding, DotvvmBindableObject control)
{
return ExecDelegate(
binding.BindingDelegate,
FindDataContextTarget(binding, control).target);
}
/// <summary>
/// Writes the value to binding - bound viewModel property is updated. May throw an exception when binding does not support assignment.
/// </summary>
public static void UpdateSource(this IUpdatableValueBinding binding, object? value, DotvvmBindableObject control)
{
ExecUpdateDelegate(
binding.UpdateDelegate,
FindDataContextTarget(binding, control).target,
value);
}
/// <summary>
/// Writes the value to binding - bound viewModel property is updated. May throw an exception when binding does not support assignment.
/// </summary>
public static void UpdateSource<T>(this IUpdatableValueBinding<T> binding, T value, DotvvmBindableObject control)
{
ExecUpdateDelegate(
binding.UpdateDelegate,
FindDataContextTarget(binding, control).target,
value);
}
/// <summary>
/// Finds expected DataContext and gets the delegate from command binding.
/// </summary>
public static Delegate GetCommandDelegate(this ICommandBinding binding, DotvvmBindableObject control)
{
return (Delegate)ExecDelegate(
binding.BindingDelegate,
FindDataContextTarget(binding, control).target).NotNull();
}
/// <summary>
/// Finds expected DataContext and gets the delegate from command binding.
/// </summary>
public static T GetCommandDelegate<T>(this ICommandBinding<T> binding, DotvvmBindableObject control)
{
return ExecDelegate(
binding.BindingDelegate,
FindDataContextTarget(binding, control).target);
}
/// <summary>
/// Finds expected DataContext, gets the delegate from command binding and evaluates it with `args`
/// </summary>
public static object? Evaluate(this ICommandBinding binding, DotvvmBindableObject control, params Func<Type, object>[] args)
{
var action = binding.GetCommandDelegate(control);
if (action is Command command) return command();
if (action is Action actionDelegate) { actionDelegate(); return null; }
if (action is Func<Task> command2) return command2();
var parameters = action.GetType().GetMethod("Invoke")!.GetParameters();
var evaluatedArgs = args.Zip(parameters, (a, p) => a(p.ParameterType)).ToArray();
return action.DynamicInvoke(evaluatedArgs);
}
/// <summary>
/// Gets DataContext-adjusted javascript that can be used for command invocation.
/// </summary>
public static ParametrizedCode GetParametrizedCommandJavascript(this ICommandBinding binding, DotvvmBindableObject control) =>
JavascriptTranslator.AdjustKnockoutScriptContext(binding.CommandJavascript,
dataContextLevel: FindDataContextTarget(binding, control).stepsUp);
public static object? GetBindingValue(this IBinding binding, DotvvmBindableObject control)
{
if (binding is IStaticValueBinding valueBinding)
{
return valueBinding.Evaluate(control);
}
else if (binding is ICommandBinding command)
{
return command.GetCommandDelegate(control);
}
else throw new BindingNotSupportedException(binding);
}
/// <summary>
/// Creates new `TBinding` with the original DataContextStack, LocationInfo, AdditionalResolvers and BindingCompilationService.
/// </summary>
public static TBinding DeriveBinding<TBinding>(this TBinding binding, DataContextStack newDataContext, Expression expression, params object?[] properties)
where TBinding : IBinding
{
return binding.DeriveBinding(
properties.Concat(new object[] {
newDataContext,
new ParsedExpressionBindingProperty(expression),
new CastedExpressionBindingProperty(expression),
new ExpectedTypeBindingProperty(expression.Type),
new ResultTypeBindingProperty(expression.Type)
}).ToArray()
);
}
/// <summary>
/// Creates new `TBinding` with the original DataContextStack, LocationInfo, AdditionalResolvers and BindingCompilationService.
/// </summary>
public static TBinding DeriveBinding<TBinding>(this TBinding binding, Expression expression, params object?[] properties)
where TBinding : IBinding
{
return binding.DeriveBinding(
properties.Concat(new object[] {
new ParsedExpressionBindingProperty(expression),
new CastedExpressionBindingProperty(expression),
new ExpectedTypeBindingProperty(expression.Type),
new ResultTypeBindingProperty(expression.Type)
}).ToArray()
);
}
/// <summary>
/// Creates new `TBinding` with the original DataContextStack, LocationInfo, AdditionalResolvers and BindingCompilationService.
/// </summary>
public static TBinding DeriveBinding<TBinding>(this TBinding binding, params object?[] properties)
where TBinding : IBinding
{
object?[] getContextProperties(IBinding b) =>
new object?[] {
b.DataContext,
b.GetProperty<BindingResolverCollection>(ErrorHandlingMode.ReturnNull),
b.GetProperty<BindingCompilationRequirementsAttribute>(ErrorHandlingMode.ReturnNull)?.ClearRequirements(),
b.GetProperty<BindingErrorReporterProperty>(ErrorHandlingMode.ReturnNull),
b.GetProperty<DotvvmLocationInfo>(ErrorHandlingMode.ReturnNull)
};
var service = binding.GetProperty<BindingCompilationService>();
var bindingType = binding.GetType();
if (bindingType.IsGenericType)
bindingType = bindingType.GetGenericTypeDefinition();
return (TBinding)service.CreateBinding(bindingType, properties.Concat(getContextProperties(binding)).ToArray());
}
/// <summary>
/// Caches all function evaluations in the closure based on parameter. TParam should be immutable, as it is used as Dictionary key.
/// It thread-safe.
/// </summary>
public static Func<TParam, TResult> Cache<TParam, TResult>(this Func<TParam, TResult> func)
where TParam: notnull
{
var cache = new ConcurrentDictionary<TParam, TResult>();
return f => cache.GetOrAdd(f, func);
}
public static IValueBinding GetThisBinding(this DotvvmBindableObject obj)
{
var dataContext = obj.GetValueBinding(DotvvmBindableObject.DataContextProperty);
return (IValueBinding)dataContext!.GetProperty<ThisBindingProperty>().binding;
}
private static readonly ConditionalWeakTable<Expression, BindingParameterAnnotation> _expressionAnnotations =
new ConditionalWeakTable<Expression, BindingParameterAnnotation>();
public static TExpression AddParameterAnnotation<TExpression>(this TExpression expr, BindingParameterAnnotation annotation)
where TExpression : Expression
{
_expressionAnnotations.Add(expr, annotation);
return expr;
}
public static BindingParameterAnnotation? GetParameterAnnotation(this Expression expr) =>
_expressionAnnotations.TryGetValue(expr, out var annotation) ? annotation : null;
public static void SetDataContextTypeFromDataSource(this DotvvmBindableObject obj, IBinding dataSourceBinding) =>
obj.SetDataContextType(dataSourceBinding.GetProperty<CollectionElementDataContextBindingProperty>().DataContext);
/// <summary> Return the expected data context type for this property. Returns null if the type is unknown. </summary>
public static DataContextStack? GetDataContextType(this DotvvmProperty property, DotvvmBindableObject obj)
{
var dataContextType = obj.GetDataContextType();
if (dataContextType == null)
{
return null;
}
if (property.DataContextManipulationAttribute != null)
{
return property.DataContextManipulationAttribute.ChangeStackForChildren(dataContextType, obj, property, (parent, changeType) => DataContextStack.Create(changeType, parent));
}
if (property.DataContextChangeAttributes == null || property.DataContextChangeAttributes.Length == 0)
{
return dataContextType;
}
var (childType, extensionParameters) = ApplyDataContextChange(dataContextType, property.DataContextChangeAttributes, obj, property);
if (childType is null) return null; // childType is null in case there is some error in processing (e.g. enumerable was expected).
else return DataContextStack.Create(childType, dataContextType, extensionParameters: extensionParameters.ToArray());
}
/// <summary> Return the expected data context type for this property. Returns null if the type is unknown. </summary>
public static DataContextStack GetDataContextType(this DotvvmProperty property, ResolvedControl obj)
{
var dataContextType = obj.DataContextTypeStack;
if (property.DataContextManipulationAttribute != null)
{
return (DataContextStack)property.DataContextManipulationAttribute.ChangeStackForChildren(
dataContextType, obj, property,
(parent, changeType) => DataContextStack.Create(ResolvedTypeDescriptor.ToSystemType(changeType), (DataContextStack)parent));
}
if (property.DataContextChangeAttributes == null || property.DataContextChangeAttributes.Length == 0)
{
return dataContextType;
}
var (childType, extensionParameters) = ApplyDataContextChange(dataContextType, property.DataContextChangeAttributes, obj, property);
if (childType is null)
childType = typeof(UnknownTypeSentinel);
return DataContextStack.Create(childType, dataContextType, extensionParameters: extensionParameters.ToArray());
}
public static (Type? type, List<BindingExtensionParameter> extensionParameters) ApplyDataContextChange(DataContextStack dataContext, DataContextChangeAttribute[] attributes, ResolvedControl control, DotvvmProperty? property)
{
var type = ResolvedTypeDescriptor.Create(dataContext.DataContextType);
var extensionParameters = new List<BindingExtensionParameter>();
foreach (var attribute in attributes.OrderBy(a => a.Order))
{
if (type == null) break;
extensionParameters.AddRange(attribute.GetExtensionParameters(type));
type = attribute.GetChildDataContextType(type, dataContext, control, property);
}
return (ResolvedTypeDescriptor.ToSystemType(type), extensionParameters);
}
private static (Type? childType, List<BindingExtensionParameter> extensionParameters) ApplyDataContextChange(DataContextStack dataContextType, DataContextChangeAttribute[] attributes, DotvvmBindableObject obj, DotvvmProperty property)
{
Type? type = dataContextType.DataContextType;
var extensionParameters = new List<BindingExtensionParameter>();
foreach (var attribute in attributes.OrderBy(a => a.Order))
{
if (type == null) break;
extensionParameters.AddRange(attribute.GetExtensionParameters(new ResolvedTypeDescriptor(type)));
type = attribute.GetChildDataContextType(type, dataContextType, obj, property);
}
return (type, extensionParameters);
}
/// <summary>
/// Annotates `_this`, `_parent`, `_root` parameters with BindingParameterAnnotation indicating their DataContext
/// </summary>
public static Expression AnnotateStandardContextParams(Expression expr, DataContextStack dataContext) =>
new ParameterAnnotatingVisitor(dataContext).Visit(expr);
class ParameterAnnotatingVisitor : ExpressionVisitor
{
public readonly DataContextStack DataContext;
public ParameterAnnotatingVisitor(DataContextStack dataContext)
{
this.DataContext = dataContext;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (node.GetParameterAnnotation() != null) return node;
if (node.Name is null) return base.VisitParameter(node);
if (node.Name == "_this") return node.AddParameterAnnotation(new BindingParameterAnnotation(DataContext));
else if (node.Name == "_parent") return node.AddParameterAnnotation(new BindingParameterAnnotation(DataContext.Parent));
else if (node.Name == "_root") return node.AddParameterAnnotation(new BindingParameterAnnotation(DataContext.EnumerableItems().Last()));
else if (node.Name.StartsWith("_parent", StringComparison.Ordinal) && int.TryParse(node.Name.Substring("_parent".Length), out int index))
return node.AddParameterAnnotation(new BindingParameterAnnotation(DataContext.EnumerableItems().ElementAt(index)));
return base.VisitParameter(node);
}
}
public static BindingDelegate<T> ToGeneric<T>(this BindingDelegate d) => (a, b) => (T)d(a, b)!;
public static BindingUpdateDelegate<T> ToGeneric<T>(this BindingUpdateDelegate d) => (a, b, c) => d(a, b, c);
public record InvalidDataContextTypeException(
DotvvmBindableObject Control,
object? ContextObject,
DataContextStack ControlContext,
DataContextStack BindingContext
)
: DotvvmExceptionBase(
RelatedBinding: ContextObject as IBinding,
RelatedControl: Control
)
{
public override string Message =>
$"Could not find DataContext space of '{ContextObject}'. The DataContextType property of the binding does not correspond to DataContextType of the {Control.GetType().Name} nor any of its ancestors. Control's context is {ControlContext}, binding's context is {BindingContext}.";
}
public record BindingNotSupportedException(IBinding Binding, [CallerMemberName] string Caller = "")
: DotvvmExceptionBase(RelatedBinding: Binding)
{
public override string Message => $"Binding {Binding} is not supported in {Caller} method";
}
public record InvalidBindingTypeException(IBinding Binding, Type ExpectedType)
: DotvvmExceptionBase(RelatedBinding: Binding)
{
public override string Message => $"The binding result type {Binding.GetProperty<ResultTypeBindingProperty>(ErrorHandlingMode.ReturnNull)?.Type.FullName} is not assignable to {ExpectedType.FullName}";
public static void CheckType(IBinding binding, Type expectedType)
{
if (binding.GetProperty<ResultTypeBindingProperty>(ErrorHandlingMode.ReturnNull) is ResultTypeBindingProperty resultType &&
!expectedType.IsAssignableFrom(resultType.Type))
throw new InvalidBindingTypeException(binding, expectedType);
}
}
}
public class BindingParameterAnnotation
{
public readonly DataContextStack? DataContext;
public readonly BindingExtensionParameter? ExtensionParameter;
public BindingParameterAnnotation(DataContextStack? context = null, BindingExtensionParameter? extensionParameter = null)
{
this.DataContext = context;
this.ExtensionParameter = extensionParameter;
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
namespace NUnit.ConsoleRunner
{
using System;
using Codeblast;
using NUnit.Util;
public class ConsoleOptions : CommandLineOptions
{
public enum DomainUsage
{
Default,
None,
Single,
Multiple
}
[Option(Description = "Fixture to test")]
public string fixture;
[Option(Description = "Project configuration to load")]
public string config;
[Option(Description = "Name of XML output file")]
public string xml;
[Option(Description = "Name of transform file")]
public string transform;
[Option(Description = "Display XML to the console")]
public bool xmlConsole;
[Option(Short="out", Description = "File to receive test output")]
public string output;
[Option(Description = ".NET Framework version to execute with (eg 'v1.0.3705')")]
public string framework;
[Option(Description = "File to receive test error output")]
public string err;
[Option(Description = "Label each test in stdOut")]
public bool labels = false;
[Option(Description = "List of categories to include")]
public string include;
[Option(Description = "List of categories to exclude")]
public string exclude;
// [Option(Description = "Run in a separate process")]
// public bool process;
[Option(Description = "AppDomain Usage for Tests")]
public DomainUsage domain;
// [Option(Description = "Disable use of a separate AppDomain for tests")]
// public bool nodomain;
[Option(Description = "Disable shadow copy when running in separate domain")]
// [Option(Description = "Disable shadow copy")]
public bool noshadow;
[Option (Description = "Disable use of a separate thread for tests")]
public bool nothread;
[Option(Description = "Wait for input before closing console window")]
public bool wait = false;
[Option(Description = "Do not display the logo")]
public bool nologo = false;
[Option(Description = "Do not display progress" )]
public bool nodots = false;
[Option(Short="?", Description = "Display help")]
public bool help = false;
private bool isInvalid = false;
//public ConsoleOptions(String[] args) : base(args) {}
public ConsoleOptions( params string[] args ) : base( args ) {}
public ConsoleOptions( bool allowForwardSlash, params string[] args ) : base( allowForwardSlash, args ) {}
protected override void InvalidOption(string name)
{
isInvalid = true;
}
public bool Validate()
{
if(isInvalid) return false;
if(HasInclude && HasExclude) return false;
if(NoArgs) return true;
if(IsFixture) return true;
if(ParameterCount >= 1) return true;
return false;
}
public bool IsAssembly
{
get
{
return ParameterCount >= 1 && !IsFixture;
}
}
public bool IsTestProject
{
get
{
return ParameterCount == 1 && NUnitProject.CanLoadAsProject( (string)Parameters[0] );
}
}
public bool IsFixture
{
get
{
return ParameterCount >= 1 &&
((fixture != null) && (fixture.Length > 0));
}
}
public bool IsXml
{
get
{
return (xml != null) && (xml.Length != 0);
}
}
public bool isOut
{
get
{
return (output != null) && (output.Length != 0);
}
}
public bool isErr
{
get
{
return (err != null) && (err.Length != 0);
}
}
public bool IsTransform
{
get
{
return (transform != null) && (transform.Length != 0);
}
}
public bool HasInclude
{
get
{
return include != null && include.Length != 0;
}
}
public bool HasExclude
{
get
{
return exclude != null && exclude.Length != 0;
}
}
public string[] IncludedCategories
{
get
{
if (HasInclude)
return include.Split( new char[] {';', ','});
return null;
}
}
public string[] ExcludedCategories
{
get
{
if (HasExclude)
return exclude.Split( new char[] {';', ','});
return null;
}
}
public override void Help()
{
Console.WriteLine();
Console.WriteLine( "NUNIT-CONSOLE [inputfiles] [options]" );
Console.WriteLine();
Console.WriteLine( "Runs a set of NUnit tests from the console." );
Console.WriteLine();
Console.WriteLine( "You may specify one or more assemblies or a single" );
Console.WriteLine( "project file of type .nunit." );
Console.WriteLine();
Console.WriteLine( "Options:" );
base.Help();
Console.WriteLine();
Console.WriteLine( "Options that take values may use an equal sign, a colon" );
Console.WriteLine( "or a space to separate the option from its value." );
Console.WriteLine();
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeItem (editable child object).<br/>
/// This is a generated base class of <see cref="ProductTypeItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="ProductTypeColl"/> collection.
/// </remarks>
[Serializable]
public partial class ProductTypeItem : BusinessBase<ProductTypeItem>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductTypeId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id");
/// <summary>
/// Gets the Product Type Id.
/// </summary>
/// <value>The Product Type Id.</value>
public int ProductTypeId
{
get { return GetProperty(ProductTypeIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeItem()
{
// Use factory methods and do not use direct creation.
Saved += OnProductTypeItemSaved;
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="ProductTypeItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(ProductTypeIdProperty, System.Threading.Interlocked.Decrement(ref _lastId));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="ProductTypeItem"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Child_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId"));
LoadProperty(NameProperty, dr.GetString("Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="ProductTypeItem"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IProductTypeItemDal>();
using (BypassPropertyChecks)
{
int productTypeId = -1;
dal.Insert(
out productTypeId,
Name
);
LoadProperty(ProductTypeIdProperty, productTypeId);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductTypeItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IProductTypeItemDal>();
using (BypassPropertyChecks)
{
dal.Update(
ProductTypeId,
Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="ProductTypeItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IProductTypeItemDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(ProductTypeIdProperty));
}
OnDeletePost(args);
}
}
#endregion
#region Saved Event
// TODO: edit "ProductTypeItem.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnProductTypeItemSaved;
private void OnProductTypeItemSaved(object sender, Csla.Core.SavedEventArgs e)
{
if (ProductTypeItemSaved != null)
ProductTypeItemSaved(sender, e);
}
/// <summary> Use this event to signal a <see cref="ProductTypeItem"/> object was saved.</summary>
public static event EventHandler<Csla.Core.SavedEventArgs> ProductTypeItemSaved;
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <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);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#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 System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Text;
namespace IBM.Data.DB2
{
public class DB2Connection : DbConnection, IDbConnection, IDisposable
{
private IntPtr dbHandle = IntPtr.Zero;
private bool transactionOpen;
private ArrayList refCommands;
private int connectionTimeout;
private WeakReference refTransaction;
private bool disposed = false;
private string connectionString;
private string databaseProductName;
private string databaseVersion;
private bool nativeOpenPerformed;
private bool autoCommit = true;
private DB2OpenConnection openConnection;
private DB2ConnectionSettings connectionSettings;
public override string Database
{
get { return databaseProductName; }
}
public IntPtr DBHandle
{
get { return openConnection.DBHandle; }
}
public bool TransactionOpen
{
get { return transactionOpen; }
set { transactionOpen = value; }
}
public bool AutoCommit
{
get { return autoCommit; }
set { autoCommit = value; }
}
public DB2Connection()
{
}
#region Constructors
public DB2Connection(string connectionString)
{
//this.connectionString = connectionString;
SetConnectionString(connectionString);
}
#endregion
#region ConnectionString property
public override string ConnectionString
{
get
{
return connectionString;
}
set
{
connectionString = value;
}
}
#endregion
#region State property
public override int ConnectionTimeout
{
get
{
return connectionTimeout;
}
}
public override ConnectionState State
{
get
{
if (!nativeOpenPerformed)
return ConnectionState.Closed;
int isDead;
DB2Constants.RetCode sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLGetConnectAttr(openConnection.DBHandle, DB2Constants.SQL_ATTR_CONNECTION_DEAD, out isDead, 0, IntPtr.Zero);
DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, openConnection.DBHandle, "Unable to connect to the database.", this);
if (((sqlRet == DB2Constants.RetCode.SQL_SUCCESS_WITH_INFO) || (sqlRet == DB2Constants.RetCode.SQL_SUCCESS)) && (isDead == DB2Constants.SQL_CD_FALSE))
{
return ConnectionState.Open;
}
return ConnectionState.Closed;
}
}
#endregion
#region events
public event DB2InfoMessageEventHandler InfoMessage;
public event StateChangeEventHandler StateChange;
internal void OnInfoMessage(short handleType, IntPtr handle)
{
if (InfoMessage != null)
{
// Don't get error information until we know for sure someone is listening
try
{
InfoMessage(this,
new DB2InfoMessageEventArgs(new DB2ErrorCollection(handleType, handle)));
}
catch (Exception)
{ }
}
}
private void OnStateChange(StateChangeEventArgs args)
{
if (StateChange != null)
StateChange(this, args);
}
#endregion
#region BeginTransaction Method
public DB2Transaction BeginTransaction()
{
return InternalBeginTransaction(IsolationLevel.ReadCommitted);
}
public DB2Transaction BeginTransaction(IsolationLevel isolationLevel)
{
return InternalBeginTransaction(isolationLevel);
}
public DB2Transaction InternalBeginTransaction()
{
return InternalBeginTransaction(IsolationLevel.ReadCommitted);
}
public DB2Transaction InternalBeginTransaction(IsolationLevel isolationLevel)
{
if ((refTransaction != null) && (refTransaction.IsAlive))
throw new InvalidOperationException("Cannot open another transaction");
if (State != ConnectionState.Open)
throw new InvalidOperationException("BeginTransaction needs an open connection");
if (refTransaction != null)
{
if (refTransaction.IsAlive)
throw new InvalidOperationException("Parallel transactions not supported");
RollbackDeadTransaction();
refTransaction = null;
}
transactionOpen = true;
DB2Transaction tran = new DB2Transaction(this, isolationLevel);
refTransaction = new WeakReference(tran);
return tran;
}
#endregion
//TODO ChangeDatabase
#region ChangeDatabase
unsafe public override void ChangeDatabase(string newDBName)
{
if (connectionSettings == null)
{
throw new InvalidOperationException("No connection string");
}
Close();
SetConnectionString(connectionSettings.ConnectionString.Replace(connectionSettings.DatabaseAlias, newDBName));
Open();
}
#endregion
//TODO Create pool functionality
public static void ReleaseObjectPool()
{
DB2Environment.Instance.Dispose();
}
public override void Close()
{
DB2Transaction transaction = null;
if (refTransaction != null)
transaction = (DB2Transaction)refTransaction.Target;
if ((transaction != null) && refTransaction.IsAlive)
{
transaction.Dispose();
}
if (refCommands != null)
{
for (int i = 0; i < refCommands.Count; i++)
{
DB2Command command = null;
if (refCommands[i] != null)
{
command = (DB2Command)((WeakReference)refCommands[i]).Target;
}
if ((command != null) && ((WeakReference)refCommands[i]).IsAlive)
{
try
{
command.ConnectionClosed();
}
catch { }
}
//?? refCommands[i] = null;
}
}
InternalClose();
}
public void InternalClose()
{
if (transactionOpen)
RollbackDeadTransaction();
FreeHandles();
}
private void SetConnectionString(string connectionString)
{
this.connectionSettings = DB2ConnectionSettings.GetConnectionSettings(connectionString);
}
public DB2Command CreateCommand()
{
return new DB2Command(null, this);
}
public string SQLGetInfo(IntPtr dbHandle, short infoType)
{
StringBuilder sb = new StringBuilder(DB2Constants.SQL_MAX_OPTION_STRING_LENGTH);
short stringLength;
DB2Constants.RetCode sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLGetInfo(dbHandle, infoType, sb, DB2Constants.SQL_MAX_OPTION_STRING_LENGTH, out stringLength);
if (sqlRet != DB2Constants.RetCode.SQL_SUCCESS && sqlRet != DB2Constants.RetCode.SQL_SUCCESS_WITH_INFO)
throw new DB2Exception(DB2Constants.SQL_HANDLE_DBC, dbHandle, "SQLGetInfo Error");
return sb.ToString().Trim();
}
#region Open
//private void InternalOpen()
//{
// try
// {
// DB2Constants.RetCode sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLAllocHandle(DB2Constants.SQL_HANDLE_DBC, DB2Environment.Instance.PenvHandle, out dbHandle);
// DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, DB2Environment.Instance.PenvHandle, "Unable to allocate database handle in DB2Connection.", this);
// StringBuilder outConnectStr = new StringBuilder(DB2Constants.SQL_MAX_OPTION_STRING_LENGTH);
// short numOutCharsReturned;
// sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLDriverConnect(dbHandle, IntPtr.Zero,
// connectionString, DB2Constants.SQL_NTS,
// outConnectStr, DB2Constants.SQL_MAX_OPTION_STRING_LENGTH, out numOutCharsReturned,
// DB2Constants.SQL_DRIVER_NOPROMPT);
// DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, dbHandle, "Unable to connect to the database.", this);
// databaseProductName = SQLGetInfo(dbHandle, DB2Constants.SQL_DBMS_NAME);
// databaseVersion = SQLGetInfo(dbHandle, DB2Constants.SQL_DBMS_VER);
// /* Set the attribute SQL_ATTR_XML_DECLARATION to skip the XML declaration from XML Data */
// sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLSetConnectAttr(dbHandle, DB2Constants.SQL_ATTR_XML_DECLARATION, new IntPtr(DB2Constants.SQL_XML_DECLARATION_NONE), DB2Constants.SQL_NTS);
// DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, dbHandle, "Unable to set SQL_ATTR_XML_DECLARATION", this);
// nativeOpenPerformed = true;
// }
// catch
// {
// if (dbHandle != IntPtr.Zero)
// {
// DB2CLIWrapper.SQLFreeHandle(DB2Constants.SQL_HANDLE_DBC, dbHandle);
// dbHandle = IntPtr.Zero;
// }
// throw;
// }
//}
public override void Open()
{
if (disposed)
{
throw new ObjectDisposedException("DB2Connection");
}
if (this.State == ConnectionState.Open)
{
throw new InvalidOperationException("Connection already open");
}
try
{
//InternalOpen();
openConnection = connectionSettings.GetRealOpenConnection(this);
}
catch (DB2Exception)
{
Close();
throw;
}
}
#endregion
public void RollbackDeadTransaction()
{
DB2CLIWrapper.SQLEndTran(DB2Constants.SQL_HANDLE_DBC, dbHandle, DB2Constants.SQL_ROLLBACK);
transactionOpen = false;
}
private void FreeHandles()
{
if (dbHandle != IntPtr.Zero)
{
short sqlRet = DB2CLIWrapper.SQLDisconnect(dbHandle);
// Note that SQLDisconnect() automatically drops any statements and
// descriptors open on the connection.
sqlRet = DB2CLIWrapper.SQLFreeHandle(DB2Constants.SQL_HANDLE_DBC, dbHandle);
dbHandle = IntPtr.Zero;
}
}
#region Dispose
protected override void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
Close();
}
}
~DB2Connection()
{
Dispose(false);
}
#endregion
private void CheckState()
{
if (ConnectionState.Closed == State)
throw new InvalidOperationException("Connection is currently closed.");
}
internal WeakReference WeakRefTransaction
{
get
{
return refTransaction;
}
set
{
refTransaction = value;
}
}
public override string DataSource
{
get { return SQLGetInfo(dbHandle, DB2Constants.SQL_DBMS_NAME); }
}
public override string ServerVersion
{
get {
return SQLGetInfo(dbHandle, DB2Constants.SQL_DBMS_VER);
}
}
internal void AddCommand(DB2Command command)
{
if (refCommands == null)
{
refCommands = new ArrayList();
}
for (int i = 0; i < refCommands.Count; i++)
{
WeakReference reference = (WeakReference)refCommands[i];
if ((reference == null) || !reference.IsAlive)
{
refCommands[i] = new WeakReference(command);
return;
}
}
refCommands.Add(new WeakReference(command));
}
internal void RemoveCommand(DB2Command command)
{
for (int i = 0; i < refCommands.Count; i++)
{
WeakReference reference = (WeakReference)refCommands[i];
if (object.ReferenceEquals(reference, command))
{
refCommands[i] = null;
return;
}
}
}
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
return InternalBeginTransaction(isolationLevel);
}
protected override DbCommand CreateDbCommand()
{
DbCommand dbCommand = new DB2Command(string.Empty, this);
return dbCommand;
}
public bool IsOpen
{
get { return State == ConnectionState.Open; }
}
public bool NativeOpenPerformed { get { return nativeOpenPerformed; } set { nativeOpenPerformed = value; } }
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using SslLabsLib.Code;
using SslLabsLib.Enums;
namespace SslLabsLib.Objects
{
public class EndpointDetails
{
/// <summary>
/// Endpoint assessment starting time, in milliseconds since 1970.
/// This field is useful when test results are retrieved in several HTTP invocations.
/// Then, you should check that the hostStartTime value matches the startTime value of the host.
/// </summary>
[JsonConverter(typeof(MillisecondEpochConverter))]
[JsonProperty("hostStartTime")]
public DateTime HostStartTime { get; set; }
/// <summary>
/// Key information
/// </summary>
[JsonProperty("key")]
public Key Key { get; set; }
/// <summary>
/// Certificate information
/// </summary>
[JsonProperty("cert")]
public Cert Cert { get; set; }
/// <summary>
/// Chain information
/// </summary>
[JsonProperty("chain")]
public Chain Chain { get; set; }
/// <summary>
/// Supported protocols
/// </summary>
[JsonProperty("protocols")]
public List<Protocol> Protocols { get; set; }
/// <summary>
/// Supported cipher suites
/// </summary>
[JsonProperty("suites")]
public Suites Suites { get; set; }
/// <summary>
/// Contents of the HTTP Server response header when known.
/// This field could be absent for one of two reasons:
/// 1) the HTTP request failed (check httpStatusCode)
/// 2) there was no Server response header returned.
/// </summary>
[JsonProperty("serverSignature")]
public string ServerSignature { get; set; }
/// <summary>
/// True if this endpoint is reachable via a hostname with the www prefix
/// </summary>
[JsonProperty("prefixDelegation")]
public bool PrefixDelegation { get; set; }
/// <summary>
/// True if this endpoint is reachable via a hostname without the www prefix
/// </summary>
[JsonProperty("nonPrefixDelegation")]
public bool NonPrefixDelegation { get; set; }
/// <summary>
/// True if the endpoint is vulnerable to the BEAST attack
/// </summary>
[JsonProperty("vulnBeast")]
public bool VulnBeast { get; set; }
/// <summary>
/// This is an integer value that describes the endpoint support for renegotiation:
/// </summary>
[JsonProperty("renegSupport")]
public RenegotiationSupport RenegSupport { get; set; }
/// <summary>
/// The contents of the Strict-Transport-Security (STS) response header, if seen
/// </summary>
[Obsolete("Deprecated")]
[JsonProperty("stsResponseHeader")]
public string StrictTransportSecurityResponseHeader { get; set; }
/// <summary>
/// The maxAge parameter extracted from the STS parameters; null if STS not seen, or -1 if the specified value is invalid (e.g., not a zero or a positive integer; the maximum value currently supported is 2,147,483,647)
/// </summary>
[Obsolete("Deprecated")]
[JsonProperty("stsMaxAge")]
public int StrictTransportSecurityMaxAge { get; set; }
/// <summary>
/// True if the includeSubDomains STS parameter is set; null if STS not seen
/// </summary>
[Obsolete("Deprecated")]
[JsonProperty("stsSubdomains")]
public bool StrictTransportSecuritySubdomains { get; set; }
/// <summary>
/// The contents of the Public-Key-Pinning response header, if seen
/// </summary>
[Obsolete("Deprecated")]
[JsonProperty("pkpResponseHeader")]
public string PublicKeyPinningResponseHeader { get; set; }
/// <summary>
/// This is an integer value that describes endpoint support for session resumption.
/// </summary>
[JsonProperty("sessionResumption")]
public SessionResumptionResult SessionResumption { get; set; }
/// <summary>
/// Integer value that describes supported compression methods
/// </summary>
[JsonProperty("compressionMethods")]
public CompressionMethodsSupported CompressionMethods { get; set; }
/// <summary>
/// True if the server supports NPN
/// </summary>
[JsonProperty("supportsNpn")]
public bool SupportsNpn { get; set; }
/// <summary>
/// List of supported protocols, separated by spaces
/// </summary>
[JsonProperty("npnProtocols", NullValueHandling = NullValueHandling.Ignore)]
public string NpnProtocols { get; set; }
/// <summary>
/// Indicates support for Session Tickets
/// </summary>
[JsonProperty("sessionTickets")]
public SessionTicketsResult SessionTickets { get; set; }
/// <summary>
/// True if OCSP stapling is deployed on the server
/// </summary>
[JsonProperty("ocspStapling")]
public bool OcspStapling { get; set; }
/// <summary>
/// RevocationStatus for the stapled OCSP response.
/// </summary>
[JsonProperty("staplingRevocationStatus")]
public RevocationStatus StaplingRevocationStatus { get; set; }
/// <summary>
/// Description of the problem with the stapled OCSP response, if any.
/// </summary>
[JsonProperty("staplingRevocationErrorMessage", NullValueHandling = NullValueHandling.Ignore)]
public string StaplingRevocationErrorMessage { get; set; }
/// <summary>
/// If SNI support is required to access the web site.
/// </summary>
[JsonProperty("sniRequired")]
public bool SniRequired { get; set; }
/// <summary>
/// Status code of the final HTTP response seen. When submitting HTTP requests, redirections are followed, but only if they lead to the same hostname.
/// If this field is not available, that means the HTTP request failed.
/// </summary>
[JsonProperty("httpStatusCode")]
public int? HttpStatusCode { get; set; }
/// <summary>
/// Available on a server that responded with a redirection to some other hostname.
/// </summary>
[JsonProperty("httpForwarding", NullValueHandling = NullValueHandling.Ignore)]
public string HttpForwarding { get; set; }
/// <summary>
/// True if the server supports at least one RC4 suite.
/// </summary>
[JsonProperty("supportsRc4")]
public bool SupportsRc4 { get; set; }
/// <summary>
/// True if RC4 is used with modern clients.
/// </summary>
[JsonProperty("rc4WithModern")]
public bool Rc4WithModern { get; set; }
/// <summary>
/// True if only RC4 suites are supported.
/// </summary>
[JsonProperty("rc4Only")]
public bool Rc4Only { get; set; }
/// <summary>
/// Indicates support for Forward Secrecy
/// </summary>
[JsonProperty("forwardSecrecy")]
public ForwardSecrecyResult ForwardSecrecy { get; set; }
/// <summary>
/// Indicates protocol version intolerance issues:
/// </summary>
[JsonProperty("protocolIntolerance")]
public ProtocolIntoleranceType ProtocolIntolerance { get; set; }
/// <summary>
/// Indicates various other types of intolerance:
/// </summary>
[JsonProperty("miscIntolerance")]
public MiscIntoleranceType MiscIntolerance { get; set; }
/// <summary>
/// Client simulation details
/// </summary>
[JsonProperty("sims")]
public SimDetails Simulations { get; set; }
/// <summary>
/// True if the server is vulnerable to the Heartbleed attack.
/// </summary>
[JsonProperty("heartbleed")]
public bool Heartbleed { get; set; }
/// <summary>
/// True if the server supports the Heartbeat extension.
/// </summary>
[JsonProperty("heartbeat")]
public bool Heartbeat { get; set; }
/// <summary>
/// Results of the CVE-2014-0224 test
/// </summary>
[JsonProperty("openSslCcs")]
public OpenSslCcsResult OpenSslCcs { get; set; }
/// <summary>
/// Results of the CVE-2016-2107 test:
/// </summary>
[JsonProperty("openSSLLuckyMinus20")]
public OpenSSLLuckyMinus20Result OpenSSLLuckyMinus20 { get; set; }
/// <summary>
/// True if the endpoint is vulnerable to POODLE; false otherwise
/// </summary>
[JsonProperty("poodle")]
public bool Poodle { get; set; }
/// <summary>
/// Results of the POODLE TLS test
/// </summary>
[JsonProperty("poodleTls")]
public PoodleResult PoodleTls { get; set; }
/// <summary>
/// True if the server supports TLS_FALLBACK_SCSV, false if it doesn't. This field will not be available if the server's support
/// for TLS_FALLBACK_SCSV can't be tested because it supports only one protocol version (e.g., only TLS 1.2).
/// </summary>
[JsonProperty("fallbackScsv")]
public bool FallbackScsv { get; set; }
/// <summary>
/// True of the server is vulnerable to the FREAK attack, meaning it supports 512-bit key exchange.
/// </summary>
[JsonProperty("freak")]
public bool Freak { get; set; }
/// <summary>
/// Information about the availability of certificate transparency information (embedded SCTs):
/// </summary>
[JsonProperty("hasSct")]
public SctResult HasSct { get; set; }
/// <summary>
/// List of hex-encoded DH primes used by the server
/// </summary>
[JsonProperty("dhPrimes")]
public string[] DhPrimes { get; set; }
/// <summary>
/// Whether the server uses known DH primes:
/// </summary>
[JsonProperty("dhUsesKnownPrimes")]
public DhKnownPrimesResult DhUsesKnownPrimes { get; set; }
/// <summary>
/// True if the DH ephemeral server value is reused.
/// </summary>
[JsonProperty("dhYsReuse")]
public bool DhYsReuse { get; set; }
/// <summary>
/// True if the server uses DH parameters weaker than 1024 bits.
/// </summary>
[JsonProperty("logjam")]
public bool LogJam { get; set; }
/// <summary>
/// True if the server takes into account client preferences when deciding if to use ChaCha20 suites.
/// </summary>
[JsonProperty("chaCha20Preference")]
public bool ChaCha20Preference { get; set; }
/// <summary>
/// Server's HSTS policy. Experimental.
/// </summary>
[JsonProperty("hstsPolicy")]
public HstsPolicy HstsPolicy { get; set; }
/// <summary>
/// Information about preloaded HSTS policies.
/// </summary>
[JsonProperty("hstsPreloads")]
public List<HstsPreload> HstsPreloads { get; set; }
/// <summary>
/// Server's HPKP policy. Experimental.
/// </summary>
[JsonProperty("hpkpPolicy")]
public HpkpPolicy HpkpPolicy { get; set; }
/// <summary>
/// Server's HPKP RO (Report Only) policy. Experimental.
/// </summary>
[JsonProperty("hpkpRoPolicy")]
public HpkpPolicy HpkpRoPolicy { get; set; }
/// <summary>
/// List of drown hosts. Experimental.
/// </summary>
[JsonProperty("drownHosts")]
public List<DrownHost> DrownHosts { get; set; }
/// <summary>
/// True if error occurred in drown test.
/// </summary>
[JsonProperty("drownErrors")]
public bool DrownErrors { get; set; }
/// <summary>
/// True if server vulnerable to drown attack.
/// </summary>
[JsonProperty("drownVulnerable")]
public bool DrownVulnerable { get; set; }
public EndpointDetails()
{
Key = new Key();
Cert = new Cert();
Chain = new Chain();
Protocols = new List<Protocol>();
Suites = new Suites();
Simulations = new SimDetails();
HstsPreloads = new List<HstsPreload>();
DrownHosts = new List<DrownHost>();
}
}
}
| |
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.C;
using CppSharp.Types;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CSharp
{
public class CSharpMarshalContext : MarshalContext
{
public CSharpMarshalContext(BindingContext context, uint indentation)
: base(context, indentation)
{
}
public bool HasCodeBlock { get; set; }
}
public abstract class CSharpMarshalPrinter : MarshalPrinter<CSharpMarshalContext, CSharpTypePrinter>
{
protected CSharpMarshalPrinter(CSharpMarshalContext context)
: base(context)
{
VisitOptions.ClearFlags(VisitFlags.FunctionParameters |
VisitFlags.TemplateArguments);
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
}
public class CSharpMarshalNativeToManagedPrinter : CSharpMarshalPrinter
{
public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context)
: base(context)
{
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CSharpMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl) => true;
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (Context.MarshalKind != MarshalKind.NativeField &&
Context.MarshalKind != MarshalKind.ReturnVariableArray)
goto case ArrayType.ArraySize.Incomplete;
var arrayType = array.Type.Desugar();
if (CheckIfArrayCanBeCopiedUsingMemoryCopy(array))
{
if (Context.Context.Options.UseSpan)
Context.Return.Write($"new Span<{arrayType}>({Context.ReturnVarName}, {array.Size})");
else
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetArray<{arrayType}>({Context.ReturnVarName}, {array.Size})");
}
else if (array.Type.IsPrimitiveType(PrimitiveType.Char) && Context.Context.Options.MarshalCharAsManagedChar)
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetCharArray({Context.ReturnVarName}, {array.Size})");
else if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
if (Context.Context.Options.UseSpan)
Context.Return.Write($"Span<IntPtr>({Context.ReturnVarName}, {array.Size})");
else
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetIntPtrArray({Context.ReturnVarName}, {array.Size})");
else
{
string value = Generator.GeneratedIdentifier("value");
var supportBefore = Context.Before;
supportBefore.WriteLine($"{arrayType}[] {value} = null;");
supportBefore.WriteLine($"if ({Context.ReturnVarName} != null)");
supportBefore.WriteOpenBraceAndIndent();
supportBefore.WriteLine($"{value} = new {arrayType}[{array.Size}];");
supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
var finalArrayType = arrayType.GetPointee() ?? arrayType;
Class @class;
if (finalArrayType.TryGetClass(out @class) && @class.IsRefType)
{
if (arrayType == finalArrayType)
supportBefore.WriteLineIndent(
"{0}[i] = {1}.{2}((IntPtr)(({1}.{3}*)&({4}[i * sizeof({1}.{3})])), true, true);",
value, array.Type, Helpers.GetOrCreateInstanceIdentifier,
Helpers.InternalStruct, Context.ReturnVarName);
else
supportBefore.WriteLineIndent(
$@"{value}[i] = {finalArrayType}.{Helpers.CreateInstanceIdentifier}(({
typePrinter.IntPtrType}) {Context.ReturnVarName}[i]);");
}
else
{
supportBefore.WriteLineIndent($"{value}[i] = {Context.ReturnVarName}[i];");
}
supportBefore.UnindentAndWriteCloseBrace();
Context.Return.Write(value);
}
break;
case ArrayType.ArraySize.Incomplete:
// const char* and const char[] are the same so we can use a string
if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
array.QualifiedType.Qualifiers.IsConst)
{
var pointer = new PointerType { QualifiedPointee = array.QualifiedType };
Context.ReturnType = new QualifiedType(pointer);
return this.VisitPointerType(pointer, quals);
}
MarshalArray(array);
break;
case ArrayType.ArraySize.Variable:
Context.Return.Write(Context.ReturnVarName);
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
var pointee = pointer.Pointee.Desugar();
var finalPointee = pointer.GetFinalPointee().Desugar();
var returnType = Context.ReturnType.Type.Desugar(
resolveTemplateSubstitution: false);
if ((pointee.IsConstCharString() && (isRefParam || returnType.IsReference())) ||
(!finalPointee.IsPrimitiveType(out PrimitiveType primitive) &&
!finalPointee.IsEnumType()))
{
if (Context.MarshalKind != MarshalKind.NativeField &&
pointee.IsPointerTo(out Type type) &&
type.Desugar().TryGetClass(out Class c))
{
string ret = Generator.GeneratedIdentifier(Context.ReturnVarName);
Context.Before.WriteLine($@"{typePrinter.IntPtrType} {ret} = {
Context.ReturnVarName} == {typePrinter.IntPtrType}.Zero ? {
typePrinter.IntPtrType}.Zero : new {
typePrinter.IntPtrType}(*(void**) {Context.ReturnVarName});");
Context.ReturnVarName = ret;
}
return pointer.QualifiedPointee.Visit(this);
}
if (isRefParam)
{
Context.Return.Write(Generator.GeneratedIdentifier(param.Name));
return true;
}
if (Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
Context.Return.Write($"({pointer}) ");
if (Context.Function != null &&
Context.Function.OperatorKind == CXXOperatorKind.Subscript)
{
if (returnType.IsPrimitiveType(primitive))
{
Context.Return.Write("*");
}
else
{
var substitution = pointer.Pointee.Desugar(
resolveTemplateSubstitution: false) as TemplateParameterSubstitutionType;
if (substitution != null)
Context.Return.Write($@"({
substitution.ReplacedParameter.Parameter.Name}) (object) *");
}
}
if (new QualifiedType(pointer, quals).IsConstRefToPrimitive())
{
Context.Return.Write("*");
if (Context.MarshalKind == MarshalKind.NativeField)
Context.Return.Write($"({pointer.QualifiedPointee.Visit(typePrinter)}*) ");
}
Context.Return.Write(Context.ReturnVarName);
return true;
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("{0} != 0", Context.ReturnVarName);
return true;
}
goto default;
default:
Context.Return.Write(Context.ReturnVarName);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!(typedef.Declaration.Type.Desugar(false) is TemplateParameterSubstitutionType) &&
!VisitType(typedef, quals))
return false;
var decl = typedef.Declaration;
Type type = decl.Type.Desugar();
var functionType = type as FunctionType;
if (functionType == null && !type.IsPointerTo(out functionType))
return decl.Type.Visit(this);
var ptrName = $@"{Generator.GeneratedIdentifier("ptr")}{
Context.ParameterIndex}";
Context.Before.WriteLine($"var {ptrName} = {Context.ReturnVarName};");
var substitution = decl.Type.Desugar(false)
as TemplateParameterSubstitutionType;
if (substitution != null)
Context.Return.Write($@"({
substitution.ReplacedParameter.Parameter.Name}) (object) (");
Context.Return.Write($@"{ptrName} == IntPtr.Zero? null : {
(substitution == null ? $"({Context.ReturnType}) " :
string.Empty)}Marshal.GetDelegateForFunctionPointer({
ptrName}, typeof({typedef}))");
if (substitution != null)
Context.Return.Write(")");
return true;
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex;
Context.Before.WriteLine("var {0} = {1};", ptrName,
Context.ReturnVarName);
Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
ptrName, function.ToString());
return true;
}
public override bool VisitClassDecl(Class @class)
{
var originalClass = @class.OriginalClass ?? @class;
Type returnType = Context.ReturnType.Type.Desugar();
// if the class is an abstract impl, use the original for the object map
var qualifiedClass = originalClass.Visit(typePrinter);
var finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
Class returnedClass;
if (finalType.TryGetClass(out returnedClass) && returnedClass.IsDependent)
Context.Return.Write($"({returnType.Visit(typePrinter)}) (object) ");
// these two aren't the same for members of templates
if (Context.Function?.OriginalReturnType.Type.Desugar().IsAddress() == true ||
returnType.IsAddress())
Context.Return.Write(HandleReturnedPointer(@class, qualifiedClass));
else
{
if (Context.MarshalKind == MarshalKind.NativeField ||
Context.MarshalKind == MarshalKind.Variable ||
Context.MarshalKind == MarshalKind.ReturnVariableArray ||
!originalClass.HasNonTrivialDestructor)
{
Context.Return.Write($"{qualifiedClass}.{Helpers.CreateInstanceIdentifier}({Context.ReturnVarName})");
}
else
{
Context.Before.WriteLine($@"var __{Context.ReturnVarName} = {
qualifiedClass}.{Helpers.CreateInstanceIdentifier}({Context.ReturnVarName});");
Method dtor = originalClass.Destructors.First();
if (dtor.IsVirtual)
{
var i = VTables.GetVTableIndex(dtor);
int vtableIndex = 0;
if (Context.Context.ParserOptions.IsMicrosoftAbi)
vtableIndex = @class.Layout.VFTables.IndexOf(@class.Layout.VFTables.First(
v => v.Layout.Components.Any(c => c.Method == dtor)));
string instance = $"new {typePrinter.IntPtrType}(&{Context.ReturnVarName})";
Context.Before.WriteLine($@"var __vtables = new IntPtr[] {{ {
string.Join(", ", originalClass.Layout.VTablePointers.Select(
x => $"*({typePrinter.IntPtrType}*) ({instance} + {x.Offset})"))} }};");
Context.Before.WriteLine($@"var __slot = *({typePrinter.IntPtrType}*) (__vtables[{
vtableIndex}] + {i} * sizeof({typePrinter.IntPtrType}));");
Context.Before.Write($"Marshal.GetDelegateForFunctionPointer<{dtor.FunctionType}>(__slot)({instance}");
if (dtor.GatherInternalParams(Context.Context.ParserOptions.IsItaniumLikeAbi).Count > 1)
{
Context.Before.Write(", 0");
}
Context.Before.WriteLine(");");
}
else
{
string suffix = string.Empty;
var specialization = @class as ClassTemplateSpecialization;
if (specialization != null)
suffix = Helpers.GetSuffixFor(specialization);
Context.Before.WriteLine($@"{typePrinter.PrintNative(originalClass)}.dtor{
suffix}(new {typePrinter.IntPtrType}(&{Context.ReturnVarName}));");
}
Context.Return.Write($"__{Context.ReturnVarName}");
}
}
return true;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("{0}", Context.ReturnVarName);
return true;
}
public override bool VisitParameterDecl(Parameter parameter)
{
if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn)
return base.VisitParameterDecl(parameter);
var ctx = new CSharpMarshalContext(Context.Context, Context.Indentation)
{
ReturnType = Context.ReturnType,
ReturnVarName = Context.ReturnVarName
};
var marshal = new CSharpMarshalNativeToManagedPrinter(ctx);
parameter.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(ctx.Before))
Context.Before.WriteLine(ctx.Before);
if (!string.IsNullOrWhiteSpace(ctx.Return) &&
!parameter.Type.IsPrimitiveTypeConvertibleToRef())
{
Context.Before.WriteLine("var _{0} = {1};", parameter.Name,
ctx.Return);
}
Context.Return.Write("{0}{1}",
parameter.Type.IsPrimitiveTypeConvertibleToRef() ? "ref *" : "_", parameter.Name);
return true;
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
Type returnType = Context.ReturnType.Type.Desugar();
Type finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
if (finalType.IsDependent)
Context.Return.Write($"({param.ReplacedParameter.Parameter.Name}) (object) ");
Type replacement = param.Replacement.Type.Desugar();
if (replacement.IsPointerToPrimitiveType() && !replacement.IsConstCharString())
Context.Return.Write($"({typePrinter.IntPtrType}) ");
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
private string HandleReturnedPointer(Class @class, string qualifiedClass)
{
var originalClass = @class.OriginalClass ?? @class;
var ret = Generator.GeneratedIdentifier("result") + Context.ParameterIndex;
if (originalClass.IsRefType)
{
var dtor = originalClass.Destructors.FirstOrDefault();
var dtorVirtual = (dtor != null && dtor.IsVirtual);
var cache = dtorVirtual && Context.Parameter == null;
var skipVTables = dtorVirtual && Context.Parameter != null;
Context.Before.WriteLine("var {0} = {1}.__GetOrCreateInstance({2}, {3}{4});",
ret, qualifiedClass, Context.ReturnVarName, cache ? "true" : "false", skipVTables ? ", skipVTables: true" : string.Empty);
}
else
{
Context.Before.WriteLine("var {0} = {1} != IntPtr.Zero ? {2}.{3}({4}) : default;",
ret, Context.ReturnVarName, qualifiedClass, Helpers.CreateInstanceIdentifier, Context.ReturnVarName);
}
return ret;
}
private void MarshalArray(ArrayType array)
{
Type arrayType = array.Type.Desugar();
if (arrayType.IsPrimitiveType() ||
arrayType.IsPointerToPrimitiveType() ||
Context.MarshalKind != MarshalKind.GenericDelegate)
{
Context.Return.Write(Context.ReturnVarName);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.ReturnVarName);
var intermediateArrayType = arrayType.Visit(typePrinter);
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if ({Context.ReturnVarName} is null)");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteOpenBraceAndIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.ReturnVarName}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
if (arrayType.IsAddress())
{
Context.Before.WriteOpenBraceAndIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.ReturnVarName}[i];");
var intPtrZero = $"{typePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = {element} == {
intPtrZero} ? null : {intermediateArrayType}.{
Helpers.CreateInstanceIdentifier}({element});");
Context.Before.UnindentAndWriteCloseBrace();
}
else
Context.Before.WriteLineIndent($@"{intermediateArray}[i] = {
intermediateArrayType}.{Helpers.CreateInstanceIdentifier}({
Context.ReturnVarName}[i]);");
Context.Before.UnindentAndWriteCloseBrace();
Context.Return.Write(intermediateArray);
}
public bool CheckIfArrayCanBeCopiedUsingMemoryCopy(ArrayType array)
{
return array.Type.IsPrimitiveType(out var primitive) &&
(!Context.Context.Options.MarshalCharAsManagedChar || primitive != PrimitiveType.Char);
}
}
public class CSharpMarshalManagedToNativePrinter : CSharpMarshalPrinter
{
public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context)
: base(context)
{
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CSharpMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl) => true;
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (string.IsNullOrEmpty(Context.ReturnVarName))
goto case ArrayType.ArraySize.Incomplete;
var supportBefore = Context.Before;
supportBefore.WriteLine($"if ({Context.ArgName} != null)");
supportBefore.WriteOpenBraceAndIndent();
Class @class;
var arrayType = array.Type.Desugar();
var finalArrayType = arrayType.GetPointee() ?? arrayType;
if (finalArrayType.TryGetClass(out @class) && @class.IsRefType)
{
supportBefore.WriteLine($"if (value.Length != {array.Size})");
ThrowArgumentOutOfRangeException();
}
supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
if (@class != null && @class.IsRefType)
{
if (finalArrayType == arrayType)
supportBefore.WriteLineIndent(
"*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};",
Context.ReturnVarName, arrayType, Helpers.InternalStruct,
Context.ArgName, Helpers.InstanceIdentifier);
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = ({
(Context.Context.TargetInfo.PointerWidth == 64 ? "long" : "int")}) {
Context.ArgName}[i].{Helpers.InstanceIdentifier};");
}
else
{
if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = (byte)({
Context.ArgName}[i] ? 1 : 0);");
else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = global::System.Convert.ToSByte({
Context.ArgName}[i]);");
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = {
Context.ArgName}[i]{
(arrayType.IsPointerToPrimitiveType(PrimitiveType.Void) ?
".ToPointer()" : string.Empty)};");
}
supportBefore.UnindentAndWriteCloseBrace();
break;
case ArrayType.ArraySize.Incomplete:
MarshalArray(array);
break;
default:
Context.Return.Write("null");
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
var pointee = pointer.Pointee.Desugar();
if (pointee.IsConstCharString())
{
if (param.IsOut)
{
MarshalString(pointee);
Context.Return.Write($"{typePrinter.IntPtrType}.Zero");
Context.ArgumentPrefix.Write("&");
return true;
}
if (param.IsInOut)
{
MarshalString(pointee);
pointer.QualifiedPointee.Visit(this);
Context.ArgumentPrefix.Write("&");
return true;
}
if (pointer.IsReference)
{
Context.Return.Write($@"({typePrinter.PrintNative(
pointee.GetQualifiedPointee())}*) ");
pointer.QualifiedPointee.Visit(this);
Context.ArgumentPrefix.Write("&");
return true;
}
}
var finalPointee = (pointee.GetFinalPointee() ?? pointee).Desugar();
if (finalPointee.IsPrimitiveType(out PrimitiveType primitive) ||
finalPointee.IsEnumType())
{
if (isRefParam)
{
var local = Generator.GeneratedIdentifier($@"{
param.Name}{Context.ParameterIndex}");
Context.Before.WriteLine($@"fixed ({
pointer.Visit(typePrinter)} {local} = &{param.Name})");
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write(local);
return true;
}
bool isConst = quals.IsConst || pointer.QualifiedPointee.Qualifiers.IsConst ||
pointer.GetFinalQualifiedPointee().Qualifiers.IsConst;
if (Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
{
Context.Return.Write($"({typePrinter.PrintNative(pointer)})");
if (isConst)
Context.Return.Write("&");
Context.Return.Write(param.Name);
return true;
}
pointer.QualifiedPointee.Visit(this);
if (Context.Parameter.IsIndirect)
Context.ArgumentPrefix.Write("&");
bool isVoid = primitive == PrimitiveType.Void && pointer.IsReference() && isConst;
if (pointer.Pointee.Desugar(false) is TemplateParameterSubstitutionType || isVoid)
{
var local = Generator.GeneratedIdentifier($@"{
param.Name}{Context.ParameterIndex}");
Context.Before.WriteLine($"var {local} = {Context.Return};");
Context.Return.StringBuilder.Clear();
Context.Return.Write(local);
}
if (new QualifiedType(pointer, quals).IsConstRefToPrimitive())
Context.Return.StringBuilder.Insert(0, '&');
return true;
}
string arg = Generator.GeneratedIdentifier(Context.ArgName);
if (pointee.TryGetClass(out Class @class) && @class.IsValueType)
{
if (Context.Parameter.Usage == ParameterUsage.Out)
{
var qualifiedIdentifier = (@class.OriginalClass ?? @class).Visit(typePrinter);
Context.Before.WriteLine("var {0} = new {1}.{2}();",
arg, qualifiedIdentifier, Helpers.InternalStruct);
}
else
{
Context.Before.WriteLine("var {0} = {1}.{2};",
arg, Context.Parameter.Name, Helpers.InstanceIdentifier);
}
Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
return true;
}
if (pointee.IsPointerTo(out Type type) &&
type.Desugar().TryGetClass(out Class c))
{
pointer.QualifiedPointee.Visit(this);
Context.Before.WriteLine($"var {arg} = {Context.Return};");
Context.Return.StringBuilder.Clear();
Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("(byte) ({0} ? 1 : 0)", Context.Parameter.Name);
return true;
}
goto default;
default:
Context.Return.Write(Context.Parameter.Name);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!VisitType(typedef, quals))
return false;
return typedef.Declaration.Type.Visit(this);
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
var replacement = param.Replacement.Type.Desugar();
if ((replacement.IsPrimitiveType() ||
replacement.IsPointerToPrimitiveType() ||
replacement.IsEnum()) &&
!replacement.IsConstCharString())
{
Context.Return.Write($"({replacement}) ");
if (replacement.IsPointerToPrimitiveType())
Context.Return.Write($"({typePrinter.IntPtrType}) ");
Context.Return.Write("(object) ");
}
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
Context.Return.Write(param.Parameter.Name);
return true;
}
public override bool VisitClassDecl(Class @class)
{
if (!VisitDeclaration(@class))
return false;
if (@class.IsValueType)
{
MarshalValueClass();
}
else
{
MarshalRefClass(@class);
}
return true;
}
private void MarshalRefClass(Class @class)
{
var method = Context.Function as Method;
if (method != null
&& method.Conversion == MethodConversionKind.FunctionToInstanceMethod
&& Context.ParameterIndex == 0)
{
Context.Return.Write("{0}", Helpers.InstanceIdentifier);
return;
}
string param = Context.Parameter.Name;
Type type = Context.Parameter.Type.Desugar(resolveTemplateSubstitution: false);
string paramInstance;
Class @interface;
var finalType = type.GetFinalPointee() ?? type;
var templateType = finalType as TemplateParameterSubstitutionType;
type = Context.Parameter.Type.Desugar();
if (templateType != null)
param = $"(({@class.Visit(typePrinter)}) (object) {param})";
if (finalType.TryGetClass(out @interface) &&
@interface.IsInterface)
paramInstance = $"{param}.__PointerTo{@interface.OriginalClass.Name}";
else
paramInstance = $"{param}.{Helpers.InstanceIdentifier}";
if (!type.IsAddress())
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent(
$@"throw new global::System.ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is passed by value."");");
var realClass = @class.OriginalClass ?? @class;
var qualifiedIdentifier = typePrinter.PrintNative(realClass);
Context.ArgumentPrefix.Write($"*({qualifiedIdentifier}*) ");
Context.Return.Write(paramInstance);
return;
}
Class decl;
if (type.TryGetClass(out decl) && decl.IsValueType)
{
Context.Return.Write(paramInstance);
return;
}
if (type.IsPointer())
{
if (Context.Parameter.IsIndirect)
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent(
$@"throw new global::System.ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is passed by value."");");
Context.Return.Write(paramInstance);
}
else
{
Context.Return.Write("{0}{1}",
method != null && method.OperatorKind == CXXOperatorKind.EqualEqual
? string.Empty
: $"{param} is null ? {typePrinter.IntPtrType}.Zero : ",
paramInstance);
}
return;
}
if (method == null ||
// redundant for comparison operators, they are handled in a special way
(method.OperatorKind != CXXOperatorKind.EqualEqual &&
method.OperatorKind != CXXOperatorKind.ExclaimEqual))
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent(
$@"throw new global::System.ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is a C++ reference (&)."");",
param);
}
Context.Return.Write(paramInstance);
}
private void MarshalValueClass()
{
Context.Return.Write("{0}.{1}", Context.Parameter.Name, Helpers.InstanceIdentifier);
}
public override bool VisitFieldDecl(Field field)
{
if (!VisitDeclaration(field))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
return field.Type.Visit(this, field.QualifiedType.Qualifiers);
}
public override bool VisitProperty(Property property)
{
if (!VisitDeclaration(property))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
return base.VisitProperty(property);
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write(Context.Parameter.Name);
return true;
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return VisitClassDecl(template.TemplatedClass);
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
Context.Return.Write("{0} == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate({0})",
Context.Parameter.Name);
return true;
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
private void ThrowArgumentOutOfRangeException()
{
Context.Before.WriteLineIndent(
"throw new ArgumentOutOfRangeException(\"{0}\", " +
"\"The dimensions of the provided array don't match the required size.\");",
Context.Parameter.Name);
}
private void MarshalArray(ArrayType arrayType)
{
if (arrayType.SizeType == ArrayType.ArraySize.Constant)
{
Context.Before.WriteLine("if ({0} == null || {0}.Length != {1})",
Context.Parameter.Name, arrayType.Size);
ThrowArgumentOutOfRangeException();
}
var elementType = arrayType.Type.Desugar();
if (elementType.IsPrimitiveType() ||
elementType.IsPointerToPrimitiveType())
{
if (Context.Context.Options.UseSpan && !elementType.IsConstCharString())
{
var local = Generator.GeneratedIdentifier($@"{
Context.Parameter.Name}{Context.ParameterIndex}");
Context.Before.WriteLine($@"fixed ({
typePrinter.PrintNative(elementType)}* {local} = &MemoryMarshal.GetReference({Context.Parameter.Name}))");
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write(local);
}
else
Context.Return.Write(Context.Parameter.Name);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.Parameter.Name);
var intermediateArrayType = typePrinter.PrintNative(elementType);
if (Context.Context.Options.UseSpan)
Context.Before.WriteLine($"Span<{intermediateArrayType}> {intermediateArray};");
else
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if ({Context.Parameter.Name} == null)");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteOpenBraceAndIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.Parameter.Name}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
Context.Before.WriteOpenBraceAndIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.Parameter.Name}[i];");
if (elementType.IsAddress())
{
var intPtrZero = $"{typePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = {
element} is null ? {intPtrZero} : {element}.{Helpers.InstanceIdentifier};");
}
else
Context.Before.WriteLine($@"{intermediateArray}[i] = {
element} is null ? new {intermediateArrayType}() : *({
intermediateArrayType}*) {element}.{Helpers.InstanceIdentifier};");
Context.Before.UnindentAndWriteCloseBrace();
Context.Before.UnindentAndWriteCloseBrace();
if (Context.Context.Options.UseSpan)
{
var local = Generator.GeneratedIdentifier($@"{
intermediateArray}{Context.ParameterIndex}");
Context.Before.WriteLine($@"fixed ({
typePrinter.PrintNative(elementType)}* {local} = &MemoryMarshal.GetReference({intermediateArray}))");
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write(local);
}
else
Context.Return.Write(intermediateArray);
}
private void MarshalString(Type pointee)
{
var marshal = new CSharpMarshalNativeToManagedPrinter(Context);
Context.ReturnVarName = Context.ArgName;
Context.ReturnType = Context.Parameter.QualifiedType;
pointee.Visit(marshal);
Context.Cleanup.WriteLine($@"{Context.Parameter.Name} = {
marshal.Context.Return};");
Context.Return.StringBuilder.Clear();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using OpenSim.Tests.Common.Setup;
namespace OpenSim.Region.CoreModules.World.Land.Tests
{
[TestFixture]
public class PrimCountModuleTests
{
protected UUID m_userId = new UUID("00000000-0000-0000-0000-100000000000");
protected UUID m_groupId = new UUID("00000000-0000-0000-8888-000000000000");
protected UUID m_otherUserId = new UUID("99999999-9999-9999-9999-999999999999");
protected TestScene m_scene;
protected PrimCountModule m_pcm;
/// <summary>
/// A parcel that covers the entire sim except for a 1 unit wide strip on the eastern side.
/// </summary>
protected ILandObject m_lo;
/// <summary>
/// A parcel that covers just the eastern strip of the sim.
/// </summary>
protected ILandObject m_lo2;
[SetUp]
public void SetUp()
{
m_pcm = new PrimCountModule();
LandManagementModule lmm = new LandManagementModule();
m_scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(m_scene, lmm, m_pcm);
int xParcelDivider = (int)Constants.RegionSize - 1;
ILandObject lo = new LandObject(m_userId, false, m_scene);
lo.LandData.Name = "m_lo";
lo.SetLandBitmap(
lo.GetSquareLandBitmap(0, 0, xParcelDivider, (int)Constants.RegionSize));
m_lo = lmm.AddLandObject(lo);
ILandObject lo2 = new LandObject(m_userId, false, m_scene);
lo2.SetLandBitmap(
lo2.GetSquareLandBitmap(xParcelDivider, 0, (int)Constants.RegionSize, (int)Constants.RegionSize));
lo2.LandData.Name = "m_lo2";
m_lo2 = lmm.AddLandObject(lo2);
}
/// <summary>
/// Test that counts before we do anything are correct.
/// </summary>
[Test]
public void TestInitialCounts()
{
IPrimCounts pc = m_lo.PrimCounts;
Assert.That(pc.Owner, Is.EqualTo(0));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(0));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(0));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(0));
}
/// <summary>
/// Test count after a parcel owner owned object is added.
/// </summary>
[Test]
public void TestAddOwnerObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
IPrimCounts pc = m_lo.PrimCounts;
SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01);
m_scene.AddNewSceneObject(sog, false);
Assert.That(pc.Owner, Is.EqualTo(3));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(3));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(3));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(3));
// Add a second object and retest
SceneObjectGroup sog2 = SceneSetupHelpers.CreateSceneObject(2, m_userId, "b", 0x10);
m_scene.AddNewSceneObject(sog2, false);
Assert.That(pc.Owner, Is.EqualTo(5));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(5));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(5));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(5));
}
/// <summary>
/// Test count after a parcel owner owned copied object is added.
/// </summary>
[Test]
public void TestCopyOwnerObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
IPrimCounts pc = m_lo.PrimCounts;
SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01);
m_scene.AddNewSceneObject(sog, false);
m_scene.SceneGraph.DuplicateObject(sog.LocalId, Vector3.Zero, 0, m_userId, UUID.Zero, Quaternion.Identity);
Assert.That(pc.Owner, Is.EqualTo(6));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(6));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(6));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(6));
}
/// <summary>
/// Test that parcel counts update correctly when an object is moved between parcels, where that movement
/// is not done directly by the user/
/// </summary>
[Test]
public void TestMoveOwnerObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01);
m_scene.AddNewSceneObject(sog, false);
SceneObjectGroup sog2 = SceneSetupHelpers.CreateSceneObject(2, m_userId, "b", 0x10);
m_scene.AddNewSceneObject(sog2, false);
// Move the first scene object to the eastern strip parcel
sog.AbsolutePosition = new Vector3(254, 2, 2);
IPrimCounts pclo1 = m_lo.PrimCounts;
Assert.That(pclo1.Owner, Is.EqualTo(2));
Assert.That(pclo1.Group, Is.EqualTo(0));
Assert.That(pclo1.Others, Is.EqualTo(0));
Assert.That(pclo1.Total, Is.EqualTo(2));
Assert.That(pclo1.Selected, Is.EqualTo(0));
Assert.That(pclo1.Users[m_userId], Is.EqualTo(2));
Assert.That(pclo1.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pclo1.Simulator, Is.EqualTo(5));
IPrimCounts pclo2 = m_lo2.PrimCounts;
Assert.That(pclo2.Owner, Is.EqualTo(3));
Assert.That(pclo2.Group, Is.EqualTo(0));
Assert.That(pclo2.Others, Is.EqualTo(0));
Assert.That(pclo2.Total, Is.EqualTo(3));
Assert.That(pclo2.Selected, Is.EqualTo(0));
Assert.That(pclo2.Users[m_userId], Is.EqualTo(3));
Assert.That(pclo2.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pclo2.Simulator, Is.EqualTo(5));
// Now move it back again
sog.AbsolutePosition = new Vector3(2, 2, 2);
Assert.That(pclo1.Owner, Is.EqualTo(5));
Assert.That(pclo1.Group, Is.EqualTo(0));
Assert.That(pclo1.Others, Is.EqualTo(0));
Assert.That(pclo1.Total, Is.EqualTo(5));
Assert.That(pclo1.Selected, Is.EqualTo(0));
Assert.That(pclo1.Users[m_userId], Is.EqualTo(5));
Assert.That(pclo1.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pclo1.Simulator, Is.EqualTo(5));
Assert.That(pclo2.Owner, Is.EqualTo(0));
Assert.That(pclo2.Group, Is.EqualTo(0));
Assert.That(pclo2.Others, Is.EqualTo(0));
Assert.That(pclo2.Total, Is.EqualTo(0));
Assert.That(pclo2.Selected, Is.EqualTo(0));
Assert.That(pclo2.Users[m_userId], Is.EqualTo(0));
Assert.That(pclo2.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pclo2.Simulator, Is.EqualTo(5));
}
/// <summary>
/// Test count after a parcel owner owned object is removed.
/// </summary>
[Test]
public void TestRemoveOwnerObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
IPrimCounts pc = m_lo.PrimCounts;
m_scene.AddNewSceneObject(SceneSetupHelpers.CreateSceneObject(1, m_userId, "a", 0x1), false);
SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_userId, "b", 0x10);
m_scene.AddNewSceneObject(sogToDelete, false);
m_scene.DeleteSceneObject(sogToDelete, false);
Assert.That(pc.Owner, Is.EqualTo(1));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(1));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(1));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(1));
}
[Test]
public void TestAddGroupObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
m_lo.DeedToGroup(m_groupId);
IPrimCounts pc = m_lo.PrimCounts;
SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_otherUserId, "a", 0x01);
sog.GroupID = m_groupId;
m_scene.AddNewSceneObject(sog, false);
Assert.That(pc.Owner, Is.EqualTo(0));
Assert.That(pc.Group, Is.EqualTo(3));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(3));
Assert.That(pc.Selected, Is.EqualTo(0));
// Is this desired behaviour? Not totally sure.
Assert.That(pc.Users[m_userId], Is.EqualTo(0));
Assert.That(pc.Users[m_groupId], Is.EqualTo(0));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(3));
Assert.That(pc.Simulator, Is.EqualTo(3));
}
/// <summary>
/// Test count after a parcel owner owned object is removed.
/// </summary>
[Test]
public void TestRemoveGroupObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
m_lo.DeedToGroup(m_groupId);
IPrimCounts pc = m_lo.PrimCounts;
SceneObjectGroup sogToKeep = SceneSetupHelpers.CreateSceneObject(1, m_userId, "a", 0x1);
sogToKeep.GroupID = m_groupId;
m_scene.AddNewSceneObject(sogToKeep, false);
SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_userId, "b", 0x10);
m_scene.AddNewSceneObject(sogToDelete, false);
m_scene.DeleteSceneObject(sogToDelete, false);
Assert.That(pc.Owner, Is.EqualTo(0));
Assert.That(pc.Group, Is.EqualTo(1));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(1));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(1));
Assert.That(pc.Users[m_groupId], Is.EqualTo(0));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(1));
}
[Test]
public void TestAddOthersObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
IPrimCounts pc = m_lo.PrimCounts;
SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_otherUserId, "a", 0x01);
m_scene.AddNewSceneObject(sog, false);
Assert.That(pc.Owner, Is.EqualTo(0));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(3));
Assert.That(pc.Total, Is.EqualTo(3));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(0));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(3));
Assert.That(pc.Simulator, Is.EqualTo(3));
}
[Test]
public void TestRemoveOthersObject()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
IPrimCounts pc = m_lo.PrimCounts;
m_scene.AddNewSceneObject(SceneSetupHelpers.CreateSceneObject(1, m_otherUserId, "a", 0x1), false);
SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_otherUserId, "b", 0x10);
m_scene.AddNewSceneObject(sogToDelete, false);
m_scene.DeleteSceneObject(sogToDelete, false);
Assert.That(pc.Owner, Is.EqualTo(0));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(1));
Assert.That(pc.Total, Is.EqualTo(1));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(0));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(1));
Assert.That(pc.Simulator, Is.EqualTo(1));
}
/// <summary>
/// Test the count is correct after is has been tainted.
/// </summary>
[Test]
public void TestTaint()
{
TestHelper.InMethod();
IPrimCounts pc = m_lo.PrimCounts;
SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01);
m_scene.AddNewSceneObject(sog, false);
m_pcm.TaintPrimCount();
Assert.That(pc.Owner, Is.EqualTo(3));
Assert.That(pc.Group, Is.EqualTo(0));
Assert.That(pc.Others, Is.EqualTo(0));
Assert.That(pc.Total, Is.EqualTo(3));
Assert.That(pc.Selected, Is.EqualTo(0));
Assert.That(pc.Users[m_userId], Is.EqualTo(3));
Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0));
Assert.That(pc.Simulator, Is.EqualTo(3));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
public static void ZeroLengthIndexOfAny_TwoInteger()
{
var sp = new Span<int>(Array.Empty<int>());
int idx = sp.IndexOfAny(0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfAny_TwoInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
var span = new Span<int>(a);
int[] targets = { default, 99 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
int target0 = targets[index];
int target1 = targets[(index + 1) % 2];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchIndexOfAny_TwoInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = i + 1;
}
var span = new Span<int>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
int target0 = a[targetIndex];
int target1 = 0;
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
int target0 = a[targetIndex + index];
int target1 = a[targetIndex + (index + 1) % 2];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
int target0 = 0;
int target1 = a[targetIndex];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
}
}
[Fact]
public static void TestNoMatchIndexOfAny_TwoInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
int target0 = rnd.Next(1, 256);
int target1 = rnd.Next(1, 256);
var span = new Span<int>(a);
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchIndexOfAny_TwoInteger()
{
for (int length = 3; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
int val = i + 1;
a[i] = val == 200 ? 201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
var span = new Span<int>(a);
int idx = span.IndexOfAny(200, 200);
Assert.Equal(length - 3, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_TwoInteger()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 98;
var span = new Span<int>(a, 1, length - 1);
int index = span.IndexOfAny(99, 98);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 99;
var span = new Span<int>(a, 1, length - 1);
int index = span.IndexOfAny(99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfAny_ThreeInteger()
{
var sp = new Span<int>(Array.Empty<int>());
int idx = sp.IndexOfAny(0, 0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfAny_ThreeInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
var span = new Span<int>(a);
int[] targets = { default, 99, 98 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
int target0 = targets[index];
int target1 = targets[(index + 1) % 2];
int target2 = targets[(index + 1) % 3];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchIndexOfAny_ThreeInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = i + 1;
}
var span = new Span<int>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
int target0 = a[targetIndex];
int target1 = 0;
int target2 = 0;
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
int index = rnd.Next(0, 3);
int target0 = a[targetIndex + index];
int target1 = a[targetIndex + (index + 1) % 2];
int target2 = a[targetIndex + (index + 1) % 3];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
int target0 = 0;
int target1 = 0;
int target2 = a[targetIndex];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
}
}
[Fact]
public static void TestNoMatchIndexOfAny_ThreeInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
int target0 = rnd.Next(1, 256);
int target1 = rnd.Next(1, 256);
int target2 = rnd.Next(1, 256);
var span = new Span<int>(a);
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchIndexOfAny_ThreeInteger()
{
for (int length = 4; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
int val = i + 1;
a[i] = val == 200 ? 201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
var span = new Span<int>(a);
int idx = span.IndexOfAny(200, 200, 200);
Assert.Equal(length - 4, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ThreeInteger()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 98;
var span = new Span<int>(a, 1, length - 1);
int index = span.IndexOfAny(99, 98, 99);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 99;
var span = new Span<int>(a, 1, length - 1);
int index = span.IndexOfAny(99, 99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfAny_ManyInteger()
{
var sp = new Span<int>(Array.Empty<int>());
var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, 0 });
int idx = sp.IndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<int>(new int[] { });
idx = sp.IndexOfAny(values);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfAny_ManyInteger()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
var span = new Span<int>(a);
var values = new ReadOnlySpan<int>(new int[] { default, 99, 98, 0 });
for (int i = 0; i < length; i++)
{
int idx = span.IndexOfAny(values);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchIndexOfAny_ManyInteger()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = i + 1;
}
var span = new Span<int>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], 0, 0, 0 });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
int index = rnd.Next(0, 4) == 0 ? 0 : 1;
var values = new ReadOnlySpan<int>(new int[]
{
a[targetIndex + index],
a[targetIndex + (index + 1) % 2],
a[targetIndex + (index + 1) % 3],
a[targetIndex + (index + 1) % 4]
});
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, a[targetIndex] });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerIndexOfAny_ManyInteger()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
var a = new int[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
continue;
}
a[i] = 255;
}
var span = new Span<int>(a);
var targets = new int[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
continue;
}
targets[i] = rnd.Next(1, 255);
}
var values = new ReadOnlySpan<int>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchIndexOfAny_ManyInteger()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length];
var targets = new int[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256);
}
var span = new Span<int>(a);
var values = new ReadOnlySpan<int>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerIndexOfAny_ManyInteger()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length];
var targets = new int[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256);
}
var span = new Span<int>(a);
var values = new ReadOnlySpan<int>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchIndexOfAny_ManyInteger()
{
for (int length = 5; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
int val = i + 1;
a[i] = val == 200 ? 201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
a[length - 5] = 200;
var span = new Span<int>(a);
var values = new ReadOnlySpan<int>(new int[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 });
int idx = span.IndexOfAny(values);
Assert.Equal(length - 5, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ManyInteger()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 98;
var span = new Span<int>(a, 1, length - 1);
var values = new Span<int>(new int[] { 99, 98, 99, 98, 99, 98 });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 99;
var span = new Span<int>(a, 1, length - 1);
var values = new ReadOnlySpan<int>(new int[] { 99, 99, 99, 99, 99, 99 });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfAny_TwoString()
{
var sp = new Span<string>(Array.Empty<string>());
int idx = sp.IndexOfAny("0", "0");
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfAny_TwoString()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
var tempSpan = new Span<string>(a);
tempSpan.Fill("");
Span<string> span = tempSpan;
string[] targets = { "", "99" };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
string target0 = targets[index];
string target1 = targets[(index + 1) % 2];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchIndexOfAny_TwoString()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
a[i] = (i + 1).ToString();
}
var span = new Span<string>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
string target0 = a[targetIndex];
string target1 = "0";
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
string target0 = a[targetIndex + index];
string target1 = a[targetIndex + (index + 1) % 2];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
string target0 = "0";
string target1 = a[targetIndex + 1];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
}
}
[Fact]
public static void TestNoMatchIndexOfAny_TwoString()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
string target0 = rnd.Next(1, 256).ToString();
string target1 = rnd.Next(1, 256).ToString();
var span = new Span<string>(a);
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchIndexOfAny_TwoString()
{
for (int length = 3; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
string val = (i + 1).ToString();
a[i] = val == "200" ? "201" : val;
}
a[length - 1] = "200";
a[length - 2] = "200";
a[length - 3] = "200";
var span = new Span<string>(a);
int idx = span.IndexOfAny("200", "200");
Assert.Equal(length - 3, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_TwoString()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "98";
var span = new Span<string>(a, 1, length - 1);
int index = span.IndexOfAny("99", "98");
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "99";
var span = new Span<string>(a, 1, length - 1);
int index = span.IndexOfAny("99", "99");
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOf_ThreeString()
{
var sp = new Span<string>(Array.Empty<string>());
int idx = sp.IndexOfAny("0", "0", "0");
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfAny_ThreeString()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
var tempSpan = new Span<string>(a);
tempSpan.Fill("");
Span<string> span = tempSpan;
string[] targets = { "", "99", "98" };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
string target0 = targets[index];
string target1 = targets[(index + 1) % 2];
string target2 = targets[(index + 1) % 3];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchIndexOfAny_ThreeString()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
a[i] = (i + 1).ToString();
}
var span = new Span<string>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
string target0 = a[targetIndex];
string target1 = "0";
string target2 = "0";
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
int index = rnd.Next(0, 3) == 0 ? 0 : 1;
string target0 = a[targetIndex + index];
string target1 = a[targetIndex + (index + 1) % 2];
string target2 = a[targetIndex + (index + 1) % 3];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
string target0 = "0";
string target1 = "0";
string target2 = a[targetIndex];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
}
}
[Fact]
public static void TestNoMatchIndexOfAny_ThreeString()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
string target0 = rnd.Next(1, 256).ToString();
string target1 = rnd.Next(1, 256).ToString();
string target2 = rnd.Next(1, 256).ToString();
var span = new Span<string>(a);
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchIndexOfAny_ThreeString()
{
for (int length = 4; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
string val = (i + 1).ToString();
a[i] = val == "200" ? "201" : val;
}
a[length - 1] = "200";
a[length - 2] = "200";
a[length - 3] = "200";
a[length - 4] = "200";
var span = new Span<string>(a);
int idx = span.IndexOfAny("200", "200", "200");
Assert.Equal(length - 4, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ThreeString()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "98";
var span = new Span<string>(a, 1, length - 1);
int index = span.IndexOfAny("99", "98", "99");
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "99";
var span = new Span<string>(a, 1, length - 1);
int index = span.IndexOfAny("99", "99", "99");
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfAny_ManyString()
{
var sp = new Span<string>(Array.Empty<string>());
var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", "0" });
int idx = sp.IndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<string>(new string[] { });
idx = sp.IndexOfAny(values);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfAny_ManyString()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
var tempSpan = new Span<string>(a);
tempSpan.Fill("");
Span<string> span = tempSpan;
var values = new ReadOnlySpan<string>(new string[] { "", "99", "98", "0" });
for (int i = 0; i < length; i++)
{
int idx = span.IndexOfAny(values);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchIndexOfAny_ManyString()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
a[i] = (i + 1).ToString();
}
var span = new Span<string>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], "0", "0", "0" });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
int index = rnd.Next(0, 4) == 0 ? 0 : 1;
var values = new ReadOnlySpan<string>(new string[]
{
a[targetIndex + index],
a[targetIndex + (index + 1) % 2],
a[targetIndex + (index + 1) % 3],
a[targetIndex + (index + 1) % 4]
});
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", a[targetIndex] });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerIndexOfAny_ManyString()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
var a = new string[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
a[i] = "val";
continue;
}
a[i] = "255";
}
var span = new Span<string>(a);
var targets = new string[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
targets[i] = "val";
continue;
}
targets[i] = rnd.Next(1, 255).ToString();
}
var values = new ReadOnlySpan<string>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchIndexOfAny_ManyString()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length];
var targets = new string[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256).ToString();
}
var span = new Span<string>(a);
var values = new ReadOnlySpan<string>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerIndexOfAny_ManyString()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length];
var targets = new string[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256).ToString();
}
var span = new Span<string>(a);
var values = new ReadOnlySpan<string>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchIndexOfAny_ManyString()
{
for (int length = 5; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
string val = (i + 1).ToString();
a[i] = val == "200" ? "201" : val;
}
a[length - 1] = "200";
a[length - 2] = "200";
a[length - 3] = "200";
a[length - 4] = "200";
a[length - 5] = "200";
var span = new Span<string>(a);
var values = new ReadOnlySpan<string>(new string[] { "200", "200", "200", "200", "200", "200", "200", "200", "200" });
int idx = span.IndexOfAny(values);
Assert.Equal(length - 5, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ManyString()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "98";
var span = new Span<string>(a, 1, length - 1);
var values = new ReadOnlySpan<string>(new string[] { "99", "98", "99", "98", "99", "98" });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "99";
var span = new Span<string>(a, 1, length - 1);
var values = new ReadOnlySpan<string>(new string[] { "99", "99", "99", "99", "99", "99" });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
}
[Theory]
[MemberData(nameof(TestHelpers.IndexOfAnyNullSequenceData), MemberType = typeof(TestHelpers))]
public static void IndexOfAnyNullSequence_String(string[] spanInput, string[] searchInput, int expected)
{
Span<string> theStrings = spanInput;
Assert.Equal(expected, theStrings.IndexOfAny(searchInput));
Assert.Equal(expected, theStrings.IndexOfAny((ReadOnlySpan<string>)searchInput));
if (searchInput != null)
{
if (searchInput.Length >= 3)
{
Assert.Equal(expected, theStrings.IndexOfAny(searchInput[0], searchInput[1], searchInput[2]));
}
if (searchInput.Length >= 2)
{
Assert.Equal(expected, theStrings.IndexOfAny(searchInput[0], searchInput[1]));
}
}
}
}
}
| |
namespace Trionic5Controls
{
partial class ctrlDisassembler
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ctrlDisassembler));
this.editor = new ICSharpCode.TextEditor.TextEditorControl();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.highlightSelectionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.splitContainerControl1 = new DevExpress.XtraEditors.SplitContainerControl();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuEditCut = new System.Windows.Forms.ToolStripMenuItem();
this.menuEditCopy = new System.Windows.Forms.ToolStripMenuItem();
this.menuEditPaste = new System.Windows.Forms.ToolStripMenuItem();
this.menuEditDelete = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.menuEditFind = new System.Windows.Forms.ToolStripMenuItem();
this.menuEditReplace = new System.Windows.Forms.ToolStripMenuItem();
this.menuFindAgain = new System.Windows.Forms.ToolStripMenuItem();
this.menuFindAgainReverse = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.menuToggleBookmark = new System.Windows.Forms.ToolStripMenuItem();
this.menuGoToNextBookmark = new System.Windows.Forms.ToolStripMenuItem();
this.menuGoToPrevBookmark = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuSplitTextArea = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.menuShowSpacesTabs = new System.Windows.Forms.ToolStripMenuItem();
this.menuShowNewlines = new System.Windows.Forms.ToolStripMenuItem();
this.menuShowLineNumbers = new System.Windows.Forms.ToolStripMenuItem();
this.menuHighlightCurrentRow = new System.Windows.Forms.ToolStripMenuItem();
this.menuBracketMatchingStyle = new System.Windows.Forms.ToolStripMenuItem();
this.menuEnableVirtualSpace = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.menuSetTabSize = new System.Windows.Forms.ToolStripMenuItem();
this.menuSetFont = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton3 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton4 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton5 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton6 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton7 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton8 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton9 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton10 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton11 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton12 = new System.Windows.Forms.ToolStripButton();
this.hexViewer1 = new Trionic5Controls.HexViewer();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar2 = new System.Windows.Forms.ToolStripProgressBar();
this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel();
this.contextMenuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainerControl1)).BeginInit();
this.splitContainerControl1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// editor
//
this.editor.ContextMenuStrip = this.contextMenuStrip1;
this.editor.Dock = System.Windows.Forms.DockStyle.Fill;
this.editor.IsIconBarVisible = true;
this.editor.IsReadOnly = false;
this.editor.Location = new System.Drawing.Point(0, 49);
this.editor.Name = "editor";
this.editor.Size = new System.Drawing.Size(258, 383);
this.editor.TabIndent = 8;
this.editor.TabIndex = 0;
this.editor.Text = "...";
this.editor.DoubleClick += new System.EventHandler(this.editor_DoubleClick);
this.editor.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.editor_MouseDoubleClick);
this.editor.KeyDown += new System.Windows.Forms.KeyEventHandler(this.editor_KeyDown);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.highlightSelectionToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(172, 26);
//
// highlightSelectionToolStripMenuItem
//
this.highlightSelectionToolStripMenuItem.Name = "highlightSelectionToolStripMenuItem";
this.highlightSelectionToolStripMenuItem.Size = new System.Drawing.Size(171, 22);
this.highlightSelectionToolStripMenuItem.Text = "Highlight selection";
this.highlightSelectionToolStripMenuItem.Click += new System.EventHandler(this.highlightSelectionToolStripMenuItem_Click);
//
// splitContainerControl1
//
this.splitContainerControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainerControl1.FixedPanel = DevExpress.XtraEditors.SplitFixedPanel.Panel2;
this.splitContainerControl1.Location = new System.Drawing.Point(0, 0);
this.splitContainerControl1.Name = "splitContainerControl1";
this.splitContainerControl1.Panel1.Controls.Add(this.editor);
this.splitContainerControl1.Panel1.Controls.Add(this.menuStrip1);
this.splitContainerControl1.Panel1.Controls.Add(this.toolStrip1);
this.splitContainerControl1.Panel1.Text = "Panel1";
this.splitContainerControl1.Panel2.Controls.Add(this.hexViewer1);
this.splitContainerControl1.Panel2.Text = "Panel2";
this.splitContainerControl1.Size = new System.Drawing.Size(841, 436);
this.splitContainerControl1.SplitterPosition = 573;
this.splitContainerControl1.TabIndex = 1;
this.splitContainerControl1.Text = "splitContainerControl1";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.editToolStripMenuItem,
this.optionsToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 25);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(258, 24);
this.menuStrip1.TabIndex = 4;
this.menuStrip1.Text = "menuStrip1";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuEditCut,
this.menuEditCopy,
this.menuEditPaste,
this.menuEditDelete,
this.toolStripSeparator4,
this.menuEditFind,
this.menuEditReplace,
this.menuFindAgain,
this.menuFindAgainReverse,
this.toolStripSeparator5,
this.menuToggleBookmark,
this.menuGoToNextBookmark,
this.menuGoToPrevBookmark});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// menuEditCut
//
this.menuEditCut.Name = "menuEditCut";
this.menuEditCut.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.menuEditCut.Size = new System.Drawing.Size(253, 22);
this.menuEditCut.Text = "Cu&t";
this.menuEditCut.Click += new System.EventHandler(this.toolStripButton2_Click);
//
// menuEditCopy
//
this.menuEditCopy.Name = "menuEditCopy";
this.menuEditCopy.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.menuEditCopy.Size = new System.Drawing.Size(253, 22);
this.menuEditCopy.Text = "&Copy";
this.menuEditCopy.Click += new System.EventHandler(this.toolStripButton3_Click);
//
// menuEditPaste
//
this.menuEditPaste.Name = "menuEditPaste";
this.menuEditPaste.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.menuEditPaste.Size = new System.Drawing.Size(253, 22);
this.menuEditPaste.Text = "&Paste";
this.menuEditPaste.Click += new System.EventHandler(this.toolStripButton4_Click);
//
// menuEditDelete
//
this.menuEditDelete.Name = "menuEditDelete";
this.menuEditDelete.Size = new System.Drawing.Size(253, 22);
this.menuEditDelete.Text = "&Delete";
this.menuEditDelete.Click += new System.EventHandler(this.toolStripButton5_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(250, 6);
//
// menuEditFind
//
this.menuEditFind.Name = "menuEditFind";
this.menuEditFind.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F)));
this.menuEditFind.Size = new System.Drawing.Size(253, 22);
this.menuEditFind.Text = "&Find...";
this.menuEditFind.Click += new System.EventHandler(this.toolStripButton6_Click);
//
// menuEditReplace
//
this.menuEditReplace.Name = "menuEditReplace";
this.menuEditReplace.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.H)));
this.menuEditReplace.Size = new System.Drawing.Size(253, 22);
this.menuEditReplace.Text = "Find and &replace...";
this.menuEditReplace.Click += new System.EventHandler(this.toolStripButton7_Click);
//
// menuFindAgain
//
this.menuFindAgain.Name = "menuFindAgain";
this.menuFindAgain.ShortcutKeys = System.Windows.Forms.Keys.F3;
this.menuFindAgain.Size = new System.Drawing.Size(253, 22);
this.menuFindAgain.Text = "Find &again";
this.menuFindAgain.Click += new System.EventHandler(this.toolStripButton8_Click);
//
// menuFindAgainReverse
//
this.menuFindAgainReverse.Name = "menuFindAgainReverse";
this.menuFindAgainReverse.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F3)));
this.menuFindAgainReverse.Size = new System.Drawing.Size(253, 22);
this.menuFindAgainReverse.Text = "Find again (&reverse)";
this.menuFindAgainReverse.Click += new System.EventHandler(this.toolStripButton9_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(250, 6);
//
// menuToggleBookmark
//
this.menuToggleBookmark.Name = "menuToggleBookmark";
this.menuToggleBookmark.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F2)));
this.menuToggleBookmark.Size = new System.Drawing.Size(253, 22);
this.menuToggleBookmark.Text = "Toggle bookmark";
this.menuToggleBookmark.Click += new System.EventHandler(this.toolStripButton10_Click);
//
// menuGoToNextBookmark
//
this.menuGoToNextBookmark.Name = "menuGoToNextBookmark";
this.menuGoToNextBookmark.ShortcutKeys = System.Windows.Forms.Keys.F2;
this.menuGoToNextBookmark.Size = new System.Drawing.Size(253, 22);
this.menuGoToNextBookmark.Text = "Go to next bookmark";
this.menuGoToNextBookmark.Click += new System.EventHandler(this.toolStripButton11_Click);
//
// menuGoToPrevBookmark
//
this.menuGoToPrevBookmark.Name = "menuGoToPrevBookmark";
this.menuGoToPrevBookmark.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F2)));
this.menuGoToPrevBookmark.Size = new System.Drawing.Size(253, 22);
this.menuGoToPrevBookmark.Text = "Go to previous bookmark";
this.menuGoToPrevBookmark.Click += new System.EventHandler(this.toolStripButton12_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuSplitTextArea,
this.toolStripSeparator6,
this.menuShowSpacesTabs,
this.menuShowNewlines,
this.menuShowLineNumbers,
this.menuHighlightCurrentRow,
this.menuBracketMatchingStyle,
this.menuEnableVirtualSpace,
this.toolStripSeparator7,
this.menuSetTabSize,
this.menuSetFont});
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(56, 20);
this.optionsToolStripMenuItem.Text = "&Options";
//
// menuSplitTextArea
//
this.menuSplitTextArea.Name = "menuSplitTextArea";
this.menuSplitTextArea.Size = new System.Drawing.Size(315, 22);
this.menuSplitTextArea.Text = "Split text area";
this.menuSplitTextArea.Click += new System.EventHandler(this.menuSplitTextArea_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(312, 6);
//
// menuShowSpacesTabs
//
this.menuShowSpacesTabs.Name = "menuShowSpacesTabs";
this.menuShowSpacesTabs.Size = new System.Drawing.Size(315, 22);
this.menuShowSpacesTabs.Text = "Show spaces && tabs";
this.menuShowSpacesTabs.Click += new System.EventHandler(this.menuShowSpacesTabs_Click);
//
// menuShowNewlines
//
this.menuShowNewlines.Name = "menuShowNewlines";
this.menuShowNewlines.Size = new System.Drawing.Size(315, 22);
this.menuShowNewlines.Text = "Show newlines";
this.menuShowNewlines.Click += new System.EventHandler(this.menuShowNewlines_Click);
//
// menuShowLineNumbers
//
this.menuShowLineNumbers.Name = "menuShowLineNumbers";
this.menuShowLineNumbers.Size = new System.Drawing.Size(315, 22);
this.menuShowLineNumbers.Text = "Show line numbers";
this.menuShowLineNumbers.Click += new System.EventHandler(this.menuShowLineNumbers_Click);
//
// menuHighlightCurrentRow
//
this.menuHighlightCurrentRow.Name = "menuHighlightCurrentRow";
this.menuHighlightCurrentRow.Size = new System.Drawing.Size(315, 22);
this.menuHighlightCurrentRow.Text = "Highlight current row";
this.menuHighlightCurrentRow.Click += new System.EventHandler(this.menuHighlightCurrentRow_Click);
//
// menuBracketMatchingStyle
//
this.menuBracketMatchingStyle.Name = "menuBracketMatchingStyle";
this.menuBracketMatchingStyle.Size = new System.Drawing.Size(315, 22);
this.menuBracketMatchingStyle.Text = "Highlight matching brackets when cursor is after";
this.menuBracketMatchingStyle.Click += new System.EventHandler(this.menuBracketMatchingStyle_Click);
//
// menuEnableVirtualSpace
//
this.menuEnableVirtualSpace.Name = "menuEnableVirtualSpace";
this.menuEnableVirtualSpace.Size = new System.Drawing.Size(315, 22);
this.menuEnableVirtualSpace.Text = "Allow cursor past end-of-line";
this.menuEnableVirtualSpace.Click += new System.EventHandler(this.menuEnableVirtualSpace_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(312, 6);
//
// menuSetTabSize
//
this.menuSetTabSize.Name = "menuSetTabSize";
this.menuSetTabSize.Size = new System.Drawing.Size(315, 22);
this.menuSetTabSize.Text = "Set tab size...";
this.menuSetTabSize.Click += new System.EventHandler(this.menuSetTabSize_Click);
//
// menuSetFont
//
this.menuSetFont.Name = "menuSetFont";
this.menuSetFont.Size = new System.Drawing.Size(315, 22);
this.menuSetFont.Text = "Set font...";
this.menuSetFont.Click += new System.EventHandler(this.menuSetFont_Click);
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton1,
this.toolStripButton2,
this.toolStripButton3,
this.toolStripButton4,
this.toolStripButton5,
this.toolStripSeparator2,
this.toolStripButton6,
this.toolStripButton7,
this.toolStripButton8,
this.toolStripButton9,
this.toolStripSeparator1,
this.toolStripButton10,
this.toolStripButton11,
this.toolStripButton12});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(258, 25);
this.toolStrip1.TabIndex = 3;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(23, 22);
this.toolStripButton1.Text = "Save";
this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// toolStripButton2
//
this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton2.Name = "toolStripButton2";
this.toolStripButton2.Size = new System.Drawing.Size(23, 22);
this.toolStripButton2.Text = "Cut";
this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click);
//
// toolStripButton3
//
this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image")));
this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton3.Name = "toolStripButton3";
this.toolStripButton3.Size = new System.Drawing.Size(23, 22);
this.toolStripButton3.Text = "Copy";
this.toolStripButton3.Click += new System.EventHandler(this.toolStripButton3_Click);
//
// toolStripButton4
//
this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image")));
this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton4.Name = "toolStripButton4";
this.toolStripButton4.Size = new System.Drawing.Size(23, 22);
this.toolStripButton4.Text = "Paste";
this.toolStripButton4.Click += new System.EventHandler(this.toolStripButton4_Click);
//
// toolStripButton5
//
this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton5.Image")));
this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton5.Name = "toolStripButton5";
this.toolStripButton5.Size = new System.Drawing.Size(23, 22);
this.toolStripButton5.Text = "Delete";
this.toolStripButton5.Click += new System.EventHandler(this.toolStripButton5_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// toolStripButton6
//
this.toolStripButton6.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton6.Image")));
this.toolStripButton6.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton6.Name = "toolStripButton6";
this.toolStripButton6.Size = new System.Drawing.Size(23, 22);
this.toolStripButton6.Text = "Find";
this.toolStripButton6.Click += new System.EventHandler(this.toolStripButton6_Click);
//
// toolStripButton7
//
this.toolStripButton7.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton7.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton7.Image")));
this.toolStripButton7.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton7.Name = "toolStripButton7";
this.toolStripButton7.Size = new System.Drawing.Size(23, 22);
this.toolStripButton7.Text = "Find and replace";
this.toolStripButton7.Click += new System.EventHandler(this.toolStripButton7_Click);
//
// toolStripButton8
//
this.toolStripButton8.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton8.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton8.Image")));
this.toolStripButton8.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton8.Name = "toolStripButton8";
this.toolStripButton8.Size = new System.Drawing.Size(23, 22);
this.toolStripButton8.Text = "Search next";
this.toolStripButton8.Click += new System.EventHandler(this.toolStripButton8_Click);
//
// toolStripButton9
//
this.toolStripButton9.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton9.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton9.Image")));
this.toolStripButton9.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton9.Name = "toolStripButton9";
this.toolStripButton9.Size = new System.Drawing.Size(23, 22);
this.toolStripButton9.Text = "Search previous";
this.toolStripButton9.Click += new System.EventHandler(this.toolStripButton9_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// toolStripButton10
//
this.toolStripButton10.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton10.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton10.Image")));
this.toolStripButton10.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton10.Name = "toolStripButton10";
this.toolStripButton10.Size = new System.Drawing.Size(23, 20);
this.toolStripButton10.Text = "Toggle bookmark";
this.toolStripButton10.Click += new System.EventHandler(this.toolStripButton10_Click);
//
// toolStripButton11
//
this.toolStripButton11.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton11.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton11.Image")));
this.toolStripButton11.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton11.Name = "toolStripButton11";
this.toolStripButton11.Size = new System.Drawing.Size(23, 20);
this.toolStripButton11.Text = "Next bookmark";
this.toolStripButton11.Click += new System.EventHandler(this.toolStripButton11_Click);
//
// toolStripButton12
//
this.toolStripButton12.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton12.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton12.Image")));
this.toolStripButton12.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton12.Name = "toolStripButton12";
this.toolStripButton12.Size = new System.Drawing.Size(23, 20);
this.toolStripButton12.Text = "Previous bookmark";
this.toolStripButton12.Click += new System.EventHandler(this.toolStripButton12_Click);
//
// hexViewer1
//
this.hexViewer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.hexViewer1.FileName = "";
this.hexViewer1.Issramviewer = false;
this.hexViewer1.LastFilename = "";
this.hexViewer1.Location = new System.Drawing.Point(0, 0);
this.hexViewer1.Name = "hexViewer1";
this.hexViewer1.Size = new System.Drawing.Size(569, 432);
this.hexViewer1.TabIndex = 0;
this.hexViewer1.Load += new System.EventHandler(this.hexViewer1_Load);
this.hexViewer1.onSelectionChanged += new Trionic5Controls.HexViewer.SelectionChanged(this.hexViewer1_onSelectionChanged);
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1,
this.toolStripProgressBar1,
this.toolStripStatusLabel2,
this.toolStripProgressBar2,
this.toolStripStatusLabel3});
this.statusStrip1.Location = new System.Drawing.Point(0, 436);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(841, 22);
this.statusStrip1.TabIndex = 3;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(65, 17);
this.toolStripStatusLabel1.Text = "Disassembly";
//
// toolStripProgressBar1
//
this.toolStripProgressBar1.Name = "toolStripProgressBar1";
this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);
//
// toolStripStatusLabel2
//
this.toolStripStatusLabel2.Name = "toolStripStatusLabel2";
this.toolStripStatusLabel2.Size = new System.Drawing.Size(61, 17);
this.toolStripStatusLabel2.Text = "Conversion";
//
// toolStripProgressBar2
//
this.toolStripProgressBar2.Name = "toolStripProgressBar2";
this.toolStripProgressBar2.Size = new System.Drawing.Size(100, 16);
//
// toolStripStatusLabel3
//
this.toolStripStatusLabel3.Name = "toolStripStatusLabel3";
this.toolStripStatusLabel3.Size = new System.Drawing.Size(19, 17);
this.toolStripStatusLabel3.Text = "...";
//
// ctrlDisassembler
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.splitContainerControl1);
this.Controls.Add(this.statusStrip1);
this.Name = "ctrlDisassembler";
this.Size = new System.Drawing.Size(841, 458);
this.Resize += new System.EventHandler(this.ctrlDisassembler_Resize);
this.contextMenuStrip1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainerControl1)).EndInit();
this.splitContainerControl1.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ICSharpCode.TextEditor.TextEditorControl editor;
private DevExpress.XtraEditors.SplitContainerControl splitContainerControl1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStrip toolStrip1;
private HexViewer hexViewer1;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripButton toolStripButton2;
private System.Windows.Forms.ToolStripButton toolStripButton3;
private System.Windows.Forms.ToolStripButton toolStripButton4;
private System.Windows.Forms.ToolStripButton toolStripButton5;
private System.Windows.Forms.ToolStripButton toolStripButton6;
private System.Windows.Forms.ToolStripButton toolStripButton7;
private System.Windows.Forms.ToolStripButton toolStripButton8;
private System.Windows.Forms.ToolStripButton toolStripButton9;
private System.Windows.Forms.ToolStripButton toolStripButton10;
private System.Windows.Forms.ToolStripButton toolStripButton11;
private System.Windows.Forms.ToolStripButton toolStripButton12;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem highlightSelectionToolStripMenuItem;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem menuEditCut;
private System.Windows.Forms.ToolStripMenuItem menuEditCopy;
private System.Windows.Forms.ToolStripMenuItem menuEditPaste;
private System.Windows.Forms.ToolStripMenuItem menuEditDelete;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem menuEditFind;
private System.Windows.Forms.ToolStripMenuItem menuEditReplace;
private System.Windows.Forms.ToolStripMenuItem menuFindAgain;
private System.Windows.Forms.ToolStripMenuItem menuFindAgainReverse;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem menuToggleBookmark;
private System.Windows.Forms.ToolStripMenuItem menuGoToNextBookmark;
private System.Windows.Forms.ToolStripMenuItem menuGoToPrevBookmark;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem menuSplitTextArea;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem menuShowSpacesTabs;
private System.Windows.Forms.ToolStripMenuItem menuShowNewlines;
private System.Windows.Forms.ToolStripMenuItem menuShowLineNumbers;
private System.Windows.Forms.ToolStripMenuItem menuHighlightCurrentRow;
private System.Windows.Forms.ToolStripMenuItem menuBracketMatchingStyle;
private System.Windows.Forms.ToolStripMenuItem menuEnableVirtualSpace;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem menuSetTabSize;
private System.Windows.Forms.ToolStripMenuItem menuSetFont;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar2;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3;
}
}
| |
// 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 {
// This file defines an internal class used to throw exceptions in BCL code.
// The main purpose is to reduce code size.
//
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
// C# source
// throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
// IL code:
// IL_0003: ldstr "key"
// IL_0008: ldstr "ArgumentNull_Key"
// IL_000d: call string System.Environment::GetResourceString(string)
// IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
// IL_0017: throw
// which is 21bytes in IL.
//
// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
// argument name and resource name in a small integer. The source code will be changed to
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
//
// The IL code will be 7 bytes.
// IL_0008: ldc.i4.4
// IL_0009: ldc.i4.4
// IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
// IL_000f: ldarg.0
//
// This will also reduce the Jitted code size a lot.
//
// It is very important we do this for generic classes because we can easily generate the same code
// multiple times for different instantiation.
//
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[Pure]
internal static class ThrowHelper {
internal static void ThrowArgumentOutOfRangeException() {
ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
}
internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) {
throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), "key");
}
internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) {
throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), "value");
}
#if FEATURE_CORECLR
internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) {
throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key));
}
#endif
internal static void ThrowKeyNotFoundException() {
throw new System.Collections.Generic.KeyNotFoundException();
}
internal static void ThrowArgumentException(ExceptionResource resource) {
throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) {
throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)), GetArgumentName(argument));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument) {
throw new ArgumentNullException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) {
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
throw new ArgumentOutOfRangeException(GetArgumentName(argument),
Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowInvalidOperationException(ExceptionResource resource) {
throw new InvalidOperationException(Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowSerializationException(ExceptionResource resource) {
throw new SerializationException(Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowSecurityException(ExceptionResource resource) {
throw new System.Security.SecurityException(Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowNotSupportedException(ExceptionResource resource) {
throw new NotSupportedException(Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) {
throw new UnauthorizedAccessException(Environment.GetResourceString(GetResourceName(resource)));
}
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) {
throw new ObjectDisposedException(objectName, Environment.GetResourceString(GetResourceName(resource)));
}
// Allow nulls for reference types and Nullable<U>, but not for value types.
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) {
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
if (value == null && !(default(T) == null))
ThrowHelper.ThrowArgumentNullException(argName);
}
//
// This function will convert an ExceptionArgument enum value to the argument name string.
//
internal static string GetArgumentName(ExceptionArgument argument) {
string argumentName = null;
switch (argument) {
case ExceptionArgument.action:
argumentName = "action";
break;
case ExceptionArgument.array:
argumentName = "array";
break;
case ExceptionArgument.arrayIndex:
argumentName = "arrayIndex";
break;
case ExceptionArgument.capacity:
argumentName = "capacity";
break;
case ExceptionArgument.collection:
argumentName = "collection";
break;
case ExceptionArgument.comparison:
argumentName = "comparison";
break;
case ExceptionArgument.list:
argumentName = "list";
break;
case ExceptionArgument.converter:
argumentName = "converter";
break;
case ExceptionArgument.count:
argumentName = "count";
break;
case ExceptionArgument.dictionary:
argumentName = "dictionary";
break;
case ExceptionArgument.dictionaryCreationThreshold:
argumentName = "dictionaryCreationThreshold";
break;
case ExceptionArgument.index:
argumentName = "index";
break;
case ExceptionArgument.info:
argumentName = "info";
break;
case ExceptionArgument.key:
argumentName = "key";
break;
case ExceptionArgument.match:
argumentName = "match";
break;
case ExceptionArgument.obj:
argumentName = "obj";
break;
case ExceptionArgument.queue:
argumentName = "queue";
break;
case ExceptionArgument.stack:
argumentName = "stack";
break;
case ExceptionArgument.startIndex:
argumentName = "startIndex";
break;
case ExceptionArgument.value:
argumentName = "value";
break;
case ExceptionArgument.name:
argumentName = "name";
break;
case ExceptionArgument.mode:
argumentName = "mode";
break;
case ExceptionArgument.item:
argumentName = "item";
break;
case ExceptionArgument.options:
argumentName = "options";
break;
case ExceptionArgument.view:
argumentName = "view";
break;
case ExceptionArgument.sourceBytesToCopy:
argumentName = "sourceBytesToCopy";
break;
default:
Contract.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum.");
return string.Empty;
}
return argumentName;
}
//
// This function will convert an ExceptionResource enum value to the resource string.
//
internal static string GetResourceName(ExceptionResource resource) {
string resourceName = null;
switch (resource) {
case ExceptionResource.Argument_ImplementIComparable:
resourceName = "Argument_ImplementIComparable";
break;
case ExceptionResource.Argument_AddingDuplicate:
resourceName = "Argument_AddingDuplicate";
break;
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
resourceName = "ArgumentOutOfRange_BiggerThanCollection";
break;
case ExceptionResource.ArgumentOutOfRange_Count:
resourceName = "ArgumentOutOfRange_Count";
break;
case ExceptionResource.ArgumentOutOfRange_Index:
resourceName = "ArgumentOutOfRange_Index";
break;
case ExceptionResource.ArgumentOutOfRange_InvalidThreshold:
resourceName = "ArgumentOutOfRange_InvalidThreshold";
break;
case ExceptionResource.ArgumentOutOfRange_ListInsert:
resourceName = "ArgumentOutOfRange_ListInsert";
break;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
resourceName = "ArgumentOutOfRange_NeedNonNegNum";
break;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
resourceName = "ArgumentOutOfRange_SmallCapacity";
break;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
resourceName = "Arg_ArrayPlusOffTooSmall";
break;
case ExceptionResource.Arg_RankMultiDimNotSupported:
resourceName = "Arg_RankMultiDimNotSupported";
break;
case ExceptionResource.Arg_NonZeroLowerBound:
resourceName = "Arg_NonZeroLowerBound";
break;
case ExceptionResource.Argument_InvalidArrayType:
resourceName = "Argument_InvalidArrayType";
break;
case ExceptionResource.Argument_InvalidOffLen:
resourceName = "Argument_InvalidOffLen";
break;
case ExceptionResource.Argument_ItemNotExist:
resourceName = "Argument_ItemNotExist";
break;
case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:
resourceName = "InvalidOperation_CannotRemoveFromStackOrQueue";
break;
case ExceptionResource.InvalidOperation_EmptyQueue:
resourceName = "InvalidOperation_EmptyQueue";
break;
case ExceptionResource.InvalidOperation_EnumOpCantHappen:
resourceName = "InvalidOperation_EnumOpCantHappen";
break;
case ExceptionResource.InvalidOperation_EnumFailedVersion:
resourceName = "InvalidOperation_EnumFailedVersion";
break;
case ExceptionResource.InvalidOperation_EmptyStack:
resourceName = "InvalidOperation_EmptyStack";
break;
case ExceptionResource.InvalidOperation_EnumNotStarted:
resourceName = "InvalidOperation_EnumNotStarted";
break;
case ExceptionResource.InvalidOperation_EnumEnded:
resourceName = "InvalidOperation_EnumEnded";
break;
case ExceptionResource.NotSupported_KeyCollectionSet:
resourceName = "NotSupported_KeyCollectionSet";
break;
case ExceptionResource.NotSupported_ReadOnlyCollection:
resourceName = "NotSupported_ReadOnlyCollection";
break;
case ExceptionResource.NotSupported_ValueCollectionSet:
resourceName = "NotSupported_ValueCollectionSet";
break;
case ExceptionResource.NotSupported_SortedListNestedWrite:
resourceName = "NotSupported_SortedListNestedWrite";
break;
case ExceptionResource.Serialization_InvalidOnDeser:
resourceName = "Serialization_InvalidOnDeser";
break;
case ExceptionResource.Serialization_MissingKeys:
resourceName = "Serialization_MissingKeys";
break;
case ExceptionResource.Serialization_NullKey:
resourceName = "Serialization_NullKey";
break;
case ExceptionResource.Argument_InvalidType:
resourceName = "Argument_InvalidType";
break;
case ExceptionResource.Argument_InvalidArgumentForComparison:
resourceName = "Argument_InvalidArgumentForComparison";
break;
case ExceptionResource.InvalidOperation_NoValue:
resourceName = "InvalidOperation_NoValue";
break;
case ExceptionResource.InvalidOperation_RegRemoveSubKey:
resourceName = "InvalidOperation_RegRemoveSubKey";
break;
case ExceptionResource.Arg_RegSubKeyAbsent:
resourceName = "Arg_RegSubKeyAbsent";
break;
case ExceptionResource.Arg_RegSubKeyValueAbsent:
resourceName = "Arg_RegSubKeyValueAbsent";
break;
case ExceptionResource.Arg_RegKeyDelHive:
resourceName = "Arg_RegKeyDelHive";
break;
case ExceptionResource.Security_RegistryPermission:
resourceName = "Security_RegistryPermission";
break;
case ExceptionResource.Arg_RegSetStrArrNull:
resourceName = "Arg_RegSetStrArrNull";
break;
case ExceptionResource.Arg_RegSetMismatchedKind:
resourceName = "Arg_RegSetMismatchedKind";
break;
case ExceptionResource.UnauthorizedAccess_RegistryNoWrite:
resourceName = "UnauthorizedAccess_RegistryNoWrite";
break;
case ExceptionResource.ObjectDisposed_RegKeyClosed:
resourceName = "ObjectDisposed_RegKeyClosed";
break;
case ExceptionResource.Arg_RegKeyStrLenBug:
resourceName = "Arg_RegKeyStrLenBug";
break;
case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck:
resourceName = "Argument_InvalidRegistryKeyPermissionCheck";
break;
case ExceptionResource.NotSupported_InComparableType:
resourceName = "NotSupported_InComparableType";
break;
case ExceptionResource.Argument_InvalidRegistryOptionsCheck:
resourceName = "Argument_InvalidRegistryOptionsCheck";
break;
case ExceptionResource.Argument_InvalidRegistryViewCheck:
resourceName = "Argument_InvalidRegistryViewCheck";
break;
default:
Contract.Assert( false, "The enum value is not defined, please checked ExceptionArgumentName Enum.");
return string.Empty;
}
return resourceName;
}
}
//
// The convention for this enum is using the argument name as the enum name
//
internal enum ExceptionArgument {
obj,
dictionary,
dictionaryCreationThreshold,
array,
info,
key,
collection,
list,
match,
converter,
queue,
stack,
capacity,
index,
startIndex,
value,
count,
arrayIndex,
name,
mode,
item,
options,
view,
sourceBytesToCopy,
action,
comparison
}
//
// The convention for this enum is using the resource name as the enum name
//
internal enum ExceptionResource {
Argument_ImplementIComparable,
Argument_InvalidType,
Argument_InvalidArgumentForComparison,
Argument_InvalidRegistryKeyPermissionCheck,
ArgumentOutOfRange_NeedNonNegNum,
Arg_ArrayPlusOffTooSmall,
Arg_NonZeroLowerBound,
Arg_RankMultiDimNotSupported,
Arg_RegKeyDelHive,
Arg_RegKeyStrLenBug,
Arg_RegSetStrArrNull,
Arg_RegSetMismatchedKind,
Arg_RegSubKeyAbsent,
Arg_RegSubKeyValueAbsent,
Argument_AddingDuplicate,
Serialization_InvalidOnDeser,
Serialization_MissingKeys,
Serialization_NullKey,
Argument_InvalidArrayType,
NotSupported_KeyCollectionSet,
NotSupported_ValueCollectionSet,
ArgumentOutOfRange_SmallCapacity,
ArgumentOutOfRange_Index,
Argument_InvalidOffLen,
Argument_ItemNotExist,
ArgumentOutOfRange_Count,
ArgumentOutOfRange_InvalidThreshold,
ArgumentOutOfRange_ListInsert,
NotSupported_ReadOnlyCollection,
InvalidOperation_CannotRemoveFromStackOrQueue,
InvalidOperation_EmptyQueue,
InvalidOperation_EnumOpCantHappen,
InvalidOperation_EnumFailedVersion,
InvalidOperation_EmptyStack,
ArgumentOutOfRange_BiggerThanCollection,
InvalidOperation_EnumNotStarted,
InvalidOperation_EnumEnded,
NotSupported_SortedListNestedWrite,
InvalidOperation_NoValue,
InvalidOperation_RegRemoveSubKey,
Security_RegistryPermission,
UnauthorizedAccess_RegistryNoWrite,
ObjectDisposed_RegKeyClosed,
NotSupported_InComparableType,
Argument_InvalidRegistryOptionsCheck,
Argument_InvalidRegistryViewCheck
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Scope;
using OrchardCore.Modules;
using OrchardCore.Recipes.Events;
using OrchardCore.Recipes.Models;
using OrchardCore.Scripting;
namespace OrchardCore.Recipes.Services
{
public class RecipeExecutor : IRecipeExecutor
{
private readonly IShellHost _shellHost;
private readonly ShellSettings _shellSettings;
private readonly IEnumerable<IRecipeEventHandler> _recipeEventHandlers;
private readonly ILogger _logger;
private readonly Dictionary<string, List<IGlobalMethodProvider>> _methodProviders = new Dictionary<string, List<IGlobalMethodProvider>>();
public RecipeExecutor(
IShellHost shellHost,
ShellSettings shellSettings,
IEnumerable<IRecipeEventHandler> recipeEventHandlers,
ILogger<RecipeExecutor> logger)
{
_shellHost = shellHost;
_shellSettings = shellSettings;
_recipeEventHandlers = recipeEventHandlers;
_logger = logger;
}
public async Task<string> ExecuteAsync(string executionId, RecipeDescriptor recipeDescriptor, IDictionary<string, object> environment, CancellationToken cancellationToken)
{
await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.RecipeExecutingAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger);
try
{
var methodProviders = new List<IGlobalMethodProvider>();
_methodProviders.Add(executionId, methodProviders);
methodProviders.Add(new ParametersMethodProvider(environment));
methodProviders.Add(new ConfigurationMethodProvider(_shellSettings.ShellConfiguration));
var result = new RecipeResult { ExecutionId = executionId };
using (var stream = recipeDescriptor.RecipeFileInfo.CreateReadStream())
{
using var file = new StreamReader(stream);
using var reader = new JsonTextReader(file);
// Go to Steps, then iterate.
while (await reader.ReadAsync())
{
if (reader.Path == "variables")
{
await reader.ReadAsync();
var variables = await JObject.LoadAsync(reader);
methodProviders.Add(new VariablesMethodProvider(variables, methodProviders));
}
if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray)
{
while (await reader.ReadAsync() && reader.Depth > 1)
{
if (reader.Depth == 2)
{
var child = await JObject.LoadAsync(reader);
var recipeStep = new RecipeExecutionContext
{
Name = child.Value<string>("name"),
Step = child,
ExecutionId = executionId,
Environment = environment,
RecipeDescriptor = recipeDescriptor
};
if (cancellationToken.IsCancellationRequested)
{
_logger.LogError("Recipe interrupted by cancellation token.");
return null;
}
var stepResult = new RecipeStepResult { StepName = recipeStep.Name };
result.Steps.Add(stepResult);
ExceptionDispatchInfo capturedException = null;
try
{
await ExecuteStepAsync(recipeStep);
stepResult.IsSuccessful = true;
}
catch (Exception e)
{
stepResult.IsSuccessful = false;
stepResult.ErrorMessage = e.ToString();
// Because we can't do some async processing the in catch or finally
// blocks, we store the exception to throw it later.
capturedException = ExceptionDispatchInfo.Capture(e);
}
stepResult.IsCompleted = true;
if (stepResult.IsSuccessful == false)
{
capturedException.Throw();
}
if (recipeStep.InnerRecipes != null)
{
foreach (var descriptor in recipeStep.InnerRecipes)
{
var innerExecutionId = Guid.NewGuid().ToString();
await ExecuteAsync(innerExecutionId, descriptor, environment, cancellationToken);
}
}
}
}
}
}
}
await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.RecipeExecutedAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger);
return executionId;
}
catch (Exception)
{
await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.ExecutionFailedAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger);
throw;
}
finally
{
_methodProviders.Remove(executionId);
}
}
private async Task ExecuteStepAsync(RecipeExecutionContext recipeStep)
{
var shellScope = recipeStep.RecipeDescriptor.RequireNewScope
? await _shellHost.GetScopeAsync(_shellSettings)
: ShellScope.Current;
await shellScope.UsingAsync(async scope =>
{
var recipeStepHandlers = scope.ServiceProvider.GetServices<IRecipeStepHandler>();
var scriptingManager = scope.ServiceProvider.GetRequiredService<IScriptingManager>();
// Substitutes the script elements by their actual values
EvaluateJsonTree(scriptingManager, recipeStep, recipeStep.Step);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Executing recipe step '{RecipeName}'.", recipeStep.Name);
}
await _recipeEventHandlers.InvokeAsync((handler, recipeStep) => handler.RecipeStepExecutingAsync(recipeStep), recipeStep, _logger);
foreach (var recipeStepHandler in recipeStepHandlers)
{
await recipeStepHandler.ExecuteAsync(recipeStep);
}
await _recipeEventHandlers.InvokeAsync((handler, recipeStep) => handler.RecipeStepExecutedAsync(recipeStep), recipeStep, _logger);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Finished executing recipe step '{RecipeName}'.", recipeStep.Name);
}
});
}
/// <summary>
/// Traverse all the nodes of the json document and replaces their value if they are scripted.
/// </summary>
private void EvaluateJsonTree(IScriptingManager scriptingManager, RecipeExecutionContext context, JToken node)
{
switch (node.Type)
{
case JTokenType.Array:
var array = (JArray)node;
for (var i = 0; i < array.Count; i++)
{
EvaluateJsonTree(scriptingManager, context, array[i]);
}
break;
case JTokenType.Object:
foreach (var property in (JObject)node)
{
EvaluateJsonTree(scriptingManager, context, property.Value);
}
break;
case JTokenType.String:
const char scriptSeparator = ':';
var value = node.Value<string>();
// Evaluate the expression while the result is another expression
while (value.StartsWith('[') && value.EndsWith(']'))
{
var scriptSeparatorIndex = value.IndexOf(scriptSeparator);
// Only remove brackets if this is a valid script expression, e.g. '[js:xxx]', or '[file:xxx]'
if (!(scriptSeparatorIndex > -1 && value[1..scriptSeparatorIndex].All(c => Char.IsLetter(c))))
{
break;
}
value = value.Trim('[', ']');
value = (scriptingManager.Evaluate(
value,
context.RecipeDescriptor.FileProvider,
context.RecipeDescriptor.BasePath,
_methodProviders[context.ExecutionId])
?? "").ToString();
((JValue)node).Value = value;
}
break;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Region.OptionalModules.Scripting;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSLinksetConstraints : BSLinkset
{
// private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]";
public class BSLinkInfoConstraint : BSLinkInfo
{
public ConstraintType constraintType;
public BSConstraint constraint;
public OMV.Vector3 linearLimitLow;
public OMV.Vector3 linearLimitHigh;
public OMV.Vector3 angularLimitLow;
public OMV.Vector3 angularLimitHigh;
public bool useFrameOffset;
public bool enableTransMotor;
public float transMotorMaxVel;
public float transMotorMaxForce;
public float cfm;
public float erp;
public float solverIterations;
//
public OMV.Vector3 frameInAloc;
public OMV.Quaternion frameInArot;
public OMV.Vector3 frameInBloc;
public OMV.Quaternion frameInBrot;
public bool useLinearReferenceFrameA;
// Spring
public bool[] springAxisEnable;
public float[] springDamping;
public float[] springStiffness;
public OMV.Vector3 springLinearEquilibriumPoint;
public OMV.Vector3 springAngularEquilibriumPoint;
public BSLinkInfoConstraint(BSPrimLinkable pMember)
: base(pMember)
{
constraint = null;
ResetLink();
member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.creation", member.LocalID);
}
// Set all the parameters for this constraint to a fixed, non-movable constraint.
public override void ResetLink()
{
// constraintType = ConstraintType.D6_CONSTRAINT_TYPE;
constraintType = ConstraintType.FIXED_CONSTRAINT_TYPE;
linearLimitLow = OMV.Vector3.Zero;
linearLimitHigh = OMV.Vector3.Zero;
angularLimitLow = OMV.Vector3.Zero;
angularLimitHigh = OMV.Vector3.Zero;
useFrameOffset = BSParam.LinkConstraintUseFrameOffset;
enableTransMotor = BSParam.LinkConstraintEnableTransMotor;
transMotorMaxVel = BSParam.LinkConstraintTransMotorMaxVel;
transMotorMaxForce = BSParam.LinkConstraintTransMotorMaxForce;
cfm = BSParam.LinkConstraintCFM;
erp = BSParam.LinkConstraintERP;
solverIterations = BSParam.LinkConstraintSolverIterations;
frameInAloc = OMV.Vector3.Zero;
frameInArot = OMV.Quaternion.Identity;
frameInBloc = OMV.Vector3.Zero;
frameInBrot = OMV.Quaternion.Identity;
useLinearReferenceFrameA = true;
springAxisEnable = new bool[6];
springDamping = new float[6];
springStiffness = new float[6];
for (int ii = 0; ii < springAxisEnable.Length; ii++)
{
springAxisEnable[ii] = false;
springDamping[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED;
springStiffness[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED;
}
springLinearEquilibriumPoint = OMV.Vector3.Zero;
springAngularEquilibriumPoint = OMV.Vector3.Zero;
member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.ResetLink", member.LocalID);
}
// Given a constraint, apply the current constraint parameters to same.
public override void SetLinkParameters(BSConstraint constrain)
{
member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.SetLinkParameters,type={1}", member.LocalID, constraintType);
switch (constraintType)
{
case ConstraintType.FIXED_CONSTRAINT_TYPE:
case ConstraintType.D6_CONSTRAINT_TYPE:
BSConstraint6Dof constrain6dof = constrain as BSConstraint6Dof;
if (constrain6dof != null)
{
// NOTE: D6_SPRING_CONSTRAINT_TYPE should be updated if you change any of this code.
// zero linear and angular limits makes the objects unable to move in relation to each other
constrain6dof.SetLinearLimits(linearLimitLow, linearLimitHigh);
constrain6dof.SetAngularLimits(angularLimitLow, angularLimitHigh);
// tweek the constraint to increase stability
constrain6dof.UseFrameOffset(useFrameOffset);
constrain6dof.TranslationalLimitMotor(enableTransMotor, transMotorMaxVel, transMotorMaxForce);
constrain6dof.SetCFMAndERP(cfm, erp);
if (solverIterations != 0f)
{
constrain6dof.SetSolverIterations(solverIterations);
}
}
break;
case ConstraintType.D6_SPRING_CONSTRAINT_TYPE:
BSConstraintSpring constrainSpring = constrain as BSConstraintSpring;
if (constrainSpring != null)
{
// zero linear and angular limits makes the objects unable to move in relation to each other
constrainSpring.SetLinearLimits(linearLimitLow, linearLimitHigh);
constrainSpring.SetAngularLimits(angularLimitLow, angularLimitHigh);
// tweek the constraint to increase stability
constrainSpring.UseFrameOffset(useFrameOffset);
constrainSpring.TranslationalLimitMotor(enableTransMotor, transMotorMaxVel, transMotorMaxForce);
constrainSpring.SetCFMAndERP(cfm, erp);
if (solverIterations != 0f)
{
constrainSpring.SetSolverIterations(solverIterations);
}
for (int ii = 0; ii < springAxisEnable.Length; ii++)
{
constrainSpring.SetAxisEnable(ii, springAxisEnable[ii]);
if (springDamping[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED)
constrainSpring.SetDamping(ii, springDamping[ii]);
if (springStiffness[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED)
constrainSpring.SetStiffness(ii, springStiffness[ii]);
}
constrainSpring.CalculateTransforms();
if (springLinearEquilibriumPoint != OMV.Vector3.Zero)
constrainSpring.SetEquilibriumPoint(springLinearEquilibriumPoint, springAngularEquilibriumPoint);
else
constrainSpring.SetEquilibriumPoint(BSAPITemplate.SPRING_NOT_SPECIFIED, BSAPITemplate.SPRING_NOT_SPECIFIED);
}
break;
default:
break;
}
}
// Return 'true' if the property updates from the physics engine should be reported
// to the simulator.
// If the constraint is fixed, we don't need to report as the simulator and viewer will
// report the right things.
public override bool ShouldUpdateChildProperties()
{
bool ret = true;
if (constraintType == ConstraintType.FIXED_CONSTRAINT_TYPE)
ret = false;
return ret;
}
}
public BSLinksetConstraints(BSScene scene, BSPrimLinkable parent) : base(scene, parent)
{
LinksetImpl = LinksetImplementation.Constraint;
}
private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINT]";
// When physical properties are changed the linkset needs to recalculate
// its internal properties.
// This is queued in the 'post taint' queue so the
// refresh will happen once after all the other taints are applied.
public override void Refresh(BSPrimLinkable requestor)
{
ScheduleRebuild(requestor);
base.Refresh(requestor);
}
private void ScheduleRebuild(BSPrimLinkable requestor)
{
DetailLog("{0},BSLinksetConstraint.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}",
requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren));
// When rebuilding, it is possible to set properties that would normally require a rebuild.
// If already rebuilding, don't request another rebuild.
// If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding.
if (!Rebuilding && HasAnyChildren)
{
// Queue to happen after all the other taint processing
m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate()
{
if (HasAnyChildren)
{
// Constraints that have not been changed are not rebuild but make sure
// the constraint of the requestor is rebuilt.
PhysicallyUnlinkAChildFromRoot(LinksetRoot, requestor);
// Rebuild the linkset and all its constraints.
RecomputeLinksetConstraints();
}
});
}
}
// The object is going dynamic (physical). Do any setup necessary
// for a dynamic linkset.
// Only the state of the passed object can be modified. The rest of the linkset
// has not yet been fully constructed.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeDynamic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraints.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child));
if (IsRoot(child))
{
// The root is going dynamic. Rebuild the linkset so parts and mass get computed properly.
Refresh(LinksetRoot);
}
return ret;
}
// The object is going static (non-physical). Do any setup necessary for a static linkset.
// Return 'true' if any properties updated on the passed object.
// This doesn't normally happen -- OpenSim removes the objects from the physical
// world if it is a static linkset.
// Called at taint-time!
public override bool MakeStatic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraint.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child));
child.ClearDisplacement();
if (IsRoot(child))
{
// Schedule a rebuild to verify that the root shape is set to the real shape.
Refresh(LinksetRoot);
}
return ret;
}
// Called at taint-time!!
public override void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable pObj)
{
// Nothing to do for constraints on property updates
}
// Routine called when rebuilding the body of some member of the linkset.
// Destroy all the constraints have have been made to root and set
// up to rebuild the constraints before the next simulation step.
// Returns 'true' of something was actually removed and would need restoring
// Called at taint-time!!
public override bool RemoveDependencies(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraint.RemoveDependencies,removeChildrenForRoot,rID={1},rBody={2}",
child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString);
lock (m_linksetActivityLock)
{
// Just undo all the constraints for this linkset. Rebuild at the end of the step.
ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot);
// Cause the constraints, et al to be rebuilt before the next simulation step.
Refresh(LinksetRoot);
}
return ret;
}
// ================================================================
// Add a new child to the linkset.
// Called while LinkActivity is locked.
protected override void AddChildToLinkset(BSPrimLinkable child)
{
if (!HasChild(child))
{
m_children.Add(child, new BSLinkInfoConstraint(child));
DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID);
// Cause constraints and assorted properties to be recomputed before the next simulation step.
Refresh(LinksetRoot);
}
return;
}
// Remove the specified child from the linkset.
// Safe to call even if the child is not really in my linkset.
protected override void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime)
{
if (m_children.Remove(child))
{
BSPrimLinkable rootx = LinksetRoot; // capture the root and body as of now
BSPrimLinkable childx = child;
DetailLog("{0},BSLinksetConstraints.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}",
childx.LocalID,
rootx.LocalID, rootx.PhysBody.AddrString,
childx.LocalID, childx.PhysBody.AddrString);
m_physicsScene.TaintedObject(inTaintTime, childx.LocalID, "BSLinksetConstraints.RemoveChildFromLinkset", delegate()
{
PhysicallyUnlinkAChildFromRoot(rootx, childx);
});
// See that the linkset parameters are recomputed at the end of the taint time.
Refresh(LinksetRoot);
}
else
{
// Non-fatal occurance.
// PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader);
}
return;
}
// Create a constraint between me (root of linkset) and the passed prim (the child).
// Called at taint time!
private void PhysicallyLinkAChildToRoot(BSPrimLinkable rootPrim, BSPrimLinkable childPrim)
{
// Don't build the constraint when asked. Put it off until just before the simulation step.
Refresh(rootPrim);
}
// Create a static constraint between the two passed objects
private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSLinkInfo li)
{
BSLinkInfoConstraint linkInfo = li as BSLinkInfoConstraint;
if (linkInfo == null)
return null;
// Zero motion for children so they don't interpolate
li.member.ZeroMotion(true);
BSConstraint constrain = null;
switch (linkInfo.constraintType)
{
case ConstraintType.FIXED_CONSTRAINT_TYPE:
case ConstraintType.D6_CONSTRAINT_TYPE:
// Relative position normalized to the root prim
// Essentually a vector pointing from center of rootPrim to center of li.member
OMV.Vector3 childRelativePosition = linkInfo.member.Position - rootPrim.Position;
// real world coordinate of midpoint between the two objects
OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2);
DetailLog("{0},BSLinksetConstraint.BuildConstraint,6Dof,rBody={1},cBody={2},rLoc={3},cLoc={4},midLoc={5}",
rootPrim.LocalID, rootPrim.PhysBody, linkInfo.member.PhysBody,
rootPrim.Position, linkInfo.member.Position, midPoint);
// create a constraint that allows no freedom of movement between the two objects
// http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818
constrain = new BSConstraint6Dof(
m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody, midPoint, true, true );
/* NOTE: below is an attempt to build constraint with full frame computation, etc.
* Using the midpoint is easier since it lets the Bullet code manipulate the transforms
* of the objects.
* Code left for future programmers.
// ==================================================================================
// relative position normalized to the root prim
OMV.Quaternion invThisOrientation = OMV.Quaternion.Inverse(rootPrim.Orientation);
OMV.Vector3 childRelativePosition = (liConstraint.member.Position - rootPrim.Position) * invThisOrientation;
// relative rotation of the child to the parent
OMV.Quaternion childRelativeRotation = invThisOrientation * liConstraint.member.Orientation;
OMV.Quaternion inverseChildRelativeRotation = OMV.Quaternion.Inverse(childRelativeRotation);
DetailLog("{0},BSLinksetConstraint.PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, liConstraint.member.LocalID);
constrain = new BS6DofConstraint(
PhysicsScene.World, rootPrim.Body, liConstraint.member.Body,
OMV.Vector3.Zero,
OMV.Quaternion.Inverse(rootPrim.Orientation),
OMV.Vector3.Zero,
OMV.Quaternion.Inverse(liConstraint.member.Orientation),
true,
true
);
// ==================================================================================
*/
break;
case ConstraintType.D6_SPRING_CONSTRAINT_TYPE:
constrain = new BSConstraintSpring(m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody,
linkInfo.frameInAloc, linkInfo.frameInArot, linkInfo.frameInBloc, linkInfo.frameInBrot,
linkInfo.useLinearReferenceFrameA,
true /*disableCollisionsBetweenLinkedBodies*/);
DetailLog("{0},BSLinksetConstraint.BuildConstraint,spring,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6}",
rootPrim.LocalID,
rootPrim.LocalID, rootPrim.PhysBody.AddrString,
linkInfo.member.LocalID, linkInfo.member.PhysBody.AddrString,
rootPrim.Position, linkInfo.member.Position);
break;
default:
break;
}
linkInfo.SetLinkParameters(constrain);
m_physicsScene.Constraints.AddConstraint(constrain);
return constrain;
}
// Remove linkage between the linkset root and a particular child
// The root and child bodies are passed in because we need to remove the constraint between
// the bodies that were present at unlink time.
// Called at taint time!
private bool PhysicallyUnlinkAChildFromRoot(BSPrimLinkable rootPrim, BSPrimLinkable childPrim)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}",
rootPrim.LocalID,
rootPrim.LocalID, rootPrim.PhysBody.AddrString,
childPrim.LocalID, childPrim.PhysBody.AddrString);
// If asked to unlink root from root, just remove all the constraints
if (rootPrim == childPrim || childPrim == LinksetRoot)
{
PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot);
ret = true;
}
else
{
// Find the constraint for this link and get rid of it from the overall collection and from my list
if (m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody))
{
// Make the child refresh its location
m_physicsScene.PE.PushUpdate(childPrim.PhysBody);
ret = true;
}
}
return ret;
}
// Remove linkage between myself and any possible children I might have.
// Returns 'true' of any constraints were destroyed.
// Called at taint time!
private bool PhysicallyUnlinkAllChildrenFromRoot(BSPrimLinkable rootPrim)
{
DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID);
return m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody);
}
// Call each of the constraints that make up this linkset and recompute the
// various transforms and variables. Create constraints of not created yet.
// Called before the simulation step to make sure the constraint based linkset
// is all initialized.
// Called at taint time!!
private void RecomputeLinksetConstraints()
{
float linksetMass = LinksetMass;
LinksetRoot.UpdatePhysicalMassProperties(linksetMass, true);
DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}",
LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString, linksetMass);
try
{
Rebuilding = true;
// There is no reason to build all this physical stuff for a non-physical linkset.
if (!LinksetRoot.IsPhysicallyActive || !HasAnyChildren)
{
DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysicalOrNoChildren", LinksetRoot.LocalID);
return; // Note the 'finally' clause at the botton which will get executed.
}
ForEachLinkInfo((li) =>
{
// A child in the linkset physically shows the mass of the whole linkset.
// This allows Bullet to apply enough force on the child to move the whole linkset.
// (Also do the mass stuff before recomputing the constraint so mass is not zero.)
li.member.UpdatePhysicalMassProperties(linksetMass, true);
BSConstraint constrain;
if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, li.member.PhysBody, out constrain))
{
// If constraint doesn't exist yet, create it.
constrain = BuildConstraint(LinksetRoot, li);
}
li.SetLinkParameters(constrain);
constrain.RecomputeConstraintVariables(linksetMass);
// PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG
return false; // 'false' says to keep processing other members
});
}
finally
{
Rebuilding = false;
}
}
#region Extension
public override object Extension(string pFunct, params object[] pParams)
{
object ret = null;
switch (pFunct)
{
// pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ]
case ExtendedPhysics.PhysFunctChangeLinkType:
if (pParams.Length > 2)
{
int requestedType = (int)pParams[2];
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,requestedType={1}", LinksetRoot.LocalID, requestedType);
if (requestedType == (int)ConstraintType.FIXED_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.D6_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.HINGE_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.CONETWIST_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.SLIDER_CONSTRAINT_TYPE)
{
BSPrimLinkable child = pParams[1] as BSPrimLinkable;
if (child != null)
{
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,rootID={1},childID={2},type={3}",
LinksetRoot.LocalID, LinksetRoot.LocalID, child.LocalID, requestedType);
m_physicsScene.TaintedObject(child.LocalID, "BSLinksetConstraint.PhysFunctChangeLinkType", delegate()
{
// Pick up all the constraints currently created.
RemoveDependencies(child);
BSLinkInfo linkInfo = null;
if (TryGetLinkInfo(child, out linkInfo))
{
BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint;
if (linkInfoC != null)
{
linkInfoC.constraintType = (ConstraintType)requestedType;
ret = (object)true;
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,link={1},type={2}",
linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType);
}
else
{
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,linkInfoNotConstraint,childID={1}", LinksetRoot.LocalID, child.LocalID);
}
}
else
{
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,noLinkInfoForChild,childID={1}", LinksetRoot.LocalID, child.LocalID);
}
// Cause the whole linkset to be rebuilt in post-taint time.
Refresh(child);
});
}
else
{
DetailLog("{0},BSLinksetConstraint.SetLinkType,childNotBSPrimLinkable", LinksetRoot.LocalID);
}
}
else
{
DetailLog("{0},BSLinksetConstraint.SetLinkType,illegalRequestedType,reqested={1},spring={2}",
LinksetRoot.LocalID, requestedType, ((int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE));
}
}
break;
// pParams = [ BSPhysObject root, BSPhysObject child ]
case ExtendedPhysics.PhysFunctGetLinkType:
if (pParams.Length > 0)
{
BSPrimLinkable child = pParams[1] as BSPrimLinkable;
if (child != null)
{
BSLinkInfo linkInfo = null;
if (TryGetLinkInfo(child, out linkInfo))
{
BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint;
if (linkInfoC != null)
{
ret = (object)(int)linkInfoC.constraintType;
DetailLog("{0},BSLinksetConstraint.GetLinkType,link={1},type={2}",
linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType);
}
}
}
}
break;
// pParams = [ BSPhysObject root, BSPhysObject child, int op, object opParams, int op, object opParams, ... ]
case ExtendedPhysics.PhysFunctChangeLinkParams:
// There should be two parameters: the childActor and a list of parameters to set
if (pParams.Length > 2)
{
BSPrimLinkable child = pParams[1] as BSPrimLinkable;
BSLinkInfo baseLinkInfo = null;
if (TryGetLinkInfo(child, out baseLinkInfo))
{
BSLinkInfoConstraint linkInfo = baseLinkInfo as BSLinkInfoConstraint;
if (linkInfo != null)
{
int valueInt;
float valueFloat;
bool valueBool;
OMV.Vector3 valueVector;
OMV.Vector3 valueVector2;
OMV.Quaternion valueQuaternion;
int axisLow, axisHigh;
int opIndex = 2;
while (opIndex < pParams.Length)
{
int thisOp = 0;
string errMsg = "";
try
{
thisOp = (int)pParams[opIndex];
DetailLog("{0},BSLinksetConstraint.ChangeLinkParams2,op={1},val={2}",
linkInfo.member.LocalID, thisOp, pParams[opIndex + 1]);
switch (thisOp)
{
case ExtendedPhysics.PHYS_PARAM_LINK_TYPE:
valueInt = (int)pParams[opIndex + 1];
ConstraintType valueType = (ConstraintType)valueInt;
if (valueType == ConstraintType.FIXED_CONSTRAINT_TYPE
|| valueType == ConstraintType.D6_CONSTRAINT_TYPE
|| valueType == ConstraintType.D6_SPRING_CONSTRAINT_TYPE
|| valueType == ConstraintType.HINGE_CONSTRAINT_TYPE
|| valueType == ConstraintType.CONETWIST_CONSTRAINT_TYPE
|| valueType == ConstraintType.SLIDER_CONSTRAINT_TYPE)
{
linkInfo.constraintType = valueType;
}
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC:
errMsg = "PHYS_PARAM_FRAMEINA_LOC takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.frameInAloc = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT:
errMsg = "PHYS_PARAM_FRAMEINA_ROT takes one parameter of type rotation";
valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1];
linkInfo.frameInArot = valueQuaternion;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC:
errMsg = "PHYS_PARAM_FRAMEINB_LOC takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.frameInBloc = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT:
errMsg = "PHYS_PARAM_FRAMEINB_ROT takes one parameter of type rotation";
valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1];
linkInfo.frameInBrot = valueQuaternion;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW:
errMsg = "PHYS_PARAM_LINEAR_LIMIT_LOW takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.linearLimitLow = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH:
errMsg = "PHYS_PARAM_LINEAR_LIMIT_HIGH takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.linearLimitHigh = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW:
errMsg = "PHYS_PARAM_ANGULAR_LIMIT_LOW takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.angularLimitLow = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH:
errMsg = "PHYS_PARAM_ANGULAR_LIMIT_HIGH takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.angularLimitHigh = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET:
errMsg = "PHYS_PARAM_USE_FRAME_OFFSET takes one parameter of type integer (bool)";
valueBool = ((int)pParams[opIndex + 1]) != 0;
linkInfo.useFrameOffset = valueBool;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR:
errMsg = "PHYS_PARAM_ENABLE_TRANSMOTOR takes one parameter of type integer (bool)";
valueBool = ((int)pParams[opIndex + 1]) != 0;
linkInfo.enableTransMotor = valueBool;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL:
errMsg = "PHYS_PARAM_TRANSMOTOR_MAXVEL takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.transMotorMaxVel = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE:
errMsg = "PHYS_PARAM_TRANSMOTOR_MAXFORCE takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.transMotorMaxForce = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_CFM:
errMsg = "PHYS_PARAM_CFM takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.cfm = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ERP:
errMsg = "PHYS_PARAM_ERP takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.erp = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS:
errMsg = "PHYS_PARAM_SOLVER_ITERATIONS takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.solverIterations = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_AXIS_ENABLE:
errMsg = "PHYS_PARAM_SPRING_AXIS_ENABLE takes two parameters of types integer and integer (bool)";
valueInt = (int)pParams[opIndex + 1];
valueBool = ((int)pParams[opIndex + 2]) != 0;
GetAxisRange(valueInt, out axisLow, out axisHigh);
for (int ii = axisLow; ii <= axisHigh; ii++)
linkInfo.springAxisEnable[ii] = valueBool;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING:
errMsg = "PHYS_PARAM_SPRING_DAMPING takes two parameters of types integer and float";
valueInt = (int)pParams[opIndex + 1];
valueFloat = (float)pParams[opIndex + 2];
GetAxisRange(valueInt, out axisLow, out axisHigh);
for (int ii = axisLow; ii <= axisHigh; ii++)
linkInfo.springDamping[ii] = valueFloat;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS:
errMsg = "PHYS_PARAM_SPRING_STIFFNESS takes two parameters of types integer and float";
valueInt = (int)pParams[opIndex + 1];
valueFloat = (float)pParams[opIndex + 2];
GetAxisRange(valueInt, out axisLow, out axisHigh);
for (int ii = axisLow; ii <= axisHigh; ii++)
linkInfo.springStiffness[ii] = valueFloat;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_EQUILIBRIUM_POINT:
errMsg = "PHYS_PARAM_SPRING_EQUILIBRIUM_POINT takes two parameters of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
valueVector2 = (OMV.Vector3)pParams[opIndex + 2];
linkInfo.springLinearEquilibriumPoint = valueVector;
linkInfo.springAngularEquilibriumPoint = valueVector2;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_USE_LINEAR_FRAMEA:
errMsg = "PHYS_PARAM_USE_LINEAR_FRAMEA takes one parameter of type integer (bool)";
valueBool = ((int)pParams[opIndex + 1]) != 0;
linkInfo.useLinearReferenceFrameA = valueBool;
opIndex += 2;
break;
default:
break;
}
}
catch (InvalidCastException e)
{
m_physicsScene.Logger.WarnFormat("{0} value of wrong type in physSetLinksetParams: {1}, err={2}",
LogHeader, errMsg, e);
}
catch (Exception e)
{
m_physicsScene.Logger.WarnFormat("{0} bad parameters in physSetLinksetParams: {1}", LogHeader, e);
}
}
}
// Something changed so a rebuild is in order
Refresh(child);
}
}
break;
default:
ret = base.Extension(pFunct, pParams);
break;
}
return ret;
}
// Bullet constraints keep some limit parameters for each linear and angular axis.
// Setting same is easier if there is an easy way to see all or types.
// This routine returns the array limits for the set of axis.
private void GetAxisRange(int rangeSpec, out int low, out int high)
{
switch (rangeSpec)
{
case ExtendedPhysics.PHYS_AXIS_LINEAR_ALL:
low = 0;
high = 2;
break;
case ExtendedPhysics.PHYS_AXIS_ANGULAR_ALL:
low = 3;
high = 5;
break;
case ExtendedPhysics.PHYS_AXIS_ALL:
low = 0;
high = 5;
break;
default:
low = high = rangeSpec;
break;
}
return;
}
#endregion // Extension
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Formula.PTG
{
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using NPOI.Util;
/**
* <c>Ptg</c> represents a syntactic token in a formula. 'PTG' is an acronym for
* '<b>p</b>arse <b>t</b>hin<b>g</b>'. Originally, the name referred to the single
* byte identifier at the start of the token, but in POI, <c>Ptg</c> encapsulates
* the whole formula token (initial byte + value data).
*
*
* <c>Ptg</c>s are logically arranged in a tree representing the structure of the
* Parsed formula. However, in BIFF files <c>Ptg</c>s are written/Read in
* <em>Reverse-Polish Notation</em> order. The RPN ordering also simplifies formula
* evaluation logic, so POI mostly accesses <c>Ptg</c>s in the same way.
*
* @author andy
* @author avik
* @author Jason Height (jheight at chariot dot net dot au)
*/
[Serializable]
public abstract class Ptg : ICloneable
{
public static Ptg[] EMPTY_PTG_ARRAY = { };
/**
* Reads <c>size</c> bytes of the input stream, to Create an array of <c>Ptg</c>s.
* Extra data (beyond <c>size</c>) may be Read if and <c>ArrayPtg</c>s are present.
*/
public static Ptg[] ReadTokens(int size, ILittleEndianInput in1)
{
ArrayList temp = new ArrayList(4 + size / 2);
int pos = 0;
bool hasArrayPtgs = false;
while (pos < size)
{
Ptg ptg = Ptg.CreatePtg(in1);
if (ptg is ArrayPtg.Initial)
{
hasArrayPtgs = true;
}
pos += ptg.Size;
temp.Add(ptg);
}
if (pos != size)
{
throw new Exception("Ptg array size mismatch");
}
if (hasArrayPtgs)
{
Ptg[] result = ToPtgArray(temp);
for (int i = 0; i < result.Length; i++)
{
if (result[i] is ArrayPtg.Initial)
{
result[i] = ((ArrayPtg.Initial)result[i]).FinishReading(in1);
}
}
return result;
}
return ToPtgArray(temp);
}
public static Ptg CreatePtg(ILittleEndianInput in1)
{
byte id = (byte)in1.ReadByte();
if (id < 0x20)
{
return CreateBasePtg(id, in1);
}
Ptg retval = CreateClassifiedPtg(id, in1);
if (id >= 0x60)
{
retval.PtgClass = CLASS_ARRAY;
}
else if (id >= 0x40)
{
retval.PtgClass = CLASS_VALUE;
}
else
{
retval.PtgClass = CLASS_REF;
}
return retval;
}
private static Ptg CreateClassifiedPtg(byte id, ILittleEndianInput in1)
{
int baseId = id & 0x1F | 0x20;
switch (baseId)
{
case ArrayPtg.sid: return new ArrayPtg.Initial(in1); // 0x20, 0x40, 0x60
case FuncPtg.sid: return FuncPtg.Create(in1); // 0x21, 0x41, 0x61
case FuncVarPtg.sid: return FuncVarPtg.Create(in1); // 0x22, 0x42, 0x62
case NamePtg.sid: return new NamePtg(in1); // 0x23, 0x43, 0x63
case RefPtg.sid: return new RefPtg(in1); // 0x24, 0x44, 0x64
case AreaPtg.sid: return new AreaPtg(in1); // 0x25, 0x45, 0x65
case MemAreaPtg.sid: return new MemAreaPtg(in1); // 0x26, 0x46, 0x66
case MemErrPtg.sid: return new MemErrPtg(in1); // 0x27, 0x47, 0x67
case MemFuncPtg.sid: return new MemFuncPtg(in1); // 0x29, 0x49, 0x69
case RefErrorPtg.sid: return new RefErrorPtg(in1);// 0x2a, 0x4a, 0x6a
case AreaErrPtg.sid: return new AreaErrPtg(in1); // 0x2b, 0x4b, 0x6b
case RefNPtg.sid: return new RefNPtg(in1); // 0x2c, 0x4c, 0x6c
case AreaNPtg.sid: return new AreaNPtg(in1); // 0x2d, 0x4d, 0x6d
case NameXPtg.sid: return new NameXPtg(in1); // 0x39, 0x49, 0x79
case Ref3DPtg.sid: return new Ref3DPtg(in1); // 0x3a, 0x5a, 0x7a
case Area3DPtg.sid: return new Area3DPtg(in1); // 0x3b, 0x5b, 0x7b
case DeletedRef3DPtg.sid: return new DeletedRef3DPtg(in1); // 0x3c, 0x5c, 0x7c
case DeletedArea3DPtg.sid: return new DeletedArea3DPtg(in1); // 0x3d, 0x5d, 0x7d
}
throw new NotSupportedException(" Unknown Ptg in Formula: 0x" +
StringUtil.ToHexString(id) + " (" + (int)id + ")");
}
private static Ptg CreateBasePtg(byte id, ILittleEndianInput in1)
{
switch (id)
{
case 0x00: return new UnknownPtg(); // TODO - not a real Ptg
case ExpPtg.sid: return new ExpPtg(in1); // 0x01
case TblPtg.sid: return new TblPtg(in1); // 0x02
case AddPtg.sid: return AddPtg.instance; // 0x03
case SubtractPtg.sid: return SubtractPtg.instance; // 0x04
case MultiplyPtg.sid: return MultiplyPtg.instance; // 0x05
case DividePtg.sid: return DividePtg.instance; // 0x06
case PowerPtg.sid: return PowerPtg.instance; // 0x07
case ConcatPtg.sid: return ConcatPtg.instance; // 0x08
case LessThanPtg.sid: return LessThanPtg.instance; // 0x09
case LessEqualPtg.sid: return LessEqualPtg.instance; // 0x0a
case EqualPtg.sid: return EqualPtg.instance; // 0x0b
case GreaterEqualPtg.sid: return GreaterEqualPtg.instance;// 0x0c
case GreaterThanPtg.sid: return GreaterThanPtg.instance; // 0x0d
case NotEqualPtg.sid: return NotEqualPtg.instance; // 0x0e
case IntersectionPtg.sid: return IntersectionPtg.instance;// 0x0f
case UnionPtg.sid: return UnionPtg.instance; // 0x10
case RangePtg.sid: return RangePtg.instance; // 0x11
case UnaryPlusPtg.sid: return UnaryPlusPtg.instance; // 0x12
case UnaryMinusPtg.sid: return UnaryMinusPtg.instance; // 0x13
case PercentPtg.sid: return PercentPtg.instance; // 0x14
case ParenthesisPtg.sid: return ParenthesisPtg.instance; // 0x15
case MissingArgPtg.sid: return MissingArgPtg.instance; // 0x16
case StringPtg.sid: return new StringPtg(in1); // 0x17
case AttrPtg.sid: return new AttrPtg(in1); // 0x19
case ErrPtg.sid: return new ErrPtg(in1); // 0x1c
case BoolPtg.sid: return new BoolPtg(in1); // 0x1d
case IntPtg.sid: return new IntPtg(in1); // 0x1e
case NumberPtg.sid: return new NumberPtg(in1); // 0x1f
}
throw new Exception("Unexpected base token id (" + id + ")");
}
private static Ptg[] ToPtgArray(ArrayList l)
{
if (l.Count == 0)
{
return EMPTY_PTG_ARRAY;
}
Ptg[] result = (Ptg[])l.ToArray(typeof(Ptg));
return result;
}
/**
* @return a distinct copy of this <c>Ptg</c> if the class is mutable, or the same instance
* if the class is immutable.
*/
//[Obsolete]
//public Ptg Copy()
//{
// // TODO - all base tokens are logically immutable, but AttrPtg needs some clean-up
// if (this is ValueOperatorPtg)
// {
// return this;
// }
// if (this is ScalarConstantPtg)
// {
// return this;
// }
// return (Ptg)Clone();
//}
public virtual object Clone()
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Position = 0;
return formatter.Deserialize(stream);
}
}
/**
* This method will return the same result as {@link #getEncodedSizeWithoutArrayData(Ptg[])}
* if there are no array tokens present.
* @return the full size taken to encode the specified <c>Ptg</c>s
*/
public static int GetEncodedSize(Ptg[] ptgs)
{
int result = 0;
for (int i = 0; i < ptgs.Length; i++)
{
result += ptgs[i].Size;
}
return result;
}
/**
* Used to calculate value that should be encoded at the start of the encoded Ptg token array;
* @return the size of the encoded Ptg tokens not including any trailing array data.
*/
public static int GetEncodedSizeWithoutArrayData(Ptg[] ptgs)
{
int result = 0;
for (int i = 0; i < ptgs.Length; i++)
{
Ptg ptg = ptgs[i];
if (ptg is ArrayPtg)
{
result += ArrayPtg.PLAIN_TOKEN_SIZE;
}
else
{
result += ptg.Size;
}
}
return result;
}
/**
* Writes the ptgs to the data buffer, starting at the specified offset.
*
* <br/>
* The 2 byte encode Length field is <b>not</b> written by this method.
* @return number of bytes written
*/
public static int SerializePtgs(Ptg[] ptgs, byte[] array, int offset)
{
int size = ptgs.Length;
LittleEndianByteArrayOutputStream out1 = new LittleEndianByteArrayOutputStream(array, offset);
ArrayList arrayPtgs = null;
for (int k = 0; k < size; k++)
{
Ptg ptg = ptgs[k];
ptg.Write(out1);
if (ptg is ArrayPtg)
{
if (arrayPtgs == null)
{
arrayPtgs = new ArrayList(5);
}
arrayPtgs.Add(ptg);
}
}
if (arrayPtgs != null)
{
for (int i = 0; i < arrayPtgs.Count; i++)
{
ArrayPtg p = (ArrayPtg)arrayPtgs[i];
p.WriteTokenValueBytes(out1);
}
}
return out1.WriteIndex - offset; ;
}
/**
* @return the encoded Length of this Ptg, including the initial Ptg type identifier byte.
*/
public abstract int Size { get; }
/**
* @return <c>false</c> if this token is classified as 'reference', 'value', or 'array'
*/
public abstract bool IsBaseToken { get; }
/** Write this Ptg to a byte array*/
public abstract void Write(ILittleEndianOutput out1);
/**
* return a string representation of this token alone
*/
public abstract String ToFormulaString();
/** Overridden toString method to Ensure object hash is not printed.
* This helps Get rid of gratuitous diffs when comparing two dumps
* Subclasses may output more relevant information by overriding this method
**/
public override String ToString()
{
return this.GetType().ToString();
}
public const byte CLASS_REF = 0x00;
public const byte CLASS_VALUE = 0x20;
public const byte CLASS_ARRAY = 0x40;
private byte ptgClass = CLASS_REF; //base ptg
/**
* @return the 'operand class' (REF/VALUE/ARRAY) for this Ptg
*/
public byte PtgClass
{
get { return ptgClass; }
set
{
if (IsBaseToken)
{
throw new Exception("SetClass should not be called on a base token");
}
ptgClass = value;
}
}
public abstract byte DefaultOperandClass { get; }
/**
* Debug / diagnostic method to get this token's 'operand class' type.
* @return 'R' for 'reference', 'V' for 'value', 'A' for 'array' and '.' for base tokens
*/
public char RVAType
{
get
{
if (IsBaseToken)
{
return '.';
}
switch (ptgClass)
{
case Ptg.CLASS_REF: return 'R';
case Ptg.CLASS_VALUE: return 'V';
case Ptg.CLASS_ARRAY: return 'A';
}
throw new InvalidOperationException("Unknown operand class (" + ptgClass + ")");
}
}
#region ICloneable Members
object ICloneable.Clone()
{
throw new NotImplementedException();
}
#endregion
public static bool DoesFormulaReferToDeletedCell(Ptg[] ptgs)
{
for (int i = 0; i < ptgs.Length; i++)
{
if (IsDeletedCellRef(ptgs[i]))
{
return true;
}
}
return false;
}
private static bool IsDeletedCellRef(Ptg ptg)
{
if (ptg == ErrPtg.REF_INVALID)
{
return true;
}
if (ptg is DeletedArea3DPtg)
{
return true;
}
if (ptg is DeletedRef3DPtg)
{
return true;
}
if (ptg is AreaErrPtg)
{
return true;
}
if (ptg is RefErrorPtg)
{
return true;
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace System
{
public partial class String
{
//
//Native Static Methods
//
private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB)
{
Contract.Requires(strA != null);
Contract.Requires(strB != null);
Contract.EndContractBlock();
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
int charA = 0, charB = 0;
while (length != 0)
{
charA = *a;
charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
//Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
return strA.Length - strB.Length;
}
}
// native call to COMString::CompareOrdinalEx
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int CompareOrdinalHelper(String strA, int indexA, int countA, String strB, int indexB, int countB);
//This will not work in case-insensitive mode for any character greater than 0x80.
//We'll throw an ArgumentException.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte* strBBytes);
//
//
// NATIVE INSTANCE METHODS
//
//
//
// Search/Query methods
//
private unsafe static bool EqualsHelper(String strA, String strB)
{
Contract.Requires(strA != null);
Contract.Requires(strB != null);
Contract.Requires(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// PERF: No length check needed as there is always an int32 worth of string allocated
// This read can also include the null terminator which both strings will have
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
// for AMD64 bit platform we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is a shorter path length.
while (length >= 12)
{
if (*(long*)a != *(long*)b) return false;
if (*(long*)(a + 4) != *(long*)(b + 4)) return false;
if (*(long*)(a + 8) != *(long*)(b + 8)) return false;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a + 2) != *(int*)(b + 2)) return false;
if (*(int*)(a + 4) != *(int*)(b + 4)) return false;
if (*(int*)(a + 6) != *(int*)(b + 6)) return false;
if (*(int*)(a + 8) != *(int*)(b + 8)) return false;
length -= 10; a += 10; b += 10;
}
#endif
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
}
return true;
}
}
private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB)
{
Contract.Requires(strA != null);
Contract.Requires(strB != null);
Contract.Requires(strA.Length == strB.Length);
Contract.EndContractBlock();
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
while (length != 0)
{
int charA = *a;
int charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (charA == charB ||
((charA | 0x20) == (charB | 0x20) &&
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
{
a++;
b++;
length--;
}
else
{
return false;
}
}
return true;
}
}
private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
{
Contract.Requires(str != null);
Contract.Requires(startsWith != null);
Contract.Requires(str.Length >= startsWith.Length);
int length = startsWith.Length;
fixed (char* ap = &str._firstChar) fixed (char* bp = &startsWith._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
while (length >= 12)
{
if (*(long*)a != *(long*)b) return false;
if (*(long*)(a + 4) != *(long*)(b + 4)) return false;
if (*(long*)(a + 8) != *(long*)(b + 8)) return false;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a+2) != *(int*)(b+2)) return false;
if (*(int*)(a+4) != *(int*)(b+4)) return false;
if (*(int*)(a+6) != *(int*)(b+6)) return false;
if (*(int*)(a+8) != *(int*)(b+8)) return false;
length -= 10; a += 10; b += 10;
}
#endif
while (length >= 2)
{
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
}
// PERF: This depends on the fact that the String objects are always zero terminated
// and that the terminating zero is not included in the length. For even string sizes
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
}
}
private unsafe static int CompareOrdinalHelper(String strA, String strB)
{
Contract.Requires(strA != null);
Contract.Requires(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined by the JIT
Debug.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string (not including sync block pointer)
// is the method table pointer + string length, which takes up
// 8 bytes on 32-bit, 12 on x64. For empty strings the null
// terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
// Provides a culture-correct string comparison. StrA is compared to StrB
// to determine whether it is lexicographically less, equal, or greater, and then returns
// either a negative integer, 0, or a positive integer; respectively.
//
[Pure]
public static int Compare(String strA, String strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase
//
[Pure]
public static int Compare(String strA, String strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
[Pure]
public static int Compare(String strA, String strB, StringComparison comparisonType)
{
// Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
if ((uint)(comparisonType - StringComparison.CurrentCulture) > (uint)(StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture))
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
// If both strings are ASCII strings, we can take the fast path.
if (strA.IsAscii() && strB.IsAscii())
{
return (CompareOrdinalIgnoreCaseHelper(strA, strB));
}
return CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
default:
throw new NotSupportedException(SR.NotSupported_StringComparison);
}
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
//
[Pure]
public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
Contract.EndContractBlock();
return culture.CompareInfo.Compare(strA, strB, options);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase, and the culture is set
// by culture
//
[Pure]
public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, strB, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length.
//
[Pure]
public static int Compare(String strA, int indexA, String strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
[Pure]
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to CompareInfo.Compare for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
// and the culture is set by culture.
//
[Pure]
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, indexA, strB, indexB, length, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
[Pure]
public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
Contract.EndContractBlock();
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
[Pure]
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
return (CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB));
default:
throw new ArgumentException(SR.NotSupported_StringComparison);
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
[Pure]
public static int CompareOrdinal(String strA, String strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
[Pure]
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
[Pure]
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
string other = value as string;
if (other == null)
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
[Pure]
public int CompareTo(String strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
[Pure]
public Boolean EndsWith(String value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
[Pure]
public Boolean EndsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
[Pure]
public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture;
if (culture == null)
referenceCulture = CultureInfo.CurrentCulture;
else
referenceCulture = culture;
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
[Pure]
public bool EndsWith(char value)
{
int thisLen = Length;
return thisLen != 0 && this[thisLen - 1] == value;
}
// Determines whether two strings match.
public override bool Equals(Object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
string str = obj as string;
if (str == null)
return false;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
// Determines whether two strings match.
[Pure]
public bool Equals(String value)
{
if (object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
}
[Pure]
public bool Equals(String value, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
Contract.EndContractBlock();
if ((Object)this == (Object)value)
{
return true;
}
if ((Object)value == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
// If both strings are ASCII strings, we can take the fast path.
if (this.IsAscii() && value.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(this, value);
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
[Pure]
public static bool Equals(String a, String b)
{
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
[Pure]
public static bool Equals(String a, String b, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
Contract.EndContractBlock();
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
else
{
// If both strings are ASCII strings, we can take the fast path.
if (a.IsAscii() && b.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(a, b);
}
// Take the slow path.
return (CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
}
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static bool operator ==(String a, String b)
{
return String.Equals(a, b);
}
public static bool operator !=(String a, String b)
{
return !String.Equals(a, b);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalMarvin32HashString(string s);
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
return InternalMarvin32HashString(this);
}
// Gets a hash code for this string and this comparison. If strings A and B and comparition C are such
// that String.Equals(A, B, C), then they will return the same hash code with this comparison C.
public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
internal int GetLegacyNonRandomizedHashCode()
{
unsafe
{
fixed (char* src = &_firstChar)
{
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
int hash1 = (5381<<16) + 5381;
#endif
int hash2 = hash1;
#if BIT64
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#else // !BIT64 (32)
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
}
#endif
#if DEBUG
// We want to ensure we can change our hash function daily.
// This is perfectly fine as long as you don't persist the
// value from GetHashCode to disk or count on String A
// hashing before string B. Those are bugs in your code.
hash1 ^= ThisAssembly.DailyBuildNumber;
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
// Determines whether a specified string is a prefix of the current instance
//
[Pure]
public Boolean StartsWith(String value)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return StartsWith(value, StringComparison.CurrentCulture);
}
[Pure]
public Boolean StartsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
StartsWithOrdinalHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
[Pure]
public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture;
if (culture == null)
referenceCulture = CultureInfo.CurrentCulture;
else
referenceCulture = culture;
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
[Pure]
public bool StartsWith(char value) => Length != 0 && _firstChar == value;
}
}
| |
/*********************************************************************************
* Author: Michael Parsons
* Based on an article by Francesco Balena - Code Architects
* http://www.cs2themax.com/showcontent.aspx?id=5f606582-4626-4c6f-a6e9-6f952f31491a
* Date: Sep. 2, 2004
* Assembly: utilityClasses
* Description:
* Notes:
*
*
* Copyright 2004, DCEO All rights reserved.
*********************************************************************************/
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ILPathways.Utilities
{
/// <summary>
/// Utility class for a ASP.NET page
/// Used to open a new browser window while keeping the current window open.
/// Can be attached to a control or to the page load (for example on a post back after an update!
/// </summary>
/// <remarks>
/// Sample uses:
/// The constructor of the BrowserWindow class lets you define the target URL and the size of the secondary window.
/// All other fields must be set by plain assignments:
/// BrowserWindow win = new BrowserWindow("www.vb2themax.com", 500, 400);
/// win.Resizable = true;
/// win.ScrollBars = true;
/// win.StatusBar = true;
///
/// The BrowserWindow class exposes two methods: AttachToControl lets you attach the window.open method to the
/// onClick client-side event of a Button, LinkButton, or any other WebControl-derived control.
/// In this case the open method runs exclusively on the client and no postpack occurs. You typically invoke this
/// method from inside the Page_Load event handler:
/// <code>
/// private void Page_Load(object sender, EventArgs e) {
/// if ( ! this.IsPostBack ) {
/// BrowserWindow win = new BrowserWindow("www.vb2themax.com", 500, 400);
/// win.Resizable = true;
/// win.ScrollBars = true;
/// win.StatusBar = true;
/// win.AttachToControl(btnOpenWindow);
/// }
/// }
/// </code>
/// The second method, AttachToPageLoad, lets you open the secondary window after a page postback.
/// This method is useful, for example, when you need to update some controls on the main page and then open a secondary window.
/// Here's an example of how to use this method:
/// <code>
/// private void btnOpen_Click(object sender, System.EventArgs e) {
/// // display a secondary window when current page is sent to the browser
/// BrowserWindow win = new BrowserWindow("www.vb2themax.com", 500, 300);
/// win.AttachToPageLoad(this);
/// }
/// </code>
/// </remarks>
public class BrowserWindow
{
public string URL; // the URL of the page to be displayed
public string Name; // the name of the new window
public int Height; // the height of the window
public int Width; // the width of the window
public bool StatusBar; // true to display a status bar
public bool Resizable; // true to make the window resizable
public bool ScrollBars; // true to display scrollbars
public bool ToolBar; // true to display a toolbar
public bool Location; // true to display the address bar
public bool MenuBar; // true to display the menu bar
public bool CopyHistory; // true to copy current history to the new window
/// <summary>
/// BrowserWindow constructor takes url and size
/// </summary>
/// <param name="url">Starting URL for window - without the http://</param>
/// <param name="width">Window Width</param>
/// <param name="height">Window Height</param>
public BrowserWindow(string url, int width, int height)
{
this.URL = url;
this.Width = width;
this.Height = height;
} //
/// <summary>
/// BrowserWindow constructor set url, size, and interface defaults
/// </summary>
/// <param name="url">Starting URL for window - without the http://</param>
/// <param name="width">Window Width</param>
/// <param name="height">Window Height</param>
/// <param name="interfaceDefaults">Set to true to show common browser interface items</param>
public BrowserWindow( string url, int width, int height, bool interfaceDefaults )
{
this.URL = url;
this.Width = width;
this.Height = height;
this.SetInterfaceDefaults( interfaceDefaults );
}
/// <summary>
/// BrowserWindow constructor set host, url, and size
/// </summary>
/// <param name="host">Web Server Host</param>
/// <param name="url">Starting URL for window - without the http://</param>
/// <param name="width">Window Width</param>
/// <param name="height">Window Height</param>
public BrowserWindow(string host, string url, int width, int height) {
char [] arr = {'/', '\\'};
//check for terminating slashes
string address = host.Trim();
address = address.TrimEnd(arr);
//if (address.EndsWith("/") > 0 || address.EndsWith("\\") > 0) address = address.TrimEnd("/", "\\");
this.URL = address + "/" + url.TrimStart(arr);
this.Width = width;
this.Height = height;
}
/// <summary>
/// Set the default value for common browser interface elements
/// - Resizable, Menubar, Location, Toolbar, Scrollbars, Status Bar
/// </summary>
/// <param name="interfaceDefaults">Use true to show items or false to hide</param>
public void SetInterfaceDefaults( bool interfaceDefaults )
{
Resizable = interfaceDefaults;
MenuBar = interfaceDefaults;
Location = interfaceDefaults;
ToolBar = interfaceDefaults;
ScrollBars = interfaceDefaults;
StatusBar = interfaceDefaults;
}
/// <summary>
/// attach the window.open method to a control
/// </summary>
/// <param name="ctrl"></param>
public void AttachToControl(WebControl ctrl)
{
// add the attribute to the control
ctrl.Attributes.Add("onClick", "javascript:" + GetScriptCode());
}
/// <summary>
/// attach to a Page's Load event
/// </summary>
/// <param name="page"></param>
public void AttachToPageLoad( Page page)
{
// register as the startup script, using a unique key name
string key = this.GetHashCode().ToString();
page.RegisterStartupScript("open", "<script language=javascript>" +
this.GetScriptCode() + "</script>");
}
/// <summary>
/// attach to a Control's Load event
/// </summary>
/// <param name="control"></param>
public void AttachToPageLoad( Control control) {
// register as the startup script, using a unique key name
string key = this.GetHashCode().ToString();
control.Page.RegisterStartupScript("open", "<script language=javascript>" +
this.GetScriptCode() + "</script>");
}
/// <summary>
/// get the javascript code that opens the window
/// </summary>
/// <returns>Javascript to open a window</returns>
public string GetScriptCode()
{
// the URL must be preceded by HTTP://
string url = this.URL;
if ( !url.ToLower().StartsWith( "http" ) )
{
//TODO guess if the domain is missing
url = "http://" + url;
}
// the window name can be null or must be encloses between single quotes
string winName = "null";
if ( this.Name != null )
winName = "'" + this.Name + "'";
// build the windows feature argument
string features = string .Format("height={0}, width={1}, status={2}, resizable={3"
+ "}, scrollbars={4}, menubar={5}, toolbar={6}, location={7}, copyhistory={8}",
this.Height, this.Width, YesNo(this.StatusBar), YesNo(this.Resizable), YesNo(
this.ScrollBars), YesNo(this.MenuBar), YesNo(this.ToolBar), YesNo(
this.Location), YesNo(this.CopyHistory));
// build and return the script code
return string .Format("window.open('{0}', {1}, '{2}');", url, winName, features);
}
/// <summary>
/// helper routine that returns "no" or "yes"
/// </summary>
/// <param name="val">Boolean value</param>
/// <returns>String yes/no</returns>
private string YesNo( bool val )
{
return val ? "yes" : "no" ;
}
} //class
} //namespace
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System.Text.RegularExpressions;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
public class HttpRequestModule : IRegionModule, IHttpRequestModule
{
private Amib.Threading.SmartThreadPool _threadPool;
private Amib.Threading.SmartThreadPool _slowPool;
private readonly object m_httpListLock = new object();
private const int HTTP_TIMEOUT = 60 * 1000; // 60 seconds
private const string m_name = "HttpScriptRequests";
/// <summary>
/// The maximum number of inflight requests for the entire region before we start
/// returning null request IDs
/// </summary>
private const int MAX_REQUEST_QUEUE_SIZE = 200;
/// <summary>
/// The maximum number of slow HTTP requests we allow in the queue
/// </summary>
private const int MAX_SLOW_REQUEST_QUEUE_SIZE = 50;
/// <summary>
/// The maximum number of inflight requests for a single object before we start
/// returning null request IDs
/// </summary>
private const int MAX_SINGLE_OBJECT_QUEUE_SIZE = 10;
/// <summary>
/// The maximum number of threads to use for normal priority requests
/// </summary>
private const int MAX_NORMAL_THREADS = 24;
/// <summary>
/// The maximum number of threads to use for known slow requests
/// </summary>
private const int MAX_SLOW_THREADS = 8;
/// <summary>
/// The amount of time above which we consider a script to be slow (ms)
/// </summary>
private const int SLOW_SCRIPT_TIME = 3000;
/// <summary>
/// The amount of time above which we consider a script to be normal (ms)
/// Objects that respond faster than this time will have their priorities raised
/// if their priority is currently below normal
/// </summary>
private const int NORMAL_SCRIPT_TIME = 1000;
/// <summary>
/// The number of seconds we wait before checking the priority list for expired objects
/// </summary>
private const int PRIORITY_MAINT_SECS = 300;
/// <summary>
/// The number of seconds we remember the lower priority of misbehaving scripts
/// </summary>
private const int PRIORITY_TIMEOUT_SECS = 600;
private string m_proxyurl = String.Empty;
private string m_proxyexcepts = String.Empty;
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestObject> m_pendingRequests;
private Queue<HttpRequestObject> m_completedRequests;
private Scene m_scene;
/// <summary>
/// Tracks the number of http requests per script
/// </summary>
private Dictionary<UUID, short> m_objectQueueSize;
/// <summary>
/// A debugging log reporting level, 0 is off. See HttpRequestConsoleCommand().
/// </summary>
private int m_debugLevel = 0;
/// <summary>
/// Priorities for HTTP calls coming from an object based on the history of its behavior
/// </summary>
private Dictionary<UUID, TimestampedItem<Amib.Threading.WorkItemPriority>> m_objectPriorities;
/// <summary>
/// The last time in ticks that we maintained the priority list
/// </summary>
private ulong m_lastPriorityMaintenance;
/// <summary>
/// The number of low priority jobs that are currently queued
/// </summary>
private int m_numLowPriorityQueued;
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate;
}
#region IRegionModule Members
public void Initialize(Scene scene, IConfigSource config)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
m_pendingRequests = new Dictionary<UUID, HttpRequestObject>();
m_completedRequests = new Queue<HttpRequestObject>();
m_objectQueueSize = new Dictionary<UUID, short>();
m_objectPriorities = new Dictionary<UUID, TimestampedItem<Amib.Threading.WorkItemPriority>>();
m_lastPriorityMaintenance = Util.GetLongTickCount();
_threadPool = new Amib.Threading.SmartThreadPool(Amib.Threading.SmartThreadPool.DefaultIdleTimeout, MAX_NORMAL_THREADS, 2);
_threadPool.Name = "HttpRequestWorkerNormal";
_slowPool = new Amib.Threading.SmartThreadPool(Amib.Threading.SmartThreadPool.DefaultIdleTimeout, MAX_SLOW_THREADS, 0);
_slowPool.Name = "HttpRequestWorkerSlow";
ReadBlacklistFromConfig(config.Configs["HttpRequest"]);
MainConsole.Instance.Commands.AddCommand(
"Comms",
true,
"httprequest queuelength",
"httprequest queuelength",
"Report on the current size of the request queue.",
"Displays the current size of the request queue.",
HttpRequestConsoleCommand);
MainConsole.Instance.Commands.AddCommand(
"Comms",
true,
"httprequest debug",
"httprequest debug <debuglevel>",
"Enable/disable debugging of the request queue.",
"Enable/disable debugging of the request queue.",
HttpRequestConsoleCommand);
}
public void PostInitialize()
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
#region IHttpRequestModule Members
public int OutstandingRequests
{
get { return m_pendingRequests.Count; }
}
public float RequestQueueFreeSpacePercentage
{
get
{
if (OutstandingRequests >= MAX_REQUEST_QUEUE_SIZE)
return 0.0f; // No space
else
return 1.0f - (float)OutstandingRequests / MAX_REQUEST_QUEUE_SIZE;
}
}
// Called only from HTTP_CUSTOM_HEADER.
private bool ScriptCanChangeHeader(string key)
{
string targetKey = key.ToLower();
// Content-type must be set via HTTP_MIMETYPE
if (targetKey == "content-type")
return false;
// These are reserved for internal use only.
// if (targetKey == "user-agent") // SL allows appending multi-line text on the end of the URL to achieve this.
// return false; // instead we'll just allow it normally.
if (targetKey.StartsWith("x-secondlife"))
return false;
return true;
}
public UUID StartHttpRequest(UUID sogId, uint localID, UUID itemID, string url, string[] parms, Dictionary<string, string> headers, string body)
{
//if there are already too many requests globally, reject this one
if (RequestQueueFreeSpacePercentage == 0.0f) return UUID.Zero;
// fast exit for the common case of scripter error passing an empty URL
if (String.IsNullOrEmpty(url)) return UUID.Zero;
if (BlockedByBlacklist(url)) return UUID.Zero;
UUID reqID = UUID.Random();
HttpRequestObject htc = new HttpRequestObject();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
try
{
int i = 0;
while (i < parms.Length)
{
switch (Int32.Parse(parms[i++]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
// This one was validated to be one of the valid values for method in LSLSystemAPI.cs
htc.HttpMethod = parms[i++];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i++];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
htc.HttpBodyMaxLength = int.Parse(parms[i++]);
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i++]) != 0);
break;
case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
htc.HttpVerboseThrottle = (int.Parse(parms[i++]) != 0);
break;
case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
string key = parms[i++];
string value = parms[i++];
// The script is not allowed to override some of the headers.
if (ScriptCanChangeHeader(key))
{
if (headers.ContainsKey(key))
{
// In SL, duplicate headers add to the existing header after a comma+space
headers[key] += ", " + value;
}
else
{
headers.Add(key, value);
}
}
break;
case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
// What if there is more than one pragma header defined?
bool noCache = (int.Parse(parms[i++]) != 0);
if (noCache == true)
headers.Add("Pragma", "no-cache");
else if (headers.ContainsKey("Pragma"))
headers.Remove("Pragma");
break;
default:
// Invalid Parameter Type. Log an error?
// Fail the request by returning a Null Key
return UUID.Zero;
}
}
}
catch (System.IndexOutOfRangeException)
{
// They passed us junk, we stepped past the end of the array.
// We'll fail the request by returning a NULL_KEY
return UUID.Zero;
}
if (m_debugLevel >= 1)
MainConsole.Instance.OutputFormat("httprequest: LocalID={0} URL={1}", localID, url);
htc.LocalID = localID;
htc.ItemID = itemID;
htc.SogID = sogId;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = HTTP_TIMEOUT;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
Amib.Threading.WorkItemPriority prio;
lock (m_httpListLock)
{
//if there are already too many requests for this script running, reject this one
if (!TryIncrementObjectQueue(sogId))
{
return UUID.Zero;
}
prio = GetObjectPriority(sogId);
if (prio == Amib.Threading.WorkItemPriority.Lowest)
{
if (m_numLowPriorityQueued < MAX_SLOW_REQUEST_QUEUE_SIZE)
{
htc.IsLowPriority = true;
++m_numLowPriorityQueued;
}
else
{
DecrementObjectQueue(sogId);
return UUID.Zero;
}
}
m_pendingRequests.Add(reqID, htc);
}
if (prio > Amib.Threading.WorkItemPriority.Lowest)
{
_threadPool.QueueWorkItem(() => this.ProcessRequest(htc));
}
else
{
_slowPool.QueueWorkItem(() => this.ProcessRequest(htc));
}
return reqID;
}
private bool TryIncrementObjectQueue(UUID sogId)
{
short size;
if (m_objectQueueSize.TryGetValue(sogId, out size))
{
if (size >= MAX_SINGLE_OBJECT_QUEUE_SIZE)
{
return false;
}
else
{
m_objectQueueSize[sogId] = ++size;
}
}
else
{
m_objectQueueSize.Add(sogId, 1);
}
return true;
}
private void ProcessRequest(HttpRequestObject req)
{
req.Process();
lock (m_httpListLock)
{
m_pendingRequests.Remove(req.ReqID);
m_completedRequests.Enqueue(req);
DecrementObjectQueue(req.SogID);
AdjustObjectPriority(req);
MaintainPriorityQueue();
}
}
private void MaintainPriorityQueue()
{
if (Util.GetLongTickCount() - m_lastPriorityMaintenance > PRIORITY_MAINT_SECS)
{
List<UUID> expiredObjects = new List<UUID>();
foreach (var kvp in m_objectPriorities)
{
if (kvp.Value.ElapsedSeconds >= PRIORITY_TIMEOUT_SECS)
{
expiredObjects.Add(kvp.Key);
}
}
foreach (var id in expiredObjects)
{
m_objectPriorities.Remove(id);
}
m_lastPriorityMaintenance = Util.GetLongTickCount();
}
}
/// <summary>
/// Based on the time it took a request to run, we adjust the priority
/// of future requests sent by an object
/// </summary>
/// <param name="req"></param>
private void AdjustObjectPriority(HttpRequestObject req)
{
Amib.Threading.WorkItemPriority prio = GetObjectPriority(req.SogID);
if (req.RequestDuration >= SLOW_SCRIPT_TIME)
{
if (prio > Amib.Threading.WorkItemPriority.Lowest)
{
prio--;
SetObjectPriority(req.SogID, prio);
}
}
else if (req.RequestDuration < NORMAL_SCRIPT_TIME)
{
if (prio < Amib.Threading.WorkItemPriority.Normal)
{
prio++;
SetObjectPriority(req.SogID, prio);
}
}
else
{
//just ping the timestamp if it exists
UpdatePriorityTimestamp(req.SogID);
}
//also if this request was low priority, maintain the counts
--m_numLowPriorityQueued;
}
private void UpdatePriorityTimestamp(UUID sogId)
{
TimestampedItem<Amib.Threading.WorkItemPriority> prio;
if (m_objectPriorities.TryGetValue(sogId, out prio))
{
prio.ResetTimestamp();
}
}
private void SetObjectPriority(UUID sogId, Amib.Threading.WorkItemPriority newPrio)
{
TimestampedItem<Amib.Threading.WorkItemPriority> prio;
if (m_objectPriorities.TryGetValue(sogId, out prio))
{
prio.Item = newPrio;
prio.ResetTimestamp();
}
else
{
m_objectPriorities[sogId] = new TimestampedItem<Amib.Threading.WorkItemPriority>(newPrio);
}
}
private Amib.Threading.WorkItemPriority GetObjectPriority(UUID sogId)
{
TimestampedItem<Amib.Threading.WorkItemPriority> prio;
if (! m_objectPriorities.TryGetValue(sogId, out prio))
{
return Amib.Threading.WorkItemPriority.Normal;
}
return prio.Item;
}
private void DecrementObjectQueue(UUID sogId)
{
short size;
if (m_objectQueueSize.TryGetValue(sogId, out size))
{
--size;
if (size == 0)
{
m_objectQueueSize.Remove(sogId);
}
else
{
m_objectQueueSize[sogId] = size;
}
}
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (m_httpListLock)
{
m_objectQueueSize.Remove(m_itemID);
}
}
//The code below has been commented out because it doesn't work
//the problem is that m_itemID is not being used as the key for
//m_pendingRequests. m_pendingRequests key is the randomly generated
//request id generated in StartHttpRequestAbove
//TODO: Actually abort requests that haven't been started yet
/*
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
m_pendingRequests.Remove(m_itemID);
}
}
}
*/
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finsihed. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (m_httpListLock)
{
if (m_completedRequests.Count == 0) return null;
else return m_completedRequests.Dequeue();
}
}
#endregion
protected void HttpRequestConsoleCommand(string module, string[] args)
{
if (args.Length < 2)
return;
if (args[1] == "queuelength")
{
MainConsole.Instance.OutputFormat(
"Region {0} httprequest queue contains {1} requests",
m_scene.RegionInfo.RegionName,
OutstandingRequests);
return;
}
if (args[1] == "debug")
{
if (args.Length >= 3)
m_debugLevel = Convert.ToInt32(args[2]);
MainConsole.Instance.OutputFormat("httprequest debug level is {0}", m_debugLevel);
return;
}
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
HttpWebRequest Request = (HttpWebRequest) sender;
if (Request.Headers.Get("NoVerifyCert") != null)
return true;
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
return true;
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
#region Blacklist Checks
private List<string> _hostsBlacklist = new List<string>();
private List<int> _portsBlacklist = new List<int>();
private List<KeyValuePair<string, int>> _hostnameAndPortBlacklist = new List<KeyValuePair<string, int>>();
/// <summary>
/// Reads the blacklist config from the given configuration file
/// </summary>
/// <param name="config"></param>
private void ReadBlacklistFromConfig(IConfig config)
{
try
{
if (config == null)
return;
string hostBlacklist = config.GetString("HostBlacklist", String.Empty);
string portBlacklist = config.GetString("PortBlacklist", String.Empty);
string hostnameAndPortBlacklist = config.GetString("HostnameAndPortBlacklist", String.Empty);
if (!string.IsNullOrEmpty(hostBlacklist))
{
string[] hosts = hostBlacklist.Split(',');
foreach (string host in hosts)
_hostsBlacklist.Add(WildcardToRegex(host));
}
if (!string.IsNullOrEmpty(portBlacklist))
{
string[] ports = portBlacklist.Split(',');
foreach (string port in ports)
_portsBlacklist.Add(int.Parse(port));
}
if (!string.IsNullOrEmpty(hostnameAndPortBlacklist))
{
string[] hosts = hostnameAndPortBlacklist.Split(',');
foreach (string host in hosts)
{
string[] url = host.Split(':');
_hostnameAndPortBlacklist.Add(new KeyValuePair<string, int>(WildcardToRegex(url[0]), int.Parse(url[1])));
}
}
/*
Tests with config as follows
HostBlacklist = "10.0.0.1,20.0.0.*,google.com"
PortBlacklist = "8010,8020"
HostnameAndPortBlacklist = "192.168.1.*:80,yahoo.com:1234"
bool blocked;
blocked = BlockedByBlacklist("http://10.0.0.1:1234"); //true
blocked = BlockedByBlacklist("http://10.0.0.2:1234"); //false
blocked = BlockedByBlacklist("http://20.0.0.2:1234"); //true
blocked = BlockedByBlacklist("http://20.0.0.1:1234"); //true
blocked = BlockedByBlacklist("http://1.2.3.4:1234"); //false
blocked = BlockedByBlacklist("http://1.2.3.4:8010"); //true
blocked = BlockedByBlacklist("http://1.2.3.4:8020"); //true
blocked = BlockedByBlacklist("http://192.168.1.1:8080"); //false
blocked = BlockedByBlacklist("http://192.168.1.1:80"); //true
blocked = BlockedByBlacklist("http://192.168.1.1/test.html");
blocked = BlockedByBlacklist("http://google.com/test.html");//true
blocked = BlockedByBlacklist("http://yahoo.com/test.html");//false
blocked = BlockedByBlacklist("http://yahoo.com:1234/test.html");//true
*/
}
catch (Exception ex)
{
MainConsole.Instance.Output("[ScriptsHttpRequest]: Failed to parse blacklist config: " + ex.ToString());
}
}
/// <summary>
/// Checks to make sure that a url is allowed by the blacklist
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private bool BlockedByBlacklist(string url)
{
try
{
Uri uri = new Uri(url);
if (uri.Scheme != "http" && uri.Scheme != "https") return true;
//Port check
if (_portsBlacklist.Contains(uri.Port))
return true;
//Hostname check
if (_hostsBlacklist.Any((h) => Regex.IsMatch(uri.Host, h)))
return true;
//Hostname+port check
if (_hostnameAndPortBlacklist.Any((kvp) => Regex.IsMatch(uri.Host, kvp.Key) && kvp.Value == uri.Port))
return true;
return false;
}
catch (Exception ex)
{
MainConsole.Instance.Output("[ScriptsHttpRequest]: Failed to parse URL for blacklist check '" + url + "': " + ex.ToString());
}
return true;
}
/// <summary>
/// Converts a normal wildcard (e.g. 192.168.1.*) to a proper regular expression (^192\.168\.1\..*$)
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
private string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern)
.Replace(@"\*", ".*")
+ "$";
}
#endregion
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// EmailPerformanceDaily
/// </summary>
[DataContract]
public partial class EmailPerformanceDaily : IEquatable<EmailPerformanceDaily>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="EmailPerformanceDaily" /> class.
/// </summary>
/// <param name="bounceCount">Bounce count.</param>
/// <param name="deliveredCount">Delivered count.</param>
/// <param name="revenue">Revenue.</param>
/// <param name="sequenceSendCount">Total sequence (campaign/flow) emails sent.</param>
/// <param name="spamCount">Spam complaints.</param>
/// <param name="statDts">The date that these statistcs are for.</param>
/// <param name="transactionalSendCount">Total transactions emails sent.</param>
public EmailPerformanceDaily(int? bounceCount = default(int?), int? deliveredCount = default(int?), decimal? revenue = default(decimal?), int? sequenceSendCount = default(int?), int? spamCount = default(int?), string statDts = default(string), int? transactionalSendCount = default(int?))
{
this.BounceCount = bounceCount;
this.DeliveredCount = deliveredCount;
this.Revenue = revenue;
this.SequenceSendCount = sequenceSendCount;
this.SpamCount = spamCount;
this.StatDts = statDts;
this.TransactionalSendCount = transactionalSendCount;
}
/// <summary>
/// Bounce count
/// </summary>
/// <value>Bounce count</value>
[DataMember(Name="bounce_count", EmitDefaultValue=false)]
public int? BounceCount { get; set; }
/// <summary>
/// Delivered count
/// </summary>
/// <value>Delivered count</value>
[DataMember(Name="delivered_count", EmitDefaultValue=false)]
public int? DeliveredCount { get; set; }
/// <summary>
/// Revenue
/// </summary>
/// <value>Revenue</value>
[DataMember(Name="revenue", EmitDefaultValue=false)]
public decimal? Revenue { get; set; }
/// <summary>
/// Total sequence (campaign/flow) emails sent
/// </summary>
/// <value>Total sequence (campaign/flow) emails sent</value>
[DataMember(Name="sequence_send_count", EmitDefaultValue=false)]
public int? SequenceSendCount { get; set; }
/// <summary>
/// Spam complaints
/// </summary>
/// <value>Spam complaints</value>
[DataMember(Name="spam_count", EmitDefaultValue=false)]
public int? SpamCount { get; set; }
/// <summary>
/// The date that these statistcs are for
/// </summary>
/// <value>The date that these statistcs are for</value>
[DataMember(Name="stat_dts", EmitDefaultValue=false)]
public string StatDts { get; set; }
/// <summary>
/// Total transactions emails sent
/// </summary>
/// <value>Total transactions emails sent</value>
[DataMember(Name="transactional_send_count", EmitDefaultValue=false)]
public int? TransactionalSendCount { 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 EmailPerformanceDaily {\n");
sb.Append(" BounceCount: ").Append(BounceCount).Append("\n");
sb.Append(" DeliveredCount: ").Append(DeliveredCount).Append("\n");
sb.Append(" Revenue: ").Append(Revenue).Append("\n");
sb.Append(" SequenceSendCount: ").Append(SequenceSendCount).Append("\n");
sb.Append(" SpamCount: ").Append(SpamCount).Append("\n");
sb.Append(" StatDts: ").Append(StatDts).Append("\n");
sb.Append(" TransactionalSendCount: ").Append(TransactionalSendCount).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as EmailPerformanceDaily);
}
/// <summary>
/// Returns true if EmailPerformanceDaily instances are equal
/// </summary>
/// <param name="input">Instance of EmailPerformanceDaily to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EmailPerformanceDaily input)
{
if (input == null)
return false;
return
(
this.BounceCount == input.BounceCount ||
(this.BounceCount != null &&
this.BounceCount.Equals(input.BounceCount))
) &&
(
this.DeliveredCount == input.DeliveredCount ||
(this.DeliveredCount != null &&
this.DeliveredCount.Equals(input.DeliveredCount))
) &&
(
this.Revenue == input.Revenue ||
(this.Revenue != null &&
this.Revenue.Equals(input.Revenue))
) &&
(
this.SequenceSendCount == input.SequenceSendCount ||
(this.SequenceSendCount != null &&
this.SequenceSendCount.Equals(input.SequenceSendCount))
) &&
(
this.SpamCount == input.SpamCount ||
(this.SpamCount != null &&
this.SpamCount.Equals(input.SpamCount))
) &&
(
this.StatDts == input.StatDts ||
(this.StatDts != null &&
this.StatDts.Equals(input.StatDts))
) &&
(
this.TransactionalSendCount == input.TransactionalSendCount ||
(this.TransactionalSendCount != null &&
this.TransactionalSendCount.Equals(input.TransactionalSendCount))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.BounceCount != null)
hashCode = hashCode * 59 + this.BounceCount.GetHashCode();
if (this.DeliveredCount != null)
hashCode = hashCode * 59 + this.DeliveredCount.GetHashCode();
if (this.Revenue != null)
hashCode = hashCode * 59 + this.Revenue.GetHashCode();
if (this.SequenceSendCount != null)
hashCode = hashCode * 59 + this.SequenceSendCount.GetHashCode();
if (this.SpamCount != null)
hashCode = hashCode * 59 + this.SpamCount.GetHashCode();
if (this.StatDts != null)
hashCode = hashCode * 59 + this.StatDts.GetHashCode();
if (this.TransactionalSendCount != null)
hashCode = hashCode * 59 + this.TransactionalSendCount.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using System.Reflection;
using System.Text;
using log4net;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLXInventoryData : IXInventoryData
{
// private static readonly ILog m_log = LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
private PGSQLFolderHandler m_Folders;
private PGSQLItemHandler m_Items;
public PGSQLXInventoryData(string conn, string realm)
{
m_Folders = new PGSQLFolderHandler(
conn, "inventoryfolders", "InventoryStore");
m_Items = new PGSQLItemHandler(
conn, "inventoryitems", String.Empty);
}
public static UUID str2UUID(string strUUID)
{
UUID newUUID = UUID.Zero;
UUID.TryParse(strUUID, out newUUID);
return newUUID;
}
public XInventoryFolder[] GetFolders(string[] fields, string[] vals)
{
return m_Folders.Get(fields, vals);
}
public XInventoryItem[] GetItems(string[] fields, string[] vals)
{
return m_Items.Get(fields, vals);
}
public bool StoreFolder(XInventoryFolder folder)
{
if (folder.folderName.Length > 64)
folder.folderName = folder.folderName.Substring(0, 64);
return m_Folders.Store(folder);
}
public bool StoreItem(XInventoryItem item)
{
if (item.inventoryName.Length > 64)
item.inventoryName = item.inventoryName.Substring(0, 64);
if (item.inventoryDescription.Length > 128)
item.inventoryDescription = item.inventoryDescription.Substring(0, 128);
return m_Items.Store(item);
}
public bool DeleteFolders(string field, string val)
{
return m_Folders.Delete(field, val);
}
public bool DeleteFolders(string[] fields, string[] vals)
{
return m_Folders.Delete(fields, vals);
}
public bool DeleteItems(string field, string val)
{
return m_Items.Delete(field, val);
}
public bool DeleteItems(string[] fields, string[] vals)
{
return m_Items.Delete(fields, vals);
}
public bool MoveItem(string id, string newParent)
{
return m_Items.MoveItem(id, newParent);
}
public bool MoveFolder(string id, string newParent)
{
return m_Folders.MoveFolder(id, newParent);
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
return m_Items.GetActiveGestures(principalID.ToString());
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Items.GetAssetPermissions(principalID, assetID);
}
}
public class PGSQLItemHandler : PGSQLInventoryHandler<XInventoryItem>
{
public PGSQLItemHandler(string c, string t, string m) :
base(c, t, m)
{
}
public bool MoveItem(string id, string newParent)
{
XInventoryItem[] retrievedItems = Get(new string[] { "inventoryID" }, new string[] { id });
if (retrievedItems.Length == 0)
return false;
UUID oldParent = retrievedItems[0].parentFolderID;
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format(@"update {0} set ""parentFolderID"" = :ParentFolderID where ""inventoryID"" = :InventoryID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("ParentFolderID", newParent));
cmd.Parameters.Add(m_database.CreateParameter("InventoryID", id ));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() == 0)
return false;
}
}
IncrementFolderVersion(oldParent);
IncrementFolderVersion(newParent);
return true;
}
public XInventoryItem[] GetActiveGestures(string principalID)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format(@"select * from inventoryitems where ""avatarID"" = :uuid and ""assetType"" = :type and ""flags"" = 1", m_Realm);
UUID princID = UUID.Zero;
UUID.TryParse(principalID, out princID);
cmd.Parameters.Add(m_database.CreateParameter("uuid", principalID));
cmd.Parameters.Add(m_database.CreateParameter("type", (int)AssetType.Gesture));
cmd.Connection = conn;
conn.Open();
return DoQuery(cmd);
}
}
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format(@"select bit_or(""inventoryCurrentPermissions"") as ""inventoryCurrentPermissions""
from inventoryitems
where ""avatarID"" = :PrincipalID
and ""assetID"" = :AssetID
group by ""assetID"" ", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("AssetID", assetID));
cmd.Connection = conn;
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
int perms = 0;
if (reader.Read())
{
perms = Convert.ToInt32(reader["inventoryCurrentPermissions"]);
}
return perms;
}
}
}
}
public override bool Store(XInventoryItem item)
{
if (!base.Store(item))
return false;
IncrementFolderVersion(item.parentFolderID);
return true;
}
}
public class PGSQLFolderHandler : PGSQLInventoryHandler<XInventoryFolder>
{
public PGSQLFolderHandler(string c, string t, string m) :
base(c, t, m)
{
}
public bool MoveFolder(string id, string newParentFolderID)
{
XInventoryFolder[] folders = Get(new string[] { "folderID" }, new string[] { id });
if (folders.Length == 0)
return false;
UUID oldParentFolderUUID = folders[0].parentFolderID;
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
UUID foldID = UUID.Zero;
UUID.TryParse(id, out foldID);
UUID newPar = UUID.Zero;
UUID.TryParse(newParentFolderID, out newPar);
cmd.CommandText = String.Format(@"update {0} set ""parentFolderID"" = :ParentFolderID where ""folderID"" = :folderID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("ParentFolderID", newPar));
cmd.Parameters.Add(m_database.CreateParameter("folderID", foldID));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() == 0)
return false;
}
}
IncrementFolderVersion(oldParentFolderUUID);
IncrementFolderVersion(newParentFolderID);
return true;
}
public override bool Store(XInventoryFolder folder)
{
if (!base.Store(folder))
return false;
IncrementFolderVersion(folder.parentFolderID);
return true;
}
}
public class PGSQLInventoryHandler<T> : PGSQLGenericTableHandler<T> where T: class, new()
{
public PGSQLInventoryHandler(string c, string t, string m) : base(c, t, m) {}
protected bool IncrementFolderVersion(UUID folderID)
{
return IncrementFolderVersion(folderID.ToString());
}
protected bool IncrementFolderVersion(string folderID)
{
// m_log.DebugFormat("[PGSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
// Util.PrintCallStack();
string sql = @"update inventoryfolders set version=version+1 where ""folderID"" = :folderID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
UUID foldID = UUID.Zero;
UUID.TryParse(folderID, out foldID);
conn.Open();
cmd.Parameters.Add( m_database.CreateParameter("folderID", foldID) );
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
return false;
}
}
}
return true;
}
}
}
| |
using Gedcomx.Model.Rt;
using Gedcomx.Model.Util;
using Gx.Common;
using Gx.Records;
using Gx.Types;
// <auto-generated>
//
//
// Generated by <a href="http://enunciate.codehaus.org">Enunciate</a>.
// </auto-generated>
using System;
using System.Xml.Serialization;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.ComponentModel;
namespace Gx.Conclusion
{
/// <remarks>
/// A conclusion about a fact applicable to a person or relationship.
/// </remarks>
/// <summary>
/// A conclusion about a fact applicable to a person or relationship.
/// </summary>
[Serializable]
[XmlType(Namespace = "http://gedcomx.org/v1/", TypeName = "Fact")]
[XmlRoot(Namespace = "http://gedcomx.org/v1/", ElementName = "fact")]
public partial class Fact : Gx.Conclusion.Conclusion
{
private bool? _primary;
private bool _primarySpecified;
private string _type;
private Gx.Conclusion.DateInfo _date;
private Gx.Conclusion.PlaceReference _place;
private string _value;
private List<Gx.Common.Qualifier> _qualifiers;
private List<Gx.Records.Field> _fields;
public Fact()
{
}
public Fact(FactType factType, String value)
{
SetType(factType);
SetValue(value);
}
public Fact(FactType factType, String date, String place)
:this(factType, new DateInfo().SetOriginal(date), new PlaceReference().SetOriginal(place), null)
{
}
public Fact(FactType factType, DateInfo date, PlaceReference place)
:this(factType, date, place, null)
{
}
public Fact(FactType factType, DateInfo date, PlaceReference place, String value)
{
SetType(factType);
SetDate(date);
SetPlace(place);
SetValue(value);
}
/// <summary>
/// Whether this fact is the primary fact of the record from which the subject was extracted.
/// </summary>
[XmlAttribute(AttributeName = "primary")]
[JsonProperty("primary")]
public bool Primary
{
get
{
return this._primary.GetValueOrDefault();
}
set
{
this._primary = value;
this._primarySpecified = true;
}
}
/// <summary>
/// Property for the XML serializer indicating whether the "Primary" property should be included in the output.
/// </summary>
[XmlIgnore]
[EditorBrowsable(EditorBrowsableState.Never)]
[JsonIgnore]
public bool PrimarySpecified
{
get
{
return this._primarySpecified;
}
set
{
this._primarySpecified = value;
}
}
/// <summary>
/// The type of the fact.
/// </summary>
[XmlAttribute(AttributeName = "type")]
[JsonProperty("type")]
public string Type
{
get
{
return this._type;
}
set
{
this._type = value;
}
}
/// <summary>
/// Convenience property for treating Type as an enum. See Gx.Types.FactTypeQNameUtil for details on getter/setter functionality.
/// </summary>
[XmlIgnore]
[JsonIgnore]
public Gx.Types.FactType KnownType
{
get
{
return XmlQNameEnumUtil.GetEnumValue<FactType>(this._type);
}
set
{
this._type = XmlQNameEnumUtil.GetNameValue(value);
}
}
/// <summary>
/// The date of applicability of this fact.
/// </summary>
[XmlElement(ElementName = "date", Namespace = "http://gedcomx.org/v1/")]
[JsonProperty("date")]
public Gx.Conclusion.DateInfo Date
{
get
{
return this._date;
}
set
{
this._date = value;
}
}
/// <summary>
/// The place of applicability of this fact.
/// </summary>
[XmlElement(ElementName = "place", Namespace = "http://gedcomx.org/v1/")]
[JsonProperty("place")]
public Gx.Conclusion.PlaceReference Place
{
get
{
return this._place;
}
set
{
this._place = value;
}
}
/// <summary>
/// The value as supplied by the user.
/// </summary>
[XmlElement(ElementName = "value", Namespace = "http://gedcomx.org/v1/")]
[JsonProperty("value")]
public string Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
/// <summary>
/// The qualifiers associated with this fact.
/// </summary>
[XmlElement(ElementName = "qualifier", Namespace = "http://gedcomx.org/v1/")]
[JsonProperty("qualifiers")]
public List<Gx.Common.Qualifier> Qualifiers
{
get
{
return this._qualifiers;
}
set
{
this._qualifiers = value;
}
}
/// <summary>
/// The references to the record fields being used as evidence.
/// </summary>
[XmlElement(ElementName = "field", Namespace = "http://gedcomx.org/v1/")]
[JsonProperty("fields")]
public List<Gx.Records.Field> Fields
{
get
{
return this._fields;
}
set
{
this._fields = value;
}
}
/**
* Accept a visitor.
*
* @param visitor The visitor.
*/
public void Accept(IGedcomxModelVisitor visitor)
{
visitor.VisitFact(this);
}
/**
* Build up this fact with a type.
*
* @param type The type.
* @return this
*/
public Fact SetType(String type)
{
Type = type;
return this;
}
/**
* Build up this fact with a type.
*
* @param type The type.
* @return this
*/
public Fact SetType(FactType type)
{
KnownType = type;
return this;
}
/**
* Build up this fact with a 'primary' flag.
*
* @param primary The primary flag.
* @return this.
*/
public Fact SetPrimary(Boolean primary)
{
Primary = primary;
return this;
}
/**
* Build up this fact with a date.
*
* @param date the date.
* @return this.
*/
public Fact SetDate(DateInfo date)
{
Date = date;
return this;
}
/**
* Build up this fact with a place.
*
* @param place The place.
* @return this.
*/
public Fact SetPlace(PlaceReference place)
{
Place = place;
return this;
}
/**
* Build up this fact with a value.
*
* @param value The value.
* @return this.
*/
public Fact SetValue(String value)
{
Value = value;
return this;
}
/**
* Build up this fact with a qualifier.
*
* @param qualifier The qualifier.
* @return this.
*/
public Fact SetQualifier(Qualifier qualifier)
{
AddQualifier(qualifier);
return this;
}
/**
* Build up this fact with a field.
*
* @param field The field.
* @return this.
*/
public Fact SetField(Field field)
{
AddField(field);
return this;
}
/**
* Add a qualifier.
*
* @param qualifier The qualifier.
*/
public void AddQualifier(Qualifier qualifier)
{
if (this._qualifiers == null)
{
this._qualifiers = new List<Qualifier>();
}
this._qualifiers.Add(qualifier);
}
/**
* Add a reference to the record field values being used as evidence.
*
* @param field The field to be added.
*/
public void AddField(Field field)
{
if (field != null)
{
if (_fields == null)
{
_fields = new List<Field>();
}
_fields.Add(field);
}
}
}
}
| |
namespace Gu.Inject.Benchmarks
{
using BenchmarkDotNet.Attributes;
using DryIoc;
using Ninject;
using Ninject.Modules;
using SimpleInjector;
using static Gu.Inject.Benchmarks.Types.Graph500;
[MemoryDiagnoser]
public class NewAndGetGraph500
{
[Benchmark]
public object Ninject()
{
using var kernel = new Ninject.StandardKernel(new Module());
return kernel.Get<Node1>();
}
[Benchmark]
public object SimpleInjector()
{
using var container = new SimpleInjector.Container
{
Options =
{
ResolveUnregisteredConcreteTypes = true,
DefaultLifestyle = Lifestyle.Singleton,
},
};
return container.GetInstance<Node1>();
}
[Benchmark]
public object DryIoc()
{
using var container = new DryIoc.Container(x => x.WithConcreteTypeDynamicRegistrations()
.WithDefaultReuse(Reuse.Singleton));
return container.Resolve<Node1>();
}
[Benchmark(Baseline = true)]
public object GuInject()
{
using var kernel = new Kernel();
return kernel.Get<Node1>();
}
[Benchmark]
public object GuInjectBound()
{
using var kernel = new Kernel()
.Bind(c => new Node1(c.Get<Node7>(), c.Get<Node8>(), c.Get<Node20>(), c.Get<Node26>(),
c.Get<Node29>(), c.Get<Node34>(), c.Get<Node37>(), c.Get<Node49>(), c.Get<Node50>(),
c.Get<Node57>(), c.Get<Node60>(), c.Get<Node63>(), c.Get<Node72>(), c.Get<Node79>(),
c.Get<Node83>(), c.Get<Node93>(), c.Get<Node96>(), c.Get<Node101>(),
c.Get<Node109>(), c.Get<Node113>(), c.Get<Node116>(), c.Get<Node118>(),
c.Get<Node121>(), c.Get<Node124>(), c.Get<Node127>(), c.Get<Node135>(),
c.Get<Node136>(), c.Get<Node144>(), c.Get<Node154>(), c.Get<Node156>(),
c.Get<Node162>(), c.Get<Node167>(), c.Get<Node179>(), c.Get<Node180>(),
c.Get<Node183>(), c.Get<Node188>(), c.Get<Node193>(), c.Get<Node200>(),
c.Get<Node202>(), c.Get<Node207>(), c.Get<Node216>(), c.Get<Node217>(),
c.Get<Node219>(), c.Get<Node221>(), c.Get<Node225>(), c.Get<Node226>(),
c.Get<Node230>(), c.Get<Node233>(), c.Get<Node234>(), c.Get<Node240>(),
c.Get<Node244>(), c.Get<Node245>(), c.Get<Node252>(), c.Get<Node254>(),
c.Get<Node259>(), c.Get<Node261>(), c.Get<Node263>(), c.Get<Node268>(),
c.Get<Node277>(), c.Get<Node282>(), c.Get<Node287>(), c.Get<Node288>(),
c.Get<Node294>(), c.Get<Node295>(), c.Get<Node300>(), c.Get<Node305>(),
c.Get<Node310>(), c.Get<Node318>(), c.Get<Node324>(), c.Get<Node328>(),
c.Get<Node334>(), c.Get<Node338>(), c.Get<Node340>(), c.Get<Node344>(),
c.Get<Node346>(), c.Get<Node348>(), c.Get<Node349>(), c.Get<Node352>(),
c.Get<Node359>(), c.Get<Node363>(), c.Get<Node375>(), c.Get<Node381>(),
c.Get<Node383>(), c.Get<Node395>(), c.Get<Node408>(), c.Get<Node411>(),
c.Get<Node412>(), c.Get<Node415>(), c.Get<Node423>(), c.Get<Node431>(),
c.Get<Node432>(), c.Get<Node437>(), c.Get<Node440>(), c.Get<Node444>(),
c.Get<Node448>(), c.Get<Node461>(), c.Get<Node466>(), c.Get<Node472>(),
c.Get<Node476>(), c.Get<Node485>(), c.Get<Node490>(), c.Get<Node498>()))
.Bind(c => new Node2(c.Get<Node18>(), c.Get<Node30>(), c.Get<Node58>(), c.Get<Node64>(),
c.Get<Node82>(), c.Get<Node86>(), c.Get<Node92>(), c.Get<Node96>(), c.Get<Node102>(),
c.Get<Node104>(), c.Get<Node106>(), c.Get<Node114>(), c.Get<Node116>(),
c.Get<Node130>(), c.Get<Node138>(), c.Get<Node140>(), c.Get<Node146>(),
c.Get<Node174>(), c.Get<Node186>(), c.Get<Node188>(), c.Get<Node190>(),
c.Get<Node208>(), c.Get<Node210>(), c.Get<Node234>(), c.Get<Node236>(),
c.Get<Node246>(), c.Get<Node256>(), c.Get<Node274>(), c.Get<Node280>(),
c.Get<Node288>(), c.Get<Node290>(), c.Get<Node298>(), c.Get<Node302>(),
c.Get<Node306>(), c.Get<Node308>(), c.Get<Node336>(), c.Get<Node356>(),
c.Get<Node358>(), c.Get<Node372>(), c.Get<Node386>(), c.Get<Node396>(),
c.Get<Node414>(), c.Get<Node422>(), c.Get<Node430>(), c.Get<Node434>(),
c.Get<Node438>(), c.Get<Node448>(), c.Get<Node456>(), c.Get<Node472>(),
c.Get<Node478>(), c.Get<Node482>(), c.Get<Node494>()))
.Bind(c => new Node3(c.Get<Node15>(), c.Get<Node36>(), c.Get<Node72>(), c.Get<Node87>(),
c.Get<Node90>(), c.Get<Node126>(), c.Get<Node138>(), c.Get<Node141>(),
c.Get<Node144>(), c.Get<Node150>(), c.Get<Node156>(), c.Get<Node174>(),
c.Get<Node186>(), c.Get<Node204>(), c.Get<Node210>(), c.Get<Node213>(),
c.Get<Node225>(), c.Get<Node279>(), c.Get<Node282>(), c.Get<Node288>(),
c.Get<Node315>(), c.Get<Node321>(), c.Get<Node336>(), c.Get<Node342>(),
c.Get<Node345>(), c.Get<Node357>(), c.Get<Node363>(), c.Get<Node366>(),
c.Get<Node369>(), c.Get<Node405>(), c.Get<Node414>(), c.Get<Node429>(),
c.Get<Node432>(), c.Get<Node438>(), c.Get<Node441>(), c.Get<Node447>(),
c.Get<Node489>()))
.Bind(c => new Node4(c.Get<Node32>(), c.Get<Node36>(), c.Get<Node44>(), c.Get<Node52>(),
c.Get<Node80>(), c.Get<Node108>(), c.Get<Node124>(), c.Get<Node136>(),
c.Get<Node196>(), c.Get<Node232>(), c.Get<Node272>(), c.Get<Node280>(),
c.Get<Node284>(), c.Get<Node292>(), c.Get<Node312>(), c.Get<Node324>(),
c.Get<Node332>(), c.Get<Node352>(), c.Get<Node364>(), c.Get<Node380>(),
c.Get<Node388>(), c.Get<Node396>(), c.Get<Node400>(), c.Get<Node404>(),
c.Get<Node416>(), c.Get<Node424>(), c.Get<Node440>(), c.Get<Node456>(),
c.Get<Node484>()))
.Bind(c => new Node5(c.Get<Node10>(), c.Get<Node30>(), c.Get<Node50>(), c.Get<Node60>(),
c.Get<Node70>(), c.Get<Node75>(), c.Get<Node95>(), c.Get<Node100>(),
c.Get<Node120>(), c.Get<Node160>(), c.Get<Node180>(), c.Get<Node190>(),
c.Get<Node200>(), c.Get<Node205>(), c.Get<Node235>(), c.Get<Node255>(),
c.Get<Node270>(), c.Get<Node310>(), c.Get<Node320>(), c.Get<Node335>(),
c.Get<Node350>(), c.Get<Node370>(), c.Get<Node375>(), c.Get<Node405>(),
c.Get<Node430>(), c.Get<Node475>(), c.Get<Node480>(), c.Get<Node495>()))
.Bind(c => new Node6(c.Get<Node66>(), c.Get<Node84>(), c.Get<Node90>(), c.Get<Node114>(),
c.Get<Node150>(), c.Get<Node180>(), c.Get<Node192>(), c.Get<Node204>(),
c.Get<Node216>(), c.Get<Node234>(), c.Get<Node240>(), c.Get<Node396>()))
.Bind(c => new Node7(c.Get<Node35>(), c.Get<Node63>(), c.Get<Node77>(), c.Get<Node105>(),
c.Get<Node210>(), c.Get<Node217>(), c.Get<Node329>(), c.Get<Node378>(),
c.Get<Node420>(), c.Get<Node441>(), c.Get<Node448>(), c.Get<Node455>()))
.Bind(c => new Node8(c.Get<Node40>(), c.Get<Node168>(), c.Get<Node216>(),
c.Get<Node232>(), c.Get<Node248>(), c.Get<Node264>(), c.Get<Node272>(),
c.Get<Node304>(), c.Get<Node312>(), c.Get<Node456>(), c.Get<Node464>()))
.Bind(c => new Node9(c.Get<Node45>(), c.Get<Node144>(), c.Get<Node216>(),
c.Get<Node315>(), c.Get<Node324>(), c.Get<Node342>(), c.Get<Node351>(),
c.Get<Node387>(), c.Get<Node405>(), c.Get<Node441>()))
.Bind(c => new Node10(c.Get<Node30>(), c.Get<Node130>(), c.Get<Node140>(),
c.Get<Node180>(), c.Get<Node200>(), c.Get<Node300>(), c.Get<Node320>(),
c.Get<Node330>(), c.Get<Node340>(), c.Get<Node370>(), c.Get<Node390>()))
.Bind(c => new Node11(c.Get<Node33>(), c.Get<Node99>(), c.Get<Node110>(),
c.Get<Node275>(), c.Get<Node374>(), c.Get<Node385>(), c.Get<Node418>()))
.Bind(c => new Node12(c.Get<Node60>(), c.Get<Node96>(), c.Get<Node420>()))
.Bind(c => new Node13(c.Get<Node78>(), c.Get<Node221>(), c.Get<Node364>(),
c.Get<Node403>(), c.Get<Node455>()))
.Bind(c => new Node14(c.Get<Node28>(), c.Get<Node84>(), c.Get<Node98>(),
c.Get<Node112>(), c.Get<Node154>(), c.Get<Node196>(), c.Get<Node238>(),
c.Get<Node252>(), c.Get<Node280>(), c.Get<Node322>(), c.Get<Node378>(),
c.Get<Node420>()))
.Bind(c => new Node15(c.Get<Node330>(), c.Get<Node405>(), c.Get<Node465>()))
.Bind(c => new Node16(c.Get<Node176>(), c.Get<Node384>(), c.Get<Node416>(),
c.Get<Node448>()))
.Bind(c => new Node17(c.Get<Node85>(), c.Get<Node102>(), c.Get<Node170>(),
c.Get<Node255>(), c.Get<Node289>(), c.Get<Node306>(), c.Get<Node357>(),
c.Get<Node425>(), c.Get<Node459>()))
.Bind(c => new Node18(c.Get<Node72>(), c.Get<Node90>(), c.Get<Node198>(),
c.Get<Node270>(), c.Get<Node378>(), c.Get<Node414>()))
.Bind(c => new Node19(c.Get<Node209>(), c.Get<Node228>(), c.Get<Node247>(),
c.Get<Node304>(), c.Get<Node342>(), c.Get<Node361>(), c.Get<Node380>(),
c.Get<Node399>(), c.Get<Node494>()))
.Bind(c => new Node20(c.Get<Node60>(), c.Get<Node240>(), c.Get<Node260>(),
c.Get<Node380>()))
.Bind(c => new Node21(c.Get<Node147>(), c.Get<Node210>(), c.Get<Node483>()))
.Bind(c => new Node22(c.Get<Node198>(), c.Get<Node220>(), c.Get<Node264>(),
c.Get<Node308>()))
.Bind(c => new Node23(c.Get<Node115>(), c.Get<Node276>(), c.Get<Node299>(), c.Get<Node368>()))
.Bind(c => new Node24(c.Get<Node96>(), c.Get<Node240>(), c.Get<Node384>()))
.Bind(c => new Node25(c.Get<Node50>(), c.Get<Node100>(), c.Get<Node175>(), c.Get<Node350>()))
.Bind(c => new Node26(c.Get<Node104>(), c.Get<Node260>(), c.Get<Node338>(), c.Get<Node364>(), c.Get<Node390>()))
.Bind(c => new Node27(c.Get<Node81>(), c.Get<Node378>()))
.Bind(c => new Node28(c.Get<Node112>(), c.Get<Node420>()))
.Bind(c => new Node29(c.Get<Node261>(), c.Get<Node406>()))
.Bind(c => new Node30(c.Get<Node150>(), c.Get<Node210>(), c.Get<Node270>(), c.Get<Node480>()))
.Bind(c => new Node31(c.Get<Node62>(), c.Get<Node93>(), c.Get<Node341>(), c.Get<Node372>(), c.Get<Node403>(), c.Get<Node434>()))
.Bind(c => new Node32(c.Get<Node256>()))
.Bind(c => new Node33(c.Get<Node198>(), c.Get<Node330>()))
.Bind(c => new Node34(c.Get<Node68>(), c.Get<Node340>(), c.Get<Node476>()))
.Bind(c => new Node35(c.Get<Node175>(), c.Get<Node210>(), c.Get<Node280>(), c.Get<Node350>(), c.Get<Node455>()))
.Bind(c => new Node36(c.Get<Node108>(), c.Get<Node180>(), c.Get<Node360>()))
.Bind(c => new Node37(c.Get<Node74>(), c.Get<Node370>()))
.Bind(c => new Node38(c.Get<Node76>(), c.Get<Node266>(), c.Get<Node380>()))
.Bind(c => new Node39())
.Bind(c => new Node40(c.Get<Node80>(), c.Get<Node160>(), c.Get<Node200>(), c.Get<Node360>(), c.Get<Node480>()))
.Bind(c => new Node41(c.Get<Node123>(), c.Get<Node246>(), c.Get<Node328>()))
.Bind(c => new Node42())
.Bind(c => new Node43())
.Bind(c => new Node44(c.Get<Node352>(), c.Get<Node396>()))
.Bind(c => new Node45(c.Get<Node135>()))
.Bind(c => new Node46(c.Get<Node92>(), c.Get<Node230>(), c.Get<Node322>()))
.Bind(c => new Node47(c.Get<Node329>()))
.Bind(c => new Node48(c.Get<Node144>(), c.Get<Node288>(), c.Get<Node336>()))
.Bind(c => new Node49(c.Get<Node147>(), c.Get<Node196>(), c.Get<Node441>(), c.Get<Node490>()))
.Bind(c => new Node50())
.Bind(c => new Node51(c.Get<Node204>()))
.Bind(c => new Node52())
.Bind(c => new Node53(c.Get<Node371>()))
.Bind(c => new Node54(c.Get<Node270>()))
.Bind(c => new Node55())
.Bind(c => new Node56())
.Bind(c => new Node57(c.Get<Node285>()))
.Bind(c => new Node58())
.Bind(c => new Node59(c.Get<Node177>(), c.Get<Node236>(), c.Get<Node354>(), c.Get<Node472>()))
.Bind(c => new Node60(c.Get<Node480>()))
.Bind(c => new Node61(c.Get<Node122>()))
.Bind(c => new Node62(c.Get<Node248>(), c.Get<Node310>()))
.Bind(c => new Node63(c.Get<Node126>()))
.Bind(c => new Node64(c.Get<Node192>()))
.Bind(c => new Node65(c.Get<Node260>(), c.Get<Node455>()))
.Bind(c => new Node66(c.Get<Node462>()))
.Bind(c => new Node67(c.Get<Node201>()))
.Bind(c => new Node68(c.Get<Node136>(), c.Get<Node476>()))
.Bind(c => new Node69(c.Get<Node207>()))
.Bind(c => new Node70(c.Get<Node490>()))
.Bind(c => new Node71(c.Get<Node142>(), c.Get<Node355>()))
.Bind(c => new Node72(c.Get<Node144>(), c.Get<Node288>()))
.Bind(c => new Node73())
.Bind(c => new Node74(c.Get<Node222>(), c.Get<Node370>()))
.Bind(c => new Node75())
.Bind(c => new Node76(c.Get<Node304>()))
.Bind(c => new Node77(c.Get<Node308>(), c.Get<Node385>(), c.Get<Node462>()))
.Bind(c => new Node78(c.Get<Node234>()))
.Bind(c => new Node79(c.Get<Node237>()))
.Bind(c => new Node80())
.Bind(c => new Node81())
.Bind(c => new Node82())
.Bind(c => new Node83(c.Get<Node249>(), c.Get<Node498>()))
.Bind(c => new Node84(c.Get<Node168>(), c.Get<Node420>()))
.Bind(c => new Node85(c.Get<Node255>()))
.Bind(c => new Node86())
.Bind(c => new Node87(c.Get<Node261>()))
.Bind(c => new Node88())
.Bind(c => new Node89())
.Bind(c => new Node90())
.Bind(c => new Node91())
.Bind(c => new Node92())
.Bind(c => new Node93())
.Bind(c => new Node94())
.Bind(c => new Node95(c.Get<Node285>(), c.Get<Node380>()))
.Bind(c => new Node96())
.Bind(c => new Node97())
.Bind(c => new Node98())
.Bind(c => new Node99(c.Get<Node396>(), c.Get<Node495>()))
.Bind(c => new Node100(c.Get<Node400>()))
.Bind(c => new Node101())
.Bind(c => new Node102())
.Bind(c => new Node103())
.Bind(c => new Node104())
.Bind(c => new Node105())
.Bind(c => new Node106(c.Get<Node424>()))
.Bind(c => new Node107(c.Get<Node214>()))
.Bind(c => new Node108(c.Get<Node216>()))
.Bind(c => new Node109(c.Get<Node327>(), c.Get<Node436>()))
.Bind(c => new Node110())
.Bind(c => new Node111())
.Bind(c => new Node112())
.Bind(c => new Node113(c.Get<Node226>()))
.Bind(c => new Node114())
.Bind(c => new Node115())
.Bind(c => new Node116(c.Get<Node348>()))
.Bind(c => new Node117())
.Bind(c => new Node118(c.Get<Node236>()))
.Bind(c => new Node119(c.Get<Node357>()))
.Bind(c => new Node120())
.Bind(c => new Node121(c.Get<Node363>()))
.Bind(c => new Node122(c.Get<Node244>()))
.Bind(c => new Node123())
.Bind(c => new Node124(c.Get<Node248>(), c.Get<Node496>()))
.Bind(c => new Node125())
.Bind(c => new Node126())
.Bind(c => new Node127())
.Bind(c => new Node128())
.Bind(c => new Node129())
.Bind(c => new Node130())
.Bind(c => new Node131())
.Bind(c => new Node132())
.Bind(c => new Node133())
.Bind(c => new Node134())
.Bind(c => new Node135())
.Bind(c => new Node136())
.Bind(c => new Node137())
.Bind(c => new Node138(c.Get<Node414>()))
.Bind(c => new Node139(c.Get<Node278>()))
.Bind(c => new Node140())
.Bind(c => new Node141())
.Bind(c => new Node142())
.Bind(c => new Node143())
.Bind(c => new Node144())
.Bind(c => new Node145())
.Bind(c => new Node146(c.Get<Node438>()))
.Bind(c => new Node147())
.Bind(c => new Node148(c.Get<Node296>()))
.Bind(c => new Node149())
.Bind(c => new Node150())
.Bind(c => new Node151())
.Bind(c => new Node152(c.Get<Node304>()))
.Bind(c => new Node153(c.Get<Node459>()))
.Bind(c => new Node154())
.Bind(c => new Node155())
.Bind(c => new Node156())
.Bind(c => new Node157())
.Bind(c => new Node158())
.Bind(c => new Node159())
.Bind(c => new Node160())
.Bind(c => new Node161())
.Bind(c => new Node162())
.Bind(c => new Node163())
.Bind(c => new Node164(c.Get<Node328>()))
.Bind(c => new Node165(c.Get<Node495>()))
.Bind(c => new Node166(c.Get<Node498>()))
.Bind(c => new Node167())
.Bind(c => new Node168())
.Bind(c => new Node169())
.Bind(c => new Node170())
.Bind(c => new Node171())
.Bind(c => new Node172())
.Bind(c => new Node173())
.Bind(c => new Node174())
.Bind(c => new Node175())
.Bind(c => new Node176())
.Bind(c => new Node177())
.Bind(c => new Node178())
.Bind(c => new Node179())
.Bind(c => new Node180())
.Bind(c => new Node181())
.Bind(c => new Node182())
.Bind(c => new Node183())
.Bind(c => new Node184())
.Bind(c => new Node185())
.Bind(c => new Node186(c.Get<Node372>()))
.Bind(c => new Node187(c.Get<Node374>()))
.Bind(c => new Node188())
.Bind(c => new Node189())
.Bind(c => new Node190())
.Bind(c => new Node191(c.Get<Node382>()))
.Bind(c => new Node192())
.Bind(c => new Node193(c.Get<Node386>()))
.Bind(c => new Node194())
.Bind(c => new Node195(c.Get<Node390>()))
.Bind(c => new Node196())
.Bind(c => new Node197())
.Bind(c => new Node198())
.Bind(c => new Node199(c.Get<Node398>()))
.Bind(c => new Node200(c.Get<Node400>()))
.Bind(c => new Node201(c.Get<Node402>()))
.Bind(c => new Node202())
.Bind(c => new Node203())
.Bind(c => new Node204(c.Get<Node408>()))
.Bind(c => new Node205(c.Get<Node410>()))
.Bind(c => new Node206())
.Bind(c => new Node207(c.Get<Node414>()))
.Bind(c => new Node208())
.Bind(c => new Node209())
.Bind(c => new Node210())
.Bind(c => new Node211())
.Bind(c => new Node212(c.Get<Node424>()))
.Bind(c => new Node213())
.Bind(c => new Node214())
.Bind(c => new Node215())
.Bind(c => new Node216(c.Get<Node432>()))
.Bind(c => new Node217())
.Bind(c => new Node218())
.Bind(c => new Node219())
.Bind(c => new Node220())
.Bind(c => new Node221(c.Get<Node442>()))
.Bind(c => new Node222())
.Bind(c => new Node223())
.Bind(c => new Node224())
.Bind(c => new Node225())
.Bind(c => new Node226(c.Get<Node452>()))
.Bind(c => new Node227())
.Bind(c => new Node228())
.Bind(c => new Node229())
.Bind(c => new Node230())
.Bind(c => new Node231())
.Bind(c => new Node232())
.Bind(c => new Node233())
.Bind(c => new Node234())
.Bind(c => new Node235())
.Bind(c => new Node236(c.Get<Node472>()))
.Bind(c => new Node237())
.Bind(c => new Node238(c.Get<Node476>()))
.Bind(c => new Node239())
.Bind(c => new Node240())
.Bind(c => new Node241(c.Get<Node482>()))
.Bind(c => new Node242())
.Bind(c => new Node243(c.Get<Node486>()))
.Bind(c => new Node244())
.Bind(c => new Node245(c.Get<Node490>()))
.Bind(c => new Node246(c.Get<Node492>()))
.Bind(c => new Node247())
.Bind(c => new Node248())
.Bind(c => new Node249())
.Bind(c => new Node250())
.Bind(c => new Node251())
.Bind(c => new Node252())
.Bind(c => new Node253())
.Bind(c => new Node254())
.Bind(c => new Node255())
.Bind(c => new Node256())
.Bind(c => new Node257())
.Bind(c => new Node258())
.Bind(c => new Node259())
.Bind(c => new Node260())
.Bind(c => new Node261())
.Bind(c => new Node262())
.Bind(c => new Node263())
.Bind(c => new Node264())
.Bind(c => new Node265())
.Bind(c => new Node266())
.Bind(c => new Node267())
.Bind(c => new Node268())
.Bind(c => new Node269())
.Bind(c => new Node270())
.Bind(c => new Node271())
.Bind(c => new Node272())
.Bind(c => new Node273())
.Bind(c => new Node274())
.Bind(c => new Node275())
.Bind(c => new Node276())
.Bind(c => new Node277())
.Bind(c => new Node278())
.Bind(c => new Node279())
.Bind(c => new Node280())
.Bind(c => new Node281())
.Bind(c => new Node282())
.Bind(c => new Node283())
.Bind(c => new Node284())
.Bind(c => new Node285())
.Bind(c => new Node286())
.Bind(c => new Node287())
.Bind(c => new Node288())
.Bind(c => new Node289())
.Bind(c => new Node290())
.Bind(c => new Node291())
.Bind(c => new Node292())
.Bind(c => new Node293())
.Bind(c => new Node294())
.Bind(c => new Node295())
.Bind(c => new Node296())
.Bind(c => new Node297())
.Bind(c => new Node298())
.Bind(c => new Node299())
.Bind(c => new Node300())
.Bind(c => new Node301())
.Bind(c => new Node302())
.Bind(c => new Node303())
.Bind(c => new Node304())
.Bind(c => new Node305())
.Bind(c => new Node306())
.Bind(c => new Node307())
.Bind(c => new Node308())
.Bind(c => new Node309())
.Bind(c => new Node310())
.Bind(c => new Node311())
.Bind(c => new Node312())
.Bind(c => new Node313())
.Bind(c => new Node314())
.Bind(c => new Node315())
.Bind(c => new Node316())
.Bind(c => new Node317())
.Bind(c => new Node318())
.Bind(c => new Node319())
.Bind(c => new Node320())
.Bind(c => new Node321())
.Bind(c => new Node322())
.Bind(c => new Node323())
.Bind(c => new Node324())
.Bind(c => new Node325())
.Bind(c => new Node326())
.Bind(c => new Node327())
.Bind(c => new Node328())
.Bind(c => new Node329())
.Bind(c => new Node330())
.Bind(c => new Node331())
.Bind(c => new Node332())
.Bind(c => new Node333())
.Bind(c => new Node334())
.Bind(c => new Node335())
.Bind(c => new Node336())
.Bind(c => new Node337())
.Bind(c => new Node338())
.Bind(c => new Node339())
.Bind(c => new Node340())
.Bind(c => new Node341())
.Bind(c => new Node342())
.Bind(c => new Node343())
.Bind(c => new Node344())
.Bind(c => new Node345())
.Bind(c => new Node346())
.Bind(c => new Node347())
.Bind(c => new Node348())
.Bind(c => new Node349())
.Bind(c => new Node350())
.Bind(c => new Node351())
.Bind(c => new Node352())
.Bind(c => new Node353())
.Bind(c => new Node354())
.Bind(c => new Node355())
.Bind(c => new Node356())
.Bind(c => new Node357())
.Bind(c => new Node358())
.Bind(c => new Node359())
.Bind(c => new Node360())
.Bind(c => new Node361())
.Bind(c => new Node362())
.Bind(c => new Node363())
.Bind(c => new Node364())
.Bind(c => new Node365())
.Bind(c => new Node366())
.Bind(c => new Node367())
.Bind(c => new Node368())
.Bind(c => new Node369())
.Bind(c => new Node370())
.Bind(c => new Node371())
.Bind(c => new Node372())
.Bind(c => new Node373())
.Bind(c => new Node374())
.Bind(c => new Node375())
.Bind(c => new Node376())
.Bind(c => new Node377())
.Bind(c => new Node378())
.Bind(c => new Node379())
.Bind(c => new Node380())
.Bind(c => new Node381())
.Bind(c => new Node382())
.Bind(c => new Node383())
.Bind(c => new Node384())
.Bind(c => new Node385())
.Bind(c => new Node386())
.Bind(c => new Node387())
.Bind(c => new Node388())
.Bind(c => new Node389())
.Bind(c => new Node390())
.Bind(c => new Node391())
.Bind(c => new Node392())
.Bind(c => new Node393())
.Bind(c => new Node394())
.Bind(c => new Node395())
.Bind(c => new Node396())
.Bind(c => new Node397())
.Bind(c => new Node398())
.Bind(c => new Node399())
.Bind(c => new Node400())
.Bind(c => new Node401())
.Bind(c => new Node402())
.Bind(c => new Node403())
.Bind(c => new Node404())
.Bind(c => new Node405())
.Bind(c => new Node406())
.Bind(c => new Node407())
.Bind(c => new Node408())
.Bind(c => new Node409())
.Bind(c => new Node410())
.Bind(c => new Node411())
.Bind(c => new Node412())
.Bind(c => new Node413())
.Bind(c => new Node414())
.Bind(c => new Node415())
.Bind(c => new Node416())
.Bind(c => new Node417())
.Bind(c => new Node418())
.Bind(c => new Node419())
.Bind(c => new Node420())
.Bind(c => new Node421())
.Bind(c => new Node422())
.Bind(c => new Node423())
.Bind(c => new Node424())
.Bind(c => new Node425())
.Bind(c => new Node426())
.Bind(c => new Node427())
.Bind(c => new Node428())
.Bind(c => new Node429())
.Bind(c => new Node430())
.Bind(c => new Node431())
.Bind(c => new Node432())
.Bind(c => new Node433())
.Bind(c => new Node434())
.Bind(c => new Node435())
.Bind(c => new Node436())
.Bind(c => new Node437())
.Bind(c => new Node438())
.Bind(c => new Node439())
.Bind(c => new Node440())
.Bind(c => new Node441())
.Bind(c => new Node442())
.Bind(c => new Node443())
.Bind(c => new Node444())
.Bind(c => new Node445())
.Bind(c => new Node446())
.Bind(c => new Node447())
.Bind(c => new Node448())
.Bind(c => new Node449())
.Bind(c => new Node450())
.Bind(c => new Node451())
.Bind(c => new Node452())
.Bind(c => new Node453())
.Bind(c => new Node454())
.Bind(c => new Node455())
.Bind(c => new Node456())
.Bind(c => new Node457())
.Bind(c => new Node458())
.Bind(c => new Node459())
.Bind(c => new Node460())
.Bind(c => new Node461())
.Bind(c => new Node462())
.Bind(c => new Node463())
.Bind(c => new Node464())
.Bind(c => new Node465())
.Bind(c => new Node466())
.Bind(c => new Node467())
.Bind(c => new Node468())
.Bind(c => new Node469())
.Bind(c => new Node470())
.Bind(c => new Node471())
.Bind(c => new Node472())
.Bind(c => new Node473())
.Bind(c => new Node474())
.Bind(c => new Node475())
.Bind(c => new Node476())
.Bind(c => new Node477())
.Bind(c => new Node478())
.Bind(c => new Node479())
.Bind(c => new Node480())
.Bind(c => new Node481())
.Bind(c => new Node482())
.Bind(c => new Node483())
.Bind(c => new Node484())
.Bind(c => new Node485())
.Bind(c => new Node486())
.Bind(c => new Node487())
.Bind(c => new Node488())
.Bind(c => new Node489())
.Bind(c => new Node490())
.Bind(c => new Node491())
.Bind(c => new Node492())
.Bind(c => new Node493())
.Bind(c => new Node494())
.Bind(c => new Node495())
.Bind(c => new Node496())
.Bind(c => new Node497())
.Bind(c => new Node498())
.Bind(c => new Node499());
return kernel.Get<Node1>();
}
private class Module : NinjectModule
{
public override void Load()
{
this.Bind<Node1>().ToSelf().InSingletonScope();
this.Bind<Node2>().ToSelf().InSingletonScope();
this.Bind<Node3>().ToSelf().InSingletonScope();
this.Bind<Node4>().ToSelf().InSingletonScope();
this.Bind<Node5>().ToSelf().InSingletonScope();
this.Bind<Node6>().ToSelf().InSingletonScope();
this.Bind<Node7>().ToSelf().InSingletonScope();
this.Bind<Node8>().ToSelf().InSingletonScope();
this.Bind<Node9>().ToSelf().InSingletonScope();
this.Bind<Node10>().ToSelf().InSingletonScope();
this.Bind<Node11>().ToSelf().InSingletonScope();
this.Bind<Node12>().ToSelf().InSingletonScope();
this.Bind<Node13>().ToSelf().InSingletonScope();
this.Bind<Node14>().ToSelf().InSingletonScope();
this.Bind<Node15>().ToSelf().InSingletonScope();
this.Bind<Node16>().ToSelf().InSingletonScope();
this.Bind<Node17>().ToSelf().InSingletonScope();
this.Bind<Node18>().ToSelf().InSingletonScope();
this.Bind<Node19>().ToSelf().InSingletonScope();
this.Bind<Node20>().ToSelf().InSingletonScope();
this.Bind<Node21>().ToSelf().InSingletonScope();
this.Bind<Node22>().ToSelf().InSingletonScope();
this.Bind<Node23>().ToSelf().InSingletonScope();
this.Bind<Node24>().ToSelf().InSingletonScope();
this.Bind<Node25>().ToSelf().InSingletonScope();
this.Bind<Node26>().ToSelf().InSingletonScope();
this.Bind<Node27>().ToSelf().InSingletonScope();
this.Bind<Node28>().ToSelf().InSingletonScope();
this.Bind<Node29>().ToSelf().InSingletonScope();
this.Bind<Node30>().ToSelf().InSingletonScope();
this.Bind<Node31>().ToSelf().InSingletonScope();
this.Bind<Node32>().ToSelf().InSingletonScope();
this.Bind<Node33>().ToSelf().InSingletonScope();
this.Bind<Node34>().ToSelf().InSingletonScope();
this.Bind<Node35>().ToSelf().InSingletonScope();
this.Bind<Node36>().ToSelf().InSingletonScope();
this.Bind<Node37>().ToSelf().InSingletonScope();
this.Bind<Node38>().ToSelf().InSingletonScope();
this.Bind<Node39>().ToSelf().InSingletonScope();
this.Bind<Node40>().ToSelf().InSingletonScope();
this.Bind<Node41>().ToSelf().InSingletonScope();
this.Bind<Node42>().ToSelf().InSingletonScope();
this.Bind<Node43>().ToSelf().InSingletonScope();
this.Bind<Node44>().ToSelf().InSingletonScope();
this.Bind<Node45>().ToSelf().InSingletonScope();
this.Bind<Node46>().ToSelf().InSingletonScope();
this.Bind<Node47>().ToSelf().InSingletonScope();
this.Bind<Node48>().ToSelf().InSingletonScope();
this.Bind<Node49>().ToSelf().InSingletonScope();
this.Bind<Node50>().ToSelf().InSingletonScope();
this.Bind<Node51>().ToSelf().InSingletonScope();
this.Bind<Node52>().ToSelf().InSingletonScope();
this.Bind<Node53>().ToSelf().InSingletonScope();
this.Bind<Node54>().ToSelf().InSingletonScope();
this.Bind<Node55>().ToSelf().InSingletonScope();
this.Bind<Node56>().ToSelf().InSingletonScope();
this.Bind<Node57>().ToSelf().InSingletonScope();
this.Bind<Node58>().ToSelf().InSingletonScope();
this.Bind<Node59>().ToSelf().InSingletonScope();
this.Bind<Node60>().ToSelf().InSingletonScope();
this.Bind<Node61>().ToSelf().InSingletonScope();
this.Bind<Node62>().ToSelf().InSingletonScope();
this.Bind<Node63>().ToSelf().InSingletonScope();
this.Bind<Node64>().ToSelf().InSingletonScope();
this.Bind<Node65>().ToSelf().InSingletonScope();
this.Bind<Node66>().ToSelf().InSingletonScope();
this.Bind<Node67>().ToSelf().InSingletonScope();
this.Bind<Node68>().ToSelf().InSingletonScope();
this.Bind<Node69>().ToSelf().InSingletonScope();
this.Bind<Node70>().ToSelf().InSingletonScope();
this.Bind<Node71>().ToSelf().InSingletonScope();
this.Bind<Node72>().ToSelf().InSingletonScope();
this.Bind<Node73>().ToSelf().InSingletonScope();
this.Bind<Node74>().ToSelf().InSingletonScope();
this.Bind<Node75>().ToSelf().InSingletonScope();
this.Bind<Node76>().ToSelf().InSingletonScope();
this.Bind<Node77>().ToSelf().InSingletonScope();
this.Bind<Node78>().ToSelf().InSingletonScope();
this.Bind<Node79>().ToSelf().InSingletonScope();
this.Bind<Node80>().ToSelf().InSingletonScope();
this.Bind<Node81>().ToSelf().InSingletonScope();
this.Bind<Node82>().ToSelf().InSingletonScope();
this.Bind<Node83>().ToSelf().InSingletonScope();
this.Bind<Node84>().ToSelf().InSingletonScope();
this.Bind<Node85>().ToSelf().InSingletonScope();
this.Bind<Node86>().ToSelf().InSingletonScope();
this.Bind<Node87>().ToSelf().InSingletonScope();
this.Bind<Node88>().ToSelf().InSingletonScope();
this.Bind<Node89>().ToSelf().InSingletonScope();
this.Bind<Node90>().ToSelf().InSingletonScope();
this.Bind<Node91>().ToSelf().InSingletonScope();
this.Bind<Node92>().ToSelf().InSingletonScope();
this.Bind<Node93>().ToSelf().InSingletonScope();
this.Bind<Node94>().ToSelf().InSingletonScope();
this.Bind<Node95>().ToSelf().InSingletonScope();
this.Bind<Node96>().ToSelf().InSingletonScope();
this.Bind<Node97>().ToSelf().InSingletonScope();
this.Bind<Node98>().ToSelf().InSingletonScope();
this.Bind<Node99>().ToSelf().InSingletonScope();
this.Bind<Node100>().ToSelf().InSingletonScope();
this.Bind<Node101>().ToSelf().InSingletonScope();
this.Bind<Node102>().ToSelf().InSingletonScope();
this.Bind<Node103>().ToSelf().InSingletonScope();
this.Bind<Node104>().ToSelf().InSingletonScope();
this.Bind<Node105>().ToSelf().InSingletonScope();
this.Bind<Node106>().ToSelf().InSingletonScope();
this.Bind<Node107>().ToSelf().InSingletonScope();
this.Bind<Node108>().ToSelf().InSingletonScope();
this.Bind<Node109>().ToSelf().InSingletonScope();
this.Bind<Node110>().ToSelf().InSingletonScope();
this.Bind<Node111>().ToSelf().InSingletonScope();
this.Bind<Node112>().ToSelf().InSingletonScope();
this.Bind<Node113>().ToSelf().InSingletonScope();
this.Bind<Node114>().ToSelf().InSingletonScope();
this.Bind<Node115>().ToSelf().InSingletonScope();
this.Bind<Node116>().ToSelf().InSingletonScope();
this.Bind<Node117>().ToSelf().InSingletonScope();
this.Bind<Node118>().ToSelf().InSingletonScope();
this.Bind<Node119>().ToSelf().InSingletonScope();
this.Bind<Node120>().ToSelf().InSingletonScope();
this.Bind<Node121>().ToSelf().InSingletonScope();
this.Bind<Node122>().ToSelf().InSingletonScope();
this.Bind<Node123>().ToSelf().InSingletonScope();
this.Bind<Node124>().ToSelf().InSingletonScope();
this.Bind<Node125>().ToSelf().InSingletonScope();
this.Bind<Node126>().ToSelf().InSingletonScope();
this.Bind<Node127>().ToSelf().InSingletonScope();
this.Bind<Node128>().ToSelf().InSingletonScope();
this.Bind<Node129>().ToSelf().InSingletonScope();
this.Bind<Node130>().ToSelf().InSingletonScope();
this.Bind<Node131>().ToSelf().InSingletonScope();
this.Bind<Node132>().ToSelf().InSingletonScope();
this.Bind<Node133>().ToSelf().InSingletonScope();
this.Bind<Node134>().ToSelf().InSingletonScope();
this.Bind<Node135>().ToSelf().InSingletonScope();
this.Bind<Node136>().ToSelf().InSingletonScope();
this.Bind<Node137>().ToSelf().InSingletonScope();
this.Bind<Node138>().ToSelf().InSingletonScope();
this.Bind<Node139>().ToSelf().InSingletonScope();
this.Bind<Node140>().ToSelf().InSingletonScope();
this.Bind<Node141>().ToSelf().InSingletonScope();
this.Bind<Node142>().ToSelf().InSingletonScope();
this.Bind<Node143>().ToSelf().InSingletonScope();
this.Bind<Node144>().ToSelf().InSingletonScope();
this.Bind<Node145>().ToSelf().InSingletonScope();
this.Bind<Node146>().ToSelf().InSingletonScope();
this.Bind<Node147>().ToSelf().InSingletonScope();
this.Bind<Node148>().ToSelf().InSingletonScope();
this.Bind<Node149>().ToSelf().InSingletonScope();
this.Bind<Node150>().ToSelf().InSingletonScope();
this.Bind<Node151>().ToSelf().InSingletonScope();
this.Bind<Node152>().ToSelf().InSingletonScope();
this.Bind<Node153>().ToSelf().InSingletonScope();
this.Bind<Node154>().ToSelf().InSingletonScope();
this.Bind<Node155>().ToSelf().InSingletonScope();
this.Bind<Node156>().ToSelf().InSingletonScope();
this.Bind<Node157>().ToSelf().InSingletonScope();
this.Bind<Node158>().ToSelf().InSingletonScope();
this.Bind<Node159>().ToSelf().InSingletonScope();
this.Bind<Node160>().ToSelf().InSingletonScope();
this.Bind<Node161>().ToSelf().InSingletonScope();
this.Bind<Node162>().ToSelf().InSingletonScope();
this.Bind<Node163>().ToSelf().InSingletonScope();
this.Bind<Node164>().ToSelf().InSingletonScope();
this.Bind<Node165>().ToSelf().InSingletonScope();
this.Bind<Node166>().ToSelf().InSingletonScope();
this.Bind<Node167>().ToSelf().InSingletonScope();
this.Bind<Node168>().ToSelf().InSingletonScope();
this.Bind<Node169>().ToSelf().InSingletonScope();
this.Bind<Node170>().ToSelf().InSingletonScope();
this.Bind<Node171>().ToSelf().InSingletonScope();
this.Bind<Node172>().ToSelf().InSingletonScope();
this.Bind<Node173>().ToSelf().InSingletonScope();
this.Bind<Node174>().ToSelf().InSingletonScope();
this.Bind<Node175>().ToSelf().InSingletonScope();
this.Bind<Node176>().ToSelf().InSingletonScope();
this.Bind<Node177>().ToSelf().InSingletonScope();
this.Bind<Node178>().ToSelf().InSingletonScope();
this.Bind<Node179>().ToSelf().InSingletonScope();
this.Bind<Node180>().ToSelf().InSingletonScope();
this.Bind<Node181>().ToSelf().InSingletonScope();
this.Bind<Node182>().ToSelf().InSingletonScope();
this.Bind<Node183>().ToSelf().InSingletonScope();
this.Bind<Node184>().ToSelf().InSingletonScope();
this.Bind<Node185>().ToSelf().InSingletonScope();
this.Bind<Node186>().ToSelf().InSingletonScope();
this.Bind<Node187>().ToSelf().InSingletonScope();
this.Bind<Node188>().ToSelf().InSingletonScope();
this.Bind<Node189>().ToSelf().InSingletonScope();
this.Bind<Node190>().ToSelf().InSingletonScope();
this.Bind<Node191>().ToSelf().InSingletonScope();
this.Bind<Node192>().ToSelf().InSingletonScope();
this.Bind<Node193>().ToSelf().InSingletonScope();
this.Bind<Node194>().ToSelf().InSingletonScope();
this.Bind<Node195>().ToSelf().InSingletonScope();
this.Bind<Node196>().ToSelf().InSingletonScope();
this.Bind<Node197>().ToSelf().InSingletonScope();
this.Bind<Node198>().ToSelf().InSingletonScope();
this.Bind<Node199>().ToSelf().InSingletonScope();
this.Bind<Node200>().ToSelf().InSingletonScope();
this.Bind<Node201>().ToSelf().InSingletonScope();
this.Bind<Node202>().ToSelf().InSingletonScope();
this.Bind<Node203>().ToSelf().InSingletonScope();
this.Bind<Node204>().ToSelf().InSingletonScope();
this.Bind<Node205>().ToSelf().InSingletonScope();
this.Bind<Node206>().ToSelf().InSingletonScope();
this.Bind<Node207>().ToSelf().InSingletonScope();
this.Bind<Node208>().ToSelf().InSingletonScope();
this.Bind<Node209>().ToSelf().InSingletonScope();
this.Bind<Node210>().ToSelf().InSingletonScope();
this.Bind<Node211>().ToSelf().InSingletonScope();
this.Bind<Node212>().ToSelf().InSingletonScope();
this.Bind<Node213>().ToSelf().InSingletonScope();
this.Bind<Node214>().ToSelf().InSingletonScope();
this.Bind<Node215>().ToSelf().InSingletonScope();
this.Bind<Node216>().ToSelf().InSingletonScope();
this.Bind<Node217>().ToSelf().InSingletonScope();
this.Bind<Node218>().ToSelf().InSingletonScope();
this.Bind<Node219>().ToSelf().InSingletonScope();
this.Bind<Node220>().ToSelf().InSingletonScope();
this.Bind<Node221>().ToSelf().InSingletonScope();
this.Bind<Node222>().ToSelf().InSingletonScope();
this.Bind<Node223>().ToSelf().InSingletonScope();
this.Bind<Node224>().ToSelf().InSingletonScope();
this.Bind<Node225>().ToSelf().InSingletonScope();
this.Bind<Node226>().ToSelf().InSingletonScope();
this.Bind<Node227>().ToSelf().InSingletonScope();
this.Bind<Node228>().ToSelf().InSingletonScope();
this.Bind<Node229>().ToSelf().InSingletonScope();
this.Bind<Node230>().ToSelf().InSingletonScope();
this.Bind<Node231>().ToSelf().InSingletonScope();
this.Bind<Node232>().ToSelf().InSingletonScope();
this.Bind<Node233>().ToSelf().InSingletonScope();
this.Bind<Node234>().ToSelf().InSingletonScope();
this.Bind<Node235>().ToSelf().InSingletonScope();
this.Bind<Node236>().ToSelf().InSingletonScope();
this.Bind<Node237>().ToSelf().InSingletonScope();
this.Bind<Node238>().ToSelf().InSingletonScope();
this.Bind<Node239>().ToSelf().InSingletonScope();
this.Bind<Node240>().ToSelf().InSingletonScope();
this.Bind<Node241>().ToSelf().InSingletonScope();
this.Bind<Node242>().ToSelf().InSingletonScope();
this.Bind<Node243>().ToSelf().InSingletonScope();
this.Bind<Node244>().ToSelf().InSingletonScope();
this.Bind<Node245>().ToSelf().InSingletonScope();
this.Bind<Node246>().ToSelf().InSingletonScope();
this.Bind<Node247>().ToSelf().InSingletonScope();
this.Bind<Node248>().ToSelf().InSingletonScope();
this.Bind<Node249>().ToSelf().InSingletonScope();
this.Bind<Node250>().ToSelf().InSingletonScope();
this.Bind<Node251>().ToSelf().InSingletonScope();
this.Bind<Node252>().ToSelf().InSingletonScope();
this.Bind<Node253>().ToSelf().InSingletonScope();
this.Bind<Node254>().ToSelf().InSingletonScope();
this.Bind<Node255>().ToSelf().InSingletonScope();
this.Bind<Node256>().ToSelf().InSingletonScope();
this.Bind<Node257>().ToSelf().InSingletonScope();
this.Bind<Node258>().ToSelf().InSingletonScope();
this.Bind<Node259>().ToSelf().InSingletonScope();
this.Bind<Node260>().ToSelf().InSingletonScope();
this.Bind<Node261>().ToSelf().InSingletonScope();
this.Bind<Node262>().ToSelf().InSingletonScope();
this.Bind<Node263>().ToSelf().InSingletonScope();
this.Bind<Node264>().ToSelf().InSingletonScope();
this.Bind<Node265>().ToSelf().InSingletonScope();
this.Bind<Node266>().ToSelf().InSingletonScope();
this.Bind<Node267>().ToSelf().InSingletonScope();
this.Bind<Node268>().ToSelf().InSingletonScope();
this.Bind<Node269>().ToSelf().InSingletonScope();
this.Bind<Node270>().ToSelf().InSingletonScope();
this.Bind<Node271>().ToSelf().InSingletonScope();
this.Bind<Node272>().ToSelf().InSingletonScope();
this.Bind<Node273>().ToSelf().InSingletonScope();
this.Bind<Node274>().ToSelf().InSingletonScope();
this.Bind<Node275>().ToSelf().InSingletonScope();
this.Bind<Node276>().ToSelf().InSingletonScope();
this.Bind<Node277>().ToSelf().InSingletonScope();
this.Bind<Node278>().ToSelf().InSingletonScope();
this.Bind<Node279>().ToSelf().InSingletonScope();
this.Bind<Node280>().ToSelf().InSingletonScope();
this.Bind<Node281>().ToSelf().InSingletonScope();
this.Bind<Node282>().ToSelf().InSingletonScope();
this.Bind<Node283>().ToSelf().InSingletonScope();
this.Bind<Node284>().ToSelf().InSingletonScope();
this.Bind<Node285>().ToSelf().InSingletonScope();
this.Bind<Node286>().ToSelf().InSingletonScope();
this.Bind<Node287>().ToSelf().InSingletonScope();
this.Bind<Node288>().ToSelf().InSingletonScope();
this.Bind<Node289>().ToSelf().InSingletonScope();
this.Bind<Node290>().ToSelf().InSingletonScope();
this.Bind<Node291>().ToSelf().InSingletonScope();
this.Bind<Node292>().ToSelf().InSingletonScope();
this.Bind<Node293>().ToSelf().InSingletonScope();
this.Bind<Node294>().ToSelf().InSingletonScope();
this.Bind<Node295>().ToSelf().InSingletonScope();
this.Bind<Node296>().ToSelf().InSingletonScope();
this.Bind<Node297>().ToSelf().InSingletonScope();
this.Bind<Node298>().ToSelf().InSingletonScope();
this.Bind<Node299>().ToSelf().InSingletonScope();
this.Bind<Node300>().ToSelf().InSingletonScope();
this.Bind<Node301>().ToSelf().InSingletonScope();
this.Bind<Node302>().ToSelf().InSingletonScope();
this.Bind<Node303>().ToSelf().InSingletonScope();
this.Bind<Node304>().ToSelf().InSingletonScope();
this.Bind<Node305>().ToSelf().InSingletonScope();
this.Bind<Node306>().ToSelf().InSingletonScope();
this.Bind<Node307>().ToSelf().InSingletonScope();
this.Bind<Node308>().ToSelf().InSingletonScope();
this.Bind<Node309>().ToSelf().InSingletonScope();
this.Bind<Node310>().ToSelf().InSingletonScope();
this.Bind<Node311>().ToSelf().InSingletonScope();
this.Bind<Node312>().ToSelf().InSingletonScope();
this.Bind<Node313>().ToSelf().InSingletonScope();
this.Bind<Node314>().ToSelf().InSingletonScope();
this.Bind<Node315>().ToSelf().InSingletonScope();
this.Bind<Node316>().ToSelf().InSingletonScope();
this.Bind<Node317>().ToSelf().InSingletonScope();
this.Bind<Node318>().ToSelf().InSingletonScope();
this.Bind<Node319>().ToSelf().InSingletonScope();
this.Bind<Node320>().ToSelf().InSingletonScope();
this.Bind<Node321>().ToSelf().InSingletonScope();
this.Bind<Node322>().ToSelf().InSingletonScope();
this.Bind<Node323>().ToSelf().InSingletonScope();
this.Bind<Node324>().ToSelf().InSingletonScope();
this.Bind<Node325>().ToSelf().InSingletonScope();
this.Bind<Node326>().ToSelf().InSingletonScope();
this.Bind<Node327>().ToSelf().InSingletonScope();
this.Bind<Node328>().ToSelf().InSingletonScope();
this.Bind<Node329>().ToSelf().InSingletonScope();
this.Bind<Node330>().ToSelf().InSingletonScope();
this.Bind<Node331>().ToSelf().InSingletonScope();
this.Bind<Node332>().ToSelf().InSingletonScope();
this.Bind<Node333>().ToSelf().InSingletonScope();
this.Bind<Node334>().ToSelf().InSingletonScope();
this.Bind<Node335>().ToSelf().InSingletonScope();
this.Bind<Node336>().ToSelf().InSingletonScope();
this.Bind<Node337>().ToSelf().InSingletonScope();
this.Bind<Node338>().ToSelf().InSingletonScope();
this.Bind<Node339>().ToSelf().InSingletonScope();
this.Bind<Node340>().ToSelf().InSingletonScope();
this.Bind<Node341>().ToSelf().InSingletonScope();
this.Bind<Node342>().ToSelf().InSingletonScope();
this.Bind<Node343>().ToSelf().InSingletonScope();
this.Bind<Node344>().ToSelf().InSingletonScope();
this.Bind<Node345>().ToSelf().InSingletonScope();
this.Bind<Node346>().ToSelf().InSingletonScope();
this.Bind<Node347>().ToSelf().InSingletonScope();
this.Bind<Node348>().ToSelf().InSingletonScope();
this.Bind<Node349>().ToSelf().InSingletonScope();
this.Bind<Node350>().ToSelf().InSingletonScope();
this.Bind<Node351>().ToSelf().InSingletonScope();
this.Bind<Node352>().ToSelf().InSingletonScope();
this.Bind<Node353>().ToSelf().InSingletonScope();
this.Bind<Node354>().ToSelf().InSingletonScope();
this.Bind<Node355>().ToSelf().InSingletonScope();
this.Bind<Node356>().ToSelf().InSingletonScope();
this.Bind<Node357>().ToSelf().InSingletonScope();
this.Bind<Node358>().ToSelf().InSingletonScope();
this.Bind<Node359>().ToSelf().InSingletonScope();
this.Bind<Node360>().ToSelf().InSingletonScope();
this.Bind<Node361>().ToSelf().InSingletonScope();
this.Bind<Node362>().ToSelf().InSingletonScope();
this.Bind<Node363>().ToSelf().InSingletonScope();
this.Bind<Node364>().ToSelf().InSingletonScope();
this.Bind<Node365>().ToSelf().InSingletonScope();
this.Bind<Node366>().ToSelf().InSingletonScope();
this.Bind<Node367>().ToSelf().InSingletonScope();
this.Bind<Node368>().ToSelf().InSingletonScope();
this.Bind<Node369>().ToSelf().InSingletonScope();
this.Bind<Node370>().ToSelf().InSingletonScope();
this.Bind<Node371>().ToSelf().InSingletonScope();
this.Bind<Node372>().ToSelf().InSingletonScope();
this.Bind<Node373>().ToSelf().InSingletonScope();
this.Bind<Node374>().ToSelf().InSingletonScope();
this.Bind<Node375>().ToSelf().InSingletonScope();
this.Bind<Node376>().ToSelf().InSingletonScope();
this.Bind<Node377>().ToSelf().InSingletonScope();
this.Bind<Node378>().ToSelf().InSingletonScope();
this.Bind<Node379>().ToSelf().InSingletonScope();
this.Bind<Node380>().ToSelf().InSingletonScope();
this.Bind<Node381>().ToSelf().InSingletonScope();
this.Bind<Node382>().ToSelf().InSingletonScope();
this.Bind<Node383>().ToSelf().InSingletonScope();
this.Bind<Node384>().ToSelf().InSingletonScope();
this.Bind<Node385>().ToSelf().InSingletonScope();
this.Bind<Node386>().ToSelf().InSingletonScope();
this.Bind<Node387>().ToSelf().InSingletonScope();
this.Bind<Node388>().ToSelf().InSingletonScope();
this.Bind<Node389>().ToSelf().InSingletonScope();
this.Bind<Node390>().ToSelf().InSingletonScope();
this.Bind<Node391>().ToSelf().InSingletonScope();
this.Bind<Node392>().ToSelf().InSingletonScope();
this.Bind<Node393>().ToSelf().InSingletonScope();
this.Bind<Node394>().ToSelf().InSingletonScope();
this.Bind<Node395>().ToSelf().InSingletonScope();
this.Bind<Node396>().ToSelf().InSingletonScope();
this.Bind<Node397>().ToSelf().InSingletonScope();
this.Bind<Node398>().ToSelf().InSingletonScope();
this.Bind<Node399>().ToSelf().InSingletonScope();
this.Bind<Node400>().ToSelf().InSingletonScope();
this.Bind<Node401>().ToSelf().InSingletonScope();
this.Bind<Node402>().ToSelf().InSingletonScope();
this.Bind<Node403>().ToSelf().InSingletonScope();
this.Bind<Node404>().ToSelf().InSingletonScope();
this.Bind<Node405>().ToSelf().InSingletonScope();
this.Bind<Node406>().ToSelf().InSingletonScope();
this.Bind<Node407>().ToSelf().InSingletonScope();
this.Bind<Node408>().ToSelf().InSingletonScope();
this.Bind<Node409>().ToSelf().InSingletonScope();
this.Bind<Node410>().ToSelf().InSingletonScope();
this.Bind<Node411>().ToSelf().InSingletonScope();
this.Bind<Node412>().ToSelf().InSingletonScope();
this.Bind<Node413>().ToSelf().InSingletonScope();
this.Bind<Node414>().ToSelf().InSingletonScope();
this.Bind<Node415>().ToSelf().InSingletonScope();
this.Bind<Node416>().ToSelf().InSingletonScope();
this.Bind<Node417>().ToSelf().InSingletonScope();
this.Bind<Node418>().ToSelf().InSingletonScope();
this.Bind<Node419>().ToSelf().InSingletonScope();
this.Bind<Node420>().ToSelf().InSingletonScope();
this.Bind<Node421>().ToSelf().InSingletonScope();
this.Bind<Node422>().ToSelf().InSingletonScope();
this.Bind<Node423>().ToSelf().InSingletonScope();
this.Bind<Node424>().ToSelf().InSingletonScope();
this.Bind<Node425>().ToSelf().InSingletonScope();
this.Bind<Node426>().ToSelf().InSingletonScope();
this.Bind<Node427>().ToSelf().InSingletonScope();
this.Bind<Node428>().ToSelf().InSingletonScope();
this.Bind<Node429>().ToSelf().InSingletonScope();
this.Bind<Node430>().ToSelf().InSingletonScope();
this.Bind<Node431>().ToSelf().InSingletonScope();
this.Bind<Node432>().ToSelf().InSingletonScope();
this.Bind<Node433>().ToSelf().InSingletonScope();
this.Bind<Node434>().ToSelf().InSingletonScope();
this.Bind<Node435>().ToSelf().InSingletonScope();
this.Bind<Node436>().ToSelf().InSingletonScope();
this.Bind<Node437>().ToSelf().InSingletonScope();
this.Bind<Node438>().ToSelf().InSingletonScope();
this.Bind<Node439>().ToSelf().InSingletonScope();
this.Bind<Node440>().ToSelf().InSingletonScope();
this.Bind<Node441>().ToSelf().InSingletonScope();
this.Bind<Node442>().ToSelf().InSingletonScope();
this.Bind<Node443>().ToSelf().InSingletonScope();
this.Bind<Node444>().ToSelf().InSingletonScope();
this.Bind<Node445>().ToSelf().InSingletonScope();
this.Bind<Node446>().ToSelf().InSingletonScope();
this.Bind<Node447>().ToSelf().InSingletonScope();
this.Bind<Node448>().ToSelf().InSingletonScope();
this.Bind<Node449>().ToSelf().InSingletonScope();
this.Bind<Node450>().ToSelf().InSingletonScope();
this.Bind<Node451>().ToSelf().InSingletonScope();
this.Bind<Node452>().ToSelf().InSingletonScope();
this.Bind<Node453>().ToSelf().InSingletonScope();
this.Bind<Node454>().ToSelf().InSingletonScope();
this.Bind<Node455>().ToSelf().InSingletonScope();
this.Bind<Node456>().ToSelf().InSingletonScope();
this.Bind<Node457>().ToSelf().InSingletonScope();
this.Bind<Node458>().ToSelf().InSingletonScope();
this.Bind<Node459>().ToSelf().InSingletonScope();
this.Bind<Node460>().ToSelf().InSingletonScope();
this.Bind<Node461>().ToSelf().InSingletonScope();
this.Bind<Node462>().ToSelf().InSingletonScope();
this.Bind<Node463>().ToSelf().InSingletonScope();
this.Bind<Node464>().ToSelf().InSingletonScope();
this.Bind<Node465>().ToSelf().InSingletonScope();
this.Bind<Node466>().ToSelf().InSingletonScope();
this.Bind<Node467>().ToSelf().InSingletonScope();
this.Bind<Node468>().ToSelf().InSingletonScope();
this.Bind<Node469>().ToSelf().InSingletonScope();
this.Bind<Node470>().ToSelf().InSingletonScope();
this.Bind<Node471>().ToSelf().InSingletonScope();
this.Bind<Node472>().ToSelf().InSingletonScope();
this.Bind<Node473>().ToSelf().InSingletonScope();
this.Bind<Node474>().ToSelf().InSingletonScope();
this.Bind<Node475>().ToSelf().InSingletonScope();
this.Bind<Node476>().ToSelf().InSingletonScope();
this.Bind<Node477>().ToSelf().InSingletonScope();
this.Bind<Node478>().ToSelf().InSingletonScope();
this.Bind<Node479>().ToSelf().InSingletonScope();
this.Bind<Node480>().ToSelf().InSingletonScope();
this.Bind<Node481>().ToSelf().InSingletonScope();
this.Bind<Node482>().ToSelf().InSingletonScope();
this.Bind<Node483>().ToSelf().InSingletonScope();
this.Bind<Node484>().ToSelf().InSingletonScope();
this.Bind<Node485>().ToSelf().InSingletonScope();
this.Bind<Node486>().ToSelf().InSingletonScope();
this.Bind<Node487>().ToSelf().InSingletonScope();
this.Bind<Node488>().ToSelf().InSingletonScope();
this.Bind<Node489>().ToSelf().InSingletonScope();
this.Bind<Node490>().ToSelf().InSingletonScope();
this.Bind<Node491>().ToSelf().InSingletonScope();
this.Bind<Node492>().ToSelf().InSingletonScope();
this.Bind<Node493>().ToSelf().InSingletonScope();
this.Bind<Node494>().ToSelf().InSingletonScope();
this.Bind<Node495>().ToSelf().InSingletonScope();
this.Bind<Node496>().ToSelf().InSingletonScope();
this.Bind<Node497>().ToSelf().InSingletonScope();
this.Bind<Node498>().ToSelf().InSingletonScope();
this.Bind<Node499>().ToSelf().InSingletonScope();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Ionic.Zlib;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Archiver;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using CompressionMode = Ionic.Zlib.CompressionMode;
using GZipStream = Ionic.Zlib.GZipStream;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
public class InventoryArchiveWriteRequest
{
protected TarArchiveWriter m_archiveWriter;
protected UuidGatherer m_assetGatherer;
/// <value>
/// Used to collect the uuids of the assets that we need to save into the archive
/// </value>
protected Dictionary<UUID, sbyte> m_assetUuids = new Dictionary<UUID, sbyte>();
/// <value>
/// ID of this request
/// </value>
protected Guid m_id;
/// <value>
/// We only use this to request modules
/// </value>
protected Scene m_scene;
/// <value>
/// Used to collect the uuids of the users that we need to save into the archive
/// </value>
protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>();
/// <value>
/// Used to select all inventory nodes in a folder but not the folder itself
/// </value>
private const string STAR_WILDCARD = "*";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_invPath;
private InventoryArchiverModule m_module;
/// <value>
/// The stream to which the inventory archive will be saved.
/// </value>
private Stream m_saveStream;
private UserAccount m_userInfo;
/// <summary>
/// Constructor
/// </summary>
public InventoryArchiveWriteRequest(
Guid id, InventoryArchiverModule module, Scene scene,
UserAccount userInfo, string invPath, string savePath)
: this(
id,
module,
scene,
userInfo,
invPath,
new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression))
{
}
/// <summary>
/// Constructor
/// </summary>
public InventoryArchiveWriteRequest(
Guid id, InventoryArchiverModule module, Scene scene,
UserAccount userInfo, string invPath, Stream saveStream)
{
m_id = id;
m_module = module;
m_scene = scene;
m_userInfo = userInfo;
m_invPath = invPath;
m_saveStream = saveStream;
m_assetGatherer = new UuidGatherer(m_scene.AssetService);
SaveAssets = true;
}
/// <summary>
/// Determine whether this archive will save assets. Default is true.
/// </summary>
public bool SaveAssets { get; set; }
/// <summary>
/// Create the archive name for a particular folder.
/// </summary>
///
/// These names are prepended with an inventory folder's UUID so that more than one folder can have the
/// same name
///
/// <param name="folder"></param>
/// <returns></returns>
public static string CreateArchiveFolderName(InventoryFolderBase folder)
{
return CreateArchiveFolderName(folder.Name, folder.ID);
}
/// <summary>
/// Create an archive folder name given its constituent components
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string CreateArchiveFolderName(string name, UUID id)
{
return string.Format(
"{0}{1}{2}/",
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
/// <summary>
/// Create the archive name for a particular item.
/// </summary>
///
/// These names are prepended with an inventory item's UUID so that more than one item can have the
/// same name
///
/// <param name="item"></param>
/// <returns></returns>
public static string CreateArchiveItemName(InventoryItemBase item)
{
return CreateArchiveItemName(item.Name, item.ID);
}
/// <summary>
/// Create an archive item name given its constituent components
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string CreateArchiveItemName(string name, UUID id)
{
return string.Format(
"{0}{1}{2}.xml",
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
/// <summary>
/// Create the control file for the archive
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public string CreateControlFile(Dictionary<string, object> options)
{
int majorVersion, minorVersion;
if (options.ContainsKey("home"))
{
majorVersion = 1;
minorVersion = 2;
}
else
{
majorVersion = 0;
minorVersion = 3;
}
m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion);
StringWriter sw = new StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement("archive");
xtw.WriteAttributeString("major_version", majorVersion.ToString());
xtw.WriteAttributeString("minor_version", minorVersion.ToString());
xtw.WriteElementString("assets_included", SaveAssets.ToString());
xtw.WriteEndElement();
xtw.Flush();
xtw.Close();
String s = sw.ToString();
sw.Close();
return s;
}
/// <summary>
/// Execute the inventory write request
/// </summary>
public void Execute(Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("noassets") && (bool)options["noassets"])
SaveAssets = false;
try
{
InventoryFolderBase inventoryFolder = null;
InventoryItemBase inventoryItem = null;
InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.PrincipalID);
bool saveFolderContentsOnly = false;
// Eliminate double slashes and any leading / on the path.
string[] components
= m_invPath.Split(
new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
int maxComponentIndex = components.Length - 1;
// If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the
// folder itself. This may get more sophisicated later on
if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD)
{
saveFolderContentsOnly = true;
maxComponentIndex--;
}
else if (maxComponentIndex == -1)
{
// If the user has just specified "/", then don't save the root "My Inventory" folder. This is
// more intuitive then requiring the user to specify "/*" for this.
saveFolderContentsOnly = true;
}
m_invPath = String.Empty;
for (int i = 0; i <= maxComponentIndex; i++)
{
m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER;
}
// Annoyingly Split actually returns the original string if the input string consists only of delimiters
// Therefore if we still start with a / after the split, then we need the root folder
if (m_invPath.Length == 0)
{
inventoryFolder = rootFolder;
}
else
{
m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER));
List<InventoryFolderBase> candidateFolders
= InventoryArchiveUtils.FindFoldersByPath(m_scene.InventoryService, rootFolder, m_invPath);
if (candidateFolders.Count > 0)
inventoryFolder = candidateFolders[0];
}
// The path may point to an item instead
if (inventoryFolder == null)
inventoryItem = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, rootFolder, m_invPath);
if (null == inventoryFolder && null == inventoryItem)
{
// We couldn't find the path indicated
string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
Exception e = new InventoryArchiverException(errorMessage);
m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e);
throw e;
}
m_archiveWriter = new TarArchiveWriter(m_saveStream);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Adding control file to archive.");
// Write out control file. This has to be done first so that subsequent loaders will see this file first
// XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this
// not sure how to fix this though, short of going with a completely different file format.
m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options));
if (inventoryFolder != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}",
inventoryFolder.Name,
inventoryFolder.ID,
m_invPath == String.Empty ? InventoryFolderImpl.PATH_DELIMITER : m_invPath);
//recurse through all dirs getting dirs and files
SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !saveFolderContentsOnly, options, userAccountService);
}
else if (inventoryItem != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, m_invPath);
SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH, options, userAccountService);
}
// Don't put all this profile information into the archive right now.
//SaveUsers();
if (SaveAssets)
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Saving {0} assets for items", m_assetUuids.Count);
AssetsRequest ar
= new AssetsRequest(
new AssetsArchiver(m_archiveWriter),
m_assetUuids, m_scene.AssetService,
m_scene.UserAccountService, m_scene.RegionInfo.ScopeID,
options, ReceivedAllAssets);
Util.RunThreadNoTimeout(o => ar.Execute(), "AssetsRequest", null);
}
else
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Not saving assets since --noassets was specified");
ReceivedAllAssets(new List<UUID>(), new List<UUID>(), false);
}
}
catch (Exception)
{
m_saveStream.Close();
throw;
}
}
protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut)
{
Exception reportedException = null;
bool succeeded = true;
try
{
m_archiveWriter.Close();
}
catch (Exception e)
{
reportedException = e;
succeeded = false;
}
finally
{
m_saveStream.Close();
}
if (timedOut)
{
succeeded = false;
reportedException = new Exception("Loading assets timed out");
}
m_module.TriggerInventoryArchiveSaved(
m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException);
}
/// <summary>
/// Save an inventory folder
/// </summary>
/// <param name="inventoryFolder">The inventory folder to save</param>
/// <param name="path">The path to which the folder should be saved</param>
/// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param>
/// <param name="options"></param>
/// <param name="userAccountService"></param>
protected void SaveInvFolder(
InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself,
Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("excludefolders"))
{
if (((List<String>)options["excludefolders"]).Contains(inventoryFolder.Name) ||
((List<String>)options["excludefolders"]).Contains(inventoryFolder.ID.ToString()))
{
if (options.ContainsKey("verbose"))
{
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Skipping folder {0} at {1}",
inventoryFolder.Name, path);
}
return;
}
}
if (options.ContainsKey("verbose"))
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving folder {0}", inventoryFolder.Name);
if (saveThisFolderItself)
{
path += CreateArchiveFolderName(inventoryFolder);
// We need to make sure that we record empty folders
m_archiveWriter.WriteDir(path);
}
InventoryCollection contents
= m_scene.InventoryService.GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID);
foreach (InventoryFolderBase childFolder in contents.Folders)
{
SaveInvFolder(childFolder, path, true, options, userAccountService);
}
foreach (InventoryItemBase item in contents.Items)
{
SaveInvItem(item, path, options, userAccountService);
}
}
protected void SaveInvItem(InventoryItemBase inventoryItem, string path, Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("exclude"))
{
if (((List<String>)options["exclude"]).Contains(inventoryItem.Name) ||
((List<String>)options["exclude"]).Contains(inventoryItem.ID.ToString()))
{
if (options.ContainsKey("verbose"))
{
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Skipping inventory item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, path);
}
return;
}
}
if (options.ContainsKey("verbose"))
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving item {0} {1} (asset UUID {2})",
inventoryItem.ID, inventoryItem.Name, inventoryItem.AssetID);
string filename = path + CreateArchiveItemName(inventoryItem);
// Record the creator of this item for user record purposes (which might go away soon)
m_userUuids[inventoryItem.CreatorIdAsUuid] = 1;
string serialization = UserInventoryItemSerializer.Serialize(inventoryItem, options, userAccountService);
m_archiveWriter.WriteFile(filename, serialization);
AssetType itemAssetType = (AssetType)inventoryItem.AssetType;
// Don't chase down link asset items as they actually point to their target item IDs rather than an asset
if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder)
m_assetGatherer.GatherAssetUuids(inventoryItem.AssetID, (sbyte)inventoryItem.AssetType, m_assetUuids);
}
/// <summary>
/// Save information for the users that we've collected.
/// </summary>
protected void SaveUsers()
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count);
foreach (UUID creatorId in m_userUuids.Keys)
{
// Record the creator of this item
UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, creatorId);
if (creator != null)
{
m_archiveWriter.WriteFile(
ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml",
UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName));
}
else
{
m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId);
}
}
}
}
}
| |
using System;
using System.Linq;
using Eto.Forms;
using Eto.Drawing;
using sw = System.Windows;
using swm = System.Windows.Media;
using swc = System.Windows.Controls;
using swi = System.Windows.Input;
using Eto.Wpf.CustomControls;
using Eto.Wpf.Forms.Menu;
using System.ComponentModel;
namespace Eto.Wpf.Forms
{
public interface IWpfWindow
{
sw.Window Control { get; }
void SetOwnerFor(sw.Window child);
}
public abstract class WpfWindow<TControl, TWidget, TCallback> : WpfPanel<TControl, TWidget, TCallback>, Window.IHandler, IWpfWindow
where TControl : sw.Window
where TWidget : Window
where TCallback : Window.ICallback
{
Icon icon;
MenuBar menu;
Eto.Forms.ToolBar toolBar;
swc.DockPanel main;
swc.ContentControl menuHolder;
swc.ContentControl toolBarHolder;
swc.DockPanel content;
Size? initialClientSize;
bool resizable = true;
bool maximizable = true;
bool minimizable = true;
public override IntPtr NativeHandle
{
get { return new System.Windows.Interop.WindowInteropHelper(Control).EnsureHandle(); }
}
protected override void Initialize()
{
content = new swc.DockPanel();
base.Initialize();
Control.SizeToContent = sw.SizeToContent.WidthAndHeight;
Control.SnapsToDevicePixels = true;
Control.UseLayoutRounding = true;
main = new swc.DockPanel();
menuHolder = new swc.ContentControl { IsTabStop = false };
toolBarHolder = new swc.ContentControl { IsTabStop = false };
content.Background = System.Windows.SystemColors.ControlBrush;
swc.DockPanel.SetDock(menuHolder, swc.Dock.Top);
swc.DockPanel.SetDock(toolBarHolder, swc.Dock.Top);
main.Children.Add(menuHolder);
main.Children.Add(toolBarHolder);
main.Children.Add(content);
Control.Content = main;
Control.Loaded += delegate
{
SetResizeMode();
if (initialClientSize != null)
{
initialClientSize = null;
SetContentSize();
}
// stop form from auto-sizing after it is shown
Control.SizeToContent = sw.SizeToContent.Manual;
Control.MoveFocus(new swi.TraversalRequest(swi.FocusNavigationDirection.Next));
};
// needed to handle Application.Terminating event
HandleEvent(Window.ClosingEvent);
}
protected override void SetContentScale(bool xscale, bool yscale)
{
base.SetContentScale(true, true);
}
public override void AttachEvent(string id)
{
switch (id)
{
case Eto.Forms.Control.ShownEvent:
Control.IsVisibleChanged += (sender, e) =>
{
if ((bool)e.NewValue)
{
// this is a trick to achieve similar behaviour as in WinForms
// (IsVisibleChanged triggers too early, we want it after measure-lay-render)
Control.Dispatcher.BeginInvoke(new Action(() =>
Callback.OnShown(Widget, EventArgs.Empty)),
sw.Threading.DispatcherPriority.ContextIdle, null);
}
};
break;
case Window.ClosedEvent:
Control.Closed += delegate
{
Callback.OnClosed(Widget, EventArgs.Empty);
};
break;
case Window.ClosingEvent:
Control.Closing += (sender, e) =>
{
var args = new CancelEventArgs { Cancel = e.Cancel };
Callback.OnClosing(Widget, args);
if (!args.Cancel && sw.Application.Current.Windows.Count == 1)
{
// last window closing, so call OnTerminating to let the app abort terminating
var app = ((ApplicationHandler)Application.Instance.Handler);
app.Callback.OnTerminating(app.Widget, args);
}
e.Cancel = args.Cancel;
};
break;
case Window.WindowStateChangedEvent:
Control.StateChanged += (sender, e) => Callback.OnWindowStateChanged(Widget, EventArgs.Empty);
break;
case Eto.Forms.Control.GotFocusEvent:
Control.Activated += (sender, e) => Callback.OnGotFocus(Widget, EventArgs.Empty);
break;
case Eto.Forms.Control.LostFocusEvent:
Control.Deactivated += (sender, e) => Callback.OnLostFocus(Widget, EventArgs.Empty);
break;
case Window.LocationChangedEvent:
Control.LocationChanged += (sender, e) => Callback.OnLocationChanged(Widget, EventArgs.Empty);
break;
default:
base.AttachEvent(id);
break;
}
}
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SetScale(false, false);
}
protected virtual void UpdateClientSize(Size size)
{
var xdiff = Control.ActualWidth - content.ActualWidth;
var ydiff = Control.ActualHeight - content.ActualHeight;
Control.Width = size.Width + xdiff;
Control.Height = size.Height + ydiff;
Control.SizeToContent = sw.SizeToContent.Manual;
}
protected override void SetSize()
{
// don't set the minimum size of a window, just the preferred size
ContainerControl.Width = PreferredSize.Width;
ContainerControl.Height = PreferredSize.Height;
ContainerControl.MinWidth = MinimumSize.Width;
ContainerControl.MinHeight = MinimumSize.Height;
}
public Eto.Forms.ToolBar ToolBar
{
get { return toolBar; }
set
{
toolBar = value;
toolBarHolder.Content = toolBar != null ? toolBar.ControlObject : null;
}
}
public void Close()
{
Control.Close();
}
void CopyKeyBindings(swc.ItemCollection items)
{
foreach (var item in items.OfType<swc.MenuItem>())
{
Control.InputBindings.AddRange(item.InputBindings);
if (item.HasItems)
CopyKeyBindings(item.Items);
}
}
public MenuBar Menu
{
get { return menu; }
set
{
menu = value;
if (menu != null)
{
var handler = (MenuBarHandler)menu.Handler;
menuHolder.Content = handler.Control;
Control.InputBindings.Clear();
CopyKeyBindings(handler.Control.Items);
}
else
{
menuHolder.Content = null;
}
}
}
public Icon Icon
{
get { return icon; }
set
{
icon = value;
if (value != null)
{
Control.Icon = (swm.ImageSource)icon.ControlObject;
}
}
}
public virtual bool Resizable
{
get { return resizable; }
set
{
if (resizable != value)
{
resizable = value;
SetResizeMode();
}
}
}
public virtual bool Maximizable
{
get { return maximizable; }
set
{
if (maximizable != value)
{
maximizable = value;
SetResizeMode();
}
}
}
public virtual bool Minimizable
{
get { return minimizable; }
set
{
if (minimizable != value)
{
minimizable = value;
SetResizeMode();
}
}
}
protected virtual void SetResizeMode()
{
if (resizable)
Control.ResizeMode = sw.ResizeMode.CanResizeWithGrip;
else if (minimizable)
Control.ResizeMode = sw.ResizeMode.CanMinimize;
else
Control.ResizeMode = sw.ResizeMode.NoResize;
var hwnd = new sw.Interop.WindowInteropHelper(Control).Handle;
if (hwnd != IntPtr.Zero)
{
var val = Win32.GetWindowLong(hwnd, Win32.GWL.STYLE);
if (maximizable)
val |= (uint)Win32.WS.MAXIMIZEBOX;
else
val &= ~(uint)Win32.WS.MAXIMIZEBOX;
if (minimizable)
val |= (uint)Win32.WS.MINIMIZEBOX;
else
val &= ~(uint)Win32.WS.MINIMIZEBOX;
Win32.SetWindowLong(hwnd, Win32.GWL.STYLE, val);
}
}
public virtual bool ShowInTaskbar
{
get { return Control.ShowInTaskbar; }
set { Control.ShowInTaskbar = value; }
}
public virtual bool Topmost
{
get { return Control.Topmost; }
set { Control.Topmost = value; }
}
public void Minimize()
{
Control.WindowState = sw.WindowState.Minimized;
}
public override Size ClientSize
{
get
{
if (Control.IsLoaded)
return new Size((int)content.ActualWidth, (int)content.ActualHeight);
return initialClientSize ?? Size.Empty;
}
set
{
if (Control.IsLoaded)
UpdateClientSize(value);
else
{
initialClientSize = value;
SetContentSize();
}
}
}
void SetContentSize()
{
if (initialClientSize != null)
{
var value = initialClientSize.Value;
content.MinWidth = value.Width >= 0 ? value.Width : 0;
content.MinHeight = value.Height >= 0 ? value.Height : 0;
content.MaxWidth = value.Width >= 0 ? value.Width : double.PositiveInfinity;
content.MaxHeight = value.Height >= 0 ? value.Height : double.PositiveInfinity;
}
else
{
content.MinWidth = content.MinHeight = 0;
content.MaxWidth = content.MaxHeight = double.PositiveInfinity;
}
}
public override Size Size
{
get { return base.Size; }
set
{
Control.SizeToContent = sw.SizeToContent.Manual;
base.Size = value;
if (!Control.IsLoaded)
{
initialClientSize = null;
SetContentSize();
}
}
}
public string Title
{
get { return Control.Title; }
set { Control.Title = value; }
}
static readonly object locationSetKey = new object();
protected bool LocationSet
{
get { return Widget.Properties.Get<bool?>(locationSetKey) ?? false; }
set { Widget.Properties[locationSetKey] = value; }
}
public new Point Location
{
get
{
var left = Control.Left;
var top = Control.Top;
if (double.IsNaN(left) || double.IsNaN(top))
return Point.Empty;
return new Point((int)left, (int)top);
}
set
{
Control.Left = value.X;
Control.Top = value.Y;
if (!Control.IsLoaded)
LocationSet = true;
}
}
public WindowState WindowState
{
get
{
switch (Control.WindowState)
{
case sw.WindowState.Maximized:
return WindowState.Maximized;
case sw.WindowState.Minimized:
return WindowState.Minimized;
case sw.WindowState.Normal:
return WindowState.Normal;
default:
throw new NotSupportedException();
}
}
set
{
switch (value)
{
case WindowState.Maximized:
Control.WindowState = sw.WindowState.Maximized;
if (!Control.IsLoaded)
Control.SizeToContent = sw.SizeToContent.Manual;
break;
case WindowState.Minimized:
Control.WindowState = sw.WindowState.Minimized;
if (!Control.IsLoaded)
Control.SizeToContent = sw.SizeToContent.WidthAndHeight;
break;
case WindowState.Normal:
Control.WindowState = sw.WindowState.Normal;
if (!Control.IsLoaded)
Control.SizeToContent = sw.SizeToContent.WidthAndHeight;
break;
default:
throw new NotSupportedException();
}
}
}
public Rectangle RestoreBounds
{
get { return Control.WindowState == sw.WindowState.Normal || Control.RestoreBounds.IsEmpty ? Widget.Bounds : Control.RestoreBounds.ToEto(); }
}
sw.Window IWpfWindow.Control
{
get { return Control; }
}
public double Opacity
{
get { return Control.Opacity; }
set
{
if (Math.Abs(value - 1.0) > 0.01f)
{
if (Control.IsLoaded)
{
GlassHelper.BlurBehindWindow(Control);
//GlassHelper.ExtendGlassFrame (Control);
Control.Opacity = value;
}
else
{
Control.Loaded += delegate
{
GlassHelper.BlurBehindWindow(Control);
//GlassHelper.ExtendGlassFrame (Control);
Control.Opacity = value;
};
}
}
else
{
Control.Opacity = value;
}
}
}
public override bool HasFocus
{
get { return Control.IsActive && ((ApplicationHandler)Application.Instance.Handler).IsActive; }
}
public WindowStyle WindowStyle
{
get { return Control.WindowStyle.ToEto(); }
set { Control.WindowStyle = value.ToWpf(); }
}
public void BringToFront()
{
if (Control.WindowState == sw.WindowState.Minimized)
Control.WindowState = sw.WindowState.Normal;
Control.Activate();
}
public void SendToBack()
{
if (Topmost)
return;
var hWnd = new sw.Interop.WindowInteropHelper(Control).Handle;
if (hWnd != IntPtr.Zero)
Win32.SetWindowPos(hWnd, Win32.HWND_BOTTOM, 0, 0, 0, 0, Win32.SWP.NOSIZE | Win32.SWP.NOMOVE);
var window = sw.Application.Current.Windows.OfType<sw.Window>().FirstOrDefault(r => r != Control);
if (window != null)
window.Focus();
}
public override Color BackgroundColor
{
get { return content.Background.ToEtoColor(); }
set { content.Background = value.ToWpfBrush(content.Background); }
}
public Screen Screen
{
get { return new Screen(new ScreenHandler(Control)); }
}
public override void SetContainerContent(sw.FrameworkElement content)
{
this.content.Children.Add(content);
}
public void SetOwnerFor(sw.Window child)
{
child.Owner = Control;
}
public void SetOwner(Window owner)
{
if (owner == null)
{
Control.Owner = null;
return;
}
var wpfWindow = owner.Handler as IWpfWindow;
if (wpfWindow != null)
wpfWindow.SetOwnerFor(Control);
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// CandidateRange
/// </summary>
[DataContract]
public partial class CandidateRange : IEquatable<CandidateRange>
{
/// <summary>
/// Gets or Sets Side
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum SideEnum
{
/// <summary>
/// Enum UNKNOWN for "UNKNOWN"
/// </summary>
[EnumMember(Value = "UNKNOWN")]
UNKNOWN,
/// <summary>
/// Enum LEFT for "LEFT"
/// </summary>
[EnumMember(Value = "LEFT")]
LEFT,
/// <summary>
/// Enum RIGHT for "RIGHT"
/// </summary>
[EnumMember(Value = "RIGHT")]
RIGHT,
/// <summary>
/// Enum BOTH for "BOTH"
/// </summary>
[EnumMember(Value = "BOTH")]
BOTH
}
/// <summary>
/// Gets or Sets OddEvenIndicator
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum OddEvenIndicatorEnum
{
/// <summary>
/// Enum UNKNOWN for "UNKNOWN"
/// </summary>
[EnumMember(Value = "UNKNOWN")]
UNKNOWN,
/// <summary>
/// Enum BOTH for "BOTH"
/// </summary>
[EnumMember(Value = "BOTH")]
BOTH,
/// <summary>
/// Enum ODD for "ODD"
/// </summary>
[EnumMember(Value = "ODD")]
ODD,
/// <summary>
/// Enum EVEN for "EVEN"
/// </summary>
[EnumMember(Value = "EVEN")]
EVEN,
/// <summary>
/// Enum IRREGULAR for "IRREGULAR"
/// </summary>
[EnumMember(Value = "IRREGULAR")]
IRREGULAR
}
/// <summary>
/// Gets or Sets Side
/// </summary>
[DataMember(Name="side", EmitDefaultValue=false)]
public SideEnum? Side { get; set; }
/// <summary>
/// Gets or Sets OddEvenIndicator
/// </summary>
[DataMember(Name="oddEvenIndicator", EmitDefaultValue=false)]
public OddEvenIndicatorEnum? OddEvenIndicator { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CandidateRange" /> class.
/// </summary>
/// <param name="PlaceName">PlaceName.</param>
/// <param name="LowHouse">LowHouse.</param>
/// <param name="HighHouse">HighHouse.</param>
/// <param name="Side">Side.</param>
/// <param name="OddEvenIndicator">OddEvenIndicator.</param>
/// <param name="Units">Units.</param>
/// <param name="CustomValues">CustomValues.</param>
public CandidateRange(string PlaceName = null, string LowHouse = null, string HighHouse = null, SideEnum? Side = null, OddEvenIndicatorEnum? OddEvenIndicator = null, List<CandidateRangeUnit> Units = null, Dictionary<string, Object> CustomValues = null)
{
this.PlaceName = PlaceName;
this.LowHouse = LowHouse;
this.HighHouse = HighHouse;
this.Side = Side;
this.OddEvenIndicator = OddEvenIndicator;
this.Units = Units;
this.CustomValues = CustomValues;
}
/// <summary>
/// Gets or Sets PlaceName
/// </summary>
[DataMember(Name="placeName", EmitDefaultValue=false)]
public string PlaceName { get; set; }
/// <summary>
/// Gets or Sets LowHouse
/// </summary>
[DataMember(Name="lowHouse", EmitDefaultValue=false)]
public string LowHouse { get; set; }
/// <summary>
/// Gets or Sets HighHouse
/// </summary>
[DataMember(Name="highHouse", EmitDefaultValue=false)]
public string HighHouse { get; set; }
/// <summary>
/// Gets or Sets Units
/// </summary>
[DataMember(Name="units", EmitDefaultValue=false)]
public List<CandidateRangeUnit> Units { get; set; }
/// <summary>
/// Gets or Sets CustomValues
/// </summary>
[DataMember(Name="customValues", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomValues { 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 CandidateRange {\n");
sb.Append(" PlaceName: ").Append(PlaceName).Append("\n");
sb.Append(" LowHouse: ").Append(LowHouse).Append("\n");
sb.Append(" HighHouse: ").Append(HighHouse).Append("\n");
sb.Append(" Side: ").Append(Side).Append("\n");
sb.Append(" OddEvenIndicator: ").Append(OddEvenIndicator).Append("\n");
sb.Append(" Units: ").Append(Units).Append("\n");
sb.Append(" CustomValues: ").Append(CustomValues).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)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CandidateRange);
}
/// <summary>
/// Returns true if CandidateRange instances are equal
/// </summary>
/// <param name="other">Instance of CandidateRange to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CandidateRange other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.PlaceName == other.PlaceName ||
this.PlaceName != null &&
this.PlaceName.Equals(other.PlaceName)
) &&
(
this.LowHouse == other.LowHouse ||
this.LowHouse != null &&
this.LowHouse.Equals(other.LowHouse)
) &&
(
this.HighHouse == other.HighHouse ||
this.HighHouse != null &&
this.HighHouse.Equals(other.HighHouse)
) &&
(
this.Side == other.Side ||
this.Side != null &&
this.Side.Equals(other.Side)
) &&
(
this.OddEvenIndicator == other.OddEvenIndicator ||
this.OddEvenIndicator != null &&
this.OddEvenIndicator.Equals(other.OddEvenIndicator)
) &&
(
this.Units == other.Units ||
this.Units != null &&
this.Units.SequenceEqual(other.Units)
) &&
(
this.CustomValues == other.CustomValues ||
this.CustomValues != null &&
this.CustomValues.SequenceEqual(other.CustomValues)
);
}
/// <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 etc, of course :)
if (this.PlaceName != null)
hash = hash * 59 + this.PlaceName.GetHashCode();
if (this.LowHouse != null)
hash = hash * 59 + this.LowHouse.GetHashCode();
if (this.HighHouse != null)
hash = hash * 59 + this.HighHouse.GetHashCode();
if (this.Side != null)
hash = hash * 59 + this.Side.GetHashCode();
if (this.OddEvenIndicator != null)
hash = hash * 59 + this.OddEvenIndicator.GetHashCode();
if (this.Units != null)
hash = hash * 59 + this.Units.GetHashCode();
if (this.CustomValues != null)
hash = hash * 59 + this.CustomValues.GetHashCode();
return hash;
}
}
}
}
| |
// ReSharper disable InconsistentNaming
using System;
using System.Text;
using System.Threading;
using EasyNetQ.Loggers;
using EasyNetQ.Topology;
using NUnit.Framework;
namespace EasyNetQ.Tests.Integration
{
[TestFixture]
public class PublishSubscribeTests
{
private IBus bus;
[SetUp]
public void SetUp()
{
bus = RabbitHutch.CreateBus("host=localhost");
while(!bus.IsConnected) Thread.Sleep(10);
}
[TearDown]
public void TearDown()
{
if(bus != null) bus.Dispose();
}
// 1. Run this first, should see no messages consumed
// 3. Run this again (after publishing below), should see published messages appear
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_subscribe()
{
var autoResetEvent = new AutoResetEvent(false);
bus.Subscribe<MyMessage>("test", message =>
{
Console.WriteLine(message.Text);
autoResetEvent.Set();
});
// allow time for messages to be consumed
autoResetEvent.WaitOne(1000);
Console.WriteLine("Stopped consuming");
}
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_subscribe_as_exlusive()
{
var countdownEvent = new CountdownEvent(10);
var firstCount = 0;
var secondCount = 0;
bus.Subscribe<MyMessage>("test", message =>
{
countdownEvent.Signal();
Interlocked.Increment(ref firstCount);
Console.WriteLine("[1] " + message.Text);
}, x => x.AsExclusive());
bus.Subscribe<MyMessage>("test", message =>
{
countdownEvent.Signal();
Interlocked.Increment(ref secondCount);
Console.WriteLine("[2] " + message.Text);
}, x => x.AsExclusive());
for (var i = 0; i < 10; ++i)
bus.Publish(new MyMessage
{
Text = "Exclusive " + i
});
countdownEvent.Wait(10 * 1000);
Assert.IsTrue(firstCount == 10 && secondCount == 0 || firstCount == 0 && secondCount == 10);
Console.WriteLine("Stopped consuming");
}
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Long_running_exclusive_subscriber_should_survive_a_rabbit_restart()
{
var autoResetEvent = new AutoResetEvent(false);
bus.Subscribe<MyMessage>("test", message =>
{
Console.Out.WriteLine("Restart RabbitMQ now.");
new Timer(x =>
{
Console.WriteLine(message.Text);
autoResetEvent.Set();
}, null, 5000, Timeout.Infinite);
}, x => x.AsExclusive());
// allow time for messages to be consumed
autoResetEvent.WaitOne(15000);
Console.WriteLine("Stopped consuming");
}
// 2. Run this a few times, should publish some messages
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_be_able_to_publish()
{
var message = new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) };
bus.Publish(message);
Console.Out.WriteLine("message.Text = {0}", message.Text);
}
// 4. Run this once to setup subscription, publish a few times using '2' above, run again to
// see messages appear.
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_also_send_messages_to_second_subscriber()
{
var autoResetEvent = new AutoResetEvent(false);
var messageQueue2 = RabbitHutch.CreateBus("host=localhost");
messageQueue2.Subscribe<MyMessage>("test2", msg =>
{
Console.WriteLine(msg.Text);
autoResetEvent.Set();
});
// allow time for messages to be consumed
autoResetEvent.WaitOne(500);
Console.WriteLine("Stopped consuming");
}
// 5. Run this once to setup subscriptions, publish a few times using '2' above, run again.
// You should see two lots messages
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_two_subscriptions_from_the_same_app_should_also_both_get_all_messages()
{
var countdownEvent = new CountdownEvent(8);
bus.Subscribe<MyMessage>("test_a", msg =>
{
Console.WriteLine(msg.Text);
countdownEvent.Signal();
});
bus.Subscribe<MyOtherMessage>("test_b", msg =>
{
Console.WriteLine(msg.Text);
countdownEvent.Signal();
});
bus.Subscribe<MyMessage>("test_c", msg =>
{
Console.WriteLine(msg.Text);
countdownEvent.Signal();
});
bus.Subscribe<MyOtherMessage>("test_d", msg =>
{
Console.WriteLine(msg.Text);
countdownEvent.Signal();
});
bus.Publish(new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) });
bus.Publish(new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) });
bus.Publish(new MyOtherMessage { Text = "Hello other! " + Guid.NewGuid().ToString().Substring(0, 5) });
bus.Publish(new MyOtherMessage { Text = "Hello other! " + Guid.NewGuid().ToString().Substring(0, 5) });
// allow time for messages to be consumed
countdownEvent.Wait(1000);
Console.WriteLine("Stopped consuming");
}
// 6. Run publish first using '2' above.
// 7. Run this test, while it's running, restart the RabbitMQ service.
//
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Long_running_subscriber_should_survive_a_rabbit_restart()
{
var autoResetEvent = new AutoResetEvent(false);
bus.Subscribe<MyMessage>("test", message =>
{
Console.Out.WriteLine("Restart RabbitMQ now.");
new Timer(x =>
{
Console.WriteLine(message.Text);
autoResetEvent.Set();
}, null, 5000, Timeout.Infinite);
});
// allow time for messages to be consumed
autoResetEvent.WaitOne(7000);
Console.WriteLine("Stopped consuming");
}
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_subscribe_OK_before_connection_to_broker_is_complete()
{
var autoResetEvent = new AutoResetEvent(false);
var testLocalBus = RabbitHutch.CreateBus("host=localhost");
testLocalBus.Subscribe<MyMessage>("test", message =>
{
Console.Out.WriteLine("message.Text = {0}", message.Text);
autoResetEvent.Set();
});
Console.WriteLine("--- subscribed ---");
// allow time for bus to connect
autoResetEvent.WaitOne(1000);
testLocalBus.Dispose();
}
[Test, Explicit("Needs a Rabbit instance on localhost to work")]
public void Should_round_robin_between_subscribers()
{
Action<IServiceRegister> setNoDebugLogger = register =>
register.Register<IEasyNetQLogger>(_ => new DelegateLogger());
const string connectionString = "host=localhost;prefetchcount=100";
var publishBus = RabbitHutch.CreateBus(connectionString, setNoDebugLogger);
var subscribeBus1 = RabbitHutch.CreateBus(connectionString, setNoDebugLogger);
var subscribeBus2 = RabbitHutch.CreateBus(connectionString, setNoDebugLogger);
// first set up the subscribers
subscribeBus1.Subscribe<MyMessage>("roundRobinTest", message =>
Console.WriteLine("Subscriber 1: {0}", message.Text));
subscribeBus2.Subscribe<MyMessage>("roundRobinTest", message =>
Console.WriteLine("Subscriber 2: {0}", message.Text));
// now publish some messages
for (int i = 0; i < 50; i++)
{
publishBus.Publish(new MyMessage { Text = string.Format("Message{0}", i) });
}
Thread.Sleep(1000);
publishBus.Dispose();
subscribeBus1.Dispose();
subscribeBus2.Dispose();
}
}
}
// ReSharper restore InconsistentNaming
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using Microsoft.Win32;
namespace WebsitePanel.Installer.Common
{
/// <summary>
/// Registry helper class.
/// </summary>
public sealed class RegistryUtils
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private RegistryUtils()
{
}
/// <summary>
/// Retrieves the specified value from the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to retrieve.</param>
/// <returns>The data associated with name.</returns>
public static string GetRegistryKeyStringValue(string subkey, string name)
{
string ret = null;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if ( rk != null )
{
ret = (string)rk.GetValue(name, string.Empty);
}
return ret;
}
/// <summary>
/// Retrieves the specified value from the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to retrieve.</param>
/// <returns>The data associated with name.</returns>
public static int GetRegistryKeyInt32Value(string subkey, string name)
{
int ret = 0;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if ( rk != null )
{
ret = (int)rk.GetValue(name, 0);
}
return ret;
}
/// <summary>
/// Retrieves an array of strings that contains all the value names associated with this key.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <returns>An array of strings that contains the value names for the current key.</returns>
public static string[] GetRegistryKeyValues(string subkey)
{
string[] ret = null;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
{
ret = rk.GetValueNames();
}
return ret;
}
public static RegistryValueKind GetRegistryKeyValueKind(string subkey, string name)
{
RegistryValueKind ret = RegistryValueKind.Unknown;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
{
ret = rk.GetValueKind(name);
}
return ret;
}
/// <summary>
/// Retrieves the specified value from the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to retrieve.</param>
/// <returns>The data associated with name.</returns>
public static bool GetRegistryKeyBooleanValue(string subkey, string name)
{
bool ret = false;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if ( rk != null )
{
string strValue = (string)rk.GetValue(name, "False");
ret = Boolean.Parse(strValue);
}
return ret;
}
/// <summary>
/// Deletes a registry subkey and any child subkeys.
/// </summary>
/// <param name="subkey">Subkey to delete.</param>
public static void DeleteRegistryKey(string subkey)
{
RegistryKey root = Registry.LocalMachine;
root.DeleteSubKeyTree(subkey);
}
/// <summary>
/// Sets the specified value to the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to store data in.</param>
/// <param name="value">Data to store. </param>
public static void SetRegistryKeyStringValue(string subkey, string name, string value)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey(subkey);
if ( rk != null )
{
rk.SetValue(name, value);
}
}
/// <summary>
/// Sets the specified value to the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to store data in.</param>
/// <param name="value">Data to store. </param>
public static void SetRegistryKeyInt32Value(string subkey, string name, int value)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey(subkey);
if ( rk != null )
{
rk.SetValue(name, value);
}
}
/// <summary>
/// Sets the specified value to the subkey.
/// </summary>
/// <param name="subkey">Subkey.</param>
/// <param name="name">Name of value to store data in.</param>
/// <param name="value">Data to store. </param>
public static void SetRegistryKeyBooleanValue(string subkey, string name, bool value)
{
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.CreateSubKey(subkey);
if ( rk != null )
{
rk.SetValue(name, value);
}
}
/// <summary>
/// Return the list of sub keys for the specified registry key.
/// </summary>
/// <param name="subkey">The name of the registry key</param>
/// <returns>The array of subkey names.</returns>
public static string[] GetRegistrySubKeys(string subkey)
{
string[] ret = new string[0];
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(subkey);
if (rk != null)
ret = rk.GetSubKeyNames();
return ret;
}
public static Version GetIISVersion()
{
int major = GetRegistryKeyInt32Value("SOFTWARE\\Microsoft\\InetStp", "MajorVersion");
int minor = GetRegistryKeyInt32Value("SOFTWARE\\Microsoft\\InetStp", "MinorVersion");
return new Version(major, minor);
}
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
namespace FeedBuilder
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.lstFiles = new System.Windows.Forms.ListView();
this.colFilename = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colHash = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.imgFiles = new System.Windows.Forms.ImageList(this.components);
this.fbdOutputFolder = new System.Windows.Forms.FolderBrowserDialog();
this.sfdFeedXML = new System.Windows.Forms.SaveFileDialog();
this.tsMain = new System.Windows.Forms.ToolStrip();
this.btnNew = new System.Windows.Forms.ToolStripButton();
this.btnOpen = new System.Windows.Forms.ToolStripButton();
this.btnSave = new System.Windows.Forms.ToolStripButton();
this.btnSaveAs = new System.Windows.Forms.ToolStripButton();
this.tsSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnRefresh = new System.Windows.Forms.ToolStripButton();
this.btnOpenOutputs = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnBuild = new System.Windows.Forms.ToolStripButton();
this.ToolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.panFiles = new System.Windows.Forms.Panel();
this.grpSettings = new System.Windows.Forms.GroupBox();
this.chkCleanUp = new System.Windows.Forms.CheckBox();
this.chkCopyFiles = new System.Windows.Forms.CheckBox();
this.lblIgnore = new System.Windows.Forms.Label();
this.lblMisc = new System.Windows.Forms.Label();
this.lblCompare = new System.Windows.Forms.Label();
this.chkHash = new System.Windows.Forms.CheckBox();
this.chkDate = new System.Windows.Forms.CheckBox();
this.chkSize = new System.Windows.Forms.CheckBox();
this.chkVersion = new System.Windows.Forms.CheckBox();
this.txtBaseURL = new FeedBuilder.HelpfulTextBox(this.components);
this.lblBaseURL = new System.Windows.Forms.Label();
this.chkIgnoreVsHost = new System.Windows.Forms.CheckBox();
this.chkIgnoreSymbols = new System.Windows.Forms.CheckBox();
this.cmdFeedXML = new System.Windows.Forms.Button();
this.txtFeedXML = new FeedBuilder.HelpfulTextBox(this.components);
this.lblFeedXML = new System.Windows.Forms.Label();
this.cmdOutputFolder = new System.Windows.Forms.Button();
this.txtOutputFolder = new FeedBuilder.HelpfulTextBox(this.components);
this.lblOutputFolder = new System.Windows.Forms.Label();
this.txtAddExtension = new FeedBuilder.HelpfulTextBox(this.components);
this.lblAddExtension = new System.Windows.Forms.Label();
this.tsMain.SuspendLayout();
this.ToolStripContainer1.ContentPanel.SuspendLayout();
this.ToolStripContainer1.TopToolStripPanel.SuspendLayout();
this.ToolStripContainer1.SuspendLayout();
this.panFiles.SuspendLayout();
this.grpSettings.SuspendLayout();
this.SuspendLayout();
//
// lstFiles
//
this.lstFiles.CheckBoxes = true;
this.lstFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colFilename,
this.colVersion,
this.colSize,
this.colDate,
this.colHash});
this.lstFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstFiles.Location = new System.Drawing.Point(0, 12);
this.lstFiles.Margin = new System.Windows.Forms.Padding(0);
this.lstFiles.Name = "lstFiles";
this.lstFiles.Size = new System.Drawing.Size(810, 230);
this.lstFiles.SmallImageList = this.imgFiles;
this.lstFiles.TabIndex = 0;
this.lstFiles.UseCompatibleStateImageBehavior = false;
this.lstFiles.View = System.Windows.Forms.View.Details;
//
// colFilename
//
this.colFilename.Text = "Filename";
this.colFilename.Width = 200;
//
// colVersion
//
this.colVersion.Text = "Version";
this.colVersion.Width = 80;
//
// colSize
//
this.colSize.Text = "Size";
this.colSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.colSize.Width = 80;
//
// colDate
//
this.colDate.Text = "Date";
this.colDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.colDate.Width = 120;
//
// colHash
//
this.colHash.Text = "Hash";
this.colHash.Width = 300;
//
// imgFiles
//
this.imgFiles.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgFiles.ImageStream")));
this.imgFiles.TransparentColor = System.Drawing.Color.Transparent;
this.imgFiles.Images.SetKeyName(0, "file_extension_other.png");
this.imgFiles.Images.SetKeyName(1, "file_extension_bmp.png");
this.imgFiles.Images.SetKeyName(2, "file_extension_dll.png");
this.imgFiles.Images.SetKeyName(3, "file_extension_doc.png");
this.imgFiles.Images.SetKeyName(4, "file_extension_exe.png");
this.imgFiles.Images.SetKeyName(5, "file_extension_htm.png");
this.imgFiles.Images.SetKeyName(6, "file_extension_jpg.png");
this.imgFiles.Images.SetKeyName(7, "file_extension_pdf.png");
this.imgFiles.Images.SetKeyName(8, "file_extension_png.png");
this.imgFiles.Images.SetKeyName(9, "file_extension_txt.png");
this.imgFiles.Images.SetKeyName(10, "file_extension_wav.png");
this.imgFiles.Images.SetKeyName(11, "file_extension_wmv.png");
this.imgFiles.Images.SetKeyName(12, "file_extension_zip.png");
//
// fbdOutputFolder
//
this.fbdOutputFolder.Description = "Select your projects output folder:";
//
// sfdFeedXML
//
this.sfdFeedXML.DefaultExt = "xml";
this.sfdFeedXML.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*";
this.sfdFeedXML.Title = "Select the location to save your NauXML file:";
//
// tsMain
//
this.tsMain.Dock = System.Windows.Forms.DockStyle.None;
this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnNew,
this.btnOpen,
this.btnSave,
this.btnSaveAs,
this.tsSeparator1,
this.btnRefresh,
this.btnOpenOutputs,
this.toolStripSeparator1,
this.btnBuild});
this.tsMain.Location = new System.Drawing.Point(0, 0);
this.tsMain.Name = "tsMain";
this.tsMain.Size = new System.Drawing.Size(834, 25);
this.tsMain.Stretch = true;
this.tsMain.TabIndex = 2;
this.tsMain.Text = "Commands";
//
// btnNew
//
this.btnNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnNew.Image = ((System.Drawing.Image)(resources.GetObject("btnNew.Image")));
this.btnNew.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnNew.Name = "btnNew";
this.btnNew.Size = new System.Drawing.Size(23, 22);
this.btnNew.Text = "&New";
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// btnOpen
//
this.btnOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnOpen.Image = ((System.Drawing.Image)(resources.GetObject("btnOpen.Image")));
this.btnOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(23, 22);
this.btnOpen.Text = "&Open";
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// btnSave
//
this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(23, 22);
this.btnSave.Text = "&Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnSaveAs
//
this.btnSaveAs.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnSaveAs.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveAs.Image")));
this.btnSaveAs.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSaveAs.Name = "btnSaveAs";
this.btnSaveAs.Size = new System.Drawing.Size(60, 22);
this.btnSaveAs.Text = "Save As...";
this.btnSaveAs.Click += new System.EventHandler(this.btnSaveAs_Click);
//
// tsSeparator1
//
this.tsSeparator1.Name = "tsSeparator1";
this.tsSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnRefresh
//
this.btnRefresh.Image = ((System.Drawing.Image)(resources.GetObject("btnRefresh.Image")));
this.btnRefresh.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(92, 22);
this.btnRefresh.Text = "Refresh Files";
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// btnOpenOutputs
//
this.btnOpenOutputs.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnOpenOutputs.Image = ((System.Drawing.Image)(resources.GetObject("btnOpenOutputs.Image")));
this.btnOpenOutputs.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpenOutputs.Name = "btnOpenOutputs";
this.btnOpenOutputs.Size = new System.Drawing.Size(133, 22);
this.btnOpenOutputs.Text = "Open Output Folder";
this.btnOpenOutputs.Click += new System.EventHandler(this.btnOpenOutputs_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnBuild
//
this.btnBuild.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnBuild.Image = ((System.Drawing.Image)(resources.GetObject("btnBuild.Image")));
this.btnBuild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnBuild.Name = "btnBuild";
this.btnBuild.Size = new System.Drawing.Size(54, 22);
this.btnBuild.Text = "Build";
this.btnBuild.Click += new System.EventHandler(this.cmdBuild_Click);
//
// ToolStripContainer1
//
//
// ToolStripContainer1.ContentPanel
//
this.ToolStripContainer1.ContentPanel.Controls.Add(this.panFiles);
this.ToolStripContainer1.ContentPanel.Controls.Add(this.grpSettings);
this.ToolStripContainer1.ContentPanel.Padding = new System.Windows.Forms.Padding(12, 8, 12, 12);
this.ToolStripContainer1.ContentPanel.Size = new System.Drawing.Size(834, 467);
this.ToolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.ToolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.ToolStripContainer1.Name = "ToolStripContainer1";
this.ToolStripContainer1.Size = new System.Drawing.Size(834, 492);
this.ToolStripContainer1.TabIndex = 3;
this.ToolStripContainer1.Text = "ToolStripContainer1";
//
// ToolStripContainer1.TopToolStripPanel
//
this.ToolStripContainer1.TopToolStripPanel.Controls.Add(this.tsMain);
//
// panFiles
//
this.panFiles.Controls.Add(this.lstFiles);
this.panFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.panFiles.Location = new System.Drawing.Point(12, 213);
this.panFiles.Name = "panFiles";
this.panFiles.Padding = new System.Windows.Forms.Padding(0, 12, 0, 0);
this.panFiles.Size = new System.Drawing.Size(810, 242);
this.panFiles.TabIndex = 2;
//
// grpSettings
//
this.grpSettings.Controls.Add(this.lblAddExtension);
this.grpSettings.Controls.Add(this.txtAddExtension);
this.grpSettings.Controls.Add(this.chkCleanUp);
this.grpSettings.Controls.Add(this.chkCopyFiles);
this.grpSettings.Controls.Add(this.lblIgnore);
this.grpSettings.Controls.Add(this.lblMisc);
this.grpSettings.Controls.Add(this.lblCompare);
this.grpSettings.Controls.Add(this.chkHash);
this.grpSettings.Controls.Add(this.chkDate);
this.grpSettings.Controls.Add(this.chkSize);
this.grpSettings.Controls.Add(this.chkVersion);
this.grpSettings.Controls.Add(this.txtBaseURL);
this.grpSettings.Controls.Add(this.lblBaseURL);
this.grpSettings.Controls.Add(this.chkIgnoreVsHost);
this.grpSettings.Controls.Add(this.chkIgnoreSymbols);
this.grpSettings.Controls.Add(this.cmdFeedXML);
this.grpSettings.Controls.Add(this.txtFeedXML);
this.grpSettings.Controls.Add(this.lblFeedXML);
this.grpSettings.Controls.Add(this.cmdOutputFolder);
this.grpSettings.Controls.Add(this.txtOutputFolder);
this.grpSettings.Controls.Add(this.lblOutputFolder);
this.grpSettings.Dock = System.Windows.Forms.DockStyle.Top;
this.grpSettings.Location = new System.Drawing.Point(12, 8);
this.grpSettings.Name = "grpSettings";
this.grpSettings.Padding = new System.Windows.Forms.Padding(12, 8, 12, 8);
this.grpSettings.Size = new System.Drawing.Size(810, 205);
this.grpSettings.TabIndex = 1;
this.grpSettings.TabStop = false;
this.grpSettings.Text = "Settings:";
//
// chkCleanUp
//
this.chkCleanUp.AutoSize = true;
this.chkCleanUp.Checked = true;
this.chkCleanUp.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCleanUp.Location = new System.Drawing.Point(293, 145);
this.chkCleanUp.Name = "chkCleanUp";
this.chkCleanUp.Size = new System.Drawing.Size(134, 17);
this.chkCleanUp.TabIndex = 17;
this.chkCleanUp.Text = "Clean Unselected Files";
this.chkCleanUp.UseVisualStyleBackColor = true;
//
// chkCopyFiles
//
this.chkCopyFiles.AutoSize = true;
this.chkCopyFiles.Checked = true;
this.chkCopyFiles.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCopyFiles.Location = new System.Drawing.Point(146, 145);
this.chkCopyFiles.Name = "chkCopyFiles";
this.chkCopyFiles.Size = new System.Drawing.Size(141, 17);
this.chkCopyFiles.TabIndex = 16;
this.chkCopyFiles.Text = "Copy Files with NauXML";
this.chkCopyFiles.UseVisualStyleBackColor = true;
this.chkCopyFiles.CheckedChanged += new System.EventHandler(this.chkCopyFiles_CheckedChanged);
//
// lblIgnore
//
this.lblIgnore.AutoSize = true;
this.lblIgnore.Location = new System.Drawing.Point(15, 174);
this.lblIgnore.Name = "lblIgnore";
this.lblIgnore.Size = new System.Drawing.Size(40, 13);
this.lblIgnore.TabIndex = 15;
this.lblIgnore.Text = "Ignore:";
//
// lblMisc
//
this.lblMisc.AutoSize = true;
this.lblMisc.Location = new System.Drawing.Point(15, 146);
this.lblMisc.Name = "lblMisc";
this.lblMisc.Size = new System.Drawing.Size(32, 13);
this.lblMisc.TabIndex = 15;
this.lblMisc.Text = "Misc:";
//
// lblCompare
//
this.lblCompare.AutoSize = true;
this.lblCompare.Location = new System.Drawing.Point(15, 118);
this.lblCompare.Name = "lblCompare";
this.lblCompare.Size = new System.Drawing.Size(52, 13);
this.lblCompare.TabIndex = 14;
this.lblCompare.Text = "Compare:";
//
// chkHash
//
this.chkHash.AutoSize = true;
this.chkHash.Checked = true;
this.chkHash.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkHash.Location = new System.Drawing.Point(320, 117);
this.chkHash.Name = "chkHash";
this.chkHash.Size = new System.Drawing.Size(51, 17);
this.chkHash.TabIndex = 13;
this.chkHash.Text = "Hash";
this.chkHash.UseVisualStyleBackColor = true;
//
// chkDate
//
this.chkDate.AutoSize = true;
this.chkDate.Location = new System.Drawing.Point(265, 117);
this.chkDate.Name = "chkDate";
this.chkDate.Size = new System.Drawing.Size(49, 17);
this.chkDate.TabIndex = 12;
this.chkDate.Text = "Date";
this.chkDate.UseVisualStyleBackColor = true;
//
// chkSize
//
this.chkSize.AutoSize = true;
this.chkSize.Location = new System.Drawing.Point(213, 117);
this.chkSize.Name = "chkSize";
this.chkSize.Size = new System.Drawing.Size(46, 17);
this.chkSize.TabIndex = 11;
this.chkSize.Text = "Size";
this.chkSize.UseVisualStyleBackColor = true;
//
// chkVersion
//
this.chkVersion.AutoSize = true;
this.chkVersion.Checked = true;
this.chkVersion.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkVersion.Location = new System.Drawing.Point(146, 117);
this.chkVersion.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.chkVersion.Name = "chkVersion";
this.chkVersion.Size = new System.Drawing.Size(61, 17);
this.chkVersion.TabIndex = 10;
this.chkVersion.Text = "Version";
this.chkVersion.UseVisualStyleBackColor = true;
//
// txtBaseURL
//
this.txtBaseURL.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtBaseURL.HelpfulText = "Where you will upload the feed and update files for distribution to clients";
this.txtBaseURL.Location = new System.Drawing.Point(146, 86);
this.txtBaseURL.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtBaseURL.Name = "txtBaseURL";
this.txtBaseURL.Size = new System.Drawing.Size(617, 20);
this.txtBaseURL.TabIndex = 9;
//
// lblBaseURL
//
this.lblBaseURL.AutoSize = true;
this.lblBaseURL.Location = new System.Drawing.Point(15, 89);
this.lblBaseURL.Name = "lblBaseURL";
this.lblBaseURL.Size = new System.Drawing.Size(59, 13);
this.lblBaseURL.TabIndex = 8;
this.lblBaseURL.Text = "Base URL:";
//
// chkIgnoreVsHost
//
this.chkIgnoreVsHost.AutoSize = true;
this.chkIgnoreVsHost.Checked = true;
this.chkIgnoreVsHost.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIgnoreVsHost.Location = new System.Drawing.Point(293, 173);
this.chkIgnoreVsHost.Name = "chkIgnoreVsHost";
this.chkIgnoreVsHost.Size = new System.Drawing.Size(103, 17);
this.chkIgnoreVsHost.TabIndex = 7;
this.chkIgnoreVsHost.Text = "VS Hosting Files";
this.chkIgnoreVsHost.UseVisualStyleBackColor = true;
//
// chkIgnoreSymbols
//
this.chkIgnoreSymbols.AutoSize = true;
this.chkIgnoreSymbols.Checked = true;
this.chkIgnoreSymbols.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIgnoreSymbols.Location = new System.Drawing.Point(146, 173);
this.chkIgnoreSymbols.Name = "chkIgnoreSymbols";
this.chkIgnoreSymbols.Size = new System.Drawing.Size(100, 17);
this.chkIgnoreSymbols.TabIndex = 7;
this.chkIgnoreSymbols.Text = "Debug Symbols";
this.chkIgnoreSymbols.UseVisualStyleBackColor = true;
this.chkIgnoreSymbols.CheckedChanged += new System.EventHandler(this.chkIgnoreSymbols_CheckedChanged);
//
// cmdFeedXML
//
this.cmdFeedXML.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdFeedXML.Location = new System.Drawing.Point(769, 53);
this.cmdFeedXML.Name = "cmdFeedXML";
this.cmdFeedXML.Size = new System.Drawing.Size(26, 23);
this.cmdFeedXML.TabIndex = 5;
this.cmdFeedXML.Text = "...";
this.cmdFeedXML.UseVisualStyleBackColor = true;
this.cmdFeedXML.Click += new System.EventHandler(this.cmdFeedXML_Click);
//
// txtFeedXML
//
this.txtFeedXML.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFeedXML.BackColor = System.Drawing.Color.White;
this.txtFeedXML.HelpfulText = "The file your application downloads to determine if there are updates";
this.txtFeedXML.Location = new System.Drawing.Point(146, 55);
this.txtFeedXML.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtFeedXML.Name = "txtFeedXML";
this.txtFeedXML.Size = new System.Drawing.Size(617, 20);
this.txtFeedXML.TabIndex = 4;
//
// lblFeedXML
//
this.lblFeedXML.AutoSize = true;
this.lblFeedXML.Location = new System.Drawing.Point(15, 58);
this.lblFeedXML.Name = "lblFeedXML";
this.lblFeedXML.Size = new System.Drawing.Size(98, 13);
this.lblFeedXML.TabIndex = 3;
this.lblFeedXML.Text = "Feed NauXML File:";
//
// cmdOutputFolder
//
this.cmdOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOutputFolder.Location = new System.Drawing.Point(769, 22);
this.cmdOutputFolder.Name = "cmdOutputFolder";
this.cmdOutputFolder.Size = new System.Drawing.Size(26, 23);
this.cmdOutputFolder.TabIndex = 2;
this.cmdOutputFolder.Text = "...";
this.cmdOutputFolder.UseVisualStyleBackColor = true;
this.cmdOutputFolder.Click += new System.EventHandler(this.cmdOutputFolder_Click);
//
// txtOutputFolder
//
this.txtOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtOutputFolder.BackColor = System.Drawing.Color.White;
this.txtOutputFolder.HelpfulText = "The folder that contains the files you want to distribute";
this.txtOutputFolder.Location = new System.Drawing.Point(146, 24);
this.txtOutputFolder.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtOutputFolder.Name = "txtOutputFolder";
this.txtOutputFolder.Size = new System.Drawing.Size(617, 20);
this.txtOutputFolder.TabIndex = 1;
//
// lblOutputFolder
//
this.lblOutputFolder.AutoSize = true;
this.lblOutputFolder.Location = new System.Drawing.Point(15, 27);
this.lblOutputFolder.Name = "lblOutputFolder";
this.lblOutputFolder.Size = new System.Drawing.Size(110, 13);
this.lblOutputFolder.TabIndex = 0;
this.lblOutputFolder.Text = "Project Output Folder:";
//
// txtAddExtension
//
this.txtAddExtension.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtAddExtension.HelpfulText = "Add extension to each file";
this.txtAddExtension.Location = new System.Drawing.Point(516, 142);
this.txtAddExtension.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtAddExtension.Name = "txtAddExtension";
this.txtAddExtension.Size = new System.Drawing.Size(98, 20);
this.txtAddExtension.TabIndex = 18;
//
// lblAddExtension
//
this.lblAddExtension.AutoSize = true;
this.lblAddExtension.Location = new System.Drawing.Point(433, 146);
this.lblAddExtension.Name = "lblAddExtension";
this.lblAddExtension.Size = new System.Drawing.Size(77, 13);
this.lblAddExtension.TabIndex = 19;
this.lblAddExtension.Text = "Add extension:";
//
// frmMain
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(834, 492);
this.Controls.Add(this.ToolStripContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(850, 530);
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Feed Builder";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.Load += new System.EventHandler(this.frmMain_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.frmMain_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.frmMain_DragEnter);
this.tsMain.ResumeLayout(false);
this.tsMain.PerformLayout();
this.ToolStripContainer1.ContentPanel.ResumeLayout(false);
this.ToolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.ToolStripContainer1.TopToolStripPanel.PerformLayout();
this.ToolStripContainer1.ResumeLayout(false);
this.ToolStripContainer1.PerformLayout();
this.panFiles.ResumeLayout(false);
this.grpSettings.ResumeLayout(false);
this.grpSettings.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog fbdOutputFolder;
private System.Windows.Forms.SaveFileDialog sfdFeedXML;
private System.Windows.Forms.ImageList imgFiles;
private System.Windows.Forms.ListView lstFiles;
private System.Windows.Forms.ColumnHeader colFilename;
private System.Windows.Forms.ColumnHeader colVersion;
private System.Windows.Forms.ColumnHeader colSize;
private System.Windows.Forms.ColumnHeader colDate;
private System.Windows.Forms.ColumnHeader colHash;
private System.Windows.Forms.ToolStrip tsMain;
private System.Windows.Forms.ToolStripButton btnNew;
private System.Windows.Forms.ToolStripButton btnOpen;
private System.Windows.Forms.ToolStripButton btnSave;
private System.Windows.Forms.ToolStripButton btnRefresh;
private System.Windows.Forms.ToolStripContainer ToolStripContainer1;
private System.Windows.Forms.GroupBox grpSettings;
private System.Windows.Forms.CheckBox chkCleanUp;
private System.Windows.Forms.CheckBox chkCopyFiles;
private System.Windows.Forms.Label lblIgnore;
private System.Windows.Forms.Label lblMisc;
private System.Windows.Forms.Label lblCompare;
private System.Windows.Forms.CheckBox chkHash;
private System.Windows.Forms.CheckBox chkDate;
private System.Windows.Forms.CheckBox chkSize;
private System.Windows.Forms.CheckBox chkVersion;
private HelpfulTextBox txtBaseURL;
private System.Windows.Forms.Label lblBaseURL;
private System.Windows.Forms.CheckBox chkIgnoreVsHost;
private System.Windows.Forms.CheckBox chkIgnoreSymbols;
private System.Windows.Forms.Button cmdFeedXML;
private HelpfulTextBox txtFeedXML;
private System.Windows.Forms.Label lblFeedXML;
private System.Windows.Forms.Button cmdOutputFolder;
private HelpfulTextBox txtOutputFolder;
private System.Windows.Forms.Label lblOutputFolder;
private System.Windows.Forms.ToolStripButton btnSaveAs;
private System.Windows.Forms.ToolStripButton btnBuild;
private System.Windows.Forms.ToolStripSeparator tsSeparator1;
private ToolStripButton btnOpenOutputs;
private Panel panFiles;
private ToolStripSeparator toolStripSeparator1;
private Label lblAddExtension;
private HelpfulTextBox txtAddExtension;
}
}
| |
namespace Tx.ApplicationInsights
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reactive;
using Newtonsoft.Json;
using Tx.ApplicationInsights.InternalData;
using Tx.ApplicationInsights.TelemetryType;
internal class PartitionableTypeMap : IPartitionableTypeMap<AppInsightsEnvelope, string>
{
private readonly Dictionary<Type, Func<AppInsightsEnvelope, object>> map = new Dictionary<Type, Func<AppInsightsEnvelope, object>>();
private readonly Dictionary<Type, string> map2 = new Dictionary<Type, string>();
public PartitionableTypeMap()
{
this.map2.Add(typeof(TraceEvent), "message");
this.map2.Add(typeof(CustomEvent), "event");
this.map2.Add(typeof(ExceptionEvent), "basicException");
this.map2.Add(typeof(RequestEvent), "request");
this.map2.Add(typeof(PerformanceCounterEvent), "performanceCounter");
this.map.Add(typeof(TraceEvent), e => Safe(e, ParseTrace));
this.map.Add(typeof(CustomEvent), e => Safe(e, ParseCustomEvent));
this.map.Add(typeof(ExceptionEvent), e => Safe(e, ParseException));
this.map.Add(typeof(RequestEvent), e => Safe(e, this.ParseRequest));
this.map.Add(typeof(PerformanceCounterEvent), e => Safe(e, this.ParsePerformanceCounter));
}
private static object Safe(AppInsightsEnvelope envelope, Func<AppInsightsEnvelope, object> transformer)
{
object result = null;
try
{
result = transformer(envelope);
}
catch (Exception)
{
// Add EventSource based tracing to track these errors
}
return result;
}
private PerformanceCounterEvent ParsePerformanceCounter(AppInsightsEnvelope envelope)
{
var result = ParseBase<PerformanceCounterEvent>(envelope);
var json = envelope.Json.Substring(envelope.PropertyJsonStart, envelope.PropertyJsonLength);
using (var stringReader = new StringReader(json))
{
var reader = new JsonTextReader(stringReader);
var counters = new List<PerformanceCounterEventData>();
reader.Read();
reader.Read();
while (reader.TokenType != JsonToken.EndArray)
{
reader.Read();
var n = reader.Value.ToString();
reader.Read();
reader.Read();
reader.Read();
var v = reader.Value.ToString();
reader.Read();
reader.Read();
reader.Read();
var categoryName = reader.Value.ToString();
reader.Read();
reader.Read();
var instanceName = reader.Value.ToString();
reader.Read();
reader.Read();
double value;
Double.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
counters.Add(new PerformanceCounterEventData
{
CategoryName = categoryName,
InstanceName = instanceName,
Values = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase)
{
{ n, value },
}
});
}
result.PerformanceCounter = counters.ToArray();
}
return result;
}
private static TEvent ParseEvent<TEvent, TEventData>(AppInsightsEnvelope envelope, Action<TEvent, TEventData> setter) where TEvent : BaseEvent, new()
{
var result = ParseBase<TEvent>(envelope);
var json = envelope.Json.Substring(envelope.PropertyJsonStart, envelope.PropertyJsonLength);
setter(result, JsonConvert.DeserializeObject<TEventData>(json));
return result;
}
private RequestEvent ParseRequest(AppInsightsEnvelope envelope)
{
var result = ParseEvent<RequestEvent, RequestEventData[]>(
envelope,
(@event, datas) => @event.Request = datas);
return result;
}
private static ExceptionEvent ParseException(AppInsightsEnvelope envelope)
{
var result = ParseEvent<ExceptionEvent, ExceptionEventData[]>(
envelope,
(@event, datas) => @event.BasicException = datas);
return result;
}
private static TraceEvent ParseTrace(AppInsightsEnvelope envelope)
{
var result = ParseEvent<TraceEvent, TraceEventData[]>(
envelope,
(@event, datas) => @event.Message = datas);
return result;
}
private static CustomEvent ParseCustomEvent(AppInsightsEnvelope envelope)
{
var result = ParseEvent<CustomEvent, CustomEventData[]>(
envelope,
(@event, datas) => @event.Event = datas);
return result;
}
private static T ParseBase<T>(AppInsightsEnvelope envelope) where T : BaseEvent, new()
{
var result = new T();
var json = envelope.Json.Substring(envelope.ContextJsonStart, envelope.ContextJsonLength);
result.Context = JsonConvert.DeserializeObject<Context>(json);
return result;
}
public Func<AppInsightsEnvelope, object> GetTransform(Type outputType)
{
Func<AppInsightsEnvelope, object> key;
if (!this.map.TryGetValue(outputType, out key))
{
key = envelope => null;
}
return key;
}
public Func<AppInsightsEnvelope, DateTimeOffset> TimeFunction
{
get
{
return e => e.Timestamp;
}
}
public string GetTypeKey(Type outputType)
{
string key;
this.map2.TryGetValue(outputType, out key);
return key;
}
public string GetInputKey(AppInsightsEnvelope evt)
{
return evt.Property;
}
public IEqualityComparer<string> Comparer
{
get
{
return StringComparer.OrdinalIgnoreCase;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SQLSingleStorage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Xml;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
internal sealed class SqlSingleStorage : DataStorage {
private SqlSingle[] values;
public SqlSingleStorage(DataColumn column)
: base(column, typeof(SqlSingle), SqlSingle.Null, SqlSingle.Null, StorageType.SqlSingle) {
}
override public Object Aggregate(int[] records, AggregateType kind) {
bool hasData = false;
try {
switch (kind) {
case AggregateType.Sum:
SqlSingle sum = 0.0f;
foreach (int record in records) {
if (IsNull(record))
continue;
checked { sum += values[record];}
hasData = true;
}
if (hasData)
return sum;
return NullValue;
case AggregateType.Mean:
SqlDouble meanSum = (SqlDouble) 0.0f;
int meanCount = 0;
foreach (int record in records) {
if (IsNull(record))
continue;
checked { meanSum += values[record].ToSqlDouble();}
meanCount++;
hasData = true;
}
if (hasData) {
SqlSingle mean = 0;
checked {mean = (meanSum /(SqlDouble) meanCount).ToSqlSingle();}
return mean;
}
return NullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
SqlDouble var = (SqlDouble)0;
SqlDouble prec = (SqlDouble)0;
SqlDouble dsum = (SqlDouble)0;
SqlDouble sqrsum = (SqlDouble)0;
foreach (int record in records) {
if (IsNull(record))
continue;
dsum += values[record].ToSqlDouble();
sqrsum += (values[record]).ToSqlDouble() * (values[record]).ToSqlDouble();
count++;
}
if (count > 1) {
var = ((SqlDouble)count * sqrsum - (dsum * dsum));
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var <0))
var = 0;
else
var = var / (count * (count -1));
if (kind == AggregateType.StDev) {
return Math.Sqrt(var.Value);
}
return var;
}
return NullValue;
case AggregateType.Min:
SqlSingle min = SqlSingle.MaxValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (IsNull(record))
continue;
if ((SqlSingle.LessThan(values[record], min)).IsTrue)
min = values[record];
hasData = true;
}
if (hasData)
return min;
return NullValue;
case AggregateType.Max:
SqlSingle max = SqlSingle.MinValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (IsNull(record))
continue;
if ((SqlSingle.GreaterThan(values[record], max)).IsTrue)
max = values[record];
hasData = true;
}
if (hasData)
return max;
return NullValue;
case AggregateType.First:
if (records.Length > 0) {
return values[records[0]];
}
return null;
case AggregateType.Count:
count = 0;
for (int i = 0; i < records.Length; i++) {
if (!IsNull(records[i]))
count++;
}
return count;
}
}
catch (OverflowException) {
throw ExprException.Overflow(typeof(SqlSingle));
}
throw ExceptionBuilder.AggregateException(kind, DataType);
}
override public int Compare(int recordNo1, int recordNo2) {
return values[recordNo1].CompareTo(values[recordNo2]);
}
override public int CompareValueTo(int recordNo, Object value) {
return values[recordNo].CompareTo((SqlSingle)value);
}
override public object ConvertValue(object value) {
if (null != value) {
return SqlConvert.ConvertToSqlSingle(value);
}
return NullValue;
}
override public void Copy(int recordNo1, int recordNo2) {
values[recordNo2] = values[recordNo1];
}
override public Object Get(int record) {
return values[record];
}
override public bool IsNull(int record) {
return (values[record].IsNull);
}
override public void Set(int record, Object value) {
values[record] = SqlConvert.ConvertToSqlSingle(value);
}
override public void SetCapacity(int capacity) {
SqlSingle[] newValues = new SqlSingle[capacity];
if (null != values) {
Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length));
}
values = newValues;
}
override public object ConvertXmlToObject(string s) {
SqlSingle newValue = new SqlSingle();
string tempStr =string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader, bug 98767
StringReader strReader = new StringReader(tempStr);
IXmlSerializable tmp = newValue;
using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) {
tmp.ReadXml(xmlTextReader);
}
return ((SqlSingle)tmp);
}
override public string ConvertObjectToXml(object value) {
Debug.Assert(!DataStorage.IsObjectNull(value), "we should have null here");
Debug.Assert((value.GetType() == typeof(SqlSingle)), "wrong input type");
StringWriter strwriter = new StringWriter(FormatProvider);
using (XmlTextWriter xmlTextWriter = new XmlTextWriter (strwriter)) {
((IXmlSerializable)value).WriteXml(xmlTextWriter);
}
return (strwriter.ToString ());
}
override protected object GetEmptyStorage(int recordCount) {
return new SqlSingle[recordCount];
}
override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) {
SqlSingle[] typedStore = (SqlSingle[]) store;
typedStore[storeIndex] = values[record];
nullbits.Set(storeIndex, IsNull(record));
}
override protected void SetStorage(object store, BitArray nullbits) {
values = (SqlSingle[]) store;
//SetNullStorage(nullbits);
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace Sample1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Matrix worldMatrix;
Matrix cameraMatrix;
Matrix projectionMatrix;
float angleHorisont = 200.14f;
float angleVertical = -50f;
float far = 0.2f;
MouseState originalMouseState;
BasicEffect cubeEffect;
ModelImportShape model;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
model = new ModelImportShape(Content);
}
/// <summary>
/// Allows the game to perform any initialization
/// it needs to before starting to run.
/// This is where it can query for any required
/// services and load any non-graphic
/// related content. Calling base. Initialize will
/// enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
initializeWorld();
}
/// <summary>
/// LoadContent will be called once
/// per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
model.shapeTexture = Content.Load<Texture2D>("Textures\\one_color");
originalMouseState = Mouse.GetState();
}
/// <summary>
/// UnloadContent will be called once per game
/// and is the place to unload all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic
/// such as updating the world,
/// checking for collisions,
/// gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">
/// Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(
PlayerIndex.One).Buttons.Back ==
ButtonState.Pressed)
this.Exit();
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Right))
angleHorisont += 0.9f;
if (keyState.IsKeyDown(Keys.Left))
angleHorisont -= 0.9f;
if (keyState.IsKeyDown(Keys.Up))
angleVertical += 0.5f;
if (keyState.IsKeyDown(Keys.Down))
angleVertical -= 0.5f;
if (keyState.IsKeyDown(Keys.A))
far *= 1.01f;
if (keyState.IsKeyDown(Keys.Z))
far *= 0.99f;
/*
MouseState currentMouseState = Mouse.GetState();
if (currentMouseState != originalMouseState)
{
angleHorisont += (currentMouseState.X - originalMouseState.X)*0.1f;
angleVertical += (currentMouseState.Y - originalMouseState.Y) * 0.1f;
Mouse.SetPosition(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2);
originalMouseState = Mouse.GetState();
}
*/
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">
/// Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
cameraMatrix = Matrix.CreateLookAt(
new Vector3(0, far * 50, far * 30),
new Vector3(0, 0, 0),
new Vector3(0, 1, 0));
worldMatrix = Matrix.CreateRotationY(
MathHelper.ToRadians(angleHorisont)) *
Matrix.CreateRotationX(
MathHelper.ToRadians(angleVertical));
cubeEffect.World = worldMatrix;
cubeEffect.View = cameraMatrix;
#region light
// primitive color
cubeEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
cubeEffect.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
cubeEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
cubeEffect.SpecularPower = 5.0f;
cubeEffect.Alpha = 1.0f;
cubeEffect.LightingEnabled = true;
if (cubeEffect.LightingEnabled)
{
cubeEffect.DirectionalLight0.Enabled = true; // enable each light individually
if (cubeEffect.DirectionalLight0.Enabled)
{
// x direction
cubeEffect.DirectionalLight0.DiffuseColor = new Vector3(1, 0, 0); // range is 0 to 1
cubeEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-1, 0, 0));
// points from the light to the origin of the scene
cubeEffect.DirectionalLight0.SpecularColor = Vector3.One;
}
cubeEffect.DirectionalLight1.Enabled = true;
if (cubeEffect.DirectionalLight1.Enabled)
{
// y direction
cubeEffect.DirectionalLight1.DiffuseColor = new Vector3(0, 0.75f, 0);
cubeEffect.DirectionalLight1.Direction = Vector3.Normalize(new Vector3(0, -1, 0));
cubeEffect.DirectionalLight1.SpecularColor = Vector3.One;
}
cubeEffect.DirectionalLight2.Enabled = true;
if (cubeEffect.DirectionalLight2.Enabled)
{
// z direction
cubeEffect.DirectionalLight2.DiffuseColor = new Vector3(0, 0, 0.5f);
cubeEffect.DirectionalLight2.Direction = Vector3.Normalize(new Vector3(0, 0, -1));
cubeEffect.DirectionalLight2.SpecularColor = Vector3.One;
}
}
#endregion light
foreach (EffectPass pass in
cubeEffect.CurrentTechnique.Passes)
{
pass.Apply();
cubeEffect.Texture = model.shapeTexture;
model.RenderShape(GraphicsDevice);
}
base.Draw(gameTime);
}
public void initializeWorld()
{
cameraMatrix = Matrix.CreateLookAt(
new Vector3(0, far * 50, far * 30),
new Vector3(0, 0, 0),
new Vector3(0, 1, 0));
projectionMatrix =
Matrix.CreatePerspectiveFieldOfView(
MathHelper.PiOver4,
Window.ClientBounds.Width /
(float)Window.ClientBounds.Height, 1.0f, 500.0f);
float tilt = MathHelper.ToRadians(22.5f);
worldMatrix = Matrix.CreateRotationX(tilt) *
Matrix.CreateRotationY(tilt);
cubeEffect = new BasicEffect(GraphicsDevice);
cubeEffect.World = worldMatrix;
cubeEffect.View = cameraMatrix;
cubeEffect.Projection = projectionMatrix;
cubeEffect.TextureEnabled = true;
}
}
}
| |
using NUnit.Framework;
using VkNet.Enums.Filters;
namespace VkNet.Tests.Enum.SafetyEnums
{
[TestFixture]
public class MultivaluedFilterTest
{
[Test]
public void AccountFieldsTest()
{
// get test
Assert.That(AccountFields.Country.ToString(), Is.EqualTo("country"));
Assert.That(AccountFields.HttpsRequired.ToString(), Is.EqualTo("https_required"));
Assert.That(AccountFields.OwnPostsDefault.ToString(), Is.EqualTo("own_posts_default"));
Assert.That(AccountFields.NoWallReplies.ToString(), Is.EqualTo("no_wall_replies"));
Assert.That(AccountFields.Intro.ToString(), Is.EqualTo("intro"));
Assert.That(AccountFields.Language.ToString(), Is.EqualTo("lang"));
// parse test
Assert.That(AccountFields.FromJson("country"), Is.EqualTo(AccountFields.Country));
Assert.That(AccountFields.FromJson("https_required"), Is.EqualTo(AccountFields.HttpsRequired));
Assert.That(AccountFields.FromJson("own_posts_default"), Is.EqualTo(AccountFields.OwnPostsDefault));
Assert.That(AccountFields.FromJson("no_wall_replies"), Is.EqualTo(AccountFields.NoWallReplies));
Assert.That(AccountFields.FromJson("intro"), Is.EqualTo(AccountFields.Intro));
Assert.That(AccountFields.FromJson("lang"), Is.EqualTo(AccountFields.Language));
}
[Test]
public void CountersFilterTest()
{
// get test
Assert.That(CountersFilter.Friends.ToString(), Is.EqualTo("friends"));
Assert.That(CountersFilter.Messages.ToString(), Is.EqualTo("messages"));
Assert.That(CountersFilter.Photos.ToString(), Is.EqualTo("photos"));
Assert.That(CountersFilter.Videos.ToString(), Is.EqualTo("videos"));
Assert.That(CountersFilter.Notes.ToString(), Is.EqualTo("notes"));
Assert.That(CountersFilter.Gifts.ToString(), Is.EqualTo("gifts"));
Assert.That(CountersFilter.Events.ToString(), Is.EqualTo("events"));
Assert.That(CountersFilter.Groups.ToString(), Is.EqualTo("groups"));
Assert.That(CountersFilter.Notifications.ToString(), Is.EqualTo("notifications"));
Assert.That(CountersFilter.All.ToString(), Is.EqualTo("friends,messages,photos,videos,notes,gifts,events,groups,notifications"));
// parse test
Assert.That(CountersFilter.FromJson("friends"), Is.EqualTo(CountersFilter.Friends));
Assert.That(CountersFilter.FromJson("messages"), Is.EqualTo(CountersFilter.Messages));
Assert.That(CountersFilter.FromJson("photos"), Is.EqualTo(CountersFilter.Photos));
Assert.That(CountersFilter.FromJson("videos"), Is.EqualTo(CountersFilter.Videos));
Assert.That(CountersFilter.FromJson("notes"), Is.EqualTo(CountersFilter.Notes));
Assert.That(CountersFilter.FromJson("gifts"), Is.EqualTo(CountersFilter.Gifts));
Assert.That(CountersFilter.FromJson("events"), Is.EqualTo(CountersFilter.Events));
Assert.That(CountersFilter.FromJson("groups"), Is.EqualTo(CountersFilter.Groups));
Assert.That(CountersFilter.FromJson("notifications"), Is.EqualTo(CountersFilter.Notifications));
Assert.That(CountersFilter.FromJson("friends,messages,photos,videos,notes,gifts,events,groups,notifications"), Is.EqualTo(CountersFilter.All));
}
[Test]
public void GroupsFieldsTest()
{
// get test
Assert.That(GroupsFields.CityId.ToString(), Is.EqualTo("city"));
Assert.That(GroupsFields.CountryId.ToString(), Is.EqualTo("country"));
Assert.That(GroupsFields.Place.ToString(), Is.EqualTo("place"));
Assert.That(GroupsFields.Description.ToString(), Is.EqualTo("description"));
Assert.That(GroupsFields.WikiPage.ToString(), Is.EqualTo("wiki_page"));
Assert.That(GroupsFields.MembersCount.ToString(), Is.EqualTo("members_count"));
Assert.That(GroupsFields.Counters.ToString(), Is.EqualTo("counters"));
Assert.That(GroupsFields.StartDate.ToString(), Is.EqualTo("start_date"));
Assert.That(GroupsFields.EndDate.ToString(), Is.EqualTo("end_date"));
Assert.That(GroupsFields.CanPost.ToString(), Is.EqualTo("can_post"));
Assert.That(GroupsFields.CanSeelAllPosts.ToString(), Is.EqualTo("can_see_all_posts"));
Assert.That(GroupsFields.CanUploadDocuments.ToString(), Is.EqualTo("can_upload_doc"));
Assert.That(GroupsFields.CanCreateTopic.ToString(), Is.EqualTo("can_create_topic"));
Assert.That(GroupsFields.Activity.ToString(), Is.EqualTo("activity"));
Assert.That(GroupsFields.Status.ToString(), Is.EqualTo("status"));
Assert.That(GroupsFields.Contacts.ToString(), Is.EqualTo("contacts"));
Assert.That(GroupsFields.Links.ToString(), Is.EqualTo("links"));
Assert.That(GroupsFields.FixedPostId.ToString(), Is.EqualTo("fixed_post"));
Assert.That(GroupsFields.IsVerified.ToString(), Is.EqualTo("verified"));
Assert.That(GroupsFields.Site.ToString(), Is.EqualTo("site"));
Assert.That(GroupsFields.BanInfo.ToString(), Is.EqualTo("ban_info"));
Assert.That(GroupsFields.All.ToString(), Is.EqualTo("city,country,place,description,wiki_page,members_count,counters,start_date,end_date,can_post,can_see_all_posts,can_create_topic,activity,status,contacts,links,fixed_post,verified,site,ban_info"));
Assert.That(GroupsFields.AllUndocumented.ToString(), Is.EqualTo("city,country,place,description,wiki_page,members_count,counters,start_date,end_date,can_post,can_see_all_posts,can_upload_doc,can_create_topic,activity,status,contacts,links,fixed_post,verified,site,ban_info"));
// parse test
Assert.That(GroupsFields.FromJson("city"), Is.EqualTo(GroupsFields.CityId));
Assert.That(GroupsFields.FromJson("country"), Is.EqualTo(GroupsFields.CountryId));
Assert.That(GroupsFields.FromJson("place"), Is.EqualTo(GroupsFields.Place));
Assert.That(GroupsFields.FromJson("description"), Is.EqualTo(GroupsFields.Description));
Assert.That(GroupsFields.FromJson("wiki_page"), Is.EqualTo(GroupsFields.WikiPage));
Assert.That(GroupsFields.FromJson("members_count"), Is.EqualTo(GroupsFields.MembersCount));
Assert.That(GroupsFields.FromJson("counters"), Is.EqualTo(GroupsFields.Counters));
Assert.That(GroupsFields.FromJson("start_date"), Is.EqualTo(GroupsFields.StartDate));
Assert.That(GroupsFields.FromJson("end_date"), Is.EqualTo(GroupsFields.EndDate));
Assert.That(GroupsFields.FromJson("can_post"), Is.EqualTo(GroupsFields.CanPost));
Assert.That(GroupsFields.FromJson("can_see_all_posts"), Is.EqualTo(GroupsFields.CanSeelAllPosts));
Assert.That(GroupsFields.FromJson("can_upload_doc"), Is.EqualTo(GroupsFields.CanUploadDocuments));
Assert.That(GroupsFields.FromJson("can_create_topic"), Is.EqualTo(GroupsFields.CanCreateTopic));
Assert.That(GroupsFields.FromJson("activity"), Is.EqualTo(GroupsFields.Activity));
Assert.That(GroupsFields.FromJson("status"), Is.EqualTo(GroupsFields.Status));
Assert.That(GroupsFields.FromJson("contacts"), Is.EqualTo(GroupsFields.Contacts));
Assert.That(GroupsFields.FromJson("links"), Is.EqualTo(GroupsFields.Links));
Assert.That(GroupsFields.FromJson("fixed_post"), Is.EqualTo(GroupsFields.FixedPostId));
Assert.That(GroupsFields.FromJson("verified"), Is.EqualTo(GroupsFields.IsVerified));
Assert.That(GroupsFields.FromJson("site"), Is.EqualTo(GroupsFields.Site));
Assert.That(GroupsFields.FromJson("ban_info"), Is.EqualTo(GroupsFields.BanInfo));
Assert.That(GroupsFields.FromJson("city,country,place,description,wiki_page,members_count,counters,start_date,end_date,can_post,can_see_all_posts,can_create_topic,activity,status,contacts,links,fixed_post,verified,site,ban_info"), Is.EqualTo(GroupsFields.All));
Assert.That(GroupsFields.FromJson("city,country,place,description,wiki_page,members_count,counters,start_date,end_date,can_post,can_see_all_posts,can_upload_doc,can_create_topic,activity,status,contacts,links,fixed_post,verified,site,ban_info"), Is.EqualTo(GroupsFields.AllUndocumented));
}
[Test]
public void GroupsFiltersTest()
{
// get test
Assert.That(GroupsFilters.Administrator.ToString(), Is.EqualTo("admin"));
Assert.That(GroupsFilters.Editor.ToString(), Is.EqualTo("editor"));
Assert.That(GroupsFilters.Moderator.ToString(), Is.EqualTo("moder"));
Assert.That(GroupsFilters.Groups.ToString(), Is.EqualTo("groups"));
Assert.That(GroupsFilters.Publics.ToString(), Is.EqualTo("publics"));
Assert.That(GroupsFilters.Events.ToString(), Is.EqualTo("events"));
Assert.That(GroupsFilters.All.ToString(), Is.EqualTo("admin,editor,moder,groups,publics,events"));
// parse test
Assert.That(GroupsFilters.FromJson("admin"), Is.EqualTo(GroupsFilters.Administrator));
Assert.That(GroupsFilters.FromJson("editor"), Is.EqualTo(GroupsFilters.Editor));
Assert.That(GroupsFilters.FromJson("moder"), Is.EqualTo(GroupsFilters.Moderator));
Assert.That(GroupsFilters.FromJson("groups"), Is.EqualTo(GroupsFilters.Groups));
Assert.That(GroupsFilters.FromJson("publics"), Is.EqualTo(GroupsFilters.Publics));
Assert.That(GroupsFilters.FromJson("events"), Is.EqualTo(GroupsFilters.Events));
Assert.That(GroupsFilters.FromJson("admin,editor,moder,groups,publics,events"), Is.EqualTo(GroupsFilters.All));
}
[Test]
public void ProfileFieldsTest()
{
// get test
Assert.That(ProfileFields.Uid.ToString(), Is.EqualTo("user_id"));
Assert.That(ProfileFields.FirstName.ToString(), Is.EqualTo("first_name"));
Assert.That(ProfileFields.LastName.ToString(), Is.EqualTo("last_name"));
Assert.That(ProfileFields.Sex.ToString(), Is.EqualTo("sex"));
Assert.That(ProfileFields.BirthDate.ToString(), Is.EqualTo("bdate"));
Assert.That(ProfileFields.City.ToString(), Is.EqualTo("city"));
Assert.That(ProfileFields.Country.ToString(), Is.EqualTo("country"));
Assert.That(ProfileFields.Photo50.ToString(), Is.EqualTo("photo_50"));
Assert.That(ProfileFields.Photo100.ToString(), Is.EqualTo("photo_100"));
Assert.That(ProfileFields.Photo200.ToString(), Is.EqualTo("photo_200"));
Assert.That(ProfileFields.Photo200Orig.ToString(), Is.EqualTo("photo_200_orig"));
Assert.That(ProfileFields.Photo400Orig.ToString(), Is.EqualTo("photo_400_orig"));
Assert.That(ProfileFields.PhotoMax.ToString(), Is.EqualTo("photo_max"));
Assert.That(ProfileFields.PhotoMaxOrig.ToString(), Is.EqualTo("photo_max_orig"));
Assert.That(ProfileFields.Online.ToString(), Is.EqualTo("online"));
Assert.That(ProfileFields.FriendLists.ToString(), Is.EqualTo("lists"));
Assert.That(ProfileFields.Domain.ToString(), Is.EqualTo("domain"));
Assert.That(ProfileFields.HasMobile.ToString(), Is.EqualTo("has_mobile"));
Assert.That(ProfileFields.Contacts.ToString(), Is.EqualTo("contacts"));
Assert.That(ProfileFields.Connections.ToString(), Is.EqualTo("connections"));
Assert.That(ProfileFields.Site.ToString(), Is.EqualTo("site"));
Assert.That(ProfileFields.Education.ToString(), Is.EqualTo("education"));
Assert.That(ProfileFields.Universities.ToString(), Is.EqualTo("universities"));
Assert.That(ProfileFields.Schools.ToString(), Is.EqualTo("schools"));
Assert.That(ProfileFields.CanPost.ToString(), Is.EqualTo("can_post"));
Assert.That(ProfileFields.CanSeeAllPosts.ToString(), Is.EqualTo("can_see_all_posts"));
Assert.That(ProfileFields.CanSeeAudio.ToString(), Is.EqualTo("can_see_audio"));
Assert.That(ProfileFields.CanWritePrivateMessage.ToString(), Is.EqualTo("can_write_private_message"));
Assert.That(ProfileFields.Status.ToString(), Is.EqualTo("status"));
Assert.That(ProfileFields.LastSeen.ToString(), Is.EqualTo("last_seen"));
Assert.That(ProfileFields.CommonCount.ToString(), Is.EqualTo("common_count"));
Assert.That(ProfileFields.Relation.ToString(), Is.EqualTo("relation"));
Assert.That(ProfileFields.Relatives.ToString(), Is.EqualTo("relatives"));
Assert.That(ProfileFields.Counters.ToString(), Is.EqualTo("counters"));
Assert.That(ProfileFields.Nickname.ToString(), Is.EqualTo("nickname"));
Assert.That(ProfileFields.Timezone.ToString(), Is.EqualTo("timezone"));
Assert.That(ProfileFields.Language.ToString(), Is.EqualTo("lang"));
Assert.That(ProfileFields.OnlineMobile.ToString(), Is.EqualTo("online_mobile"));
Assert.That(ProfileFields.OnlineApp.ToString(), Is.EqualTo("online_app"));
Assert.That(ProfileFields.RelationPartner.ToString(), Is.EqualTo("relation_partner"));
Assert.That(ProfileFields.StandInLife.ToString(), Is.EqualTo("personal"));
Assert.That(ProfileFields.Interests.ToString(), Is.EqualTo("interests"));
Assert.That(ProfileFields.Music.ToString(), Is.EqualTo("music"));
Assert.That(ProfileFields.Activities.ToString(), Is.EqualTo("activities"));
Assert.That(ProfileFields.Movies.ToString(), Is.EqualTo("movies"));
Assert.That(ProfileFields.Tv.ToString(), Is.EqualTo("tv"));
Assert.That(ProfileFields.Books.ToString(), Is.EqualTo("books"));
Assert.That(ProfileFields.Games.ToString(), Is.EqualTo("games"));
Assert.That(ProfileFields.About.ToString(), Is.EqualTo("about"));
Assert.That(ProfileFields.Quotes.ToString(), Is.EqualTo("quotes"));
Assert.That(ProfileFields.InvitedBy.ToString(), Is.EqualTo("invited_by"));
Assert.That(ProfileFields.BlacklistedByMe.ToString(), Is.EqualTo("blacklisted_by_me"));
Assert.That(ProfileFields.Blacklisted.ToString(), Is.EqualTo("blacklisted"));
Assert.That(ProfileFields.Military.ToString(), Is.EqualTo("military"));
Assert.That(ProfileFields.Career.ToString(), Is.EqualTo("career"));
Assert.That(ProfileFields.FriendStatus.ToString(), Is.EqualTo("friend_status"));
Assert.That(ProfileFields.IsFriend.ToString(), Is.EqualTo("is_friend"));
Assert.That(ProfileFields.ScreenName.ToString(), Is.EqualTo("screen_name"));
Assert.That(ProfileFields.IsHiddenFromFeed.ToString(), Is.EqualTo("is_hidden_from_feed"));
Assert.That(ProfileFields.IsFavorite.ToString(), Is.EqualTo("is_favorite"));
Assert.That(ProfileFields.CanSendFriendRequest.ToString(), Is.EqualTo("can_send_friend_request"));
Assert.That(ProfileFields.WallComments.ToString(), Is.EqualTo("wall_comments"));
Assert.That(ProfileFields.Verified.ToString(), Is.EqualTo("verified"));
Assert.That(ProfileFields.All.ToString(), Is.EqualTo("user_id,first_name,last_name,sex,bdate,city,country,photo_50,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_max,photo_max_orig,online,lists,domain,has_mobile,contacts,connections,site,education,universities,schools,can_post,can_see_all_posts,can_see_audio,can_write_private_message,status,last_seen,common_count,relation,relatives,counters,nickname,timezone,blacklisted_by_me,blacklisted,military,career,friend_status,is_friend,screen_name,is_hidden_from_feed,is_favorite,can_send_friend_request,wall_comments,verified"));
Assert.That(ProfileFields.AllUndocumented.ToString(), Is.EqualTo("user_id,first_name,last_name,sex,bdate,city,country,photo_50,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_max,photo_max_orig,online,lists,domain,has_mobile,contacts,connections,site,education,universities,schools,can_post,can_see_all_posts,can_see_audio,can_write_private_message,status,last_seen,common_count,relation,relatives,counters,nickname,timezone,lang,online_mobile,online_app,relation_partner,personal,interests,music,activities,movies,tv,books,games,about,quotes,invited_by,blacklisted_by_me,blacklisted,military,career,friend_status,is_friend,screen_name,is_hidden_from_feed,is_favorite,can_send_friend_request,wall_comments,verified"));
// parse test
Assert.That(ProfileFields.FromJson("user_id"), Is.EqualTo(ProfileFields.Uid));
Assert.That(ProfileFields.FromJson("first_name"), Is.EqualTo(ProfileFields.FirstName));
Assert.That(ProfileFields.FromJson("last_name"), Is.EqualTo(ProfileFields.LastName));
Assert.That(ProfileFields.FromJson("sex"), Is.EqualTo(ProfileFields.Sex));
Assert.That(ProfileFields.FromJson("bdate"), Is.EqualTo(ProfileFields.BirthDate));
Assert.That(ProfileFields.FromJson("city"), Is.EqualTo(ProfileFields.City));
Assert.That(ProfileFields.FromJson("country"), Is.EqualTo(ProfileFields.Country));
Assert.That(ProfileFields.FromJson("photo_50"), Is.EqualTo(ProfileFields.Photo50));
Assert.That(ProfileFields.FromJson("photo_100"), Is.EqualTo(ProfileFields.Photo100));
Assert.That(ProfileFields.FromJson("photo_200"), Is.EqualTo(ProfileFields.Photo200));
Assert.That(ProfileFields.FromJson("photo_200_orig"), Is.EqualTo(ProfileFields.Photo200Orig));
Assert.That(ProfileFields.FromJson("photo_400_orig"), Is.EqualTo(ProfileFields.Photo400Orig));
Assert.That(ProfileFields.FromJson("photo_max"), Is.EqualTo(ProfileFields.PhotoMax));
Assert.That(ProfileFields.FromJson("photo_max_orig"), Is.EqualTo(ProfileFields.PhotoMaxOrig));
Assert.That(ProfileFields.FromJson("online"), Is.EqualTo(ProfileFields.Online));
Assert.That(ProfileFields.FromJson("lists"), Is.EqualTo(ProfileFields.FriendLists));
Assert.That(ProfileFields.FromJson("domain"), Is.EqualTo(ProfileFields.Domain));
Assert.That(ProfileFields.FromJson("has_mobile"), Is.EqualTo(ProfileFields.HasMobile));
Assert.That(ProfileFields.FromJson("contacts"), Is.EqualTo(ProfileFields.Contacts));
Assert.That(ProfileFields.FromJson("connections"), Is.EqualTo(ProfileFields.Connections));
Assert.That(ProfileFields.FromJson("site"), Is.EqualTo(ProfileFields.Site));
Assert.That(ProfileFields.FromJson("education"), Is.EqualTo(ProfileFields.Education));
Assert.That(ProfileFields.FromJson("universities"), Is.EqualTo(ProfileFields.Universities));
Assert.That(ProfileFields.FromJson("schools"), Is.EqualTo(ProfileFields.Schools));
Assert.That(ProfileFields.FromJson("can_post"), Is.EqualTo(ProfileFields.CanPost));
Assert.That(ProfileFields.FromJson("can_see_all_posts"), Is.EqualTo(ProfileFields.CanSeeAllPosts));
Assert.That(ProfileFields.FromJson("can_see_audio"), Is.EqualTo(ProfileFields.CanSeeAudio));
Assert.That(ProfileFields.FromJson("can_write_private_message"), Is.EqualTo(ProfileFields.CanWritePrivateMessage));
Assert.That(ProfileFields.FromJson("status"), Is.EqualTo(ProfileFields.Status));
Assert.That(ProfileFields.FromJson("last_seen"), Is.EqualTo(ProfileFields.LastSeen));
Assert.That(ProfileFields.FromJson("common_count"), Is.EqualTo(ProfileFields.CommonCount));
Assert.That(ProfileFields.FromJson("relation"), Is.EqualTo(ProfileFields.Relation));
Assert.That(ProfileFields.FromJson("relatives"), Is.EqualTo(ProfileFields.Relatives));
Assert.That(ProfileFields.FromJson("counters"), Is.EqualTo(ProfileFields.Counters));
Assert.That(ProfileFields.FromJson("nickname"), Is.EqualTo(ProfileFields.Nickname));
Assert.That(ProfileFields.FromJson("timezone"), Is.EqualTo(ProfileFields.Timezone));
Assert.That(ProfileFields.FromJson("lang"), Is.EqualTo(ProfileFields.Language));
Assert.That(ProfileFields.FromJson("online_mobile"), Is.EqualTo(ProfileFields.OnlineMobile));
Assert.That(ProfileFields.FromJson("online_app"), Is.EqualTo(ProfileFields.OnlineApp));
Assert.That(ProfileFields.FromJson("relation_partner"), Is.EqualTo(ProfileFields.RelationPartner));
Assert.That(ProfileFields.FromJson("personal"), Is.EqualTo(ProfileFields.StandInLife));
Assert.That(ProfileFields.FromJson("interests"), Is.EqualTo(ProfileFields.Interests));
Assert.That(ProfileFields.FromJson("music"), Is.EqualTo(ProfileFields.Music));
Assert.That(ProfileFields.FromJson("activities"), Is.EqualTo(ProfileFields.Activities));
Assert.That(ProfileFields.FromJson("movies"), Is.EqualTo(ProfileFields.Movies));
Assert.That(ProfileFields.FromJson("tv"), Is.EqualTo(ProfileFields.Tv));
Assert.That(ProfileFields.FromJson("books"), Is.EqualTo(ProfileFields.Books));
Assert.That(ProfileFields.FromJson("games"), Is.EqualTo(ProfileFields.Games));
Assert.That(ProfileFields.FromJson("about"), Is.EqualTo(ProfileFields.About));
Assert.That(ProfileFields.FromJson("quotes"), Is.EqualTo(ProfileFields.Quotes));
Assert.That(ProfileFields.FromJson("invited_by"), Is.EqualTo(ProfileFields.InvitedBy));
Assert.That(ProfileFields.FromJson("blacklisted_by_me"), Is.EqualTo(ProfileFields.BlacklistedByMe));
Assert.That(ProfileFields.FromJson("blacklisted"), Is.EqualTo(ProfileFields.Blacklisted));
Assert.That(ProfileFields.FromJson("military"), Is.EqualTo(ProfileFields.Military));
Assert.That(ProfileFields.FromJson("career"), Is.EqualTo(ProfileFields.Career));
Assert.That(ProfileFields.FromJson("friend_status"), Is.EqualTo(ProfileFields.FriendStatus));
Assert.That(ProfileFields.FromJson("is_friend"), Is.EqualTo(ProfileFields.IsFriend));
Assert.That(ProfileFields.FromJson("screen_name"), Is.EqualTo(ProfileFields.ScreenName));
Assert.That(ProfileFields.FromJson("is_hidden_from_feed"), Is.EqualTo(ProfileFields.IsHiddenFromFeed));
Assert.That(ProfileFields.FromJson("is_favorite"), Is.EqualTo(ProfileFields.IsFavorite));
Assert.That(ProfileFields.FromJson("can_send_friend_request"), Is.EqualTo(ProfileFields.CanSendFriendRequest));
Assert.That(ProfileFields.FromJson("wall_comments"), Is.EqualTo(ProfileFields.WallComments));
Assert.That(ProfileFields.FromJson("verified"), Is.EqualTo(ProfileFields.Verified));
Assert.That(ProfileFields.FromJson("user_id,first_name,last_name,sex,bdate,city,country,photo_50,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_max,photo_max_orig,online,lists,domain,has_mobile,contacts,connections,site,education,universities,schools,can_post,can_see_all_posts,can_see_audio,can_write_private_message,status,last_seen,common_count,relation,relatives,counters,nickname,timezone,blacklisted_by_me,blacklisted,military,career,friend_status,is_friend,screen_name,is_hidden_from_feed,is_favorite,can_send_friend_request,wall_comments,verified"), Is.EqualTo(ProfileFields.All));
Assert.That(ProfileFields.FromJson("user_id,first_name,last_name,sex,bdate,city,country,photo_50,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_max,photo_max_orig,online,lists,domain,has_mobile,contacts,connections,site,education,universities,schools,can_post,can_see_all_posts,can_see_audio,can_write_private_message,status,last_seen,common_count,relation,relatives,counters,nickname,timezone,lang,online_mobile,online_app,relation_partner,personal,interests,music,activities,movies,tv,books,games,about,quotes,invited_by,blacklisted_by_me,blacklisted,military,career,friend_status,is_friend,screen_name,is_hidden_from_feed,is_favorite,can_send_friend_request,wall_comments,verified"), Is.EqualTo(ProfileFields.AllUndocumented));
}
[Test]
public void SettingsTest()
{
// get test
Assert.That(Settings.Notify.ToString(), Is.EqualTo("notify"));
Assert.That(Settings.Friends.ToString(), Is.EqualTo("friends"));
Assert.That(Settings.Photos.ToString(), Is.EqualTo("photos"));
Assert.That(Settings.Audio.ToString(), Is.EqualTo("audio"));
Assert.That(Settings.Video.ToString(), Is.EqualTo("video"));
Assert.That(Settings.Pages.ToString(), Is.EqualTo("pages"));
Assert.That(Settings.AddLinkToLeftMenu.ToString(), Is.EqualTo("addLinkToLeftMenu"));
Assert.That(Settings.Status.ToString(), Is.EqualTo("status"));
Assert.That(Settings.Notes.ToString(), Is.EqualTo("notes"));
Assert.That(Settings.Messages.ToString(), Is.EqualTo("messages"));
Assert.That(Settings.Wall.ToString(), Is.EqualTo("wall"));
Assert.That(Settings.Ads.ToString(), Is.EqualTo("ads"));
Assert.That(Settings.Offline.ToString(), Is.EqualTo("offline"));
Assert.That(Settings.Documents.ToString(), Is.EqualTo("docs"));
Assert.That(Settings.Groups.ToString(), Is.EqualTo("groups"));
Assert.That(Settings.Notifications.ToString(), Is.EqualTo("notifications"));
Assert.That(Settings.Statistic.ToString(), Is.EqualTo("stats"));
Assert.That(Settings.Email.ToString(), Is.EqualTo("email"));
Assert.That(Settings.Market.ToString(), Is.EqualTo("market"));
Assert.That(Settings.All.ToString(), Is.EqualTo("notify,friends,photos,audio,video,pages,status,notes,messages,wall,ads,docs,groups,notifications,stats,email,market"));
// parse test
Assert.That(Settings.FromJson("notify"), Is.EqualTo(Settings.Notify));
Assert.That(Settings.FromJson("friends"), Is.EqualTo(Settings.Friends));
Assert.That(Settings.FromJson("photos"), Is.EqualTo(Settings.Photos));
Assert.That(Settings.FromJson("audio"), Is.EqualTo(Settings.Audio));
Assert.That(Settings.FromJson("video"), Is.EqualTo(Settings.Video));
Assert.That(Settings.FromJson("pages"), Is.EqualTo(Settings.Pages));
Assert.That(Settings.FromJson("addLinkToLeftMenu"), Is.EqualTo(Settings.AddLinkToLeftMenu));
Assert.That(Settings.FromJson("status"), Is.EqualTo(Settings.Status));
Assert.That(Settings.FromJson("notes"), Is.EqualTo(Settings.Notes));
Assert.That(Settings.FromJson("messages"), Is.EqualTo(Settings.Messages));
Assert.That(Settings.FromJson("wall"), Is.EqualTo(Settings.Wall));
Assert.That(Settings.FromJson("ads"), Is.EqualTo(Settings.Ads));
Assert.That(Settings.FromJson("offline"), Is.EqualTo(Settings.Offline));
Assert.That(Settings.FromJson("docs"), Is.EqualTo(Settings.Documents));
Assert.That(Settings.FromJson("groups"), Is.EqualTo(Settings.Groups));
Assert.That(Settings.FromJson("notifications"), Is.EqualTo(Settings.Notifications));
Assert.That(Settings.FromJson("stats"), Is.EqualTo(Settings.Statistic));
Assert.That(Settings.FromJson("email"), Is.EqualTo(Settings.Email));
Assert.That(Settings.FromJson("market"), Is.EqualTo(Settings.Market));
Assert.That(Settings.FromJson("notify,friends,photos,audio,video,pages,status,notes,messages,wall,ads,docs,groups,notifications,stats,email,market"), Is.EqualTo(Settings.All));
}
[Test]
public void SubscribeFilterTest()
{
// get test
Assert.That(SubscribeFilter.Message.ToString(), Is.EqualTo("msg"));
Assert.That(SubscribeFilter.Friend.ToString(), Is.EqualTo("friend"));
Assert.That(SubscribeFilter.Call.ToString(), Is.EqualTo("call"));
Assert.That(SubscribeFilter.Reply.ToString(), Is.EqualTo("reply"));
Assert.That(SubscribeFilter.Mention.ToString(), Is.EqualTo("mention"));
Assert.That(SubscribeFilter.Group.ToString(), Is.EqualTo("group"));
Assert.That(SubscribeFilter.Like.ToString(), Is.EqualTo("like"));
Assert.That(SubscribeFilter.All.ToString(), Is.EqualTo("msg,friend,call,reply,mention,group,like"));
// parse test
Assert.That(SubscribeFilter.FromJson("msg"), Is.EqualTo(SubscribeFilter.Message));
Assert.That(SubscribeFilter.FromJson("friend"), Is.EqualTo(SubscribeFilter.Friend));
Assert.That(SubscribeFilter.FromJson("call"), Is.EqualTo(SubscribeFilter.Call));
Assert.That(SubscribeFilter.FromJson("reply"), Is.EqualTo(SubscribeFilter.Reply));
Assert.That(SubscribeFilter.FromJson("mention"), Is.EqualTo(SubscribeFilter.Mention));
Assert.That(SubscribeFilter.FromJson("group"), Is.EqualTo(SubscribeFilter.Group));
Assert.That(SubscribeFilter.FromJson("like"), Is.EqualTo(SubscribeFilter.Like));
Assert.That(SubscribeFilter.FromJson("msg,friend,call,reply,mention,group,like"), Is.EqualTo(SubscribeFilter.All));
}
[Test]
public void UsersFieldsTest()
{
// get test
Assert.That(UsersFields.Nickname.ToString(), Is.EqualTo("nickname"));
Assert.That(UsersFields.Domain.ToString(), Is.EqualTo("domain"));
Assert.That(UsersFields.Sex.ToString(), Is.EqualTo("sex"));
Assert.That(UsersFields.BirthDate.ToString(), Is.EqualTo("bdate"));
Assert.That(UsersFields.City.ToString(), Is.EqualTo("city"));
Assert.That(UsersFields.Country.ToString(), Is.EqualTo("country"));
Assert.That(UsersFields.Timezone.ToString(), Is.EqualTo("timezone"));
Assert.That(UsersFields.Photo50.ToString(), Is.EqualTo("photo_50"));
Assert.That(UsersFields.Photo100.ToString(), Is.EqualTo("photo_100"));
Assert.That(UsersFields.Photo200Orig.ToString(), Is.EqualTo("photo_200_orig"));
Assert.That(UsersFields.Photo200.ToString(), Is.EqualTo("photo_200"));
Assert.That(UsersFields.Photo400Orig.ToString(), Is.EqualTo("photo_400_orig"));
Assert.That(UsersFields.PhotoMax.ToString(), Is.EqualTo("photo_max"));
Assert.That(UsersFields.PhotoMaxOrig.ToString(), Is.EqualTo("photo_max_orig"));
Assert.That(UsersFields.HasMobile.ToString(), Is.EqualTo("has_mobile"));
Assert.That(UsersFields.Contacts.ToString(), Is.EqualTo("contacts"));
Assert.That(UsersFields.Education.ToString(), Is.EqualTo("education"));
Assert.That(UsersFields.Online.ToString(), Is.EqualTo("online"));
Assert.That(UsersFields.OnlineMobile.ToString(), Is.EqualTo("online_mobile"));
Assert.That(UsersFields.FriendLists.ToString(), Is.EqualTo("lists"));
Assert.That(UsersFields.Relation.ToString(), Is.EqualTo("relation"));
Assert.That(UsersFields.LastSeen.ToString(), Is.EqualTo("last_seen"));
Assert.That(UsersFields.Status.ToString(), Is.EqualTo("status"));
Assert.That(UsersFields.CanWritePrivateMessage.ToString(), Is.EqualTo("can_write_private_message"));
Assert.That(UsersFields.CanSeeAllPosts.ToString(), Is.EqualTo("can_see_all_posts"));
Assert.That(UsersFields.CanPost.ToString(), Is.EqualTo("can_post"));
Assert.That(UsersFields.Universities.ToString(), Is.EqualTo("universities"));
Assert.That(UsersFields.Connections.ToString(), Is.EqualTo("connections"));
Assert.That(UsersFields.Site.ToString(), Is.EqualTo("site"));
Assert.That(UsersFields.Schools.ToString(), Is.EqualTo("schools"));
Assert.That(UsersFields.CanSeeAudio.ToString(), Is.EqualTo("can_see_audio"));
Assert.That(UsersFields.CommonCount.ToString(), Is.EqualTo("common_count"));
Assert.That(UsersFields.Relatives.ToString(), Is.EqualTo("relatives"));
Assert.That(UsersFields.Counters.ToString(), Is.EqualTo("counters"));
Assert.That(UsersFields.All.ToString(), Is.EqualTo("nickname,domain,sex,bdate,city,country,timezone,photo_50,photo_100,photo_200_orig,photo_200,photo_400_orig,photo_max,photo_max_orig,has_mobile,contacts,education,online,online_mobile,lists,relation,last_seen,status,can_write_private_message,can_see_all_posts,can_post,universities,connections,site,schools,can_see_audio,common_count,relatives,counters"));
// parse test
Assert.That(UsersFields.FromJson("nickname"), Is.EqualTo(UsersFields.Nickname));
Assert.That(UsersFields.FromJson("domain"), Is.EqualTo(UsersFields.Domain));
Assert.That(UsersFields.FromJson("sex"), Is.EqualTo(UsersFields.Sex));
Assert.That(UsersFields.FromJson("bdate"), Is.EqualTo(UsersFields.BirthDate));
Assert.That(UsersFields.FromJson("city"), Is.EqualTo(UsersFields.City));
Assert.That(UsersFields.FromJson("country"), Is.EqualTo(UsersFields.Country));
Assert.That(UsersFields.FromJson("timezone"), Is.EqualTo(UsersFields.Timezone));
Assert.That(UsersFields.FromJson("photo_50"), Is.EqualTo(UsersFields.Photo50));
Assert.That(UsersFields.FromJson("photo_100"), Is.EqualTo(UsersFields.Photo100));
Assert.That(UsersFields.FromJson("photo_200_orig"), Is.EqualTo(UsersFields.Photo200Orig));
Assert.That(UsersFields.FromJson("photo_200"), Is.EqualTo(UsersFields.Photo200));
Assert.That(UsersFields.FromJson("photo_400_orig"), Is.EqualTo(UsersFields.Photo400Orig));
Assert.That(UsersFields.FromJson("photo_max"), Is.EqualTo(UsersFields.PhotoMax));
Assert.That(UsersFields.FromJson("photo_max_orig"), Is.EqualTo(UsersFields.PhotoMaxOrig));
Assert.That(UsersFields.FromJson("has_mobile"), Is.EqualTo(UsersFields.HasMobile));
Assert.That(UsersFields.FromJson("contacts"), Is.EqualTo(UsersFields.Contacts));
Assert.That(UsersFields.FromJson("education"), Is.EqualTo(UsersFields.Education));
Assert.That(UsersFields.FromJson("online"), Is.EqualTo(UsersFields.Online));
Assert.That(UsersFields.FromJson("online_mobile"), Is.EqualTo(UsersFields.OnlineMobile));
Assert.That(UsersFields.FromJson("lists"), Is.EqualTo(UsersFields.FriendLists));
Assert.That(UsersFields.FromJson("relation"), Is.EqualTo(UsersFields.Relation));
Assert.That(UsersFields.FromJson("last_seen"), Is.EqualTo(UsersFields.LastSeen));
Assert.That(UsersFields.FromJson("status"), Is.EqualTo(UsersFields.Status));
Assert.That(UsersFields.FromJson("can_write_private_message"), Is.EqualTo(UsersFields.CanWritePrivateMessage));
Assert.That(UsersFields.FromJson("can_see_all_posts"), Is.EqualTo(UsersFields.CanSeeAllPosts));
Assert.That(UsersFields.FromJson("can_post"), Is.EqualTo(UsersFields.CanPost));
Assert.That(UsersFields.FromJson("universities"), Is.EqualTo(UsersFields.Universities));
Assert.That(UsersFields.FromJson("connections"), Is.EqualTo(UsersFields.Connections));
Assert.That(UsersFields.FromJson("site"), Is.EqualTo(UsersFields.Site));
Assert.That(UsersFields.FromJson("schools"), Is.EqualTo(UsersFields.Schools));
Assert.That(UsersFields.FromJson("can_see_audio"), Is.EqualTo(UsersFields.CanSeeAudio));
Assert.That(UsersFields.FromJson("common_count"), Is.EqualTo(UsersFields.CommonCount));
Assert.That(UsersFields.FromJson("relatives"), Is.EqualTo(UsersFields.Relatives));
Assert.That(UsersFields.FromJson("counters"), Is.EqualTo(UsersFields.Counters));
Assert.That(UsersFields.FromJson("nickname,domain,sex,bdate,city,country,timezone,photo_50,photo_100,photo_200_orig,photo_200,photo_400_orig,photo_max,photo_max_orig,has_mobile,contacts,education,online,online_mobile,lists,relation,last_seen,status,can_write_private_message,can_see_all_posts,can_post,universities,connections,site,schools,can_see_audio,common_count,relatives,counters"), Is.EqualTo(UsersFields.All));
}
[Test]
public void VideoFiltersTest()
{
// get test
Assert.That(VideoFilters.Mp4.ToString(), Is.EqualTo("mp4"));
Assert.That(VideoFilters.Youtube.ToString(), Is.EqualTo("youtube"));
Assert.That(VideoFilters.Vimeo.ToString(), Is.EqualTo("vimeo"));
Assert.That(VideoFilters.Short.ToString(), Is.EqualTo("short"));
Assert.That(VideoFilters.Long.ToString(), Is.EqualTo("long"));
Assert.That(VideoFilters.All.ToString(), Is.EqualTo("mp4,youtube,vimeo,short,long"));
// parse test
Assert.That(VideoFilters.FromJson("mp4"), Is.EqualTo(VideoFilters.Mp4));
Assert.That(VideoFilters.FromJson("youtube"), Is.EqualTo(VideoFilters.Youtube));
Assert.That(VideoFilters.FromJson("vimeo"), Is.EqualTo(VideoFilters.Vimeo));
Assert.That(VideoFilters.FromJson("short"), Is.EqualTo(VideoFilters.Short));
Assert.That(VideoFilters.FromJson("long"), Is.EqualTo(VideoFilters.Long));
Assert.That(VideoFilters.FromJson("mp4,youtube,vimeo,short,long"), Is.EqualTo(VideoFilters.All));
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.UserModel
{
using System;
using System.Collections.Generic;
using System.Globalization;
/**
* Utility to identify built-in formats. The following is a list of the formats as
* returned by this class.<p/>
*<p/>
* 0, "General"<br/>
* 1, "0"<br/>
* 2, "0.00"<br/>
* 3, "#,##0"<br/>
* 4, "#,##0.00"<br/>
* 5, "$#,##0_);($#,##0)"<br/>
* 6, "$#,##0_);[Red]($#,##0)"<br/>
* 7, "$#,##0.00);($#,##0.00)"<br/>
* 8, "$#,##0.00_);[Red]($#,##0.00)"<br/>
* 9, "0%"<br/>
* 0xa, "0.00%"<br/>
* 0xb, "0.00E+00"<br/>
* 0xc, "# ?/?"<br/>
* 0xd, "# ??/??"<br/>
* 0xe, "m/d/yy"<br/>
* 0xf, "d-mmm-yy"<br/>
* 0x10, "d-mmm"<br/>
* 0x11, "mmm-yy"<br/>
* 0x12, "h:mm AM/PM"<br/>
* 0x13, "h:mm:ss AM/PM"<br/>
* 0x14, "h:mm"<br/>
* 0x15, "h:mm:ss"<br/>
* 0x16, "m/d/yy h:mm"<br/>
*<p/>
* // 0x17 - 0x24 reserved for international and undocumented
* 0x25, "#,##0_);(#,##0)"<br/>
* 0x26, "#,##0_);[Red](#,##0)"<br/>
* 0x27, "#,##0.00_);(#,##0.00)"<br/>
* 0x28, "#,##0.00_);[Red](#,##0.00)"<br/>
* 0x29, "_(*#,##0_);_(*(#,##0);_(* \"-\"_);_(@_)"<br/>
* 0x2a, "_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"<br/>
* 0x2b, "_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"<br/>
* 0x2c, "_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"<br/>
* 0x2d, "mm:ss"<br/>
* 0x2e, "[h]:mm:ss"<br/>
* 0x2f, "mm:ss.0"<br/>
* 0x30, "##0.0E+0"<br/>
* 0x31, "@" - This is text format.<br/>
* 0x31 "text" - Alias for "@"<br/>
* <p/>
*
* @author Yegor Kozlov
*
* Modified 6/17/09 by Stanislav Shor - positive formats don't need starting '('
*
*/
public class BuiltinFormats
{
/**
* The first user-defined format starts at 164.
*/
public const int FIRST_USER_DEFINED_FORMAT_INDEX = 164;
private static String[] _formats;
/*
0 General General 18 Time h:mm AM/PM
1 Decimal 0 19 Time h:mm:ss AM/PM
2 Decimal 0.00 20 Time h:mm
3 Decimal #,##0 21 Time h:mm:ss
4 Decimal #,##0.00 2232 Date/Time M/D/YY h:mm
531 Currency "$"#,##0_);("$"#,##0) 37 Account. _(#,##0_);(#,##0)
631 Currency "$"#,##0_);[Red]("$"#,##0) 38 Account. _(#,##0_);[Red](#,##0)
731 Currency "$"#,##0.00_);("$"#,##0.00) 39 Account. _(#,##0.00_);(#,##0.00)
831 Currency "$"#,##0.00_);[Red]("$"#,##0.00) 40 Account. _(#,##0.00_);[Red](#,##0.00)
9 Percent 0% 4131 Currency _("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_)
10 Percent 0.00% 4231 33 Currency _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
11 Scientific 0.00E+00 4331 Currency _("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)
12 Fraction # ?/? 4431 33 Currency _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
13 Fraction # ??/?? 45 Time mm:ss
1432 Date M/D/YY 46 Time [h]:mm:ss
15 Date D-MMM-YY 47 Time mm:ss.0
16 Date D-MMM 48 Scientific ##0.0E+0
17 Date MMM-YY 49 Text @
* */
static BuiltinFormats()
{
List<String> m = new List<String>();
PutFormat(m, 0, "General");
PutFormat(m, 1, "0");
PutFormat(m, 2, "0.00");
PutFormat(m, 3, "#,##0");
PutFormat(m, 4, "#,##0.00");
PutFormat(m, 5, "\"$\"#,##0_);(\"$\"#,##0)");
PutFormat(m, 6, "\"$\"#,##0_);[Red](\"$\"#,##0)");
PutFormat(m, 7, "\"$\"#,##0.00_);(\"$\"#,##0.00)");
PutFormat(m, 8, "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)");
PutFormat(m, 9, "0%");
PutFormat(m, 0xa, "0.00%");
PutFormat(m, 0xb, "0.00E+00");
PutFormat(m, 0xc, "# ?/?");
PutFormat(m, 0xd, "# ??/??");
PutFormat(m, 0xe, "m/d/yy");
PutFormat(m, 0xf, "d-mmm-yy");
PutFormat(m, 0x10, "d-mmm");
PutFormat(m, 0x11, "mmm-yy");
PutFormat(m, 0x12, "h:mm AM/PM");
PutFormat(m, 0x13, "h:mm:ss AM/PM");
PutFormat(m, 0x14, "h:mm");
PutFormat(m, 0x15, "h:mm:ss");
PutFormat(m, 0x16, "m/d/yy h:mm");
// 0x17 - 0x24 reserved for international and undocumented
for (int i = 0x17; i <= 0x24; i++)
{
// TODO - one junit relies on these values which seems incorrect
PutFormat(m, i, "reserved-0x" + (i).ToString("X", CultureInfo.CurrentCulture));
}
PutFormat(m, 0x25, "#,##0_);(#,##0)");
PutFormat(m, 0x26, "#,##0_);[Red](#,##0)");
PutFormat(m, 0x27, "#,##0.00_);(#,##0.00)");
PutFormat(m, 0x28, "#,##0.00_);[Red](#,##0.00)");
PutFormat(m, 0x29, "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)");
PutFormat(m, 0x2a, "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)");
PutFormat(m, 0x2b, "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)");
PutFormat(m, 0x2c, "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)");
PutFormat(m, 0x2d, "mm:ss");
PutFormat(m, 0x2e, "[h]:mm:ss");
PutFormat(m, 0x2f, "mm:ss.0");
PutFormat(m, 0x30, "##0.0E+0");
PutFormat(m, 0x31, "@");
//String[] ss = new String[m.Count];
String[] ss = m.ToArray();
_formats = ss;
}
private static void PutFormat(List<String> m, int index, String value)
{
if (m.Count != index)
{
throw new InvalidOperationException("index " + index + " is wrong");
}
m.Add(value);
}
/**
* @deprecated (May 2009) use {@link #getAll()}
*/
[Obsolete]
public static Dictionary<int, String> GetBuiltinFormats()
{
Dictionary<int, String> result = new Dictionary<int, String>();
for (int i = 0; i < _formats.Length; i++)
{
result.Add(i, _formats[i]);
}
return result;
}
/**
* @return array of built-in data formats
*/
public static String[] GetAll()
{
return (String[])_formats.Clone();
}
/**
* Get the format string that matches the given format index
*
* @param index of a built in format
* @return string represented at index of format or <code>null</code> if there is not a built-in format at that index
*/
public static String GetBuiltinFormat(int index)
{
if (index < 0 || index >= _formats.Length)
{
return null;
}
return _formats[index];
}
/**
* Get the format index that matches the given format string.
*
* <p>
* Automatically converts "text" to excel's format string to represent text.
* </p>
* @param pFmt string matching a built-in format
* @return index of format or -1 if undefined.
*/
public static int GetBuiltinFormat(String pFmt)
{
String fmt;
if (string.Compare(pFmt, ("TEXT"), StringComparison.OrdinalIgnoreCase) == 0)
{
fmt = "@";
}
else
{
fmt = pFmt;
}
for (int i = 0; i < _formats.Length; i++)
{
if (fmt.Equals(_formats[i]))
{
return i;
}
}
return -1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Imaging.MetafileHeader.cs
//
// Author: Everaldo Canuto
// eMail: [email protected]
// Dennis Hayes ([email protected])
//
// (C) 2002 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004, 2006 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.Drawing.Drawing2D;
using System.Runtime.InteropServices;
namespace System.Drawing.Imaging
{
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct EnhMetafileHeader
{
public int type;
public int size;
public Rectangle bounds;
public Rectangle frame;
public int signature;
public int version;
public int bytes;
public int records;
public short handles;
public short reserved;
public int description;
public int off_description;
public int palette_entires;
public Size device;
public Size millimeters;
}
// hack: keep public type as Sequential while making it possible to get the required union
[StructLayout(LayoutKind.Explicit)]
struct MonoMetafileHeader
{
[FieldOffset(0)]
public MetafileType type;
[FieldOffset(4)]
public int size;
[FieldOffset(8)]
public int version;
[FieldOffset(12)]
public int emf_plus_flags;
[FieldOffset(16)]
public float dpi_x;
[FieldOffset(20)]
public float dpi_y;
[FieldOffset(24)]
public int x;
[FieldOffset(28)]
public int y;
[FieldOffset(32)]
public int width;
[FieldOffset(36)]
public int height;
[FieldOffset(40)]
public WmfMetaHeader wmf_header;
[FieldOffset(40)]
public EnhMetafileHeader emf_header;
[FieldOffset(128)]
public int emfplus_header_size;
[FieldOffset(132)]
public int logical_dpi_x;
[FieldOffset(136)]
public int logical_dpi_y;
}
[MonoTODO("Metafiles, both WMF and EMF formats, aren't supported.")]
[StructLayout(LayoutKind.Sequential)]
public sealed class MetafileHeader
{
private MonoMetafileHeader header;
//constructor
internal MetafileHeader(IntPtr henhmetafile)
{
Marshal.PtrToStructure(henhmetafile, this);
}
// methods
[MonoTODO("always returns false")]
public bool IsDisplay()
{
return false;
}
public bool IsEmf()
{
return (Type == MetafileType.Emf);
}
public bool IsEmfOrEmfPlus()
{
return (Type >= MetafileType.Emf);
}
public bool IsEmfPlus()
{
return (Type >= MetafileType.EmfPlusOnly);
}
public bool IsEmfPlusDual()
{
return (Type == MetafileType.EmfPlusDual);
}
public bool IsEmfPlusOnly()
{
return (Type == MetafileType.EmfPlusOnly);
}
public bool IsWmf()
{
return (Type <= MetafileType.WmfPlaceable);
}
public bool IsWmfPlaceable()
{
return (Type == MetafileType.WmfPlaceable);
}
// properties
public Rectangle Bounds
{
get { return new Rectangle(header.x, header.y, header.width, header.height); }
}
public float DpiX
{
get { return header.dpi_x; }
}
public float DpiY
{
get { return header.dpi_y; }
}
public int EmfPlusHeaderSize
{
get { return header.emfplus_header_size; }
}
public int LogicalDpiX
{
get { return header.logical_dpi_x; }
}
public int LogicalDpiY
{
get { return header.logical_dpi_y; }
}
public int MetafileSize
{
get { return header.size; }
}
public MetafileType Type
{
get { return header.type; }
}
public int Version
{
get { return header.version; }
}
// note: this always returns a new instance (where we can change
// properties even if they don't seems to affect anything)
public MetaHeader WmfHeader
{
get
{
if (IsWmf())
return new MetaHeader(header.wmf_header);
throw new ArgumentException("WmfHeader only available on WMF files.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using KiloWatt.Animation.Graphics;
using KiloWatt.Animation.Animation;
namespace AnimationViewer
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class AnimationViewer : Microsoft.Xna.Framework.Game, IScene
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public static AnimationViewer Global;
public AnimationViewer()
{
Global = this;
graphics = new GraphicsDeviceManager(this);
#if XBOX360
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
#else
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 576;
#endif
graphics.SynchronizeWithVerticalRetrace = true;
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
#if !XBOX360
Mouse.SetPosition(GraphicsDevice.PresentationParameters.BackBufferWidth / 2,
GraphicsDevice.PresentationParameters.BackBufferHeight / 2);
curMouse_ = prevMouse_ = Mouse.GetState();
#endif
debugLines_ = new DebugLines(GraphicsDevice);
}
DebugLines debugLines_;
SpriteFont font_;
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
SetPath("");
showingBrowser_ = true;
font_ = Content.Load<SpriteFont>("Tw Cen MT");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
GamePadState prevGamePad_;
GamePadState curGamePad_;
KeyboardState prevKeyboard_;
KeyboardState curKeyboard_;
#if !XBOX360
MouseState prevMouse_;
MouseState curMouse_;
#endif
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
prevGamePad_ = curGamePad_;
curGamePad_ = GamePad.GetState(PlayerIndex.One);
prevKeyboard_ = curKeyboard_;
curKeyboard_ = Keyboard.GetState(PlayerIndex.One);
#if !XBOX360
prevMouse_ = curMouse_;
curMouse_ = Mouse.GetState();
int wid = GraphicsDevice.PresentationParameters.BackBufferWidth / 2;
int hei = GraphicsDevice.PresentationParameters.BackBufferHeight / 2;
Mouse.SetPosition(wid, hei);
if (curMouse_.RightButton == ButtonState.Pressed)
{
if (curMouse_.LeftButton == ButtonState.Pressed)
{
// reset all
pan_ = Vector3.Zero;
relativeDistance_ = 0;
Heading = 0;
Pitch = 0;
}
else
{
Heading = Heading + (curMouse_.X - wid) * 0.025f;
Pitch = Pitch + (curMouse_.Y - hei) * 0.025f;
}
}
else if (curMouse_.LeftButton == ButtonState.Pressed)
{
pan_ = pan_ + viewInv_.Right * (curMouse_.X - wid) * 0.025f +
viewInv_.Down * (curMouse_.Y - hei) * 0.025f;
}
float dWheel = (curMouse_.ScrollWheelValue - prevMouse_.ScrollWheelValue) * -0.001f;
if (dWheel != 0)
relativeDistance_ += dWheel;
#endif
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (dt > 0.1f) dt = 0.1f;
Heading = Heading + curGamePad_.ThumbSticks.Left.X * dt * 5;
if (Heading < -(float)Math.PI) Heading = Heading + 2 * (float)Math.PI;
if (Heading > (float)Math.PI) Heading = Heading - 2 * (float)Math.PI;
Pitch = Pitch + curGamePad_.ThumbSticks.Left.Y * dt * 5;
if (Pitch < -1.5f) Pitch = -1.5f;
if (Pitch > 1.5f) Pitch = 1.5f;
relativeDistance_ = relativeDistance_ + curGamePad_.ThumbSticks.Right.Y * dt * -2;
if (relativeDistance_ < -10f)
relativeDistance_ = -10f;
if (relativeDistance_ > 10f)
relativeDistance_ = 10f;
if (showingBrowser_)
{
if (ButtonPressed(Buttons.A) || ButtonPressed(Buttons.Start)
|| KeyPressed(Keys.Space) || KeyPressed(Keys.Enter))
{
if (CurEntryIsDir)
{
SetPath(System.IO.Path.Combine(CurPath, CurEntryName));
}
else
{
LoadModel(System.IO.Path.Combine(CurPath, CurEntryName));
}
showingBrowser_ = false;
}
else if (ButtonPressed(Buttons.B) || ButtonPressed(Buttons.Back)
|| KeyPressed(Keys.Escape) || KeyPressed(Keys.Back))
{
showingBrowser_ = false;
}
else if (CurEntry < NumEntries-1 &&
(ButtonPressed(Buttons.DPadDown)
|| KeyPressed(Keys.Down)))
{
CurEntry = CurEntry + 1;
}
else if (CurEntry > 0 &&
(ButtonPressed(Buttons.DPadUp)
|| KeyPressed(Keys.Up)))
{
CurEntry = CurEntry - 1;
}
else if (ButtonPressed(Buttons.Y)
|| KeyPressed(Keys.PageUp))
{
int ind = CurPath.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
if (ind > 0)
SetPath(CurPath.Substring(0, ind));
}
}
else if (ButtonPressed(Buttons.A) || ButtonPressed(Buttons.Start)
|| KeyPressed(Keys.Space) || KeyPressed(Keys.Enter))
{
showingBrowser_ = true;
}
else if (ButtonPressed(Buttons.Back)
|| KeyPressed(Keys.Escape))
{
Exit();
}
else if (instances_ != null
&& curAnimationInstance_ < instances_.Length - 1
&& (ButtonPressed(Buttons.RightShoulder)
|| KeyPressed(Keys.OemCloseBrackets)))
{
curAnimationInstance_ += 1;
Message = String.Format("{0} : {1}", loadedModel_.Name, instances_[curAnimationInstance_].Animation.Name);
if (curAnimationInstance_ > 0)
instances_[curAnimationInstance_].Time = instances_[curAnimationInstance_-1].Time;
blender_.TransitionAnimations(GetBlended(curAnimationInstance_-1), GetBlended(curAnimationInstance_), 1.0f);
}
else if (instances_ != null
&& curAnimationInstance_ > -1
&& (ButtonPressed(Buttons.LeftShoulder)
|| KeyPressed(Keys.OemOpenBrackets)))
{
curAnimationInstance_ -= 1;
if (curAnimationInstance_ >= 0)
Message = String.Format("{0} : {1}", loadedModel_.Name, instances_[curAnimationInstance_].Animation.Name);
else
Message = loadedModel_.Name;
if (curAnimationInstance_ > 0)
instances_[curAnimationInstance_].Time = instances_[curAnimationInstance_ - 1].Time;
blender_.TransitionAnimations(GetBlended(curAnimationInstance_ + 1), GetBlended(curAnimationInstance_), 1.0f);
}
if (blender_ != null)
blender_.Advance(dt);
base.Update(gameTime);
}
IBlendedAnimation GetBlended(int ix)
{
unchecked
{
return (ix < 0) ? null : (ix >= blended_.Length) ? null : blended_[ix];
}
}
public bool ButtonPressed(Buttons b)
{
return !prevGamePad_.IsButtonDown(b) && curGamePad_.IsButtonDown(b);
}
public bool KeyPressed(Keys k)
{
return !prevKeyboard_.IsKeyDown(k) && curKeyboard_.IsKeyDown(k);
}
DrawDetails drawDetails_ = new DrawDetails();
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.DarkKhaki);
// Set up camera parameters
float d = baseDistance_ * (float)(Math.Pow(2, relativeDistance_ - 1));
view_ = Matrix.CreateTranslation(pan_) * Matrix.CreateRotationY(Heading) *
Matrix.CreateRotationX(Pitch) * Matrix.CreateTranslation(0, 0, -d);
float near = d * 0.25f;
projection_ = Matrix.CreatePerspective(1.6f * zoom_ * near, 0.9f * zoom_ * near, near, d * 10.0f + 10.0f);
viewInv_ = Matrix.Invert(view_);
// if I have a model, set up the scene drawing parameters and draw the model
if (loadedModel_ != null)
{
// the drawdetails set-up can be re-used for all items in the scene
DrawDetails dd = drawDetails_;
dd.dev = GraphicsDevice;
dd.fogColor = new Vector4(0.5f, 0.5f, 0.5f, 1);
dd.fogDistance = 10 * baseDistance_;
dd.lightAmbient = new Vector4(0.2f, 0.2f, 0.2f, 1.0f);
dd.lightDiffuse = new Vector4(0.8f, 0.8f, 0.8f, 0);
dd.lightDir = Vector3.Normalize(new Vector3(1, 3, 2));
dd.viewInv = viewInv_;
dd.viewProj = view_ * projection_;
dd.world = Matrix.Identity;
// draw the loaded model (the only model I have)
loadedModel_.ScenePrepare(dd);
if (loadedModel_.SceneDraw(dd, 0))
{
loadedModel_.SceneDrawTransparent(dd, 0);
}
}
// when everything else is drawn, Z sort and draw the transparent parts
// draw any components
base.Draw(gameTime);
// draw any visualization lines
debugLines_.Draw(view_, projection_);
debugLines_.Reset();
// draw text information
spriteBatch.Begin();
spriteBatch.DrawString(font_, Message,
new Vector2(30, GraphicsDevice.PresentationParameters.BackBufferHeight - 40),
Color.White);
spriteBatch.DrawString(font_, String.Format("Pan: {0} Distance: {1}", pan_, d),
new Vector2(30, GraphicsDevice.PresentationParameters.BackBufferHeight - 65),
Color.White);
// draw the very primitive file browser
if (ShowingBrowser)
{
spriteBatch.DrawString(font_, CurPath, new Vector2(30, 30), Color.LightYellow);
float x = GraphicsDevice.PresentationParameters.BackBufferWidth / 2;
for (int i = 0; i < entries_.Count; ++i)
{
spriteBatch.DrawString(font_, entries_[i].Name,
new Vector2(x, i * 30 + 30),
i == CurEntry ? Color.Red : entries_[i].IsDir ? Color.LightYellow : Color.DarkBlue);
}
}
spriteBatch.End();
}
internal class CaseInsensitiveComparer : System.Collections.IComparer
{
public int Compare(object x, object y)
{
return String.Compare((string)x, (string)y, true);
}
}
void SetPath(string path)
{
curPath_ = path;
entries_.Clear();
string[] dirs = System.IO.Directory.GetDirectories(System.IO.Path.Combine(Content.RootDirectory, path));
string[] files = System.IO.Directory.GetFiles(System.IO.Path.Combine(Content.RootDirectory, path));
System.Collections.IComparer cic = new CaseInsensitiveComparer();
Array.Sort(dirs, cic);
Array.Sort(files, cic);
foreach (string dir in dirs)
if (dir[0] != '.' && dir.IndexOf('%') < 0)
entries_.Add(new FileEntry(dir, true));
foreach (string file in files)
if (file[0] != '.' && file.IndexOf('%') < 0)
if (IsInstanceOf<Model>(file))
entries_.Add(new FileEntry(file, false));
curEntry_ = 0;
}
void LoadModel(string path)
{
try
{
// the file name that comes from the browser contains .xnb
if (path.EndsWith(".xnb"))
path = path.Substring(0, path.Length - 4);
// load the model from disk, and prepare it for animation
loadedModel_ = new ModelDraw(Content.Load<Model>(path), System.IO.Path.GetFileName(path));
loadedModel_.Attach(this);
// create a blender that can compose the animations for transition
blender_ = new AnimationBlender(loadedModel_.Model, loadedModel_.Name);
loadedModel_.CurrentAnimation = blender_;
// remember things about this model
ResetModelData(path);
// figure out what the animations are, if any.
LoadAnimations();
}
catch (System.Exception x)
{
// couldn't load model
Message = x.Message;
System.Diagnostics.Debug.WriteLine(Message);
}
}
void ResetModelData(string path)
{
Heading = 0;
Pitch = 0;
RelativeDistance = 0;
modelSize_ = loadedModel_.Bounds;
baseDistance_ = (modelSize_.Center.Length() + modelSize_.Radius) * 2;
modelPath_ = path;
Message = String.Format("Viewing {0}", modelPath_);
animations_ = null;
}
internal struct FileEntry
{
public FileEntry(string name, bool isDir)
{
int i = name.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
if (i <= 0)
Name = name;
else
Name = name.Substring(i+1);
IsDir = isDir;
}
public string Name;
public bool IsDir;
}
public static bool IsInstanceOf<T>(string name) where T : class
{
ContentManager mgr = new ContentManager(AnimationViewer.Global.Services);
try
{
int ind = name.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
mgr.RootDirectory = name.Substring(0, ind);
String toLoad = name.Substring(ind + 1, name.Length - (ind + 5));
object o = mgr.Load<object>(toLoad);
Console.WriteLine("{0} is a {1}", name, o.GetType().Name);
if (typeof(T).IsAssignableFrom(o.GetType()))
return true;
}
catch (System.Exception x)
{
Console.WriteLine("{0} threw {1}", name, x.Message);
}
finally
{
mgr.Dispose();
}
return false;
}
void LoadAnimations()
{
// clear current state
curAnimationInstance_ = -1;
instances_ = null;
blended_ = null;
// get the list of animations from our dictionary
Dictionary<string, object> tag = loadedModel_.Model.Tag as Dictionary<string, object>;
object aobj = null;
if (tag != null)
tag.TryGetValue("AnimationSet", out aobj);
animations_ = aobj as AnimationSet;
// set up animations
if (animations_ != null)
{
instances_ = new AnimationInstance[animations_.NumAnimations];
// I'll need a BlendedAnimation per animation, so that I can let the
// blender object transition between them.
blended_ = new IBlendedAnimation[instances_.Length];
int ix = 0;
foreach (Animation a in animations_.Animations)
{
instances_[ix] = new AnimationInstance(a);
blended_[ix] = AnimationBlender.CreateBlendedAnimation(instances_[ix]);
++ix;
}
}
}
ModelDraw loadedModel_; // loaded geometry
BoundingSphere modelSize_; // calculated size of the model
AnimationSet animations_; // the animations I have to choose from
AnimationInstance[] instances_; // the animation data, as loaded
IBlendedAnimation[] blended_; // state about the different animations (that can change)
AnimationBlender blender_; // object that blends between playing animations
int curAnimationInstance_ = -1; // which animation is playing? (-1 for none)
// camera support
float heading_;
public float Heading { get { return heading_; } set { heading_ = value; } }
float pitch_;
public float Pitch { get { return pitch_; } set { pitch_ = value; } }
float relativeDistance_;
public float RelativeDistance { get { return relativeDistance_; } set { relativeDistance_ = value; } }
float zoom_ = 0.7f;
public float Zoom { get { return zoom_; } set { zoom_ = value; } }
Vector3 pan_;
public Vector3 Pan { get { return pan_; } set { pan_ = value; } }
float baseDistance_ = 1;
Matrix view_;
Matrix projection_;
Matrix viewInv_;
// file browser support
string modelPath_;
public string ModelPath { get { return modelPath_; } }
bool showingBrowser_;
public bool ShowingBrowser { get { return showingBrowser_; } set { showingBrowser_ = value; } }
string curPath_ = "";
public string CurPath { get { return curPath_; } set { curPath_ = value; } }
List<FileEntry> entries_ = new List<FileEntry>();
int curEntry_;
public int CurEntry { get { return curEntry_; } set { curEntry_ = value; } }
public int NumEntries { get { return entries_.Count; } }
public string CurEntryName { get { return entries_[curEntry_].Name; } }
public bool CurEntryIsDir { get { return entries_[curEntry_].IsDir; } }
// the message displayed at the bottom
string message_ = "Art is only licensed for inclusion with AnimationViewer.";
public string Message { get { return message_; } set { message_ = value; } }
#region IScene Members
public int TechniqueIndex(string technique)
{
return 0;
}
public void AddRenderable(ISceneRenderable sr)
{
throw new NotImplementedException();
}
public void RemoveRenderable(ISceneRenderable sr)
{
throw new NotImplementedException();
}
public ISceneTexture GetSceneTexture()
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2004 April 13
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used to translate between UTF-8,
** UTF-16, UTF-16BE, and UTF-16LE.
**
** Notes on UTF-8:
**
** Byte-0 Byte-1 Byte-2 Byte-3 Value
** 0xxxxxxx 00000000 00000000 0xxxxxxx
** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
**
**
** Notes on UTF-16: (with wwww+1==uuuuu)
**
** Word-0 Word-1 Value
** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
**
**
** BOM or Byte Order Mark:
** 0xff 0xfe little-endian utf-16 follows
** 0xfe 0xff big-endian utf-16 follows
**
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d
**
** $Header$
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <assert.h>
//#include "vdbeInt.h"
#if !SQLITE_AMALGAMATION
/*
** The following constant value is used by the SQLITE_BIGENDIAN and
** SQLITE_LITTLEENDIAN macros.
*/
//const int sqlite3one = 1;
#endif //* SQLITE_AMALGAMATION */
/*
** This lookup table is used to help decode the first byte of
** a multi-byte UTF8 character.
*/
static byte[] sqlite3Utf8Trans1 = new byte[] {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
};
//#define WRITE_UTF8(zOut, c) { \
// if( c<0x00080 ){ \
// *zOut++ = (u8)(c&0xFF); \
// } \
// else if( c<0x00800 ){ \
// *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
// *zOut++ = 0x80 + (u8)(c & 0x3F); \
// } \
// else if( c<0x10000 ){ \
// *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
// *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
// *zOut++ = 0x80 + (u8)(c & 0x3F); \
// }else{ \
// *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
// *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
// *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
// *zOut++ = 0x80 + (u8)(c & 0x3F); \
// } \
//}
//#define WRITE_UTF16LE(zOut, c) { \
// if( c<=0xFFFF ){ \
// *zOut++ = (u8)(c&0x00FF); \
// *zOut++ = (u8)((c>>8)&0x00FF); \
// }else{ \
// *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
// *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
// *zOut++ = (u8)(c&0x00FF); \
// *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
// } \
//}
//#define WRITE_UTF16BE(zOut, c) { \
// if( c<=0xFFFF ){ \
// *zOut++ = (u8)((c>>8)&0x00FF); \
// *zOut++ = (u8)(c&0x00FF); \
// }else{ \
// *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
// *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
// *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
// *zOut++ = (u8)(c&0x00FF); \
// } \
//}
//#define READ_UTF16LE(zIn, TERM, c){ \
// c = (*zIn++); \
// c += ((*zIn++)<<8); \
// if( c>=0xD800 && c<0xE000 && TERM ){ \
// int c2 = (*zIn++); \
// c2 += ((*zIn++)<<8); \
// c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
// } \
//}
//#define READ_UTF16BE(zIn, TERM, c){ \
// c = ((*zIn++)<<8); \
// c += (*zIn++); \
// if( c>=0xD800 && c<0xE000 && TERM ){ \
// int c2 = ((*zIn++)<<8); \
// c2 += (*zIn++); \
// c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
// } \
//}
/*
** Translate a single UTF-8 character. Return the unicode value.
**
** During translation, assume that the byte that zTerm points
** is a 0x00.
**
** Write a pointer to the next unread byte back into pzNext.
**
** Notes On Invalid UTF-8:
**
** * This routine never allows a 7-bit character (0x00 through 0x7f) to
** be encoded as a multi-byte character. Any multi-byte character that
** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
**
** * This routine never allows a UTF16 surrogate value to be encoded.
** If a multi-byte character attempts to encode a value between
** 0xd800 and 0xe000 then it is rendered as 0xfffd.
**
** * Bytes in the range of 0x80 through 0xbf which occur as the first
** byte of a character are interpreted as single-byte characters
** and rendered as themselves even though they are technically
** invalid characters.
**
** * This routine accepts an infinite number of different UTF8 encodings
** for unicode values 0x80 and greater. It do not change over-length
** encodings to 0xfffd as some systems recommend.
*/
//#define READ_UTF8(zIn, zTerm, c) \
// c = *(zIn++); \
// if( c>=0xc0 ){ \
// c = sqlite3Utf8Trans1[c-0xc0]; \
// while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
// c = (c<<6) + (0x3f & *(zIn++)); \
// } \
// if( c<0x80 \
// || (c&0xFFFFF800)==0xD800 \
// || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
// }
static int sqlite3Utf8Read(
string zIn, /* First byte of UTF-8 character */
ref string pzNext /* Write first byte past UTF-8 char here */
)
{
//int c;
/* Same as READ_UTF8() above but without the zTerm parameter.
** For this routine, we assume the UTF8 string is always zero-terminated.
*/
if ( zIn == null || zIn.Length == 0 ) return 0;
//c = *( zIn++ );
//if ( c >= 0xc0 )
//{
// c = sqlite3Utf8Trans1[c - 0xc0];
// while ( ( *zIn & 0xc0 ) == 0x80 )
// {
// c = ( c << 6 ) + ( 0x3f & *( zIn++ ) );
// }
// if ( c < 0x80
// || ( c & 0xFFFFF800 ) == 0xD800
// || ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; }
//}
//*pzNext = zIn;
int zIndex = 0;
int c = zIn[zIndex++];
if ( c >= 0xc0 )
{
if ( c > 0xff ) c = 0;
else
{
c = sqlite3Utf8Trans1[c - 0xc0];
while ( zIndex != zIn.Length && ( zIn[zIndex] & 0xc0 ) == 0x80 )
{
c = ( c << 6 ) + ( 0x3f & zIn[zIndex++] );
}
if ( c < 0x80
|| ( c & 0xFFFFF800 ) == 0xD800
|| ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; }
}
} pzNext = zIn.Substring( zIndex );
return c;
}
/*
** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
*/
/* #define TRANSLATE_TRACE 1 */
#if ! SQLITE_OMIT_UTF16
/*
** This routine transforms the internal text encoding used by pMem to
** desiredEnc. It is an error if the string is already of the desired
** encoding, or if pMem does not contain a string value.
*/
static int sqlite3VdbeMemTranslate(Mem pMem, int desiredEnc){
int len; /* Maximum length of output string in bytes */
Debugger.Break (); // TODO -
//unsigned char *zOut; /* Output buffer */
//unsigned char *zIn; /* Input iterator */
//unsigned char *zTerm; /* End of input */
//unsigned char *z; /* Output iterator */
//unsigned int c;
Debug.Assert( pMem.db==null || sqlite3_mutex_held(pMem.db.mutex) );
Debug.Assert( (pMem.flags&MEM_Str )!=0);
Debug.Assert( pMem.enc!=desiredEnc );
Debug.Assert( pMem.enc!=0 );
Debug.Assert( pMem.n>=0 );
#if TRANSLATE_TRACE && SQLITE_DEBUG
{
char zBuf[100];
sqlite3VdbeMemPrettyPrint(pMem, zBuf);
fprintf(stderr, "INPUT: %s\n", zBuf);
}
#endif
/* If the translation is between UTF-16 little and big endian, then
** all that is required is to swap the byte order. This case is handled
** differently from the others.
*/
Debugger.Break (); // TODO -
//if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
// u8 temp;
// int rc;
// rc = sqlite3VdbeMemMakeWriteable(pMem);
// if( rc!=SQLITE_OK ){
// Debug.Assert( rc==SQLITE_NOMEM );
// return SQLITE_NOMEM;
// }
// zIn = (u8*)pMem.z;
// zTerm = &zIn[pMem->n&~1];
// while( zIn<zTerm ){
// temp = *zIn;
// *zIn = *(zIn+1);
// zIn++;
// *zIn++ = temp;
// }
// pMem->enc = desiredEnc;
// goto translate_out;
//}
/* Set len to the maximum number of bytes required in the output buffer. */
if( desiredEnc==SQLITE_UTF8 ){
/* When converting from UTF-16, the maximum growth results from
** translating a 2-byte character to a 4-byte UTF-8 character.
** A single byte is required for the output string
** nul-terminator.
*/
pMem->n &= ~1;
len = pMem.n * 2 + 1;
}else{
/* When converting from UTF-8 to UTF-16 the maximum growth is caused
** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
** character. Two bytes are required in the output buffer for the
** nul-terminator.
*/
len = pMem.n * 2 + 2;
}
/* Set zIn to point at the start of the input buffer and zTerm to point 1
** byte past the end.
**
** Variable zOut is set to point at the output buffer, space obtained
** from sqlite3Malloc().
*/
Debugger.Break (); // TODO -
//zIn = (u8*)pMem.z;
//zTerm = &zIn[pMem->n];
//zOut = sqlite3DbMallocRaw(pMem->db, len);
//if( !zOut ){
// return SQLITE_NOMEM;
//}
//z = zOut;
//if( pMem->enc==SQLITE_UTF8 ){
// if( desiredEnc==SQLITE_UTF16LE ){
// /* UTF-8 -> UTF-16 Little-endian */
// while( zIn<zTerm ){
///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
//READ_UTF8(zIn, zTerm, c);
// WRITE_UTF16LE(z, c);
// }
// }else{
// Debug.Assert( desiredEnc==SQLITE_UTF16BE );
// /* UTF-8 -> UTF-16 Big-endian */
// while( zIn<zTerm ){
///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
//READ_UTF8(zIn, zTerm, c);
// WRITE_UTF16BE(z, c);
// }
// }
// pMem->n = (int)(z - zOut);
// *z++ = 0;
//}else{
// Debug.Assert( desiredEnc==SQLITE_UTF8 );
// if( pMem->enc==SQLITE_UTF16LE ){
// /* UTF-16 Little-endian -> UTF-8 */
// while( zIn<zTerm ){
// READ_UTF16LE(zIn, zIn<zTerm, c);
// WRITE_UTF8(z, c);
// }
// }else{
// /* UTF-16 Big-endian -> UTF-8 */
// while( zIn<zTerm ){
// READ_UTF16BE(zIn, zIn<zTerm, c);
// WRITE_UTF8(z, c);
// }
// }
// pMem->n = (int)(z - zOut);
//}
//*z = 0;
//Debug.Assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
//sqlite3VdbeMemRelease(pMem);
//pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
//pMem->enc = desiredEnc;
//pMem->flags |= (MEM_Term|MEM_Dyn);
//pMem.z = (char*)zOut;
//pMem.zMalloc = pMem.z;
translate_out:
#if TRANSLATE_TRACE && SQLITE_DEBUG
{
char zBuf[100];
sqlite3VdbeMemPrettyPrint(pMem, zBuf);
fprintf(stderr, "OUTPUT: %s\n", zBuf);
}
#endif
return SQLITE_OK;
}
/*
** This routine checks for a byte-order mark at the beginning of the
** UTF-16 string stored in pMem. If one is present, it is removed and
** the encoding of the Mem adjusted. This routine does not do any
** byte-swapping, it just sets Mem.enc appropriately.
**
** The allocation (static, dynamic etc.) and encoding of the Mem may be
** changed by this function.
*/
static int sqlite3VdbeMemHandleBom(Mem pMem){
int rc = SQLITE_OK;
int bom = 0;
byte[] b01 = new byte[2];
Encoding.Unicode.GetBytes( pMem.z, 0, 1,b01,0 );
assert( pMem->n>=0 );
if( pMem->n>1 ){
// u8 b1 = *(u8 *)pMem.z;
// u8 b2 = *(((u8 *)pMem.z) + 1);
if( b01[0]==0xFE && b01[1]==0xFF ){// if( b1==0xFE && b2==0xFF ){
bom = SQLITE_UTF16BE;
}
if( b01[0]==0xFF && b01[1]==0xFE ){ // if( b1==0xFF && b2==0xFE ){
bom = SQLITE_UTF16LE;
}
}
if( bom!=0 ){
rc = sqlite3VdbeMemMakeWriteable(pMem);
if( rc==SQLITE_OK ){
pMem.n -= 2;
Debugger.Break (); // TODO -
//memmove(pMem.z, pMem.z[2], pMem.n);
//pMem.z[pMem.n] = '\0';
//pMem.z[pMem.n+1] = '\0';
pMem.flags |= MEM_Term;
pMem.enc = bom;
}
}
return rc;
}
#endif // * SQLITE_OMIT_UTF16 */
/*
** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
** return the number of unicode characters in pZ up to (but not including)
** the first 0x00 byte. If nByte is not less than zero, return the
** number of unicode characters in the first nByte of pZ (or up to
** the first 0x00, whichever comes first).
*/
static int sqlite3Utf8CharLen( string zIn, int nByte )
{
//int r = 0;
//string z = zIn;
if ( zIn.Length == 0 ) return 0;
int zInLength = zIn.Length;
int zTerm = ( nByte >= 0 && nByte <= zInLength ) ? nByte : zInLength;
//Debug.Assert( z<=zTerm );
//for ( int i = 0 ; i < zTerm ; i++ ) //while( *z!=0 && z<zTerm ){
//{
// SQLITE_SKIP_UTF8( ref z);// SQLITE_SKIP_UTF8(z);
// r++;
//}
//return r;
if ( zTerm == zInLength )
return zInLength - ( zIn[zTerm - 1] == 0 ? 1 : 0 );
else
return nByte;
}
/* This test function is not currently used by the automated test-suite.
** Hence it is only available in debug builds.
*/
#if SQLITE_TEST && SQLITE_DEBUG
/*
** Translate UTF-8 to UTF-8.
**
** This has the effect of making sure that the string is well-formed
** UTF-8. Miscoded characters are removed.
**
** The translation is done in-place (since it is impossible for the
** correct UTF-8 encoding to be longer than a malformed encoding).
*/
//int sqlite3Utf8To8(unsigned char *zIn){
// unsigned char *zOut = zIn;
// unsigned char *zStart = zIn;
// u32 c;
// while( zIn[0] ){
// c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
// if( c!=0xfffd ){
// WRITE_UTF8(zOut, c);
// }
// }
// *zOut = 0;
// return (int)(zOut - zStart);
//}
#endif
#if !SQLITE_OMIT_UTF16
/*
** Convert a UTF-16 string in the native encoding into a UTF-8 string.
** Memory to hold the UTF-8 string is obtained from sqlite3Malloc and must
** be freed by the calling function.
**
** NULL is returned if there is an allocation error.
*/
static string sqlite3Utf16to8(sqlite3 db, string z, int nByte, u8 enc){
Debugger.Break (); // TODO -
Mem m = Pool.Allocate_Mem();
// memset(&m, 0, sizeof(m));
// m.db = db;
// sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
// sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
// if( db.mallocFailed !=0{
// sqlite3VdbeMemRelease(&m);
// m.z = 0;
// }
// Debug.Assert( (m.flags & MEM_Term)!=0 || db.mallocFailed !=0);
// Debug.Assert( (m.flags & MEM_Str)!=0 || db.mallocFailed !=0);
assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
assert( m.z || db->mallocFailed );
return m.z;
}
/*
** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
** enc. A pointer to the new string is returned, and the value of *pnOut
** is set to the length of the returned string in bytes. The call should
** arrange to call sqlite3DbFree() on the returned pointer when it is
** no longer required.
**
** If a malloc failure occurs, NULL is returned and the db.mallocFailed
** flag set.
*/
#if SQLITE_ENABLE_STAT2
char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
Mem m;
memset(&m, 0, sizeof(m));
m.db = db;
sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
if( sqlite3VdbeMemTranslate(&m, enc) ){
assert( db->mallocFailed );
return 0;
}
assert( m.z==m.zMalloc );
*pnOut = m.n;
return m.z;
}
#endif
/*
** zIn is a UTF-16 encoded unicode string at least nChar characters long.
** Return the number of bytes in the first nChar unicode characters
** in pZ. nChar must be non-negative.
*/
int sqlite3Utf16ByteLen(const void *zIn, int nChar){
int c;
unsigned char const *z = zIn;
int n = 0;
if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
while( n<nChar ){
READ_UTF16BE(z, 1, c);
n++;
}
}else{
while( n<nChar ){
READ_UTF16LE(z, 1, c);
n++;
}
}
return (int)(z-(unsigned char const *)zIn);
}
#if SQLITE_TEST
/*
** This routine is called from the TCL test function "translate_selftest".
** It checks that the primitives for serializing and deserializing
** characters in each encoding are inverses of each other.
*/
/*
** This routine is called from the TCL test function "translate_selftest".
** It checks that the primitives for serializing and deserializing
** characters in each encoding are inverses of each other.
*/
void sqlite3UtfSelfTest(void){
unsigned int i, t;
unsigned char zBuf[20];
unsigned char *z;
int n;
unsigned int c;
for(i=0; i<0x00110000; i++){
z = zBuf;
WRITE_UTF8(z, i);
n = (int)(z-zBuf);
assert( n>0 && n<=4 );
z[0] = 0;
z = zBuf;
c = sqlite3Utf8Read(z, (const u8**)&z);
t = i;
if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
assert( c==t );
assert( (z-zBuf)==n );
}
for(i=0; i<0x00110000; i++){
if( i>=0xD800 && i<0xE000 ) continue;
z = zBuf;
WRITE_UTF16LE(z, i);
n = (int)(z-zBuf);
assert( n>0 && n<=4 );
z[0] = 0;
z = zBuf;
READ_UTF16LE(z, 1, c);
assert( c==i );
assert( (z-zBuf)==n );
}
for(i=0; i<0x00110000; i++){
if( i>=0xD800 && i<0xE000 ) continue;
z = zBuf;
WRITE_UTF16BE(z, i);
n = (int)(z-zBuf);
assert( n>0 && n<=4 );
z[0] = 0;
z = zBuf;
READ_UTF16BE(z, 1, c);
assert( c==i );
assert( (z-zBuf)==n );
}
}
#endif // * SQLITE_TEST */
#endif // * SQLITE_OMIT_UTF16 */
}
}
| |
/*
Copyright 2010 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Google.Apis.Util
{
/// <summary>
/// Provides the base class for a generic read-only dictionary.
/// </summary>
/// <typeparam name="TKey">
/// The type of keys in the dictionary.
/// </typeparam>
/// <typeparam name="TValue">
/// The type of values in the dictionary.
/// </typeparam>
/// <remarks>
/// <para>
/// An instance of the <b>ReadOnlyDictionary</b> generic class is
/// always read-only. A dictionary that is read-only is simply a
/// dictionary with a wrapper that prevents modifying the
/// dictionary; therefore, if changes are made to the underlying
/// dictionary, the read-only dictionary reflects those changes.
/// See <see cref="Dictionary{TKey,TValue}"/> for a modifiable version of
/// this class.
/// </para>
/// <para>
/// <b>Notes to Implementers</b> This base class is provided to
/// make it easier for implementers to create a generic read-only
/// custom dictionary. Implementers are encouraged to extend this
/// base class instead of creating their own.
/// </para>
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ReadOnlyDictionaryDebugView<,>))]
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
{
private readonly IDictionary<TKey, TValue> source;
/// <summary>
/// Initializes a new instance of the
/// <see cref="T:ReadOnlyDictionary`2" /> class that wraps
/// the supplied <paramref name="dictionaryToWrap"/>.
/// </summary>
/// <param name="dictionaryToWrap">The <see cref="T:IDictionary`2" />
/// that will be wrapped.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the dictionary is null.
/// </exception>
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionaryToWrap)
{
if (dictionaryToWrap == null)
{
throw new ArgumentNullException("dictionaryToWrap");
}
source = dictionaryToWrap;
}
#region IDictionary Members
/// <summary>Gets a value indicating whether the
/// dictionary has a fixed size. This property will
/// always return true.</summary>
bool IDictionary.IsFixedSize
{
get { return true; }
}
/// <summary>Gets a value indicating whether the
/// dictionary is read-only.This property will
/// always return true.</summary>
bool IDictionary.IsReadOnly
{
get { return true; }
}
/// <summary>Gets an <see cref="ICollection"/> object
/// containing the keys of the dictionary object.</summary>
ICollection IDictionary.Keys
{
get { return ((IDictionary)source).Keys; }
}
/// <summary>
/// Gets an ICollection object containing the values in the DictionaryBase object.
/// </summary>
ICollection IDictionary.Values
{
get { return ((IDictionary)source).Values; }
}
/// <summary>
/// Gets a value indicating whether access to the dictionary
/// is synchronized (thread safe).
/// </summary>
bool ICollection.IsSynchronized
{
get { return ((ICollection)source).IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to dictionary.
/// </summary>
object ICollection.SyncRoot
{
get { return ((ICollection)source).SyncRoot; }
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
/// <returns>The element with the specified key. </returns>
/// <exception cref="NotSupportedException">
/// Thrown when a value is set.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown when the key is a null reference (<b>Nothing</b> in Visual Basic).
/// </exception>
object IDictionary.this[object key]
{
get { return ((IDictionary)source)[key]; }
set { ThrowNotSupportedException(); }
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <param name="key">
/// The System.Object to use as the key of the element to add.
/// </param>
/// <param name="value">
/// The System.Object to use as the value of the element to add.
/// </param>
void IDictionary.Add(object key, object value)
{
ThrowNotSupportedException();
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
void IDictionary.Clear()
{
ThrowNotSupportedException();
}
/// <summary>
/// Determines whether the IDictionary object contains an element
/// with the specified key.
/// </summary>
/// <param name="key">
/// The key to locate in the IDictionary object.
/// </param>
/// <returns>
/// <b>true</b> if the IDictionary contains an element with the key;
/// otherwise, <b>false</b>.
/// </returns>
bool IDictionary.Contains(object key)
{
return ((IDictionary)source).Contains(key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> for the
/// <see cref="IDictionary"/>.
/// </summary>
/// <returns>
/// An IDictionaryEnumerator for the IDictionary.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return ((IDictionary)source).GetEnumerator();
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <param name="key">
/// Gets an <see cref="ICollection"/> object containing the keys of the
/// <see cref="IDictionary"/> object.
/// </param>
void IDictionary.Remove(object key)
{
ThrowNotSupportedException();
}
/// <summary>
/// For a description of this member, see <see cref="ICollection.CopyTo"/>.
/// </summary>
/// <param name="array">
/// The one-dimensional Array that is the destination of the elements copied from
/// ICollection. The Array must have zero-based indexing.
/// </param>
/// <param name="index">
/// The zero-based index in Array at which copying begins.
/// </param>
void ICollection.CopyTo(Array array, int index)
{
((ICollection)source).CopyTo(array, index);
}
#endregion
#region IDictionary<TKey,TValue> Members
/// <summary>
/// Gets the number of key/value pairs contained in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.
/// </summary>
/// <value>The number of key/value pairs.</value>
/// <returns>The number of key/value pairs contained in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.</returns>
public int Count
{
get { return source.Count; }
}
/// <summary>Gets a collection containing the keys in the
/// <see cref="T:ReadOnlyDictionary{TKey,TValue}"></see>.</summary>
/// <value>A <see cref="Dictionary{TKey,TValue}.KeyCollection"/>
/// containing the keys.</value>
/// <returns>A
/// <see cref="Dictionary{TKey,TValue}.KeyCollection"/>
/// containing the keys in the
/// <see cref="Dictionary{TKey,TValue}"></see>.
/// </returns>
public ICollection<TKey> Keys
{
get { return source.Keys; }
}
/// <summary>
/// Gets a collection containing the values of the
/// <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <value>The collection of values.</value>
public ICollection<TValue> Values
{
get { return source.Values; }
}
/// <summary>Gets a value indicating whether the dictionary is read-only.
/// This value will always be true.</summary>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <returns>
/// The value associated with the specified key. If the specified key
/// is not found, a get operation throws a
/// <see cref="T:System.Collections.Generic.KeyNotFoundException" />,
/// and a set operation creates a new element with the specified key.
/// </returns>
/// <param name="key">The key of the value to get or set.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the key is null.
/// </exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and key does not exist in the collection.
/// </exception>
public TValue this[TKey key]
{
get { return source[key]; }
set { ThrowNotSupportedException(); }
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
/// <param name="key">
/// The object to use as the key of the element to add.</param>
/// <param name="value">
/// The object to use as the value of the element to add.</param>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
ThrowNotSupportedException();
}
/// <summary>Determines whether the <see cref="T:ReadOnlyDictionary`2" />
/// contains the specified key.</summary>
/// <returns>
/// True if the <see cref="T:ReadOnlyDictionary`2" /> contains
/// an element with the specified key; otherwise, false.
/// </returns>
/// <param name="key">The key to locate in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the key is null.
/// </exception>
public bool ContainsKey(TKey key)
{
return source.ContainsKey(key);
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// True if the element is successfully removed; otherwise, false.
/// </returns>
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
ThrowNotSupportedException();
return false;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value
/// associated with the specified key, if the key is found;
/// otherwise, the default value for the type of the value parameter.
/// This parameter is passed uninitialized.</param>
/// <returns>
/// <b>true</b> if the <see cref="T:ReadOnlyDictionary`2" /> contains
/// an element with the specified key; otherwise, <b>false</b>.
/// </returns>
public bool TryGetValue(TKey key, out TValue value)
{
return source.TryGetValue(key, out value);
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
/// <param name="item">
/// The object to add to the <see cref="T:ICollection`1"/>.
/// </param>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
ThrowNotSupportedException();
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
ThrowNotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="T:ICollection`1"/> contains a
/// specific value.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="T:ICollection`1"/>.
/// </param>
/// <returns>
/// <b>true</b> if item is found in the <b>ICollection</b>;
/// otherwise, <b>false</b>.
/// </returns>
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return (source).Contains(item);
}
/// <summary>
/// Copies the elements of the ICollection to an Array, starting at a
/// particular Array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the
/// destination of the elements copied from ICollection.
/// The Array must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in array at which copying begins.
/// </param>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
(source).CopyTo(array, arrayIndex);
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
/// <param name="item">
/// The object to remove from the ICollection.
/// </param>
/// <returns>Will never return a value.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
ThrowNotSupportedException();
return false;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return (source).GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)source).GetEnumerator();
}
#endregion
private static void ThrowNotSupportedException()
{
throw new NotSupportedException("This Dictionary is read-only");
}
}
internal sealed class ReadOnlyDictionaryDebugView<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> dict;
public ReadOnlyDictionaryDebugView(ReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
dict = dictionary;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Items
{
get
{
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[dict.Count];
dict.CopyTo(array, 0);
return array;
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.PythonTools.EnvironmentsList.Properties;
using Microsoft.PythonTools.Intellisense;
using Microsoft.VisualStudio;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.EnvironmentsList {
internal sealed partial class PipExtension : UserControl {
public static readonly ICommand InstallPackage = new RoutedCommand();
public static readonly ICommand UpgradePackage = new RoutedCommand();
public static readonly ICommand UninstallPackage = new RoutedCommand();
public static readonly ICommand InstallPip = new RoutedCommand();
private readonly PipExtensionProvider _provider;
public PipExtension(PipExtensionProvider provider) {
_provider = provider;
DataContextChanged += PackageExtension_DataContextChanged;
InitializeComponent();
}
private void PackageExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
var view = e.NewValue as EnvironmentView;
if (view != null) {
var current = Subcontext.DataContext as PipEnvironmentView;
if (current == null || current.EnvironmentView != view) {
if (current != null) {
current.Dispose();
}
Subcontext.DataContext = new PipEnvironmentView(view, _provider);
}
}
}
private void UninstallPackage_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = _provider.CanExecute && e.Parameter is PipPackageView;
e.Handled = true;
}
private async void UninstallPackage_Executed(object sender, ExecutedRoutedEventArgs e) {
try {
var view = (PipPackageView)e.Parameter;
await _provider.UninstallPackage(view.PackageSpec);
} catch (OperationCanceledException) {
} catch (Exception ex) {
if (ErrorHandler.IsCriticalException(ex)) {
throw;
}
ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex));
}
}
private void UpgradePackage_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.Handled = true;
if (!_provider.CanExecute) {
e.CanExecute = false;
return;
}
var view = e.Parameter as PipPackageView;
if (view == null) {
e.CanExecute = false;
return;
}
e.CanExecute = !view.UpgradeVersion.IsEmpty && view.UpgradeVersion.CompareTo(view.Version) > 0;
}
private async void UpgradePackage_Executed(object sender, ExecutedRoutedEventArgs e) {
try {
var view = (PipPackageView)e.Parameter;
// Provide Name, not PackageSpec, or we'll upgrade to our
// current version.
await _provider.InstallPackage(view.Name, true);
} catch (OperationCanceledException) {
} catch (Exception ex) {
if (ErrorHandler.IsCriticalException(ex)) {
throw;
}
ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex));
}
}
private void InstallPackage_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = _provider.CanExecute && !string.IsNullOrEmpty(e.Parameter as string);
e.Handled = true;
}
private async void InstallPackage_Executed(object sender, ExecutedRoutedEventArgs e) {
try {
await _provider.InstallPackage((string)e.Parameter, true);
} catch (OperationCanceledException) {
} catch (Exception ex) {
if (ErrorHandler.IsCriticalException(ex)) {
throw;
}
ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex));
}
}
private void InstallPip_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = _provider.CanExecute;
e.Handled = true;
}
private async void InstallPip_Executed(object sender, ExecutedRoutedEventArgs e) {
try {
await _provider.InstallPip();
} catch (OperationCanceledException) {
} catch (Exception ex) {
if (ErrorHandler.IsCriticalException(ex)) {
throw;
}
ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex));
}
}
private void ForwardMouseWheel(object sender, MouseWheelEventArgs e) {
PackagesList.RaiseEvent(new MouseWheelEventArgs(
e.MouseDevice,
e.Timestamp,
e.Delta
) { RoutedEvent = UIElement.MouseWheelEvent });
e.Handled = true;
}
private void Delete_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var tb = e.OriginalSource as TextBox;
if (tb != null) {
e.Handled = true;
e.CanExecute = !string.IsNullOrEmpty(tb.Text);
return;
}
}
private void Delete_Executed(object sender, ExecutedRoutedEventArgs e) {
var tb = e.OriginalSource as TextBox;
if (tb != null) {
tb.Clear();
e.Handled = true;
return;
}
}
}
sealed class PipEnvironmentView : DependencyObject, IDisposable {
private readonly EnvironmentView _view;
private ObservableCollection<PipPackageView> _installed;
private List<PackageResultView> _installable;
private List<PackageResultView> _installableFiltered;
private CollectionViewSource _installedView;
private CollectionViewSource _installableView;
private readonly Timer _installableViewRefreshTimer;
internal readonly PipExtensionProvider _provider;
private readonly InstallPackageView _installCommandView;
private readonly FuzzyStringMatcher _matcher;
internal PipEnvironmentView(
EnvironmentView view,
PipExtensionProvider provider
) {
_view = view;
_provider = provider;
_provider.UpdateStarted += PipExtensionProvider_UpdateStarted;
_provider.UpdateComplete += PipExtensionProvider_UpdateComplete;
_provider.IsPipInstalledChanged += PipExtensionProvider_IsPipInstalledChanged;
_installCommandView = new InstallPackageView(this);
_matcher = new FuzzyStringMatcher(FuzzyMatchMode.FuzzyIgnoreCase);
_installed = new ObservableCollection<PipPackageView>();
_installedView = new CollectionViewSource { Source = _installed };
_installedView.Filter += InstalledView_Filter;
_installedView.View.CurrentChanged += InstalledView_CurrentChanged;
_installable = new List<PackageResultView>();
_installableFiltered = new List<PackageResultView>();
_installableView = new CollectionViewSource { Source = _installableFiltered };
_installableView.View.CurrentChanged += InstallableView_CurrentChanged;
_installableViewRefreshTimer = new Timer(InstallablePackages_Refresh);
FinishInitialization();
}
private async void PipExtensionProvider_IsPipInstalledChanged(object sender, EventArgs e) {
await Dispatcher.InvokeAsync(() => { IsPipInstalled = _provider.IsPipInstalled ?? true; });
}
private void InstalledView_CurrentChanged(object sender, EventArgs e) {
if (_installedView.View.CurrentItem != null) {
_installableView.View.MoveCurrentTo(null);
}
}
private void InstallableView_CurrentChanged(object sender, EventArgs e) {
if (_installableView.View.CurrentItem != null) {
_installedView.View.MoveCurrentTo(null);
}
}
private async void FinishInitialization() {
try {
await RefreshPackages();
} catch (OperationCanceledException) {
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex));
}
}
public void Dispose() {
_provider.UpdateStarted -= PipExtensionProvider_UpdateStarted;
_provider.UpdateComplete -= PipExtensionProvider_UpdateComplete;
_provider.IsPipInstalledChanged -= PipExtensionProvider_IsPipInstalledChanged;
_installableViewRefreshTimer.Dispose();
}
public EnvironmentView EnvironmentView {
get { return _view; }
}
public InstallPackageView InstallCommand {
get { return _installCommandView; }
}
private async void PipExtensionProvider_UpdateStarted(object sender, EventArgs e) {
try {
await Dispatcher.InvokeAsync(() => { IsListRefreshing = true; });
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex));
}
}
private async void PipExtensionProvider_UpdateComplete(object sender, EventArgs e) {
try {
await RefreshPackages();
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex));
}
}
public bool IsPipInstalled {
get { return (bool)GetValue(IsPipInstalledProperty); }
private set { SetValue(IsPipInstalledPropertyKey, value); }
}
private static readonly DependencyPropertyKey IsPipInstalledPropertyKey = DependencyProperty.RegisterReadOnly(
"IsPipInstalled",
typeof(bool),
typeof(PipEnvironmentView),
new PropertyMetadata(true)
);
public static readonly DependencyProperty IsPipInstalledProperty = IsPipInstalledPropertyKey.DependencyProperty;
public string SearchQuery {
get { return (string)GetValue(SearchQueryProperty); }
set { SetValue(SearchQueryProperty, value); }
}
public static readonly DependencyProperty SearchQueryProperty = DependencyProperty.Register(
"SearchQuery",
typeof(string),
typeof(PipEnvironmentView),
new PropertyMetadata(Filter_Changed)
);
private static void Filter_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var view = d as PipEnvironmentView;
if (view != null) {
try {
view._installedView.View.Refresh();
view._installableViewRefreshTimer.Change(500, Timeout.Infinite);
} catch (ObjectDisposedException) {
}
}
}
private async void InstallablePackages_Refresh(object state) {
string query = null;
try {
query = await Dispatcher.InvokeAsync(() => SearchQuery);
} catch (OperationCanceledException) {
return;
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex));
}
lock (_installable) {
_installableFiltered.Clear();
if (_installable.Any() && !string.IsNullOrEmpty(query)) {
_installableFiltered.AddRange(
_installable
.Select(p => Tuple.Create(_matcher.GetSortKey(p.Package.PackageSpec, query), p))
.Where(t => _matcher.IsCandidateMatch(t.Item2.Package.PackageSpec, query, t.Item1))
.OrderByDescending(t => t.Item1)
.Select(t => t.Item2)
.Take(20)
);
}
}
try {
await Dispatcher.InvokeAsync(() => {
_installableView.View.Refresh();
});
} catch (OperationCanceledException) {
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex));
}
}
public ICollectionView InstalledPackages {
get {
if (EnvironmentView == null || EnvironmentView.Factory == null) {
return null;
}
return _installedView.View;
}
}
public ICollectionView InstallablePackages {
get {
if (EnvironmentView == null || EnvironmentView.Factory == null) {
return null;
}
return _installableView.View;
}
}
private void InstalledView_Filter(object sender, FilterEventArgs e) {
PipPackageView package;
PackageResultView result;
var query = SearchQuery;
var matcher = string.IsNullOrEmpty(query) ? null : _matcher;
if ((package = e.Item as PipPackageView) != null) {
e.Accepted = matcher == null || matcher.IsCandidateMatch(package.PackageSpec, query);
} else if (e.Item is InstallPackageView) {
e.Accepted = matcher != null;
} else if ((result = e.Item as PackageResultView) != null) {
e.Accepted = matcher != null && matcher.IsCandidateMatch(result.Package.PackageSpec, query);
}
}
private async Task RefreshPackages() {
await Dispatcher.InvokeAsync(() => {
IsListRefreshing = true;
CommandManager.InvalidateRequerySuggested();
});
try {
if (IsPipInstalled) {
await Task.WhenAll(
RefreshInstalledPackages(),
RefreshInstallablePackages()
);
}
} finally {
Dispatcher.Invoke(() => {
IsListRefreshing = false;
CommandManager.InvalidateRequerySuggested();
});
}
}
private async Task RefreshInstalledPackages() {
var installed = await _provider.GetInstalledPackagesAsync();
if (installed == null || !installed.Any()) {
return;
}
await Dispatcher.InvokeAsync(() => {
lock (_installed) {
_installed.Merge(installed, PackageViewComparer.Instance, PackageViewComparer.Instance);
}
});
}
private async Task RefreshInstallablePackages() {
var installable = await _provider.GetAvailablePackagesAsync();
lock (_installable) {
_installable.Clear();
_installable.AddRange(installable.Select(pv => new PackageResultView(this, pv)));
}
try {
_installableViewRefreshTimer.Change(100, Timeout.Infinite);
} catch (ObjectDisposedException) {
}
}
public bool IsListRefreshing {
get { return (bool)GetValue(IsListRefreshingProperty); }
private set { SetValue(IsListRefreshingPropertyKey, value); }
}
private static readonly DependencyPropertyKey IsListRefreshingPropertyKey = DependencyProperty.RegisterReadOnly(
"IsListRefreshing",
typeof(bool),
typeof(PipEnvironmentView),
new PropertyMetadata(true, Filter_Changed)
);
public static readonly DependencyProperty IsListRefreshingProperty =
IsListRefreshingPropertyKey.DependencyProperty;
}
class PackageViewComparer :
IEqualityComparer<PipPackageView>,
IComparer<PipPackageView>,
IEqualityComparer<PackageResultView>,
IComparer<PackageResultView> {
public static readonly PackageViewComparer Instance = new PackageViewComparer();
public bool Equals(PipPackageView x, PipPackageView y) {
return StringComparer.OrdinalIgnoreCase.Equals(x.PackageSpec, y.PackageSpec);
}
public int GetHashCode(PipPackageView obj) {
return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.PackageSpec);
}
public int Compare(PipPackageView x, PipPackageView y) {
return StringComparer.OrdinalIgnoreCase.Compare(x.PackageSpec, y.PackageSpec);
}
public bool Equals(PackageResultView x, PackageResultView y) {
return Equals(x.Package, y.Package);
}
public int GetHashCode(PackageResultView obj) {
return StringComparer.OrdinalIgnoreCase.GetHashCode(
obj.IndexName + ":" + obj.Package.PackageSpec
);
}
public int Compare(PackageResultView x, PackageResultView y) {
return Compare(x.Package, y.Package);
}
}
class InstallPackageView {
private readonly PipEnvironmentView _view;
public InstallPackageView(PipEnvironmentView view) {
_view = view;
}
public PipEnvironmentView View {
get { return _view; }
}
public string IndexName {
get { return _view._provider.IndexName; }
}
}
class PackageResultView {
private readonly PipEnvironmentView _view;
private readonly PipPackageView _package;
public PackageResultView(PipEnvironmentView view, PipPackageView package) {
_view = view;
_package = package;
}
public PipEnvironmentView View {
get { return _view; }
}
public string PackageSpec {
get { return _package.PackageSpec; }
}
public string IndexName {
get { return _view._provider.IndexName; }
}
public PipPackageView Package {
get { return _package; }
}
}
}
| |
using System ;
using System.IO ;
using ICSharpCode.SharpZipLib.BZip2 ;
namespace alby.core.crypto
{
public class Bzip2Compression
{
//
//
//
protected const int BUFFER_SIZE = 1000000 ;
//
//
//
public Bzip2Compression()
{
}
//
// inStream --> compress --> outStream
//
public void Compress( Stream inStream, Stream outStream )
{
if ( inStream == null ) return ;
if ( outStream == null ) return ;
byte[] buffer = new byte[ BUFFER_SIZE ] ;
using ( BZip2OutputStream bz2out = new BZip2OutputStream( outStream ) )
{
while ( true )
{
int bytesRead = inStream.Read( buffer, 0, buffer.Length ) ;
if ( bytesRead <= 0 ) break ;
bz2out.Write( buffer, 0, bytesRead ) ;
}
bz2out.Flush() ;
}
}
//
//
//
public MemoryStream Compress( Stream stream )
{
if ( stream == null ) return null ;
byte[] buffer = new byte[ BUFFER_SIZE ] ;
MemoryStream outStream = new MemoryStream() ;
using ( BZip2OutputStream bz2Stream = new BZip2OutputStream( outStream ) )
{
while ( true )
{
int bytesRead = stream.Read( buffer, 0, buffer.Length ) ;
if ( bytesRead <= 0 ) break ;
bz2Stream.Write( buffer, 0, bytesRead ) ;
}
bz2Stream.Flush() ;
} // OUCH - doesnt work if you dont close the output stream
outStream.Position = 0 ;
return outStream ;
}
//
// Because SharpZipLib needs to close the compressed stream to save its compressed bytes,
// you cant leave the output stream open, so if you need to get at the stream afterwards, you cant.
// So here I just copy the compressed bytes to a new stream - UGLY and wont work on big streams.
//
public MemoryStream Compress2( Stream stream )
{
using ( MemoryStream outStream = new MemoryStream() )
{
this.Compress( stream, outStream ) ;
MemoryStream ms = new MemoryStream() ;
byte[] bytes = outStream.ToArray() ;
ms.Write( bytes, 0, bytes.Length ) ;
ms.Position = 0 ;
return ms ;
}
}
//
//
//
public byte[] Compress( byte[] bytes )
{
if ( bytes == null ) bytes = new byte[0] ;
using ( MemoryStream outStream = this.Compress( new MemoryStream( bytes ) ) )
return outStream.ToArray() ;
}
//
//
//
public byte[] Compress( string str )
{
if ( str == null ) str = "" ;
return this.Compress( System.Text.Encoding.Unicode.GetBytes( str ) ) ;
}
//
//
//
public void CompressFile( string inFilename, string outFilename )
{
if ( inFilename == null ) return ;
if ( outFilename == null ) return ;
using ( Stream inStream = new FileStream( inFilename, FileMode.Open, FileAccess.Read, FileShare.Read ) )
using ( Stream outStream = new FileStream( outFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.None ) )
this.Compress( inStream, outStream ) ;
}
//
//
//
public void Decompress( Stream inStream, Stream outStream )
{
if ( inStream == null ) return ;
if ( outStream == null ) return ;
byte[] buffer = new byte[ BUFFER_SIZE ] ;
using ( BZip2InputStream bz2Stream = new BZip2InputStream( inStream ) )
{
while ( true )
{
int bytesRead = bz2Stream.Read( buffer, 0, buffer.Length ) ;
if ( bytesRead <= 0 ) break ;
outStream.Write( buffer, 0, bytesRead ) ;
}
outStream.Flush() ;
}
}
//
//
//
public MemoryStream Decompress( Stream stream )
{
if ( stream == null ) return null ;
byte[] buffer = new byte[ BUFFER_SIZE ] ;
MemoryStream outStream = new MemoryStream() ;
using ( BZip2InputStream bz2Stream = new BZip2InputStream( stream ) )
{
while ( true )
{
int bytesRead = bz2Stream.Read( buffer, 0, buffer.Length ) ;
if ( bytesRead <= 0 ) break ;
outStream.Write( buffer, 0, bytesRead ) ;
}
outStream.Flush() ;
}
outStream.Position = 0 ;
return outStream ;
}
//
//
//
public byte[] Decompress( byte[] bytes )
{
if ( bytes == null ) bytes = new byte[0] ;
using ( MemoryStream outStream = this.Decompress( new MemoryStream( bytes ) ) )
return outStream.ToArray() ;
}
//
//
//
public void DecompressFile( string inFilename, string outFilename )
{
if ( inFilename == null ) return ;
if ( outFilename == null ) return ;
using ( Stream inStream = new FileStream( inFilename, FileMode.Open, FileAccess.Read, FileShare.Read ) )
using ( Stream outStream = new FileStream( outFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.None ) )
this.Decompress( inStream, outStream ) ;
}
////
//// unit testing follows
////
//public static void Main( string[] args )
//{
// Test( "" ) ;
// Test( "hello charlie" ) ;
// Test( "the fat cat sat on the mat on the hat with a bat in his hat." ) ;
// //string file = @"/home/albert/albyStuff/documents/albert/LukaAtBambi2005.html" ;
// //TestFile( file ) ;
// //TestStream( file ) ;
// //string bigfile = @"/home/albert/albyStuff/downloads/knoppix/KNOPPIX_V4.0.2CD-2005-09-23-EN.iso" ;
// //TestBigFile( bigfile ) ;
// //TestBigFileDecompress() ;
//}
////
////
////
//protected static void Test( string str )
//{
// Console.WriteLine( "@@@" + str + "@@@" ) ;
// Bzip2Compression bz2 = new Bzip2Compression() ;
// byte[] bytes = bz2.Compress( str ) ;
// byte[] bytesOut = bz2.Decompress( bytes ) ;
// string stringOut = System.Text.Encoding.Unicode.GetString( bytesOut ) ;
// Console.WriteLine( "@@@" + stringOut + "@@@" ) ;
//}
////
////
////
//protected static void TestFile( string file )
//{
// Base64String base64 = new Base64String() ;
// HashingHelper hh = new HashingHelper() ;
// Bzip2Compression bz2 = new Bzip2Compression() ;
// string fileCompressed = @"/tmp/compressed.html.bz2" ;
// string fileDecompressed = @"/tmp/decompressed.html" ;
// byte[] hash = hh.Sha256HashFile( file ) ;
// Console.WriteLine( file + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
// Console.WriteLine( "Compressing " + file ) ;
// bz2.CompressFile( file, fileCompressed ) ;
// Console.WriteLine( "Decompressing " + fileCompressed ) ;
// bz2.DecompressFile( fileCompressed, fileDecompressed ) ;
// hash = hh.Sha256HashFile( fileDecompressed ) ;
// Console.WriteLine( fileDecompressed + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
//}
////
////
////
//protected static void TestStream( string file )
//{
// Base64String base64 = new Base64String() ;
// HashingHelper hh = new HashingHelper() ;
// Bzip2Compression bz2 = new Bzip2Compression() ;
// Stream stream = new FileStream( file, FileMode.Open, FileAccess.Read, FileShare.Read ) ;
// MemoryStream compressedStream = bz2.Compress( stream ) ;
// MemoryStream decompressedStream = bz2.Decompress( compressedStream ) ;
// stream.Close() ;
// string fileOut2 = "/tmp/decompressed2.html" ;
// using ( FileStream fs = new FileStream( fileOut2, FileMode.Create, FileAccess.ReadWrite ) )
// {
// byte[] bytes = decompressedStream.ToArray() ;
// fs.Write( bytes, 0, bytes.Length ) ;
// }
// byte[] hash = hh.Sha256HashFile( file ) ;
// Console.WriteLine( file + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
// hash = hh.Sha256HashFile( fileOut2 ) ;
// Console.WriteLine( fileOut2 + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
// byte[] bytes2 = decompressedStream.ToArray() ;
// bytes2 = bz2.Compress( bytes2 ) ;
// bytes2 = bz2.Decompress( bytes2 ) ;
// string fileOut3 = "/tmp/decompressed3.html" ;
// using ( FileStream fs = new FileStream( fileOut3, FileMode.Create, FileAccess.ReadWrite ) )
// {
// fs.Write( bytes2, 0, bytes2.Length ) ;
// }
// hash = hh.Sha256HashFile( fileOut3 ) ;
// Console.WriteLine( fileOut3 + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
//}
////
////
////
//protected static void TestBigFile( string file )
//{
// Base64String base64 = new Base64String() ;
// HashingHelper hh = new HashingHelper() ;
// Bzip2Compression bz2 = new Bzip2Compression() ;
// string fileCompressed = @"/tmp/big_compressed.bz2" ;
// string fileDecompressed = @"/tmp/big_decompressed.bin" ;
// byte[] hash = hh.Sha256HashFile( file ) ;
// Console.WriteLine( file + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
// Console.WriteLine( "Compressing " + file ) ;
// bz2.CompressFile( file, fileCompressed ) ;
// Console.WriteLine( "Decompressing " + fileCompressed ) ;
// bz2.DecompressFile( fileCompressed, fileDecompressed ) ;
// hash = hh.Sha256HashFile( fileDecompressed ) ;
// Console.WriteLine( fileDecompressed + " sha256 hash [" + base64.BytesToString( hash ) + "]" ) ;
//}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Runtime;
using Internal.Runtime.CompilerHelpers;
namespace System.Runtime.CompilerServices
{
internal static partial class ClassConstructorRunner
{
//==============================================================================================================
// Ensures the class constructor for the given type has run.
//
// Called by the runtime when it finds a class whose static class constructor has probably not run
// (probably because it checks in the initialized flag without thread synchronization).
//
// The context structure passed by reference lives in the image of one of the application's modules.
// The contents are thus fixed (do not require pinning) and the address can be used as a unique
// identifier for the context.
//
// This guarantee is violated in one specific case: where a class constructor cycle would cause a deadlock. If
// so, per ECMA specs, this method returns without guaranteeing that the .cctor has run.
//
// No attempt is made to detect or break deadlocks due to other synchronization mechanisms.
//==============================================================================================================
#if PROJECTN
[RuntimeExport("CheckStaticClassConstruction")]
public static unsafe void* CheckStaticClassConstruction(void* returnValue, StaticClassConstructionContext* pContext)
{
EnsureClassConstructorRun(pContext);
return returnValue;
}
#else
private static unsafe object CheckStaticClassConstructionReturnGCStaticBase(StaticClassConstructionContext* context, object gcStaticBase)
{
EnsureClassConstructorRun(context);
return gcStaticBase;
}
private static unsafe IntPtr CheckStaticClassConstructionReturnNonGCStaticBase(StaticClassConstructionContext* context, IntPtr nonGcStaticBase)
{
EnsureClassConstructorRun(context);
return nonGcStaticBase;
}
private unsafe static object CheckStaticClassConstructionReturnThreadStaticBase(TypeManagerSlot* pModuleData, Int32 typeTlsIndex, StaticClassConstructionContext* context)
{
object threadStaticBase = ThreadStatics.GetThreadStaticBaseForType(pModuleData, typeTlsIndex);
EnsureClassConstructorRun(context);
return threadStaticBase;
}
#endif
public static unsafe void EnsureClassConstructorRun(StaticClassConstructionContext* pContext)
{
IntPtr pfnCctor = pContext->cctorMethodAddress;
NoisyLog("EnsureClassConstructorRun, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId);
// If we were called from MRT, this check is redundant but harmless. This is in case someone within classlib
// (cough, Reflection) needs to call this explicitly.
if (pContext->initialized == 1)
{
NoisyLog("Cctor already run, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId);
return;
}
CctorHandle cctor = Cctor.GetCctor(pContext);
Cctor[] cctors = cctor.Array;
int cctorIndex = cctor.Index;
try
{
Lock cctorLock = cctors[cctorIndex].Lock;
if (DeadlockAwareAcquire(cctor, pfnCctor))
{
int currentManagedThreadId = CurrentManagedThreadId;
try
{
NoisyLog("Acquired cctor lock, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
cctors[cctorIndex].HoldingThread = currentManagedThreadId;
if (pContext->initialized == 0) // Check again in case some thread raced us while we were acquiring the lock.
{
TypeInitializationException priorException = cctors[cctorIndex].Exception;
if (priorException != null)
throw priorException;
try
{
NoisyLog("Calling cctor, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
Call<int>(pfnCctor);
// Insert a memory barrier here to order any writes executed as part of static class
// construction above with respect to the initialized flag update we're about to make
// below. This is important since the fast path for checking the cctor uses a normal read
// and doesn't come here so without the barrier it could observe initialized == 1 but
// still see uninitialized static fields on the class.
Interlocked.MemoryBarrier();
NoisyLog("Set type inited, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
pContext->initialized = 1;
}
catch (Exception e)
{
TypeInitializationException wrappedException = new TypeInitializationException(null, SR.TypeInitialization_Type_NoTypeAvailable, e);
cctors[cctorIndex].Exception = wrappedException;
throw wrappedException;
}
}
}
finally
{
cctors[cctorIndex].HoldingThread = ManagedThreadIdNone;
NoisyLog("Releasing cctor lock, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
cctorLock.Release();
}
}
else
{
// Cctor cycle resulted in a deadlock. We will break the guarantee and return without running the
// .cctor.
}
}
finally
{
Cctor.Release(cctor);
}
NoisyLog("EnsureClassConstructorRun complete, cctor={0}, thread={1}", pfnCctor, CurrentManagedThreadId);
}
//=========================================================================================================
// Return value:
// true - lock acquired.
// false - deadlock detected. Lock not acquired.
//=========================================================================================================
private static bool DeadlockAwareAcquire(CctorHandle cctor, IntPtr pfnCctor)
{
const int WaitIntervalSeedInMS = 1; // seed with 1ms and double every time through the loop
const int WaitIntervalLimitInMS = WaitIntervalSeedInMS << 7; // limit of 128ms
int waitIntervalInMS = WaitIntervalSeedInMS;
int cctorIndex = cctor.Index;
Cctor[] cctors = cctor.Array;
Lock lck = cctors[cctorIndex].Lock;
if (lck.IsAcquired)
return false; // Thread recursively triggered the same cctor.
if (lck.TryAcquire(waitIntervalInMS))
return true;
// We couldn't acquire the lock. See if this .cctor is involved in a cross-thread deadlock. If so, break
// the deadlock by breaking the guarantee - we'll skip running the .cctor and let the caller take his chances.
int currentManagedThreadId = CurrentManagedThreadId;
int unmarkCookie = -1;
try
{
// We'll spin in a forever-loop of checking for a deadlock state, then waiting a short time, then
// checking for a deadlock state again, and so on. This is because the BlockedRecord info has a built-in
// lag time - threads don't report themselves as blocking until they've been blocked for a non-trivial
// amount of time.
//
// If the threads are deadlocked for any reason other a class constructor cycling, this loop will never
// terminate - this is by design. If the user code inside the class constructors were to
// deadlock themselves, then that's a bug in user code.
for (;;)
{
using (LockHolder.Hold(s_cctorGlobalLock))
{
// Ask the guy who holds the cctor lock we're trying to acquire who he's waiting for. Keep
// walking down that chain until we either discover a cycle or reach a non-blocking state. Note
// that reaching a non-blocking state is not proof that we've avoided a deadlock due to the
// BlockingRecord reporting lag.
CctorHandle cctorWalk = cctor;
int chainStepCount = 0;
for (; chainStepCount < Cctor.Count; chainStepCount++)
{
int cctorWalkIndex = cctorWalk.Index;
Cctor[] cctorWalkArray = cctorWalk.Array;
int holdingThread = cctorWalkArray[cctorWalkIndex].HoldingThread;
if (holdingThread == currentManagedThreadId)
{
// Deadlock detected. We will break the guarantee and return without running the .cctor.
DebugLog("A class constructor was skipped due to class constructor cycle. cctor={0}, thread={1}",
pfnCctor, currentManagedThreadId);
// We are maintaining an invariant that the BlockingRecords never show a cycle because,
// before we add a record, we first check for a cycle. As a result, once we've said
// we're waiting, we are committed to waiting and will not need to skip running this
// .cctor.
Debug.Assert(unmarkCookie == -1);
return false;
}
if (holdingThread == ManagedThreadIdNone)
{
// No one appears to be holding this cctor lock. Give the current thread some more time
// to acquire the lock.
break;
}
cctorWalk = BlockingRecord.GetCctorThatThreadIsBlockedOn(holdingThread);
if (cctorWalk.Array == null)
{
// The final thread in the chain appears to be blocked on nothing. Give the current
// thread some more time to acquire the lock.
break;
}
}
// We don't allow cycles in the BlockingRecords, so we must always enumerate at most each entry,
// but never more.
Debug.Assert(chainStepCount < Cctor.Count);
// We have not discovered a deadlock, so let's register the fact that we're waiting on another
// thread and continue to wait. It is important that we only signal that we are blocked after
// we check for a deadlock because, otherwise, we give all threads involved in the deadlock the
// opportunity to break it themselves and that leads to "ping-ponging" between the cctors
// involved in the cycle, allowing intermediate cctor results to be observed.
//
// The invariant here is that we never 'publish' a BlockingRecord that forms a cycle. So it is
// important that the look-for-cycle-and-then-publish-wait-status operation be atomic with
// respect to other updates to the BlockingRecords.
if (unmarkCookie == -1)
{
NoisyLog("Mark thread blocked, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
unmarkCookie = BlockingRecord.MarkThreadAsBlocked(currentManagedThreadId, cctor);
}
} // _cctorGlobalLock scope
if (waitIntervalInMS < WaitIntervalLimitInMS)
waitIntervalInMS *= 2;
// We didn't find a cycle yet, try to take the lock again.
if (lck.TryAcquire(waitIntervalInMS))
return true;
} // infinite loop
}
finally
{
if (unmarkCookie != -1)
{
NoisyLog("Unmark thread blocked, cctor={0}, thread={1}", pfnCctor, currentManagedThreadId);
BlockingRecord.UnmarkThreadAsBlocked(unmarkCookie);
}
}
}
//==============================================================================================================
// These structs are allocated on demand whenever the runtime tries to run a class constructor. Once the
// the class constructor has been successfully initialized, we reclaim this structure. The structure is long-
// lived only if the class constructor threw an exception.
//==============================================================================================================
private unsafe struct Cctor
{
public Lock Lock;
public TypeInitializationException Exception;
public int HoldingThread;
private int _refCount;
private StaticClassConstructionContext* _pContext;
//==========================================================================================================
// Gets the Cctor entry associated with a specific class constructor context (creating it if necessary.)
//==========================================================================================================
public static CctorHandle GetCctor(StaticClassConstructionContext* pContext)
{
#if DEBUG
const int Grow = 2;
#else
const int Grow = 10;
#endif
// WASMTODO: Remove this when the Initialize method gets called by the runtime startup
#if WASM
if (s_cctorGlobalLock == null)
{
Interlocked.CompareExchange(ref s_cctorGlobalLock, new Lock(), null);
}
if (s_cctorArrays == null)
{
Interlocked.CompareExchange(ref s_cctorArrays, new Cctor[10][], null);
}
#endif // WASM
using (LockHolder.Hold(s_cctorGlobalLock))
{
Cctor[] resultArray = null;
int resultIndex = -1;
if (s_count != 0)
{
// Search for the cctor context in our existing arrays
for (int cctorIndex = 0; cctorIndex < s_cctorArraysCount; ++cctorIndex)
{
Cctor[] segment = s_cctorArrays[cctorIndex];
for (int i = 0; i < segment.Length; i++)
{
if (segment[i]._pContext == pContext)
{
resultArray = segment;
resultIndex = i;
break;
}
}
if (resultArray != null)
break;
}
}
if (resultArray == null)
{
// look for an empty entry in an existing array
for (int cctorIndex = 0; cctorIndex < s_cctorArraysCount; ++cctorIndex)
{
Cctor[] segment = s_cctorArrays[cctorIndex];
for (int i = 0; i < segment.Length; i++)
{
if (segment[i]._pContext == default(StaticClassConstructionContext*))
{
resultArray = segment;
resultIndex = i;
break;
}
}
if (resultArray != null)
break;
}
if (resultArray == null)
{
// allocate a new array
resultArray = new Cctor[Grow];
if (s_cctorArraysCount == s_cctorArrays.Length)
{
// grow the container
Array.Resize(ref s_cctorArrays, (s_cctorArrays.Length * 2) + 1);
}
// store the array in the container, this cctor gets index 0
s_cctorArrays[s_cctorArraysCount] = resultArray;
s_cctorArraysCount++;
resultIndex = 0;
}
Debug.Assert(resultArray[resultIndex]._pContext == default(StaticClassConstructionContext*));
resultArray[resultIndex]._pContext = pContext;
resultArray[resultIndex].Lock = new Lock();
s_count++;
}
Interlocked.Increment(ref resultArray[resultIndex]._refCount);
return new CctorHandle(resultArray, resultIndex);
}
}
public static int Count
{
get
{
Debug.Assert(s_cctorGlobalLock.IsAcquired);
return s_count;
}
}
public static void Release(CctorHandle cctor)
{
using (LockHolder.Hold(s_cctorGlobalLock))
{
Cctor[] cctors = cctor.Array;
int cctorIndex = cctor.Index;
if (0 == Interlocked.Decrement(ref cctors[cctorIndex]._refCount))
{
if (cctors[cctorIndex].Exception == null)
{
cctors[cctorIndex] = new Cctor();
s_count--;
}
}
}
}
}
private struct CctorHandle
{
public CctorHandle(Cctor[] array, int index)
{
_array = array;
_index = index;
}
public Cctor[] Array { get { return _array; } }
public int Index { get { return _index; } }
private Cctor[] _array;
private int _index;
}
//==============================================================================================================
// Keeps track of threads that are blocked on a cctor lock (alas, we don't have ThreadLocals here in
// System.Private.CoreLib so we have to use a side table.)
//
// This is used for cross-thread deadlock detection.
//
// - Data is only entered here if a thread has been blocked past a certain timeout (otherwise, it's certainly
// not participating of a deadlock.)
// - Reads and writes to _blockingRecord are guarded by _cctorGlobalLock.
// - BlockingRecords for individual threads are created on demand. Since this is a rare event, we won't attempt
// to recycle them directly (however,
// ManagedThreadId's are themselves recycled pretty quickly - and threads that inherit the managed id also
// inherit the BlockingRecord.)
//==============================================================================================================
private struct BlockingRecord
{
public int ManagedThreadId; // ManagedThreadId of the blocked thread
public CctorHandle BlockedOn;
public static int MarkThreadAsBlocked(int managedThreadId, CctorHandle blockedOn)
{
#if DEBUG
const int Grow = 2;
#else
const int Grow = 10;
#endif
using (LockHolder.Hold(s_cctorGlobalLock))
{
if (s_blockingRecords == null)
s_blockingRecords = new BlockingRecord[Grow];
int found;
for (found = 0; found < s_nextBlockingRecordIndex; found++)
{
if (s_blockingRecords[found].ManagedThreadId == managedThreadId)
break;
}
if (found == s_nextBlockingRecordIndex)
{
if (s_nextBlockingRecordIndex == s_blockingRecords.Length)
{
BlockingRecord[] newBlockingRecords = new BlockingRecord[s_blockingRecords.Length + Grow];
for (int i = 0; i < s_blockingRecords.Length; i++)
{
newBlockingRecords[i] = s_blockingRecords[i];
}
s_blockingRecords = newBlockingRecords;
}
s_blockingRecords[s_nextBlockingRecordIndex].ManagedThreadId = managedThreadId;
s_nextBlockingRecordIndex++;
}
s_blockingRecords[found].BlockedOn = blockedOn;
return found;
}
}
public static void UnmarkThreadAsBlocked(int blockRecordIndex)
{
// This method must never throw
s_cctorGlobalLock.Acquire();
s_blockingRecords[blockRecordIndex].BlockedOn = new CctorHandle(null, 0);
s_cctorGlobalLock.Release();
}
public static CctorHandle GetCctorThatThreadIsBlockedOn(int managedThreadId)
{
Debug.Assert(s_cctorGlobalLock.IsAcquired);
for (int i = 0; i < s_nextBlockingRecordIndex; i++)
{
if (s_blockingRecords[i].ManagedThreadId == managedThreadId)
return s_blockingRecords[i].BlockedOn;
}
return new CctorHandle(null, 0);
}
private static BlockingRecord[] s_blockingRecords;
private static int s_nextBlockingRecordIndex;
}
private static Lock s_cctorGlobalLock;
// These three statics are used by ClassConstructorRunner.Cctor but moved out to avoid an unnecessary
// extra class constructor call.
//
// Because Cctor's are mutable structs, we have to give our callers raw references to the underlying arrays
// for this collection to be usable. This also means once we place a Cctor in an array, we can't grow or
// reallocate the array.
private static Cctor[][] s_cctorArrays;
private static int s_cctorArraysCount;
private static int s_count;
// Eager construction called from LibraryInitialize Cctor.GetCctor uses _cctorGlobalLock.
internal static void Initialize()
{
s_cctorArrays = new Cctor[10][];
s_cctorGlobalLock = new Lock();
}
[Conditional("ENABLE_NOISY_CCTOR_LOG")]
private static void NoisyLog(string format, IntPtr cctorMethod, int threadId)
{
// We cannot utilize any of the typical number formatting code because it triggers globalization code to run
// and this cctor code is layered below globalization.
#if DEBUG
Debug.WriteLine(format, ToHexString(cctorMethod), ToHexString(threadId));
#endif // DEBUG
}
[Conditional("DEBUG")]
private static void DebugLog(string format, IntPtr cctorMethod, int threadId)
{
// We cannot utilize any of the typical number formatting code because it triggers globalization code to run
// and this cctor code is layered below globalization.
#if DEBUG
Debug.WriteLine(format, ToHexString(cctorMethod), ToHexString(threadId));
#endif
}
// We cannot utilize any of the typical number formatting code because it triggers globalization code to run
// and this cctor code is layered below globalization.
#if DEBUG
private static string ToHexString(int num)
{
return ToHexStringUnsignedLong((ulong)num, false, 8);
}
private static string ToHexString(IntPtr num)
{
return ToHexStringUnsignedLong((ulong)num, false, 16);
}
private static char GetHexChar(uint u)
{
if (u < 10)
return unchecked((char)('0' + u));
return unchecked((char)('a' + (u - 10)));
}
public static unsafe string ToHexStringUnsignedLong(ulong u, bool zeroPrepad, int numChars)
{
char[] chars = new char[numChars];
int i = numChars - 1;
for (; i >= 0; i--)
{
chars[i] = GetHexChar((uint)(u % 16));
u = u / 16;
if ((i == 0) || (!zeroPrepad && (u == 0)))
break;
}
string str;
fixed (char* p = &chars[i])
{
str = new String(p, 0, numChars - i);
}
return str;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
namespace System.IO.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib decompression API.
/// </summary>
internal sealed class Inflater : IDisposable
{
private const int MinWindowBits = -15; // WindowBits must be between -8..-15 to ignore the header, 8..15 for
private const int MaxWindowBits = 47; // zlib headers, 24..31 for GZip headers, or 40..47 for either Zlib or GZip
private bool _finished; // Whether the end of the stream has been reached
private bool _isDisposed; // Prevents multiple disposals
private ZLibNative.ZLibStreamHandle _zlibStream; // The handle to the primary underlying zlib stream
private GCHandle _inputBufferHandle; // The handle to the buffer that provides input to _zlibStream
private object SyncLock => this; // Used to make writing to unmanaged structures atomic
/// <summary>
/// Initialized the Inflater with the given windowBits size
/// </summary>
internal Inflater(int windowBits)
{
Debug.Assert(windowBits >= MinWindowBits && windowBits <= MaxWindowBits);
_finished = false;
_isDisposed = false;
InflateInit(windowBits);
}
public int AvailableOutput => (int)_zlibStream.AvailOut;
/// <summary>
/// Returns true if the end of the stream has been reached.
/// </summary>
public bool Finished() => _finished && _zlibStream.AvailIn == 0 && _zlibStream.AvailOut == 0;
public unsafe bool Inflate(out byte b)
{
fixed (byte* bufPtr = &b)
{
int bytesRead = InflateVerified(bufPtr, 1);
Debug.Assert(bytesRead == 0 || bytesRead == 1);
return bytesRead != 0;
}
}
public unsafe int Inflate(byte[] bytes, int offset, int length)
{
// If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read.
if (length == 0)
return 0;
Debug.Assert(null != bytes, "Can't pass in a null output buffer!");
fixed (byte* bufPtr = bytes)
{
return InflateVerified(bufPtr + offset, length);
}
}
public unsafe int Inflate(Span<byte> destination)
{
// If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read.
if (destination.Length == 0)
return 0;
fixed (byte* bufPtr = &destination.DangerousGetPinnableReference())
{
return InflateVerified(bufPtr, destination.Length);
}
}
public unsafe int InflateVerified(byte* bufPtr, int length)
{
// State is valid; attempt inflation
try
{
int bytesRead;
if (ReadInflateOutput(bufPtr, length, ZLibNative.FlushCode.NoFlush, out bytesRead) == ZLibNative.ErrorCode.StreamEnd)
{
_finished = true;
}
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated)
{
DeallocateInputBufferHandle();
}
}
}
public bool NeedsInput() => _zlibStream.AvailIn == 0;
public void SetInput(byte[] inputBuffer, int startIndex, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(inputBuffer != null);
Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length);
Debug.Assert(!_inputBufferHandle.IsAllocated);
if (0 == count)
return;
lock (SyncLock)
{
_inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned);
_zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex;
_zlibStream.AvailIn = (uint)count;
_finished = false;
}
}
[SecuritySafeCritical]
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
if (_inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Inflater()
{
Dispose(false);
}
/// <summary>
/// Creates the ZStream that will handle inflation.
/// </summary>
[SecuritySafeCritical]
private void InflateInit(int windowBits)
{
ZLibNative.ErrorCode error;
try
{
error = ZLibNative.CreateZLibStreamForInflate(out _zlibStream, windowBits);
}
catch (Exception exception) // could not load the ZLib dll
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, exception);
}
switch (error)
{
case ZLibNative.ErrorCode.Ok: // Successful initialization
return;
case ZLibNative.ErrorCode.MemError: // Not enough memory
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.VersionError: //zlib library is incompatible with the version assumed
throw new ZLibException(SR.ZLibErrorVersionMismatch, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.StreamError: // Parameters are invalid
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
}
}
/// <summary>
/// Wrapper around the ZLib inflate function, configuring the stream appropriately.
/// </summary>
private unsafe ZLibNative.ErrorCode ReadInflateOutput(byte* bufPtr, int length, ZLibNative.FlushCode flushCode, out int bytesRead)
{
lock (SyncLock)
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)length;
ZLibNative.ErrorCode errC = Inflate(flushCode);
bytesRead = length - (int)_zlibStream.AvailOut;
return errC;
}
}
/// <summary>
/// Wrapper around the ZLib inflate function
/// </summary>
[SecuritySafeCritical]
private ZLibNative.ErrorCode Inflate(ZLibNative.FlushCode flushCode)
{
ZLibNative.ErrorCode errC;
try
{
errC = _zlibStream.Inflate(flushCode);
}
catch (Exception cause) // could not load the Zlib DLL correctly
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZLibNative.ErrorCode.Ok: // progress has been made inflating
case ZLibNative.ErrorCode.StreamEnd: // The end of the input stream has been reached
return errC;
case ZLibNative.ErrorCode.BufError: // No room in the output buffer - inflate() can be called again with more space to continue
return errC;
case ZLibNative.ErrorCode.MemError: // Not enough memory to complete the operation
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.DataError: // The input data was corrupted (input stream not conforming to the zlib format or incorrect check value)
throw new InvalidDataException(SR.UnsupportedCompression);
case ZLibNative.ErrorCode.StreamError: //the stream structure was inconsistent (for example if next_in or next_out was NULL),
throw new ZLibException(SR.ZLibErrorInconsistentStream, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
}
}
/// <summary>
/// Frees the GCHandle being used to store the input buffer
/// </summary>
private void DeallocateInputBufferHandle()
{
Debug.Assert(_inputBufferHandle.IsAllocated);
lock (SyncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Free();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using static SharpLayout.InlineVerticalAlign;
namespace SharpLayout
{
public class Span
{
private readonly IValue textValue;
private string GetTextOrEmpty(Document document, TextMode mode, Option<Table> table) =>
Text(table).GetText(document, mode) ?? "";
public ISoftLinePart[] GetSoftLineParts(Span span, Document document, DrawCache drawCache, Option<Table> table, TextMode mode)
{
var lines = GetTextOrEmpty(document, mode, table).SplitToLines();
if (lines.Length == 0)
return new ISoftLinePart[] {
new SoftLinePart(span, GetTextOrEmpty(document, mode, table),
drawCache.GetCharSizeCache(span.Font(table)))
};
else
{
var result = new ISoftLinePart[lines.Length];
for (var index = 0; index < lines.Length; index++)
result[index] = new SoftLinePart(span, lines[index], drawCache.GetCharSizeCache(span.Font(table)));
return result;
}
}
private class SoftLinePart : ISoftLinePart
{
private readonly string stringText;
public Span Span { get; }
public CharSizeCache CharSizeCache { get; }
public string Text(TextMode mode) => stringText;
public IValue SubText(int startIndex, int length)
{
return new TextValue(stringText.Substring(startIndex, length));
}
public SoftLinePart(Span span, string stringText, CharSizeCache charSizeCache)
{
Span = span;
CharSizeCache = charSizeCache;
this.stringText = stringText;
}
}
public IValue Text(Option<Table> table)
{
if (!FontOrNone(table).HasValue) return new TextValue("Font not set");
return textValue;
}
private Option<Font> font;
public Option<Font> Font() => font;
public Span Font(Option<Font> value)
{
font = value;
return this;
}
internal Option<Font> FontOrNone(Option<Table> table)
{
if (Font().HasValue) return Font().Value;
var tableFont = table.Select(_ => _.Font());
if (tableFont.HasValue) return tableFont.Value;
return new Option<Font>();
}
internal Font Font(Option<Table> table)
{
var xFont = FontWithoutInlineVerticalAlign(table);
if (InlineVerticalAlign() == Sub || InlineVerticalAlign() == Super)
{
var ascent = xFont.FontFamily.GetCellAscent(xFont.Style);
var lineSpacing = xFont.FontFamily.GetLineSpacing(xFont.Style);
var inlineVerticalAlignScaling = 0.8 * ascent / lineSpacing;
return new Font(xFont.FamilyInfo, inlineVerticalAlignScaling * xFont.Size, xFont.Style, xFont.PdfOptions);
}
else
return xFont;
}
internal Font FontWithoutInlineVerticalAlign(Option<Table> table) => FontOrNone(table).Match(
_ => _,
() => new Font(DefaultFontFamilies.Roboto, 10, XFontStyle.Regular, new XPdfFontOptions(PdfFontEncoding.Unicode)));
private InlineVerticalAlign inlineVerticalAlign;
public InlineVerticalAlign InlineVerticalAlign() => inlineVerticalAlign;
public Span InlineVerticalAlign(InlineVerticalAlign value)
{
inlineVerticalAlign = value;
return this;
}
private Option<XBrush> brush;
public Option<XBrush> Brush() => brush;
public Span Brush(Option<XBrush> value)
{
brush = value;
return this;
}
private XColor? backgroundColor;
public XColor? BackgroundColor() => backgroundColor;
public Span BackgroundColor(XColor? value)
{
backgroundColor = value;
return this;
}
public Span(IValue value)
{
textValue = value;
}
public Span(string text): this(new TextValue(text))
{
}
public Span(Func<RenderContext, string> func) : this(new RenderContextValue(func))
{
}
public Span(Func<string> expression):
this(ExpressionValue.Get(expression))
{
}
public static Span Create<T>(Func<T> expression, Func<T, string> converter) =>
new Span(ExpressionValue.Get(expression, converter));
public Span(IValue value, Font font) : this(value)
{
this.font = font;
}
public Span(string text, Font font): this(new TextValue(text), font)
{
}
public Span(Func<RenderContext, string> func, Font font) : this(new RenderContextValue(func), font)
{
}
public Span(Func<string> expression, Font font):
this(ExpressionValue.Get(expression), font)
{
}
public static Span Create<T>(Func<T> expression, Func<T, string> converter, Font font) =>
new Span(ExpressionValue.Get(expression, converter), font);
internal List<Func<Section, Table>> Footnotes { get; } = new List<Func<Section, Table>>();
public Span AddFootnote(Table table)
{
Footnotes.Add(section => table);
return this;
}
public Span AddFootnote(Paragraph paragraph, [CallerLineNumber] int line = 0, [CallerFilePath] string filePath = "")
{
Footnotes.Add(section => {
var table = new Table(line);
var c = table.AddColumn(section.PageSettings.PageWidthWithoutMargins);
var r = table.AddRow();
r[c, line, filePath].Add(paragraph);
return table;
});
return this;
}
}
public interface IValue
{
string GetText(Document document, TextMode mode);
bool IsExpression { get; }
}
public class TextValue : IValue
{
private readonly string text;
public string GetText(Document document, TextMode mode) => text;
public bool IsExpression => false;
public TextValue(string text)
{
this.text = text;
}
}
public class RenderContextValue : IValue
{
private readonly Func<RenderContext, string> func;
public string GetText(Document document, TextMode mode) => func(mode.RenderContext);
public bool IsExpression => false;
public RenderContextValue(Func<RenderContext, string> func)
{
this.func = func;
}
}
public class RenderContext
{
private readonly int pageIndex;
public RenderContext(int pageIndex, int pagesCount)
{
this.pageIndex = pageIndex;
PageCount = pagesCount;
}
public int PageNumber => pageIndex + 1;
public int PageCount { get; }
}
public class ExpressionValue<T> : IValue
{
private readonly Func<T> expression;
private readonly Func<T, string> converter;
public ExpressionValue(Func<T> expression, Func<T, string> converter)
{
this.expression = expression;
this.converter = converter;
}
public string GetText(Document document, TextMode mode) =>
document.ExpressionVisible ? ReflectionUtil.GetMemberInfo(expression).Name : converter(expression());
public bool IsExpression => true;
}
public static class ExpressionValue
{
public static ExpressionValue<T> Get<T>(Func<T> expression, Func<T, string> converter) =>
new ExpressionValue<T>(expression, converter);
public static ExpressionValue<string> Get(Func<string> expression) =>
Get(expression, StringConverter);
public static Func<string, string> StringConverter => _ => _;
}
public interface ISoftLinePart
{
Span Span { get; }
CharSizeCache CharSizeCache { get; }
string Text(TextMode mode);
IValue SubText(int startIndex, int length);
}
public abstract class TextMode
{
public const int DefaultNumber = 8;
public class Measure: TextMode
{
public override RenderContext RenderContext => new RenderContext(pageIndex: DefaultNumber, pagesCount: DefaultNumber);
}
public class Draw: TextMode
{
public int PageIndex { get; }
public int PagesCount { get; }
public Draw(int pageIndex, int pagesCount)
{
PageIndex = pageIndex;
PagesCount = pagesCount;
}
public override RenderContext RenderContext => new RenderContext(PageIndex, PagesCount);
}
public abstract RenderContext RenderContext { get; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// ResourceLib Original Code from http://resourcelib.codeplex.com
// Original Copyright (c) 2008-2009 Vestris Inc.
// Changes Copyright (c) 2011 Garrett Serack . All rights reserved.
// </copyright>
// <license>
// MIT License
// You may freely use and distribute this software under the terms of the following license agreement.
//
// 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
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Windows.PeBinary.ResourceLib {
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Api;
using Api.Enumerations;
/// <summary>
/// A version resource.
/// </summary>
public abstract class Resource {
/// <summary>
/// Loaded binary nodule.
/// </summary>
protected IntPtr _hModule = IntPtr.Zero;
/// <summary>
/// Pointer to the resource.
/// </summary>
protected IntPtr _hResource = IntPtr.Zero;
/// <summary>
/// Resource language.
/// </summary>
protected UInt16 _language;
/// <summary>
/// Resource name.
/// </summary>
protected ResourceId _name;
/// <summary>
/// Resource size.
/// </summary>
protected int _size;
/// <summary>
/// Resource type.
/// </summary>
protected ResourceId _type;
/// <summary>
/// A new resource.
/// </summary>
internal Resource() {
}
/// <summary>
/// A structured resource embedded in an executable module.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="hResource">Resource handle.</param>
/// <param name="type">Resource type.</param>
/// <param name="name">Resource name.</param>
/// <param name="language">Language ID.</param>
/// <param name="size">Resource size.</param>
internal Resource(IntPtr hModule, IntPtr hResource, ResourceId type, ResourceId name, UInt16 language, int size) {
_hModule = hModule;
_type = type;
_name = name;
_language = language;
_hResource = hResource;
_size = size;
LockAndReadResource(hModule, hResource);
}
/// <summary>
/// Version resource size in bytes.
/// </summary>
public int Size {
get {
return _size;
}
}
/// <summary>
/// Language ID.
/// </summary>
public UInt16 Language {
get {
return _language;
}
set {
_language = value;
}
}
/// <summary>
/// Resource type.
/// </summary>
public ResourceId Type {
get {
return _type;
}
}
/// <summary>
/// String representation of the resource type.
/// </summary>
public string TypeName {
get {
return _type.TypeName;
}
}
/// <summary>
/// Resource name.
/// </summary>
public ResourceId Name {
get {
return _name;
}
set {
_name = value;
}
}
/// <summary>
/// Lock and read the resource.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="hResource">Resource handle.</param>
internal void LockAndReadResource(IntPtr hModule, IntPtr hResource) {
if (hResource == IntPtr.Zero) {
return;
}
var lpRes = Kernel32.LockResource(hResource);
if (lpRes == IntPtr.Zero) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
Read(hModule, lpRes);
}
/// <summary>
/// Load a resource from an executable (.exe or .dll) file.
/// </summary>
/// <param name="filename">An executable (.exe or .dll) file.</param>
public virtual void LoadFrom(string filename) {
LoadFrom(filename, _type, _name, _language);
}
/// <summary>
/// Load a resource from an executable (.exe or .dll) file.
/// </summary>
/// <param name="filename">An executable (.exe or .dll) file.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="lang">Resource language.</param>
internal void LoadFrom(string filename, ResourceId type, ResourceId name, UInt16 lang) {
var hModule = IntPtr.Zero;
try {
hModule = Kernel32.LoadLibraryEx(filename, IntPtr.Zero, Kernel32Contants.DONT_RESOLVE_DLL_REFERENCES | Kernel32Contants.LOAD_LIBRARY_AS_DATAFILE);
LoadFrom(hModule, type, name, lang);
} finally {
if (hModule != IntPtr.Zero) {
Kernel32.FreeLibrary(hModule);
}
}
}
/// <summary>
/// Load a resource from an executable (.exe or .dll) module.
/// </summary>
/// <param name="hModule">An executable (.exe or .dll) module.</param>
/// <param name="type">Resource type.</param>
/// <param name="name">Resource name.</param>
/// <param name="lang">Resource language.</param>
internal void LoadFrom(IntPtr hModule, ResourceId type, ResourceId name, UInt16 lang) {
if (IntPtr.Zero == hModule) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var hRes = Kernel32.FindResourceEx(hModule, type.Id, name.Id, lang);
if (IntPtr.Zero == hRes) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var hGlobal = Kernel32.LoadResource(hModule, hRes);
if (IntPtr.Zero == hGlobal) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var lpRes = Kernel32.LockResource(hGlobal);
if (lpRes == IntPtr.Zero) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
_size = Kernel32.SizeofResource(hModule, hRes);
if (_size <= 0) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
_type = type;
_name = name;
_language = lang;
Read(hModule, lpRes);
}
/// <summary>
/// Read a resource from a previously loaded module.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="lpRes">Pointer to the beginning of the resource.</param>
/// <returns>Pointer to the end of the resource.</returns>
internal abstract IntPtr Read(IntPtr hModule, IntPtr lpRes);
/// <summary>
/// Write the resource to a memory stream.
/// </summary>
/// <param name="w">Binary stream.</param>
internal abstract void Write(BinaryWriter w);
/// <summary>
/// Return resource data.
/// </summary>
/// <returns>Resource data.</returns>
public byte[] WriteAndGetBytes() {
var ms = new MemoryStream();
var w = new BinaryWriter(ms, Encoding.Default);
Write(w);
w.Close();
return ms.ToArray();
}
/// <summary>
/// Save a resource.
/// </summary>
/// <param name="filename">Name of an executable file (.exe or .dll).</param>
public virtual void SaveTo(string filename) {
SaveTo(filename, _type, _name, _language);
}
/// <summary>
/// Save a resource to an executable (.exe or .dll) file.
/// </summary>
/// <param name="filename">Path to an executable file.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="langid">Language id.</param>
internal void SaveTo(string filename, ResourceId type, ResourceId name, UInt16 langid) {
var data = WriteAndGetBytes();
SaveTo(filename, type, name, langid, data);
}
/// <summary>
/// Delete a resource from an executable (.exe or .dll) file.
/// </summary>
/// <param name="filename">Path to an executable file.</param>
public virtual void DeleteFrom(string filename) {
Delete(filename, _type, _name, _language);
}
/// <summary>
/// Delete a resource from an executable (.exe or .dll) file.
/// </summary>
/// <param name="filename">Path to an executable file.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="lang">Resource language.</param>
public static void Delete(string filename, ResourceId type, ResourceId name, UInt16 lang) {
SaveTo(filename, type, name, lang, null);
}
/// <summary>
/// Save a resource to an executable (.exe or .dll) file.
/// </summary>
/// <param name="filename">Path to an executable file.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="lang">Resource language.</param>
/// <param name="data">Resource data.</param>
internal static void SaveTo(string filename, ResourceId type, ResourceId name, UInt16 lang, byte[] data) {
var h = Kernel32.BeginUpdateResource(filename, false);
if (h == IntPtr.Zero) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (!Kernel32.UpdateResource(h, type.Id, name.Id, lang, data, (data == null ? 0 : (uint)data.Length))) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (!Kernel32.EndUpdateResource(h, false)) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.