context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Xilium.CefGlue;
namespace NetDimension.NanUI.JavaScript;
public enum JavaScriptValueType
{
Undefined = 0,
Null,
Bool,
Int,
Double,
String,
DateTime,
Object,
Array,
Function,
Property,
JSON
}
public class JavaScriptValue
{
public static implicit operator string(JavaScriptValue jsvalue) => jsvalue.GetString();
public static implicit operator int(JavaScriptValue jsvalue) => jsvalue.GetInt();
public static implicit operator double(JavaScriptValue jsvalue) => jsvalue.GetDouble();
public static implicit operator DateTime(JavaScriptValue jsvalue) => jsvalue.GetDateTime();
public static implicit operator bool(JavaScriptValue jsvalue) => jsvalue.GetBool();
internal protected CefFrame Frame { get; internal set; }
public bool IsUndefined { get; }
public bool IsNull { get; }
public bool IsBool { get; }
public bool IsNumber { get; }
public bool IsString { get; }
public bool IsDateTime { get; }
public bool IsObject { get; }
public bool IsArray { get; }
public bool IsFunction { get; }
public bool IsProperty { get; }
public bool IsJSON { get; }
internal string Name
{
get
{
if (Parent is JavaScriptArray)
{
var p = (JavaScriptArray)Parent;
var index = p.IndexOf(this);
return $"{index}";
}
else if (Parent is JavaScriptObject)
{
var p = (JavaScriptObject)Parent;
var name = p.NameOf(this);
return name;
}
return null;
}
}
//public static JavaScriptValue Create(bool value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Bool);
//}
//public static JavaScriptValue Create(uint value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Int);
//}
//public static JavaScriptValue Create(int value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Int);
//}
//public static JavaScriptValue Create(long value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Int);
//}
//public static JavaScriptValue Create(ulong value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Int);
//}
//public static JavaScriptValue Create(short value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Int);
//}
//public static JavaScriptValue Create(ushort value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Int);
//}
//public static JavaScriptValue Create(double value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Double);
//}
//public static JavaScriptValue Create(float value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Double);
//}
//public static JavaScriptValue Create(decimal value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.Double);
//}
//public static JavaScriptValue Create(DateTime value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.DateTime);
//}
//public static JavaScriptValue Create(string value)
//{
// return new JavaScriptValue(value, JavaScriptValueType.String);
//}
internal static JavaScriptValue CreateUndefined()
{
return new JavaScriptValue(null, JavaScriptValueType.Undefined);
}
internal readonly object RawValue = null;
internal protected Guid Uuid { get; set; } = Guid.NewGuid();
internal JavaScriptValueType ValueType { get; } = JavaScriptValueType.Undefined;
internal JavaScriptValue Parent { get; set; } = null;
public JavaScriptValue()
{
IsNull = true;
}
public JavaScriptValue(bool value)
: this(value, JavaScriptValueType.Bool)
{
}
public JavaScriptValue(uint value)
: this(value, JavaScriptValueType.Int)
{
}
public JavaScriptValue(int value)
: this(value, JavaScriptValueType.Int)
{
}
public JavaScriptValue(long value)
: this(value, JavaScriptValueType.Int)
{
}
public JavaScriptValue(ulong value)
: this(value, JavaScriptValueType.Int)
{
}
public JavaScriptValue(short value)
: this(value, JavaScriptValueType.Int)
{
}
public JavaScriptValue(ushort value)
: this(value, JavaScriptValueType.Int)
{
}
public JavaScriptValue(double value)
: this(value, JavaScriptValueType.Double)
{
}
public JavaScriptValue(float value)
: this(value, JavaScriptValueType.Double)
{
}
public JavaScriptValue(decimal value)
: this(value, JavaScriptValueType.Double)
{
}
public JavaScriptValue(DateTime value)
: this(value, JavaScriptValueType.DateTime)
{
}
public JavaScriptValue(string value)
: this(value, JavaScriptValueType.String)
{
}
internal JavaScriptValue(JavaScriptValueType valueType)
{
switch (valueType)
{
case JavaScriptValueType.Object:
IsObject = true;
break;
case JavaScriptValueType.Array:
IsArray = true;
break;
case JavaScriptValueType.Function:
IsFunction = true;
break;
case JavaScriptValueType.Property:
IsProperty = true;
break;
}
ValueType = valueType;
}
internal JavaScriptValue(object value, JavaScriptValueType valueType)
{
switch (valueType)
{
case JavaScriptValueType.Null:
IsNull = true;
break;
case JavaScriptValueType.Bool:
IsBool = true;
break;
case JavaScriptValueType.Int:
case JavaScriptValueType.Double:
IsNumber = true;
break;
case JavaScriptValueType.String:
IsString = true;
break;
case JavaScriptValueType.DateTime:
IsDateTime = true;
break;
case JavaScriptValueType.Undefined:
IsUndefined = true;
break;
case JavaScriptValueType.JSON:
IsJSON = true;
break;
}
ValueType = valueType;
RawValue = value;
}
internal virtual JSValueDefinition ToDefinition()
{
var def = new JSValueDefinition();
def.ValueType = ValueType;
def.Uuid = Uuid;
def.Name = Name;
def.ValueDefinition = RawValue;
return def;
}
internal virtual string ToJson()
{
return JsonConvert.SerializeObject(ToDefinition());
}
//public override string ToString()
//{
// return ToJson();
//}
internal static JavaScriptValue FromJson(string json)
{
return FromDefinition(JsonConvert.DeserializeObject<JSValueDefinition>(json));
}
internal static JavaScriptValue FromDefinition(JSValueDefinition definition)
{
if (definition == null)
{
return CreateUndefined();
}
var type = definition.ValueType;
var def = definition.ValueDefinition;
var uuid = definition.Uuid;
JavaScriptValue value = null;
if (type == JavaScriptValueType.Property)
{
value = JavaScriptProperty.FromJson(def.ToString());
}
if (type == JavaScriptValueType.Function)
{
var funcDef = JSFunctionDefinition.FromJson(def.ToString());
if (funcDef.Side == CefProcessType.Browser)
{
if (funcDef.IsAsyncFunction)
{
value = new JavaScriptFunction
{
IsAsyncFunction = true,
Side = CefProcessType.Browser
};
}
else
{
value = new JavaScriptFunction
{
IsAsyncFunction = false,
Side = CefProcessType.Browser
};
}
}
else
{
value = new JavaScriptFunction
{
IsAsyncFunction = false,
Side = CefProcessType.Renderer
};
}
}
if (type == JavaScriptValueType.JSON)
{
value = new JavaScriptJsonValue((string)def);
}
if (type == JavaScriptValueType.Null)
{
value = new JavaScriptValue();
}
if (type == JavaScriptValueType.Bool)
{
value = new JavaScriptValue((bool)def);
}
if (type == JavaScriptValueType.Int)
{
value = new JavaScriptValue(Convert.ToInt32(def));
}
if (type == JavaScriptValueType.Double)
{
value = new JavaScriptValue(Convert.ToDouble(def));
}
if (type == JavaScriptValueType.String)
{
value = new JavaScriptValue((string)def);
}
if (type == JavaScriptValueType.DateTime)
{
value = new JavaScriptValue((DateTime)def);
}
if (type == JavaScriptValueType.Object)
{
value = JavaScriptObject.FromJson(def.ToString());
}
if (type == JavaScriptValueType.Array)
{
value = JavaScriptArray.FromJson(def.ToString());
}
if (value == null)
{
value = CreateUndefined();
}
else
{
value.Uuid = uuid;
}
return value;
}
public string GetString()
{
switch (ValueType)
{
case JavaScriptValueType.Bool:
case JavaScriptValueType.Int:
case JavaScriptValueType.Double:
return $"{RawValue}";
case JavaScriptValueType.DateTime:
return $"{((DateTime)RawValue).ToLocalTime()}";
case JavaScriptValueType.JSON:
case JavaScriptValueType.String:
return (string)RawValue;
case JavaScriptValueType.Object:
return $"[object]";
case JavaScriptValueType.Array:
return $"[array]";
case JavaScriptValueType.Function:
return $"[function]";
case JavaScriptValueType.Property:
return $"[property]";
default:
return null;
}
}
public int GetInt()
{
if (ValueType == JavaScriptValueType.Double || ValueType == JavaScriptValueType.Int)
{
return (int)RawValue;
}
if (ValueType == JavaScriptValueType.Bool)
{
return ((bool)RawValue) ? 1 : 0;
}
return 0;
}
public double GetDouble()
{
if (ValueType == JavaScriptValueType.Double || ValueType == JavaScriptValueType.Int)
{
return Convert.ToDouble(RawValue);
}
if (ValueType == JavaScriptValueType.Bool)
{
return ((bool)RawValue) ? 1 : 0;
}
return 0;
}
public DateTime GetDateTime()
{
if (ValueType == JavaScriptValueType.String)
{
if (DateTime.TryParse((string)RawValue, out var retval))
{
retval = retval.ToLocalTime();
return retval;
}
}
if (ValueType == JavaScriptValueType.DateTime)
{
return ((DateTime)RawValue).ToLocalTime();
}
return default;
}
public bool GetBool()
{
if (ValueType == JavaScriptValueType.Int || ValueType == JavaScriptValueType.Double)
{
return (int)RawValue != 0;
}
if (ValueType == JavaScriptValueType.Bool)
{
return (bool)RawValue;
}
return false;
}
internal bool IsFreeze { get; private set; } = false;
internal void BindToFrame(CefFrame frame, bool isFreeze = false)
{
if (IsObject)
{
foreach (var item in ((JavaScriptObject)this).PropertySymbols)
{
item.BindToFrame(frame, isFreeze);
}
}
else if (IsArray)
{
var target = this.ToArray();
for (int i = 0; i < target.Count; i++)
{
var item = target[i];
item.BindToFrame(frame, isFreeze);
}
}
Frame = frame;
IsFreeze = isFreeze;
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Relisten.Api.Models;
using Dapper;
using Relisten.Vendor;
using Relisten.Data;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using Hangfire.Server;
using Hangfire.Console;
using System.Threading;
namespace Relisten.Import
{
[Flags]
public enum ImportableData
{
Nothing = 0,
Eras = 1 << 0,
Tours = 1 << 1,
Venues = 1 << 2,
SetlistShowsAndSongs = 1 << 3,
SourceReviews = 1 << 4,
SourceRatings = 1 << 5,
Sources = 1 << 6
}
public class ImportStats
{
public static readonly ImportStats None = new ImportStats();
public int Updated { get; set; } = 0;
public int Created { get; set; } = 0;
public int Removed { get; set; } = 0;
public static ImportStats operator +(ImportStats c1, ImportStats c2)
{
return new ImportStats()
{
Updated = c1.Updated + c2.Updated,
Removed = c1.Removed + c2.Removed,
Created = c1.Created + c2.Created
};
}
public override string ToString()
{
return $"Created: {Created}; Updated: {Updated}; Removed: {Removed}";
}
}
public class ImporterService
{
IDictionary<string, ImporterBase> importers { get; set; }
public ImporterService(
ArchiveOrgImporter _archiveOrg,
SetlistFmImporter _setlistFm,
PhishinImporter _phishin,
PhishNetImporter _phishnet,
JerryGarciaComImporter _jerry,
PanicStreamComImporter _panic,
PhantasyTourImporter _phantasy
)
{
var imps = new ImporterBase[] {
_setlistFm,
_archiveOrg,
_panic,
_jerry,
_phishin,
_phishnet,
_phantasy
};
importers = new Dictionary<string, ImporterBase>();
foreach (var i in imps)
{
importers[i.ImporterName] = i;
}
}
public IEnumerable<ImporterBase> ImportersForArtist(Artist art)
{
return art.upstream_sources.Select(s => importers[s.upstream_source.name]);
}
public ImporterBase ImporterForUpstreamSource(UpstreamSource source)
{
return importers[source.name];
}
public Task<ImportStats> Import(Artist artist, Func<ArtistUpstreamSource, bool> filterUpstreamSources, PerformContext ctx)
{
return Import(artist, filterUpstreamSources, null, ctx);
}
public async Task<ImportStats> Rebuild(Artist artist, PerformContext ctx)
{
var importer = artist.upstream_sources.First().upstream_source.importer;
ctx?.WriteLine("Rebuilding Shows");
var stats = await importer.RebuildShows(artist);
ctx?.WriteLine("Rebuilding Years");
stats += await importer.RebuildYears(artist);
ctx?.WriteLine("Done!");
return stats;
}
public async Task<ImportStats> Import(Artist artist, Func<ArtistUpstreamSource, bool> filterUpstreamSources, string showIdentifier, PerformContext ctx)
{
var stats = new ImportStats();
var srcs = artist.upstream_sources.ToList();
ctx?.WriteLine($"Found {srcs.Count} valid importers.");
var prog = ctx?.WriteProgressBar();
await srcs.AsyncForEachWithProgress(prog, async item =>
{
if (filterUpstreamSources != null && !filterUpstreamSources(item))
{
ctx?.WriteLine($"Skipping (rejected by filter): {item.upstream_source_id}, {item.upstream_identifier}");
return;
}
ctx?.WriteLine($"Importing with {item.upstream_source_id}, {item.upstream_identifier}");
if(showIdentifier != null)
{
stats += await item.upstream_source.importer.ImportSpecificShowDataForArtist(artist, item, showIdentifier, ctx);
}
else
{
stats += await item.upstream_source.importer.ImportDataForArtist(artist, item, ctx);
}
});
return stats;
}
}
public abstract class ImporterBase : IDisposable
{
protected DbService db { get; set; }
protected HttpClient http { get; set; }
public ImporterBase(DbService db)
{
this.db = db;
http = new HttpClient();
// iPhone on iOS 11.4
http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1");
http.DefaultRequestHeaders.Add("Accept", "*/*");
}
public abstract ImportableData ImportableDataForArtist(Artist artist);
public abstract Task<ImportStats> ImportDataForArtist(Artist artist, ArtistUpstreamSource src, PerformContext ctx);
public abstract Task<ImportStats> ImportSpecificShowDataForArtist(Artist artist, ArtistUpstreamSource src, string showIdentifier, PerformContext ctx);
public abstract string ImporterName { get; }
public void Dispose()
{
this.http.Dispose();
}
IDictionary<string, int> trackSlugCounts { get; set; } = new Dictionary<string, int>();
/// <summary>
/// Resets the slug counts. This needs to be called after each source is imported otherwise you'll get thing like you-enjoy-myself-624
/// </summary>
public void ResetTrackSlugCounts()
{
trackSlugCounts.Clear();
}
public string Slugify(string full)
{
var slug = Regex.Replace(full.ToLower().Normalize(), @"['.]", "");
slug = Regex.Replace(slug, @"[^a-z0-9\s-]", " ");
return Regex.Replace(slug, @"\s+", " ").
Trim().
Replace(" ", "-").
Trim('-');
}
public string SlugifyTrack(string full)
{
var slug = Slugify(full);
if(trackSlugCounts.ContainsKey(slug))
{
var count = 0;
do
{
count = trackSlugCounts[slug];
count++;
trackSlugCounts[slug] = count;
// keep incrementing until we find a slug that isn't taken
} while(trackSlugCounts.ContainsKey(slug + $"-{count}"));
slug += $"-{count}";
trackSlugCounts[slug] = 1;
}
else
{
trackSlugCounts[slug] = 1;
}
return slug;
}
public async Task<ImportStats> RebuildYears(Artist artist)
{
await db.WithConnection(con => con.ExecuteAsync(@"
BEGIN TRANSACTION;
-- Build Years
WITH year_sources AS (
SELECT
to_char(sh.date, 'YYYY') as year,
COUNT(*) as source_count
FROM
shows sh
JOIN sources s ON sh.id = s.show_id
WHERE
sh.artist_id = @id
GROUP BY
to_char(sh.date, 'YYYY')
)
INSERT INTO
years
(year, show_count, source_count, duration, avg_duration, avg_rating, artist_id, updated_at, uuid)
SELECT
to_char(s.date, 'YYYY') as year,
COUNT(DISTINCT s.id) as show_count,
COUNT(DISTINCT so.id) as source_count,
SUM(so.duration) as duration,
AVG(s.avg_duration) as avg_duration,
AVG(s.avg_rating) as avg_rating,
s.artist_id as artist_id,
MAX(so.updated_at) as updated_at,
md5(s.artist_id || '::year::' || to_char(s.date, 'YYYY'))::uuid as uuid
FROM
shows s
JOIN sources so ON so.show_id = s.id
WHERE
s.artist_id = @id
GROUP BY
s.artist_id, to_char(s.date, 'YYYY')
ON CONFLICT ON CONSTRAINT years_uuid_key
DO
UPDATE SET -- don't update artist_id or year since uuid is based on that
show_count = EXCLUDED.show_count,
source_count = EXCLUDED.source_count,
duration = EXCLUDED.duration,
avg_duration = EXCLUDED.avg_duration,
avg_rating = EXCLUDED.avg_rating,
updated_at = EXCLUDED.updated_at
;
COMMIT;
-- Associate shows with years
UPDATE
shows s
SET
year_id = y.id
FROM
years y
WHERE
y.year = to_char(s.date, 'YYYY')
AND s.artist_id = @id
AND y.artist_id = @id
;
REFRESH MATERIALIZED VIEW show_source_information;
REFRESH MATERIALIZED VIEW venue_show_counts;
", new { id = artist.id }));
return ImportStats.None;
}
public async Task<ImportStats> RebuildShows(Artist artist)
{
var sql = @"
-- Update durations
WITH durs AS (
SELECT
t.source_id,
SUM(t.duration) as duration
FROM
source_tracks t
JOIN sources s ON t.source_id = s.id
WHERE
s.artist_id = @id
GROUP BY
t.source_id
)
UPDATE
sources s
SET
duration = d.duration
FROM
durs d
WHERE
s.id = d.source_id
AND s.artist_id = @id
;
BEGIN TRANSACTION;
-- Generate shows table without years or rating information
INSERT INTO
shows
(artist_id, date, display_date, updated_at, tour_id, era_id, venue_id, avg_duration, uuid)
SELECT
--array_agg(source.id) as srcs,
--array_agg(setlist_show.id) as setls,
--array_agg(source.display_date),
--array_agg(setlist_show.date),
source.artist_id,
COALESCE(setlist_show.date, CASE
WHEN MIN(source.display_date) LIKE '%X%' THEN to_date(MIN(source.display_date), 'YYYY')
ELSE to_date(MIN(source.display_date), 'YYYY-MM-DD')
END) as date,
MIN(source.display_date) as display_date,
MAX(source.updated_at) as updated_at,
MAX(setlist_show.tour_id) as tour_id,
MAX(setlist_show.era_id) as era_id,
COALESCE(MAX(setlist_show.venue_id), MAX(source.venue_id)) as venue_id,
MAX(source.duration) as avg_duration,
md5(source.artist_id || '::show::' || source.display_date)::uuid
FROM
sources source
LEFT JOIN setlist_shows setlist_show ON to_char(setlist_show.date, 'YYYY-MM-DD') = source.display_date AND setlist_show.artist_id = @id
WHERE
(setlist_show.artist_id = @id OR setlist_show.artist_id IS NULL)
AND source.artist_id = @id
AND source.show_id IS NULL
GROUP BY
date, source.display_date, source.artist_id
ORDER BY
setlist_show.date
ON CONFLICT ON CONSTRAINT shows_uuid_key
DO
UPDATE SET -- don't update artist_id or display_date since uuid is based on those
date = EXCLUDED.date,
updated_at = EXCLUDED.updated_at,
tour_id = EXCLUDED.tour_id,
era_id = EXCLUDED.era_id,
venue_id = EXCLUDED.venue_id,
avg_duration = EXCLUDED.avg_duration
;
COMMIT;
BEGIN;
-- Associate sources with show
WITH show_assoc AS (
SELECT
src.id as source_id,
sh.id as show_id
FROM
sources src
JOIN shows sh ON src.display_date = sh.display_date AND sh.artist_id = @id
WHERE
src.artist_id = @id
)
UPDATE
sources s
SET
show_id = a.show_id
FROM
show_assoc a
WHERE
a.source_id = s.id
AND s.artist_id = @id
;
COMMIT;
";
if (artist.features.reviews_have_ratings)
{
sql += @"
BEGIN;
-- Update sources with calculated rating/review information
WITH review_info AS (
SELECT
s.id as id,
COALESCE(AVG(rating), 0) as avg,
COUNT(r.rating) as num_reviews
FROM
sources s
LEFT JOIN source_reviews r ON r.source_id = s.id
WHERE
s.artist_id = @id
GROUP BY
s.id
ORDER BY
s.id
)
UPDATE
sources s
SET
avg_rating = i.avg,
num_reviews = i.num_reviews
FROM
review_info i
WHERE
s.id = i.id
AND s.artist_id = @id
;
-- Calculate weighted averages for sources once we have average data and update sources
WITH review_info AS (
SELECT
s.id as id,
COALESCE(AVG(r.rating), 0) as avg,
COUNT(r.rating) as num_reviews
FROM
sources s
LEFT JOIN source_reviews r ON r.source_id = s.id
WHERE
s.artist_id = @id
GROUP BY
s.id
ORDER BY
s.id
), show_info AS (
SELECT
s.show_id,
SUM(s.num_reviews) as num_reviews,
AVG(s.avg_rating) as avg
FROM
sources s
WHERE
s.artist_id = @id
GROUP BY
s.show_id
), weighted_info AS (
SELECT
s.id as id,
i_show.show_id,
i.num_reviews,
i.avg,
i_show.num_reviews,
i_show.avg,
(i_show.num_reviews * i_show.avg) + (i.num_reviews * i.avg) / (i_show.num_reviews + i.num_reviews + 1) as avg_rating_weighted
FROM
sources s
LEFT JOIN review_info i ON i.id = s.id
LEFT JOIN show_info i_show ON i_show.show_id = s.show_id
WHERE
s.artist_id = @id
GROUP BY
s.id, i_show.show_id, i.num_reviews, i.avg, i_show.num_reviews, i_show.avg
ORDER BY
s.id
)
UPDATE
sources s
SET
avg_rating_weighted = i.avg_rating_weighted
FROM
weighted_info i
WHERE
i.id = s.id
AND s.artist_id = @id
;
COMMIT;
";
}
else {
sql += @"
BEGIN;
-- used for things like Phish where ratings aren't attached to textual reviews
-- Calculate weighted averages for sources once we have average data and update sources
WITH show_info AS (
SELECT
s.show_id,
SUM(s.num_ratings) as num_reviews,
AVG(s.avg_rating) as avg
FROM
sources s
WHERE
s.artist_id = @id
GROUP BY
s.show_id
), weighted_info AS (
SELECT
s.id as id,
i_show.show_id,
s.num_ratings,
s.avg_rating,
i_show.num_reviews,
i_show.avg,
(i_show.num_reviews * i_show.avg) + (s.num_ratings * s.avg_rating) / (i_show.num_reviews + s.num_ratings + 1) as avg_rating_weighted
FROM
sources s
LEFT JOIN show_info i_show ON i_show.show_id = s.show_id
WHERE
s.artist_id = @id
GROUP BY
s.id, i_show.show_id, s.num_ratings, s.avg_rating, i_show.num_reviews, i_show.avg
ORDER BY
s.id
)
UPDATE
sources s
SET
avg_rating_weighted = i.avg_rating_weighted
FROM
weighted_info i
WHERE
i.id = s.id
AND s.artist_id = @id
;
COMMIT;
";
}
sql += @"
BEGIN;
-- Update shows with rating based on weighted averages
WITH rating_ranks AS (
SELECT
sh.id as show_id,
s.avg_rating,
s.updated_at as updated_at,
s.num_reviews,
s.avg_rating_weighted,
RANK() OVER (PARTITION BY sh.id ORDER BY s.avg_rating_weighted DESC) as rank
FROM
sources s
JOIN shows sh ON s.show_id = sh.id
WHERE
s.artist_id = @id
), max_rating AS (
SELECT
show_id,
AVG(avg_rating) as avg_rating,
MAX(updated_at) as updated_at
FROM
rating_ranks
WHERE
rank = 1
GROUP BY
show_id
)
UPDATE
shows s
SET
avg_rating = r.avg_rating,
updated_at = r.updated_at
FROM max_rating r
WHERE
r.show_id = s.id
AND s.artist_id = @id
;
COMMIT;
REFRESH MATERIALIZED VIEW show_source_information;
REFRESH MATERIALIZED VIEW venue_show_counts;
REFRESH MATERIALIZED VIEW source_review_counts;
";
await db.WithConnection(con => con.ExecuteAsync(sql, new { id = artist.id }));
return ImportStats.None;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Storages.Algo
File: AllSecurityMarketDataStorage.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Storages
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Ecng.Collections;
using Ecng.Interop;
using StockSharp.Algo.Candles;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
class AllSecurityMarketDataStorage<T> : IMarketDataStorage<T>, IMarketDataStorageInfo<T>
where T : Message
{
private sealed class BasketEnumerable : SimpleEnumerable<T>
{
public BasketEnumerable(Func<IEnumerator<T>> createEnumerator)
: base(createEnumerator)
{
}
}
private readonly Security _security;
private readonly IExchangeInfoProvider _exchangeInfoProvider;
private readonly BasketMarketDataStorage<T> _basket;
public AllSecurityMarketDataStorage(Security security,
object arg,
Func<T, DateTimeOffset> getTime,
Func<T, Security> getSecurity,
Func<Security, IMarketDataDrive, IMarketDataStorage<T>> getStorage,
IMarketDataStorageDrive drive,
IExchangeInfoProvider exchangeInfoProvider)
{
if (security == null)
throw new ArgumentNullException(nameof(security));
if (getTime == null)
throw new ArgumentNullException(nameof(getTime));
if (getSecurity == null)
throw new ArgumentNullException(nameof(getSecurity));
if (getStorage == null)
throw new ArgumentNullException(nameof(getStorage));
if (drive == null)
throw new ArgumentNullException(nameof(drive));
if (exchangeInfoProvider == null)
throw new ArgumentNullException(nameof(exchangeInfoProvider));
_security = security;
_exchangeInfoProvider = exchangeInfoProvider;
_getTime = getTime;
_arg = arg;
Drive = drive;
_basket = new BasketMarketDataStorage<T>();
var idGenerator = new SecurityIdGenerator();
var id = idGenerator.Split(security.Id);
var code = id.SecurityCode;
var securities = InteropHelper
.GetDirectories(Path.Combine(Drive.Drive.Path, code.Substring(0, 1)), code + "*")
.Select(p => Path.GetFileName(p).FolderNameToSecurityId())
.Select(s =>
{
var idInfo = idGenerator.Split(s);
var clone = security.Clone();
clone.Id = s;
clone.Board = _exchangeInfoProvider.GetOrCreateBoard(idInfo.BoardCode);
return clone;
});
foreach (var sec in securities)
_basket.InnerStorages.Add(getStorage(sec, Drive.Drive));
}
IMarketDataSerializer IMarketDataStorage.Serializer => ((IMarketDataStorage<T>)this).Serializer;
IMarketDataSerializer<T> IMarketDataStorage<T>.Serializer
{
get { throw new NotSupportedException(); }
}
IEnumerable<DateTime> IMarketDataStorage.Dates => Drive.Dates;
Type IMarketDataStorage.DataType => typeof(T);
Security IMarketDataStorage.Security => _security;
private readonly object _arg;
object IMarketDataStorage.Arg => _arg;
public IMarketDataStorageDrive Drive { get; }
bool IMarketDataStorage.AppendOnlyNew { get; set; } = true;
/// <summary>
/// To save market data in storage.
/// </summary>
/// <param name="data">Market data.</param>
public int Save(IEnumerable<T> data)
{
throw new NotSupportedException();
}
/// <summary>
/// To delete market data from storage.
/// </summary>
/// <param name="data">Market data to be deleted.</param>
public void Delete(IEnumerable<T> data)
{
throw new NotSupportedException();
}
void IMarketDataStorage.Delete(IEnumerable data)
{
throw new NotSupportedException();
}
void IMarketDataStorage.Delete(DateTime date)
{
throw new NotSupportedException();
}
int IMarketDataStorage.Save(IEnumerable data)
{
throw new NotSupportedException();
}
IEnumerable IMarketDataStorage.Load(DateTime date)
{
return Load(date);
}
IMarketDataMetaInfo IMarketDataStorage.GetMetaInfo(DateTime date)
{
return _basket.InnerStorages.First().GetMetaInfo(date);
}
/// <summary>
/// To load data.
/// </summary>
/// <param name="date">Date, for which data shall be loaded.</param>
/// <returns>Data. If there is no data, the empty set will be returned.</returns>
public IEnumerable<T> Load(DateTime date)
{
return new BasketEnumerable(() => _basket.Load(date));
}
private readonly Func<T, DateTimeOffset> _getTime;
DateTimeOffset IMarketDataStorageInfo.GetTime(object data)
{
return _getTime((T)data);
}
DateTimeOffset IMarketDataStorageInfo<T>.GetTime(T data)
{
return _getTime(data);
}
}
class ConvertableAllSecurityMarketDataStorage<TMessage, TEntity> : AllSecurityMarketDataStorage<TMessage>, IMarketDataStorage<TEntity>, IMarketDataStorageInfo<TEntity>
where TMessage : Message
{
private readonly Security _security;
private readonly Func<TEntity, DateTimeOffset> _getEntityTime;
public ConvertableAllSecurityMarketDataStorage(Security security,
object arg,
Func<TMessage, DateTimeOffset> getTime,
Func<TMessage, Security> getSecurity,
Func<TEntity, DateTimeOffset> getEntityTime,
Func<Security, IMarketDataDrive, IMarketDataStorage<TMessage>> getStorage,
IMarketDataStorageDrive drive,
IExchangeInfoProvider exchangeInfoProvider)
: base(security, arg, getTime, getSecurity, getStorage, drive, exchangeInfoProvider)
{
if (getEntityTime == null)
throw new ArgumentNullException(nameof(getEntityTime));
_security = security;
_getEntityTime = getEntityTime;
}
int IMarketDataStorage<TEntity>.Save(IEnumerable<TEntity> data)
{
throw new NotSupportedException();
}
void IMarketDataStorage<TEntity>.Delete(IEnumerable<TEntity> data)
{
throw new NotSupportedException();
}
IEnumerable<TEntity> IMarketDataStorage<TEntity>.Load(DateTime date)
{
if (typeof(TEntity) != typeof(Candle))
return Load(date).ToEntities<TMessage, TEntity>(_security);
var messages = Load(date);
return messages
.Cast<CandleMessage>()
.ToCandles<TEntity>(_security);
}
IMarketDataSerializer<TEntity> IMarketDataStorage<TEntity>.Serializer
{
get { throw new NotSupportedException(); }
}
DateTimeOffset IMarketDataStorageInfo.GetTime(object data)
{
return _getEntityTime((TEntity)data);
}
DateTimeOffset IMarketDataStorageInfo<TEntity>.GetTime(TEntity data)
{
return _getEntityTime(data);
}
}
}
| |
//
// Mono.Data.TdsClient.TdsParameter.cs
//
// Author:
// Rodrigo Moya (rodrigo@ximian.com)
// Daniel Morgan (danmorg@sc.rr.com)
// Tim Coleman (tim@timcoleman.com)
//
// (C) Ximian, Inc. 2002
// Copyright (C) Tim Coleman, 2002
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Mono.Data.Tds;
using Mono.Data.Tds.Protocol;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Runtime.InteropServices;
using System.Text;
namespace Mono.Data.TdsClient {
public sealed class TdsParameter : MarshalByRefObject, IDbDataParameter, IDataParameter, ICloneable
{
#region Fields
TdsMetaParameter metaParameter;
TdsParameterCollection container = null;
DbType dbType;
ParameterDirection direction = ParameterDirection.Input;
bool isNullable;
bool isSizeSet = false;
bool isTypeSet = false;
int offset;
TdsType sybaseType;
string sourceColumn;
DataRowVersion sourceVersion;
#endregion // Fields
#region Constructors
public TdsParameter ()
: this (String.Empty, TdsType.NVarChar, 0, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
{
}
public TdsParameter (string parameterName, object value)
{
metaParameter = new TdsMetaParameter (parameterName, value);
this.sourceVersion = DataRowVersion.Current;
InferTdsType (value);
}
public TdsParameter (string parameterName, TdsType dbType)
: this (parameterName, dbType, 0, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
{
}
public TdsParameter (string parameterName, TdsType dbType, int size)
: this (parameterName, dbType, size, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
{
}
public TdsParameter (string parameterName, TdsType dbType, int size, string sourceColumn)
: this (parameterName, dbType, size, ParameterDirection.Input, false, 0, 0, sourceColumn, DataRowVersion.Current, null)
{
}
[EditorBrowsable (EditorBrowsableState.Advanced)]
public TdsParameter (string parameterName, TdsType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
{
metaParameter = new TdsMetaParameter (parameterName, size, isNullable, precision, scale, value);
TdsType = dbType;
Direction = direction;
SourceColumn = sourceColumn;
SourceVersion = sourceVersion;
}
// This constructor is used internally to construct a
// TdsParameter. The value array comes from sp_procedure_params_rowset.
// This is in TdsCommand.DeriveParameters.
internal TdsParameter (object[] dbValues)
{
Precision = 0;
Scale = 0;
Direction = ParameterDirection.Input;
ParameterName = (string) dbValues[3];
switch ((short) dbValues[5]) {
case 1:
Direction = ParameterDirection.Input;
break;
case 2:
Direction = ParameterDirection.Output;
break;
case 3:
Direction = ParameterDirection.InputOutput;
break;
case 4:
Direction = ParameterDirection.ReturnValue;
break;
}
IsNullable = (bool) dbValues[8];
if (dbValues[12] != null)
Precision = (byte) ((short) dbValues[12]);
if (dbValues[13] != null)
Scale = (byte) ((short) dbValues[13]);
SetDbTypeName ((string) dbValues[16]);
}
#endregion // Constructors
#region Properties
// Used to ensure that only one collection can contain this
// parameter
internal TdsParameterCollection Container {
get { return container; }
set { container = value; }
}
public DbType DbType {
get { return dbType; }
set {
SetDbType (value);
isTypeSet = true;
}
}
public ParameterDirection Direction {
get { return direction; }
set {
direction = value;
if (direction == ParameterDirection.Output)
MetaParameter.Direction = TdsParameterDirection.Output;
}
}
internal TdsMetaParameter MetaParameter {
get { return metaParameter; }
}
string IDataParameter.ParameterName {
get { return metaParameter.ParameterName; }
set { metaParameter.ParameterName = value; }
}
public bool IsNullable {
get { return metaParameter.IsNullable; }
set { metaParameter.IsNullable = value; }
}
public int Offset {
get { return offset; }
set { offset = value; }
}
public string ParameterName {
get { return metaParameter.ParameterName; }
set { metaParameter.ParameterName = value; }
}
public byte Precision {
get { return metaParameter.Precision; }
set { metaParameter.Precision = value; }
}
public byte Scale {
get { return metaParameter.Scale; }
set { metaParameter.Scale = value; }
}
public int Size {
get { return metaParameter.Size; }
set { metaParameter.Size = value; }
}
public string SourceColumn {
get { return sourceColumn; }
set { sourceColumn = value; }
}
public DataRowVersion SourceVersion {
get { return sourceVersion; }
set { sourceVersion = value; }
}
public TdsType TdsType {
get { return sybaseType; }
set {
SetTdsType (value);
isTypeSet = true;
}
}
public object Value {
get { return metaParameter.Value; }
set {
if (!isTypeSet)
InferTdsType (value);
metaParameter.Value = value;
}
}
#endregion // Properties
#region Methods
object ICloneable.Clone ()
{
return new TdsParameter (ParameterName, TdsType, Size, Direction, IsNullable, Precision, Scale, SourceColumn, SourceVersion, Value);
}
// If the value is set without the DbType/TdsType being set, then we
// infer type information.
private void InferTdsType (object value)
{
Type type = value.GetType ();
string exception = String.Format ("The parameter data type of {0} is invalid.", type.Name);
switch (type.FullName) {
case "System.Int64":
SetTdsType (TdsType.BigInt);
break;
case "System.Boolean":
SetTdsType (TdsType.Bit);
break;
case "System.String":
SetTdsType (TdsType.NVarChar);
break;
case "System.DateTime":
SetTdsType (TdsType.DateTime);
break;
case "System.Decimal":
SetTdsType (TdsType.Decimal);
break;
case "System.Double":
SetTdsType (TdsType.Float);
break;
case "System.Byte[]":
SetTdsType (TdsType.VarBinary);
break;
case "System.Byte":
SetTdsType (TdsType.TinyInt);
break;
case "System.Int32":
SetTdsType (TdsType.Int);
break;
case "System.Single":
SetTdsType (TdsType.Real);
break;
case "System.Int16":
SetTdsType (TdsType.SmallInt);
break;
case "System.Guid":
SetTdsType (TdsType.UniqueIdentifier);
break;
case "System.Object":
SetTdsType (TdsType.Variant);
break;
default:
throw new ArgumentException (exception);
}
}
// When the DbType is set, we also set the TdsType, as well as the SQL Server
// string representation of the type name. If the DbType is not convertible
// to an TdsType, throw an exception.
private void SetDbType (DbType type)
{
string exception = String.Format ("No mapping exists from DbType {0} to a known TdsType.", type);
switch (type) {
case DbType.AnsiString:
MetaParameter.TypeName = "varchar";
sybaseType = TdsType.VarChar;
break;
case DbType.AnsiStringFixedLength:
MetaParameter.TypeName = "char";
sybaseType = TdsType.Char;
break;
case DbType.Binary:
MetaParameter.TypeName = "varbinary";
sybaseType = TdsType.VarBinary;
break;
case DbType.Boolean:
MetaParameter.TypeName = "bit";
sybaseType = TdsType.Bit;
break;
case DbType.Byte:
MetaParameter.TypeName = "tinyint";
sybaseType = TdsType.TinyInt;
break;
case DbType.Currency:
sybaseType = TdsType.Money;
MetaParameter.TypeName = "money";
break;
case DbType.Date:
case DbType.DateTime:
MetaParameter.TypeName = "datetime";
sybaseType = TdsType.DateTime;
break;
case DbType.Decimal:
MetaParameter.TypeName = "decimal";
sybaseType = TdsType.Decimal;
break;
case DbType.Double:
MetaParameter.TypeName = "float";
sybaseType = TdsType.Float;
break;
case DbType.Guid:
MetaParameter.TypeName = "uniqueidentifier";
sybaseType = TdsType.UniqueIdentifier;
break;
case DbType.Int16:
MetaParameter.TypeName = "smallint";
sybaseType = TdsType.SmallInt;
break;
case DbType.Int32:
MetaParameter.TypeName = "int";
sybaseType = TdsType.Int;
break;
case DbType.Int64:
MetaParameter.TypeName = "bigint";
sybaseType = TdsType.BigInt;
break;
case DbType.Object:
MetaParameter.TypeName = "sql_variant";
sybaseType = TdsType.Variant;
break;
case DbType.Single:
MetaParameter.TypeName = "real";
sybaseType = TdsType.Real;
break;
case DbType.String:
MetaParameter.TypeName = "nvarchar";
sybaseType = TdsType.NVarChar;
break;
case DbType.StringFixedLength:
MetaParameter.TypeName = "nchar";
sybaseType = TdsType.NChar;
break;
case DbType.Time:
MetaParameter.TypeName = "datetime";
sybaseType = TdsType.DateTime;
break;
default:
throw new ArgumentException (exception);
}
dbType = type;
}
// Used by internal constructor which has a SQL Server typename
private void SetDbTypeName (string dbTypeName)
{
switch (dbTypeName.ToLower ()) {
case "bigint":
TdsType = TdsType.BigInt;
break;
case "binary":
TdsType = TdsType.Binary;
break;
case "bit":
TdsType = TdsType.Bit;
break;
case "char":
TdsType = TdsType.Char;
break;
case "datetime":
TdsType = TdsType.DateTime;
break;
case "decimal":
TdsType = TdsType.Decimal;
break;
case "float":
TdsType = TdsType.Float;
break;
case "image":
TdsType = TdsType.Image;
break;
case "int":
TdsType = TdsType.Int;
break;
case "money":
TdsType = TdsType.Money;
break;
case "nchar":
TdsType = TdsType.NChar;
break;
case "ntext":
TdsType = TdsType.NText;
break;
case "nvarchar":
TdsType = TdsType.NVarChar;
break;
case "real":
TdsType = TdsType.Real;
break;
case "smalldatetime":
TdsType = TdsType.SmallDateTime;
break;
case "smallint":
TdsType = TdsType.SmallInt;
break;
case "smallmoney":
TdsType = TdsType.SmallMoney;
break;
case "text":
TdsType = TdsType.Text;
break;
case "timestamp":
TdsType = TdsType.Timestamp;
break;
case "tinyint":
TdsType = TdsType.TinyInt;
break;
case "uniqueidentifier":
TdsType = TdsType.UniqueIdentifier;
break;
case "varbinary":
TdsType = TdsType.VarBinary;
break;
case "varchar":
TdsType = TdsType.VarChar;
break;
default:
TdsType = TdsType.Variant;
break;
}
}
// When the TdsType is set, we also set the DbType, as well as the SQL Server
// string representation of the type name. If the TdsType is not convertible
// to a DbType, throw an exception.
private void SetTdsType (TdsType type)
{
string exception = String.Format ("No mapping exists from TdsType {0} to a known DbType.", type);
switch (type) {
case TdsType.BigInt:
MetaParameter.TypeName = "bigint";
dbType = DbType.Int64;
break;
case TdsType.Binary:
MetaParameter.TypeName = "binary";
dbType = DbType.Binary;
break;
case TdsType.Timestamp:
MetaParameter.TypeName = "timestamp";
dbType = DbType.Binary;
break;
case TdsType.VarBinary:
MetaParameter.TypeName = "varbinary";
dbType = DbType.Binary;
break;
case TdsType.Bit:
MetaParameter.TypeName = "bit";
dbType = DbType.Boolean;
break;
case TdsType.Char:
MetaParameter.TypeName = "char";
dbType = DbType.AnsiStringFixedLength;
break;
case TdsType.DateTime:
MetaParameter.TypeName = "datetime";
dbType = DbType.DateTime;
break;
case TdsType.SmallDateTime:
MetaParameter.TypeName = "smalldatetime";
dbType = DbType.DateTime;
break;
case TdsType.Decimal:
MetaParameter.TypeName = "decimal";
dbType = DbType.Decimal;
break;
case TdsType.Float:
MetaParameter.TypeName = "float";
dbType = DbType.Double;
break;
case TdsType.Image:
MetaParameter.TypeName = "image";
dbType = DbType.Binary;
break;
case TdsType.Int:
MetaParameter.TypeName = "int";
dbType = DbType.Int32;
break;
case TdsType.Money:
MetaParameter.TypeName = "money";
dbType = DbType.Currency;
break;
case TdsType.SmallMoney:
MetaParameter.TypeName = "smallmoney";
dbType = DbType.Currency;
break;
case TdsType.NChar:
MetaParameter.TypeName = "nchar";
dbType = DbType.StringFixedLength;
break;
case TdsType.NText:
MetaParameter.TypeName = "ntext";
dbType = DbType.String;
break;
case TdsType.NVarChar:
MetaParameter.TypeName = "nvarchar";
dbType = DbType.String;
break;
case TdsType.Real:
MetaParameter.TypeName = "real";
dbType = DbType.Single;
break;
case TdsType.SmallInt:
MetaParameter.TypeName = "smallint";
dbType = DbType.Int16;
break;
case TdsType.Text:
MetaParameter.TypeName = "text";
dbType = DbType.AnsiString;
break;
case TdsType.VarChar:
MetaParameter.TypeName = "varchar";
dbType = DbType.AnsiString;
break;
case TdsType.TinyInt:
MetaParameter.TypeName = "tinyint";
dbType = DbType.Byte;
break;
case TdsType.UniqueIdentifier:
MetaParameter.TypeName = "uniqueidentifier";
dbType = DbType.Guid;
break;
case TdsType.Variant:
MetaParameter.TypeName = "sql_variant";
dbType = DbType.Object;
break;
default:
throw new ArgumentException (exception);
}
sybaseType = type;
}
public override string ToString()
{
return ParameterName;
}
#endregion // Methods
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="CollectionContainer.cs" company="Microsoft">
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Holds an existing collection structure
// (e.g. ObservableCollection or DataSet) inside the ItemCollection.
//
// See specs at http://avalon/connecteddata/M5%20General%20Docs/ItemCollection.mht
// http://avalon/connecteddata/M5%20Specs/IDataCollection.mht
//
// History:
// 07/14/2003 : [....] - Created
//
//---------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using MS.Utility;
using MS.Internal; // Invariant.Assert
using MS.Internal.Utility;
using MS.Internal.Data; // IndexedEnumerable
using System;
namespace System.Windows.Data
{
/// <summary>
/// Holds an existing collection structure
/// (e.g. ObservableCollection or DataSet) for use under a CompositeCollection.
/// </summary>
public class CollectionContainer : DependencyObject, INotifyCollectionChanged, IWeakEventListener
{
//------------------------------------------------------
//
// Dynamic properties and events
//
//------------------------------------------------------
/// <summary>
/// Collection to be added into flattened ItemCollection
/// </summary>
public static readonly DependencyProperty CollectionProperty =
DependencyProperty.Register(
"Collection",
typeof(IEnumerable),
typeof(CollectionContainer),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnCollectionPropertyChanged)));
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static CollectionContainer()
{
}
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
//ISSUE/[....]/030820 perf will potentially degrade if assigned collection
// is only IEnumerable, but will improve if it
// implements ICollection (for Count property), or,
// better yet IList (for IndexOf and forward/backward enum using indexer)
/// <summary>
/// Collection to be added into flattened ItemCollection.
/// </summary>
public IEnumerable Collection
{
get { return (IEnumerable) GetValue(CollectionContainer.CollectionProperty); }
set { SetValue(CollectionContainer.CollectionProperty, value); }
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeCollection()
{
if (Collection == null)
{
return false;
}
// Try to see if there is an item in the Collection without
// creating an enumerator.
ICollection collection = Collection as ICollection;
if (collection != null && collection.Count == 0)
{
return false;
}
// If MoveNext returns true, then the enumerator is non-empty.
IEnumerator enumerator = Collection.GetEnumerator();
bool result = enumerator.MoveNext();
IDisposable d = enumerator as IDisposable;
if (d != null)
{
d.Dispose();
}
return result;
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
internal ICollectionView View
{
get
{
return _view;
}
}
internal int ViewCount
{
get
{
if (View == null)
return 0;
CollectionView cv = View as CollectionView;
if (cv != null)
return cv.Count;
ICollection coll = View as ICollection;
if (coll != null)
return coll.Count;
// As a last resort, use the IList interface or IndexedEnumerable to find the count.
if (ViewList != null)
return ViewList.Count;
return 0;
}
}
internal bool ViewIsEmpty
{
get
{
if (View == null)
return true;
ICollectionView cv = View as ICollectionView;
if (cv != null)
return cv.IsEmpty;
ICollection coll = View as ICollection;
if (coll != null)
return (coll.Count == 0);
// As a last resort, use the IList interface or IndexedEnumerable to find the count.
if (ViewList != null)
{
IndexedEnumerable le = ViewList as IndexedEnumerable;
if (le != null)
return le.IsEmpty;
else
return (ViewList.Count == 0);
}
return true;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
internal object ViewItem(int index)
{
Invariant.Assert(index >= 0 && View != null);
CollectionView cv = View as CollectionView;
if (cv != null)
{
return cv.GetItemAt(index);
}
// As a last resort, use the IList interface or IndexedEnumerable to iterate to the nth item.
if (ViewList != null)
return ViewList[index];
return null;
}
internal int ViewIndexOf(object item)
{
if (View == null)
return -1;
CollectionView cv = View as CollectionView;
if (cv != null)
{
return cv.IndexOf(item);
}
// As a last resort, use the IList interface or IndexedEnumerable to look for the item.
if (ViewList != null)
return ViewList.IndexOf(item);
return -1;
}
internal void GetCollectionChangedSources(int level, Action<int, object, bool?, List<string>> format, List<string> sources)
{
format(level, this, false, sources);
if (_view != null)
{
CollectionView cv = _view as CollectionView;
if (cv != null)
{
cv.GetCollectionChangedSources(level+1, format, sources);
}
else
{
format(level+1, _view, true, sources);
}
}
}
#endregion Internal Methods
#region INotifyCollectionChanged
/// <summary>
/// Occurs when the contained collection changes
/// </summary>
event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged
{
add { CollectionChanged += value; }
remove { CollectionChanged -= value; }
}
/// <summary>
/// Occurs when the contained collection changes
/// </summary>
protected virtual event NotifyCollectionChangedEventHandler CollectionChanged;
/// <summary>
/// Called when the contained collection changes
/// </summary>
protected virtual void OnContainedCollectionChanged(NotifyCollectionChangedEventArgs args)
{
if (CollectionChanged != null)
CollectionChanged(this, args);
}
#endregion INotifyCollectionChanged
#region IWeakEventListener
/// <summary>
/// Handle events from the centralized event table
/// </summary>
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return ReceiveWeakEvent(managerType, sender, e);
}
/// <summary>
/// Handle events from the centralized event table
/// </summary>
protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return false; // this method is no longer used (but must remain, for compat)
}
#endregion IWeakEventListener
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
private IndexedEnumerable ViewList
{
get
{
if (_viewList == null && View != null)
{
_viewList = new IndexedEnumerable(View);
}
return _viewList;
}
}
#endregion
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// called when value of CollectionProperty is required by property store
private static object OnGetCollection(DependencyObject d)
{
return ((CollectionContainer) d).Collection;
}
// Called when CollectionProperty is changed on "d."
private static void OnCollectionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CollectionContainer cc = (CollectionContainer) d;
cc.HookUpToCollection((IEnumerable) e.NewValue, true);
}
// To prevent CollectionContainer memory leak:
// HookUpToCollection() is called to start listening to CV only when
// the Container is being used by a CompositeCollectionView.
// When the last CCV stops using the container (or the CCV is GC'ed),
// HookUpToCollection() is called to stop listening to its CV, so that
// this container can be GC'ed if no one else is holding on to it.
// unhook old collection/view and hook up new collection/view
private void HookUpToCollection(IEnumerable newCollection, bool shouldRaiseChangeEvent)
{
// clear cached helper
_viewList = null;
// unhook from the old collection view
if (View != null)
{
CollectionChangedEventManager.RemoveHandler(View, OnCollectionChanged);
if (_traceLog != null)
_traceLog.Add("Unsubscribe to CollectionChange from {0}",
TraceLog.IdFor(View));
}
// change to the new view
if (newCollection != null)
_view = CollectionViewSource.GetDefaultCollectionView(newCollection, this);
else
_view = null;
// hook up to the new collection view
if (View != null)
{
CollectionChangedEventManager.AddHandler(View, OnCollectionChanged);
if (_traceLog != null)
_traceLog.Add("Subscribe to CollectionChange from {0}", TraceLog.IdFor(View));
}
if (shouldRaiseChangeEvent) // it's as if this were a refresh of the container's collection
OnContainedCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// forward the event to CompositeCollections that use this container
OnContainedCollectionChanged(e);
}
#endregion Private Methods
// this method is here just to avoid the compiler error
// error CS0649: Warning as Error: Field '..._traceLog' is never assigned to, and will always have its default value null
void InitializeTraceLog()
{
_traceLog = new TraceLog(20);
}
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private TraceLog _traceLog;
private ICollectionView _view;
private IndexedEnumerable _viewList; // cache of list wrapper for view
#endregion Private Fields
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Mathematics.Interop;
using System;
using System.Diagnostics;
namespace SharpDX.Direct3D11
{
public partial class EffectVectorVariable
{
private const string VectorInvalidSize = "Invalid Vector size: Must be 16 bytes or 4 x 4 bytes";
/// <summary>
/// Get a four-component vector that contains integer data.
/// </summary>
/// <returns>Returns a four-component vector that contains integer data </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetIntVector([Out] int* pData)</unmanaged>
public RawInt4 GetIntVector()
{
RawInt4 temp;
GetIntVector(out temp);
return temp;
}
/// <summary>
/// Get a four-component vector that contains floating-point data.
/// </summary>
/// <returns>Returns a four-component vector that contains floating-point data.</returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetFloatVector([Out] float* pData)</unmanaged>
public RawVector4 GetFloatVector()
{
RawVector4 temp;
GetFloatVector(out temp);
return temp;
}
/// <summary>
/// Get a four-component vector that contains boolean data.
/// </summary>
/// <returns>a four-component vector that contains boolean data. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetBoolVector([Out, Buffer] BOOL* pData)</unmanaged>
public RawBool4 GetBoolVector()
{
RawBool4 temp;
GetBoolVector(out temp);
return temp;
}
/// <summary>
/// Get a four-component vector.
/// </summary>
/// <typeparam name="T">Type of the four-component vector</typeparam>
/// <returns>a four-component vector. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetFloatVector([Out, Buffer] BOOL* pData)</unmanaged>
public unsafe T GetVector<T>() where T : struct
{
T temp;
GetIntVector(out *(RawInt4*)Interop.CastOut(out temp));
return temp;
}
/// <summary>
/// Set an array of four-component vectors that contain integer data.
/// </summary>
/// <param name="array">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetIntVectorArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(RawInt4[] array)
{
Set(array, 0, array.Length);
}
/// <summary>
/// Set an array of four-component vectors that contain floating-point data.
/// </summary>
/// <param name="array">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(RawVector4[] array)
{
Set(array, 0, array.Length);
}
/// <summary>
/// Set an array of four-component vectors that contain floating-point data.
/// </summary>
/// <typeparam name="T">Type of the four-component vector</typeparam>
/// <param name="array">A reference to the start of the data to set.</param>
/// <returns>
/// Returns one of the following {{Direct3D 10 Return Codes}}.
/// </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set<T>(T[] array) where T : struct
{
System.Diagnostics.Debug.Assert(Utilities.SizeOf<T>() == 16, VectorInvalidSize);
Set(Interop.CastArray<RawVector4,T>(array), 0, array.Length);
}
/// <summary>
/// Set a x-component vector.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set<T>(T value) where T : struct
{
Set(ref value);
}
/// <summary>
/// Set a x-component vector.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public unsafe void Set<T>(ref T value) where T : struct
{
System.Diagnostics.Debug.Assert(Utilities.SizeOf<T>() <= 16, VectorInvalidSize);
SetRawValue(new IntPtr(Interop.Fixed(ref value)), 0, Utilities.SizeOf<T>());
}
/// <summary>
/// Set a two-component vector that contains floating-point data.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set(RawVector2 value)
{
unsafe
{
SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<RawVector2>());
}
}
/// <summary>
/// Set a three-component vector that contains floating-point data.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set(RawVector3 value)
{
unsafe
{
SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<RawVector3>());
}
}
/// <summary>
/// Set a four-component color that contains floating-point data.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set(RawColor4 value)
{
unsafe
{
SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<RawColor4>());
}
}
/// <summary>
/// Set an array of four-component color that contain floating-point data.
/// </summary>
/// <param name="array">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(RawColor4[] array)
{
unsafe
{
fixed (void* pArray = &array[0]) SetRawValue((IntPtr)pArray, 0, array.Length * Utilities.SizeOf<RawColor4>());
}
}
/// <summary>
/// Get an array of four-component vectors that contain integer data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of four-component vectors that contain integer data. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetIntVectorArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public RawInt4[] GetIntVectorArray(int count)
{
var temp = new RawInt4[count];
GetIntVectorArray(temp, 0, count);
return temp;
}
/// <summary>
/// Get an array of four-component vectors that contain floating-point data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of four-component vectors that contain floating-point data. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetFloatVectorArray([None] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public RawVector4[] GetFloatVectorArray(int count)
{
var temp = new RawVector4[count];
GetFloatVectorArray(temp, 0, count);
return temp;
}
/// <summary>
/// Get an array of four-component vectors that contain boolean data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>an array of four-component vectors that contain boolean data. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetBoolVectorArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public RawBool4[] GetBoolVectorArray(int count)
{
var temp = new RawBool4[count];
GetBoolVectorArray(temp, 0, count);
return temp;
}
/// <summary>
/// Get an array of four-component vectors that contain boolean data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>an array of four-component vectors that contain boolean data. </returns>
/// <unmanaged>HRESULT ID3D11EffectVectorVariable::GetBoolVectorArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public T[] GetVectorArray<T>(int count) where T : struct
{
var temp = new T[count];
GetIntVectorArray(Interop.CastArray<RawInt4,T>(temp), 0, count);
return temp;
}
}
}
| |
// <copyright file="WorkOnThreadPoolUnitTests.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Threading;
using System.Threading.Tasks;
using IX.DataGeneration;
using IX.StandardExtensions;
using IX.StandardExtensions.Contracts;
using IX.StandardExtensions.Threading;
using Xunit;
using Xunit.Abstractions;
namespace IX.UnitTests;
/// <summary>
/// Unit tests for working on thread pool.
/// </summary>
public class WorkOnThreadPoolUnitTests
{
private const int MaxWaitTime = 5000;
private const int StandardWaitTime = 300;
private readonly ITestOutputHelper output;
/// <summary>
/// Initializes a new instance of the <see cref="WorkOnThreadPoolUnitTests"/> class.
/// </summary>
/// <param name="output">The test output.</param>
public WorkOnThreadPoolUnitTests(ITestOutputHelper output)
{
Requires.NotNull(out this.output, output, nameof(output));
}
/// <summary>
/// Tests running on the thread pool and, because of a lack of a synchronization context, not returning to the same
/// thread.
/// </summary>
/// <returns>A <see cref="Task" /> representing the asynchronous unit test.</returns>
[Fact(DisplayName = "Test running on thread pool and not returning to thread context.")]
public async Task Test1()
{
// ARRANGE
var currentThreadId = Thread.CurrentThread.ManagedThreadId;
var separateThreadId = currentThreadId;
void LocalMethod()
{
separateThreadId = Thread.CurrentThread.ManagedThreadId;
}
// ACT
await Work.OnThreadPoolAsync(LocalMethod);
// ASSERT
Assert.NotEqual(
currentThreadId,
separateThreadId);
}
/// <summary>
/// Test basic Fire.AndForget mechanism.
/// </summary>
[Fact(DisplayName = "Test basic Fire.AndForget mechanism")]
public void Test2()
{
// ARRANGE
int initialValue = DataGenerator.RandomInteger();
int floatingValue = initialValue;
int waitTime = DataGenerator.RandomNonNegativeInteger(StandardWaitTime) + 1;
bool result;
// ACT
using (var mre = new ManualResetEventSlim())
{
_ = Work.OnThreadPoolAsync(
ev =>
{
Thread.Sleep(waitTime);
Interlocked.Exchange(
ref floatingValue,
DataGenerator.RandomInteger());
ev.Set();
},
mre);
result = mre.Wait(MaxWaitTime);
}
// ASSERT
try
{
Assert.True(result);
Assert.NotEqual(initialValue, floatingValue);
}
catch
{
this.output.WriteLine("Assert phase failed.");
this.output.WriteLine($"Test parameters: Expected Value: {initialValue}; Actual Value: {floatingValue}; Wait Time: {waitTime}; Wait Result: {result}.");
throw;
}
}
/// <summary>
/// Test Fire.AndForget distinct threading mechanism.
/// </summary>
[Fact(DisplayName = "Test Fire.AndForget distinct threading mechanism")]
public void Test3()
{
// ARRANGE
int initialValue = Thread.CurrentThread.ManagedThreadId;
int floatingValue = initialValue;
int waitTime = DataGenerator.RandomNonNegativeInteger(StandardWaitTime) + 1;
bool result;
// ACT
using (var mre = new ManualResetEventSlim())
{
_ = Work.OnThreadPoolAsync(
ev =>
{
Thread.Sleep(waitTime);
Interlocked.Exchange(
ref floatingValue,
Thread.CurrentThread.ManagedThreadId);
ev.Set();
},
mre);
result = mre.Wait(MaxWaitTime);
}
// ASSERT
try
{
Assert.True(result);
Assert.NotEqual(initialValue, floatingValue);
}
catch
{
this.output.WriteLine("Assert phase failed.");
this.output.WriteLine($"Test parameters: Expected Value: {initialValue}; Actual Value: {floatingValue}; Wait Time: {waitTime}; Wait Result: {result}.");
throw;
}
}
/// <summary>
/// Test Fire.AndForget eexception mechanism.
/// </summary>
[Fact(DisplayName = "Test Fire.AndForget exception mechanism")]
public void Test4()
{
// ARRANGE
string argumentName = DataGenerator.RandomLowercaseString(
DataGenerator.RandomInteger(
5,
10));
int waitTime = DataGenerator.RandomNonNegativeInteger(StandardWaitTime) + 1;
bool result;
Exception ex = null;
// ACT
using (var mre = new ManualResetEventSlim())
{
#if DEBUG
DateTime dt = DateTime.UtcNow;
#endif
Work.OnThreadPoolAsync(
() =>
{
#if DEBUG
this.output.WriteLine($"Beginning inner method after {(DateTime.UtcNow - dt).TotalMilliseconds} ms.");
#endif
Thread.Sleep(waitTime);
#if DEBUG
this.output.WriteLine($"Inner method wait finished after {(DateTime.UtcNow - dt).TotalMilliseconds} ms.");
#endif
throw new ArgumentNotPositiveIntegerException(argumentName);
}).ContinueWith(
task =>
{
var exception = task.Exception!.GetBaseException();
#if DEBUG
this.output.WriteLine($"Exception handler started after {(DateTime.UtcNow - dt).TotalMilliseconds} ms.");
#endif
Interlocked.Exchange(
ref ex,
exception);
// ReSharper disable once AccessToDisposedClosure - Guaranteed to either not be disposed or not relevant to context anymore at this point
mre.Set();
},
TaskContinuationOptions.OnlyOnFaulted);
result = mre.Wait(MaxWaitTime);
#if DEBUG
this.output.WriteLine($"Outer method unlocked after {(DateTime.UtcNow - dt).TotalMilliseconds} ms.");
#endif
}
// ASSERT
try
{
Assert.True(result);
Assert.NotNull(ex);
Assert.IsType<ArgumentNotPositiveIntegerException>(ex);
Assert.Equal(argumentName, ((ArgumentNotPositiveIntegerException)ex).ParamName);
}
catch
{
this.output.WriteLine("Assert phase failed.");
this.output.WriteLine($"Test parameters: Wait Time: {waitTime}; Wait Result: {result}; Resulting exception: {ex?.ToString() ?? "null"}.");
throw;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>Artifact</c> resource.</summary>
public sealed partial class ArtifactName : gax::IResourceName, sys::IEquatable<ArtifactName>
{
/// <summary>The possible contents of <see cref="ArtifactName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>.
/// </summary>
ProjectLocationMetadataStoreArtifact = 1,
}
private static gax::PathTemplate s_projectLocationMetadataStoreArtifact = new gax::PathTemplate("projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}");
/// <summary>Creates a <see cref="ArtifactName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ArtifactName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static ArtifactName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ArtifactName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ArtifactName"/> with the pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="artifactId">The <c>Artifact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ArtifactName"/> constructed from the provided ids.</returns>
public static ArtifactName FromProjectLocationMetadataStoreArtifact(string projectId, string locationId, string metadataStoreId, string artifactId) =>
new ArtifactName(ResourceNameType.ProjectLocationMetadataStoreArtifact, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), metadataStoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId)), artifactId: gax::GaxPreconditions.CheckNotNullOrEmpty(artifactId, nameof(artifactId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ArtifactName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="artifactId">The <c>Artifact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ArtifactName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string metadataStoreId, string artifactId) =>
FormatProjectLocationMetadataStoreArtifact(projectId, locationId, metadataStoreId, artifactId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ArtifactName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="artifactId">The <c>Artifact</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ArtifactName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>.
/// </returns>
public static string FormatProjectLocationMetadataStoreArtifact(string projectId, string locationId, string metadataStoreId, string artifactId) =>
s_projectLocationMetadataStoreArtifact.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId)), gax::GaxPreconditions.CheckNotNullOrEmpty(artifactId, nameof(artifactId)));
/// <summary>Parses the given resource name string into a new <see cref="ArtifactName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="artifactName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ArtifactName"/> if successful.</returns>
public static ArtifactName Parse(string artifactName) => Parse(artifactName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ArtifactName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="artifactName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ArtifactName"/> if successful.</returns>
public static ArtifactName Parse(string artifactName, bool allowUnparsed) =>
TryParse(artifactName, allowUnparsed, out ArtifactName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ArtifactName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="artifactName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ArtifactName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string artifactName, out ArtifactName result) => TryParse(artifactName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ArtifactName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="artifactName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ArtifactName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string artifactName, bool allowUnparsed, out ArtifactName result)
{
gax::GaxPreconditions.CheckNotNull(artifactName, nameof(artifactName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationMetadataStoreArtifact.TryParseName(artifactName, out resourceName))
{
result = FromProjectLocationMetadataStoreArtifact(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(artifactName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ArtifactName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string artifactId = null, string locationId = null, string metadataStoreId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ArtifactId = artifactId;
LocationId = locationId;
MetadataStoreId = metadataStoreId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ArtifactName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="artifactId">The <c>Artifact</c> ID. Must not be <c>null</c> or empty.</param>
public ArtifactName(string projectId, string locationId, string metadataStoreId, string artifactId) : this(ResourceNameType.ProjectLocationMetadataStoreArtifact, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), metadataStoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId)), artifactId: gax::GaxPreconditions.CheckNotNullOrEmpty(artifactId, nameof(artifactId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Artifact</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ArtifactId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>MetadataStore</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string MetadataStoreId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationMetadataStoreArtifact: return s_projectLocationMetadataStoreArtifact.Expand(ProjectId, LocationId, MetadataStoreId, ArtifactId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ArtifactName);
/// <inheritdoc/>
public bool Equals(ArtifactName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ArtifactName a, ArtifactName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ArtifactName a, ArtifactName b) => !(a == b);
}
public partial class Artifact
{
/// <summary>
/// <see cref="gcav::ArtifactName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::ArtifactName ArtifactName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ArtifactName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
//using System.Runtime.Serialization;
namespace HTLib2
{
[Serializable]
public abstract partial class Matrix : IMatrix<double>
{
//////////////////////////////////////////////////////////////////////////////////////////////////
// IMatrix
public abstract int ColSize { get; } //public int NumRows { get { return ColSize; } }
public abstract int RowSize { get; } //public int NumCols { get { return RowSize; } }
public abstract double this[int c, int r] { get; set; }
public abstract double this[long c, long r] { get; set; }
//////////////////////////////////////////////////////////////////////////////////////////////////
// abstract
public abstract Matrix Clone();
public static bool Zeros_Selftest = HDebug.IsDebuggerAttached;
public static Matrix Zeros(int colsize, int rowsize)
{
if(Zeros_Selftest)
{
Zeros_Selftest = false;
HDebug.Assert(Matrix.Zeros( 3, 2).IsZero());
HDebug.Assert(Matrix.Zeros(100, 100).IsZero());
}
if((colsize < 10) && (rowsize < 10))
return MatrixByArr.Zeros(colsize, rowsize);
return MatrixByColRow.Zeros(colsize, rowsize);
}
public static Matrix Ones(int colsize, int rowsize)
{
return Ones(colsize, rowsize, 1);
}
public static Matrix Ones(int colsize, int rowsize, double mul)
{
if(Zeros_Selftest)
{
Zeros_Selftest = false;
Matrix tm0 = new double[2, 2] { { 1, 1 }, { 1, 1 } };
Matrix tm1 = tm0 * 1.1;
HDebug.Assert((tm0 - Ones(2, 2 )).IsZero());
HDebug.Assert((tm1 - Ones(2, 2, 1.1)).IsZero());
HDebug.Assert((Zeros(10,10) - Ones(10, 10, 0)).IsZero());
}
Matrix mat = null;
if((colsize < 10) && (rowsize < 10)) mat = MatrixByArr .Zeros(colsize, rowsize);
else mat = MatrixByColRow.Zeros(colsize, rowsize);
if(mul == 0)
return mat;
for(int c=0; c<colsize; c++)
for(int r=0; r<rowsize; r++)
mat[c, r] = mul;
return mat;
}
public virtual double[,] ToArray()
{
double[,] arr = new double[ColSize, RowSize];
for(int c=0; c<ColSize; c++)
for(int r=0; r<RowSize; r++)
arr[c, r] = this[c, r];
return arr;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// operators
public static implicit operator Matrix(double[,] mat)
{
return new MatrixByArr(mat);
}
public static Matrix operator-(Matrix left ) { Matrix mat = left.Clone(); mat.UpdateMul(-1 ); return mat; }
public static Matrix operator+(Matrix left, IMatrix<double> right) { Matrix mat = left.Clone(); mat.UpdateAdd(right, 1); return mat; }
public static Matrix operator-(Matrix left, IMatrix<double> right) { Matrix mat = left.Clone(); mat.UpdateAdd(right,-1); return mat; }
public static Matrix operator*(Matrix left, IMatrix<double> right) { Matrix mat = left.GetMul(right); return mat; }
public static Matrix operator*(Matrix left, double right) { Matrix mat = left.Clone(); mat.UpdateMul(right ); return mat; }
public static Matrix operator*(double left, Matrix right) { Matrix mat = right.Clone(); mat.UpdateMul(left ); return mat; }
public static Matrix operator/(Matrix left, double right) { Matrix mat = left.Clone(); mat.UpdateMul(1/right); return mat; }
//////////////////////////////////////////////////////////////////////////////////////////////////
// ToString()
public override string ToString()
{
//return "no display...";
StringBuilder str = new StringBuilder();
str.Append("Matrix ["+ColSize+","+RowSize+"] ");
str.Append(HToString("0.00000", null, "{{", "}}", ", ", "}, {", 100));
return str.ToString();
}
//public string ToString(string format)
//{
// return ToString(format, null, "{{", "}}", ", ", "}, {");
//}
//public string ToString(string coldelim, string rowdelim)
//{
// return ToString(null, null, "{{", "}}", coldelim, rowdelim);
//}
//public string ToString(string format, string coldelim, string rowdelim)
//{
// return ToString(format, null, "{{", "}}", coldelim, rowdelim);
//}
public string HToString( string format = "0.00000"
, IFormatProvider formatProvider = null
, string begindelim = "{{"
, string enddelim = "}}"
, string rowdelim = ", "
, string coldelim = "}, {"
, int? maxcount = null
)
{
StringBuilder str = new StringBuilder();
str.Append(begindelim);
int count = 0;
for(int c = 0; c < ColSize; c++) {
if(c != 0) str.Append(coldelim);
for(int r = 0; r < RowSize; r++) {
if(r != 0) str.Append(rowdelim);
// str += this[c, r].ToString(format, formatProvider);
if(maxcount != null && count > maxcount.Value)
break;
str.Append(this[c, r].ToString(format));
count++;
}
}
str.Append(enddelim);
return str.ToString();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// others
public virtual void UpdateAdd(IMatrix<double> other, double other_mul)
{
HDebug.Exception(ColSize == other.ColSize);
HDebug.Exception(RowSize == other.RowSize);
if(other_mul == 1)
{
for(int c=0; c<ColSize; c++)
for(int r=0; r<RowSize; r++)
this[c, r] += other[c, r];
}
else if(other_mul == -1)
{
for(int c=0; c<ColSize; c++)
for(int r=0; r<RowSize; r++)
this[c, r] -= other[c, r];
}
else
{
for(int c=0; c<ColSize; c++)
for(int r=0; r<RowSize; r++)
this[c, r] += (other[c, r] * other_mul);
}
}
//public virtual void UpdateAdd(IMatrix other)
//{
// HDebug.Exception(ColSize == other.ColSize);
// HDebug.Exception(RowSize == other.RowSize);
// for(int c=0; c<ColSize; c++)
// for(int r=0; r<RowSize; r++)
// this[c, r] += other[c, r];
//}
//public virtual void UpdateSub(IMatrix other)
//{
// HDebug.Exception(ColSize == other.ColSize);
// HDebug.Exception(RowSize == other.RowSize);
// for(int c=0; c<ColSize; c++)
// for(int r=0; r<RowSize; r++)
// this[c, r] -= other[c, r];
//}
public virtual Matrix GetMul(IMatrix<double> right)
{
return Matrix.GetMul(this, right);
}
public static Matrix GetMul(Matrix left, IMatrix<double> right)
{
int RowSize = left.RowSize;
int ColSize = left.ColSize;
HDebug.Exception(RowSize == right.ColSize);
Matrix mul = Matrix.Zeros(ColSize, right.RowSize);
int colsize = mul.ColSize;
int midsize = RowSize;
int rowsize = mul.RowSize;
for(int c=0; c<colsize; c++)
for(int r=0; r<rowsize; r++)
for(int i=0; i<midsize; i++)
mul[c, r] += left[c, i] * right[i, r];
return mul;
}
public virtual void UpdateMul(double other)
{
for(int c=0; c<ColSize; c++)
for(int r=0; r<RowSize; r++)
this[c, r] *= other;
}
public virtual Vector GetColVector(int row)
{
HDebug.AssertAnd(0<=row, row<RowSize);
double[] vec = new double[ColSize];
for(int col=0; col<ColSize; col++)
vec[col] = this[col, row];
return vec;
}
public virtual Vector GetRowVector(int col)
{
HDebug.AssertAnd(0<=col, col<ColSize);
double[] vec = new double[RowSize];
for(int row=0; row<RowSize; row++)
vec[row] = this[col, row];
return vec;
}
public void SetValue(double value)
{
for(int c=0; c<ColSize; c++)
for(int r=0; r<RowSize; r++)
this[c, r] = value;
}
}
}
| |
//
// PackedByteArray.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
namespace MimeKit.Utils {
class PackedByteArray : IList<byte>
{
const int InitialBufferSize = 64;
ushort[] buffer;
int length;
int cursor;
public PackedByteArray ()
{
buffer = new ushort[InitialBufferSize];
Clear ();
}
#region ICollection implementation
public int Count {
get { return length; }
}
public bool IsReadOnly {
get { return false; }
}
void EnsureBufferSize (int size)
{
if (buffer.Length > size)
return;
int ideal = (size + 63) & ~63;
Array.Resize<ushort> (ref buffer, ideal);
}
public void Add (byte item)
{
if (cursor < 0 || item != (byte) (buffer[cursor] & 0xFF) || (buffer[cursor] & 0xFF00) == 0xFF00) {
EnsureBufferSize (cursor + 2);
buffer[++cursor] = (ushort) ((1 << 8) | item);
} else {
buffer[cursor] += (1 << 8);
}
length++;
}
public void Clear ()
{
cursor = -1;
length = 0;
}
public bool Contains (byte item)
{
for (int i = 0; i <= cursor; i++) {
if (item == (byte) (buffer[i] & 0xFF))
return true;
}
return false;
}
public void CopyTo (byte[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException ("array");
if (arrayIndex < 0 || arrayIndex + length > array.Length)
throw new ArgumentOutOfRangeException ("arrayIndex");
int index = arrayIndex;
int count;
byte c;
for (int i = 0; i <= cursor; i++) {
count = (buffer[i] >> 8) & 0xFF;
c = (byte) (buffer[i] & 0xFF);
for (int n = 0; n < count; n++)
array[index++] = c;
}
}
public bool Remove (byte item)
{
int count = 0;
int i;
// find the index of the element we need to remove
for (i = 0; i <= cursor; i++) {
if (item == (byte) (buffer[i] & 0xFF)) {
count = ((buffer[i] >> 8) & 0xFF);
break;
}
}
if (i > cursor)
return false;
if (count > 1) {
// this byte was repeated more than once, so just decrement the count
buffer[i] = (ushort) (((count - 1) << 8) | item);
} else if (i < cursor) {
// to remove the element at position i, we need to shift the
// remaining data one item to the left
Array.Copy (buffer, i + 1, buffer, i, cursor - i);
cursor--;
} else {
// removing the last byte added
cursor--;
}
length--;
return true;
}
#endregion
#region IList implementation
public int IndexOf (byte item)
{
int offset = 0;
for (int i = 0; i <= cursor; i++) {
if (item == (byte) (buffer[i] & 0xFF))
return offset;
offset += ((buffer[i] >> 8) & 0xFF);
}
return -1;
}
public void Insert (int index, byte item)
{
throw new NotSupportedException ();
}
public void RemoveAt (int index)
{
if (index < 0 || index > length)
throw new ArgumentOutOfRangeException ("index");
int offset = 0;
int count = 0;
int i;
// find the index of the element we need to remove
for (i = 0; i <= cursor; i++) {
count = ((buffer[i] >> 8) & 0xFF);
if (offset + count > index)
break;
offset += count;
}
if (count > 1) {
// this byte was repeated more than once, so just decrement the count
byte c = (byte) (buffer[i] & 0xFF);
buffer[i] = (ushort) (((count - 1) << 8) | c);
} else if (i < cursor) {
// to remove the element at position i, we need to shift the
// remaining data one item to the left
Array.Copy (buffer, i + 1, buffer, i, cursor - i);
cursor--;
} else {
// removing the last byte added
cursor--;
}
length--;
}
public byte this [int index] {
get {
if (index < 0 || index > length)
throw new ArgumentOutOfRangeException ("index");
int offset = 0;
int count, i;
for (i = 0; i <= cursor; i++) {
count = ((buffer[i] >> 8) & 0xFF);
if (offset + count > index)
break;
offset += count;
}
return (byte) (buffer[i] & 0xFF);
}
set {
throw new NotSupportedException ();
}
}
#endregion
#region IEnumerable implementation
public IEnumerator<byte> GetEnumerator ()
{
int count;
byte c;
for (int i = 0; i <= cursor; i++) {
count = (buffer[i] >> 8) & 0xFF;
c = (byte) (buffer[i] & 0xFF);
for (int n = 0; n < count; n++)
yield return c;
}
yield break;
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
}
| |
// Copyright ?2004, 2013, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// 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; version 2 of the License.
//
// 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.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using MySql.Data.Types;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Collections;
#if !RT
using System.Data;
using System.Data.Common;
#endif
namespace MySql.Data.MySqlClient
{
/// <summary>
/// Represents a parameter to a <see cref="MySqlCommand"/>, and optionally, its mapping to <see cref="DataSet"/> columns. This class cannot be inherited.
/// </summary>
public sealed partial class MySqlParameter : ICloneable
{
private const int UNSIGNED_MASK = 0x8000;
private object paramValue;
private string paramName;
private MySqlDbType mySqlDbType;
private bool inferType = true;
private const int GEOMETRY_LENGTH = 25;
#region Constructors
public MySqlParameter()
{
Init();
}
/// <summary>
/// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name and a value of the new MySqlParameter.
/// </summary>
/// <param name="parameterName">The name of the parameter to map. </param>
/// <param name="value">An <see cref="Object"/> that is the value of the <see cref="MySqlParameter"/>. </param>
public MySqlParameter(string parameterName, object value) : this()
{
ParameterName = parameterName;
Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name and the data type.
/// </summary>
/// <param name="parameterName">The name of the parameter to map. </param>
/// <param name="dbType">One of the <see cref="MySqlDbType"/> values. </param>
public MySqlParameter(string parameterName, MySqlDbType dbType) : this(parameterName, null)
{
MySqlDbType = dbType;
}
/// <summary>
/// Initializes a new instance of the <see cref="MySqlParameter"/> class with the parameter name, the <see cref="MySqlDbType"/>, and the size.
/// </summary>
/// <param name="parameterName">The name of the parameter to map. </param>
/// <param name="dbType">One of the <see cref="MySqlDbType"/> values. </param>
/// <param name="size">The length of the parameter. </param>
public MySqlParameter(string parameterName, MySqlDbType dbType, int size) : this(parameterName, dbType)
{
Size = size;
}
partial void Init();
#endregion
#region Properties
[Category("Misc")]
public override String ParameterName
{
get { return paramName; }
set { SetParameterName(value); }
}
internal MySqlParameterCollection Collection { get; set; }
internal Encoding Encoding { get; set; }
internal bool TypeHasBeenSet
{
get { return inferType == false; }
}
internal string BaseName
{
get
{
if (ParameterName.StartsWith("@", StringComparison.Ordinal) || ParameterName.StartsWith("?", StringComparison.Ordinal))
return ParameterName.Substring(1);
return ParameterName;
}
}
/// <summary>
/// Gets or sets a value indicating whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter.
/// As of MySql version 4.1 and earlier, input-only is the only valid choice.
/// </summary>
[Category("Data")]
public override ParameterDirection Direction { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the parameter accepts null values.
/// </summary>
[Browsable(false)]
public override Boolean IsNullable { get; set; }
/// <summary>
/// Gets or sets the MySqlDbType of the parameter.
/// </summary>
[Category("Data")]
[DbProviderSpecificTypeProperty(true)]
public MySqlDbType MySqlDbType
{
get { return mySqlDbType; }
set
{
SetMySqlDbType(value);
inferType = false;
}
}
/// <summary>
/// Gets or sets the maximum number of digits used to represent the <see cref="Value"/> property.
/// </summary>
[Category("Data")]
public byte Precision { get; set; }
/// <summary>
/// Gets or sets the number of decimal places to which <see cref="Value"/> is resolved.
/// </summary>
[Category("Data")]
public byte Scale { get; set; }
/// <summary>
/// Gets or sets the maximum size, in bytes, of the data within the column.
/// </summary>
[Category("Data")]
public override int Size { get; set; }
/// <summary>
/// Gets or sets the value of the parameter.
/// </summary>
#if !RT
[TypeConverter(typeof(StringConverter))]
[Category("Data")]
#endif
public override object Value
{
get { return paramValue; }
set
{
paramValue = value;
byte[] valueAsByte = value as byte[];
string valueAsString = value as string;
if (valueAsByte != null)
Size = valueAsByte.Length;
else if (valueAsString != null)
Size = valueAsString.Length;
if (inferType)
SetTypeFromValue();
}
}
private IMySqlValue _valueObject;
internal IMySqlValue ValueObject
{
get { return _valueObject; }
private set
{
_valueObject = value;
}
}
/// <summary>
/// Returns the possible values for this parameter if this parameter is of type
/// SET or ENUM. Returns null otherwise.
/// </summary>
public IList PossibleValues { get; internal set; }
#endregion
private void SetParameterName(string name)
{
if (Collection != null)
Collection.ParameterNameChanged(this, paramName, name);
paramName = name;
}
/// <summary>
/// Overridden. Gets a string containing the <see cref="ParameterName"/>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return paramName;
}
internal int GetPSType()
{
switch (mySqlDbType)
{
case MySqlDbType.Bit:
return (int)MySqlDbType.Int64 | UNSIGNED_MASK;
case MySqlDbType.UByte:
return (int)MySqlDbType.Byte | UNSIGNED_MASK;
case MySqlDbType.UInt64:
return (int)MySqlDbType.Int64 | UNSIGNED_MASK;
case MySqlDbType.UInt32:
return (int)MySqlDbType.Int32 | UNSIGNED_MASK;
case MySqlDbType.UInt24:
return (int)MySqlDbType.Int32 | UNSIGNED_MASK;
case MySqlDbType.UInt16:
return (int)MySqlDbType.Int16 | UNSIGNED_MASK;
default:
return (int)mySqlDbType;
}
}
internal void Serialize(MySqlPacket packet, bool binary, MySqlConnectionStringBuilder settings)
{
if (!binary && (paramValue == null || paramValue == DBNull.Value))
packet.WriteStringNoNull("NULL");
else
{
if (ValueObject.MySqlDbType == MySqlDbType.Guid)
{
MySqlGuid g = (MySqlGuid)ValueObject;
g.OldGuids = settings.OldGuids;
ValueObject = g;
}
if (ValueObject.MySqlDbType == MySqlDbType.Geometry)
{
MySqlGeometry v = (MySqlGeometry)ValueObject;
if (v.IsNull && Value != null)
{
MySqlGeometry.TryParse(Value.ToString(), out v);
}
ValueObject = v;
}
ValueObject.WriteValue(packet, binary, paramValue, Size);
}
}
partial void SetDbTypeFromMySqlDbType();
private void SetMySqlDbType(MySqlDbType mysql_dbtype)
{
mySqlDbType = mysql_dbtype;
ValueObject = MySqlField.GetIMySqlValue(mySqlDbType);
SetDbTypeFromMySqlDbType();
}
private void SetTypeFromValue()
{
if (paramValue == null || paramValue == DBNull.Value) return;
if (paramValue is Guid)
MySqlDbType = MySqlDbType.Guid;
else if (paramValue is TimeSpan)
MySqlDbType = MySqlDbType.Time;
else if (paramValue is bool)
MySqlDbType = MySqlDbType.Byte;
else
{
Type t = paramValue.GetType();
switch (t.Name)
{
case "SByte": MySqlDbType = MySqlDbType.Byte; break;
case "Byte": MySqlDbType = MySqlDbType.UByte; break;
case "Int16": MySqlDbType = MySqlDbType.Int16; break;
case "UInt16": MySqlDbType = MySqlDbType.UInt16; break;
case "Int32": MySqlDbType = MySqlDbType.Int32; break;
case "UInt32": MySqlDbType = MySqlDbType.UInt32; break;
case "Int64": MySqlDbType = MySqlDbType.Int64; break;
case "UInt64": MySqlDbType = MySqlDbType.UInt64; break;
case "DateTime": MySqlDbType = MySqlDbType.DateTime; break;
case "String": MySqlDbType = MySqlDbType.VarChar; break;
case "Single": MySqlDbType = MySqlDbType.Float; break;
case "Double": MySqlDbType = MySqlDbType.Double; break;
case "Decimal": MySqlDbType = MySqlDbType.Decimal; break;
case "Object":
default:
#if RT
if (t.GetTypeInfo().BaseType == typeof(Enum))
#else
if( t.BaseType == typeof( Enum ) )
#endif
MySqlDbType = MySqlDbType.Int32;
else
MySqlDbType = MySqlDbType.Blob;
break;
}
}
}
#region ICloneable
public MySqlParameter Clone()
{
#if RT
MySqlParameter clone = new MySqlParameter(paramName, mySqlDbType);
#else
MySqlParameter clone = new MySqlParameter(paramName, mySqlDbType, Direction, SourceColumn, SourceVersion, paramValue);
#endif
// if we have not had our type set yet then our clone should not either
clone.inferType = inferType;
return clone;
}
object ICloneable.Clone()
{
return this.Clone();
}
#endregion
// this method is pretty dumb but we want it to be fast. it doesn't return size based
// on value and type but just on the value.
internal long EstimatedSize()
{
if (Value == null || Value == DBNull.Value)
return 4; // size of NULL
if (Value is byte[])
return (Value as byte[]).Length;
if (Value is string)
return (Value as string).Length * 4; // account for UTF-8 (yeah I know)
if (Value is decimal || Value is float)
return 64;
return 32;
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementSimpleIf()
{
string source = @"
class P
{
private void M()
{
bool condition = false;
/*<bind>*/if (true)
{
condition = true;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... }')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'condition = true;')
Expression:
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Boolean) (Syntax: 'condition = true')
Left:
ILocalReferenceExpression: condition (OperationKind.LocalReferenceExpression, Type: System.Boolean) (Syntax: 'condition')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfFalse:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0219: The variable 'condition' is assigned but its value is never used
// bool condition = false;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "condition").WithArguments("condition").WithLocation(6, 14)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementSimpleIfWithElse()
{
string source = @"
class P
{
private void M()
{
bool condition = false;
/*<bind>*/if (true)
{
condition = true;
}
else
{
condition = false;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... }')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'condition = true;')
Expression:
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Boolean) (Syntax: 'condition = true')
Left:
ILocalReferenceExpression: condition (OperationKind.LocalReferenceExpression, Type: System.Boolean) (Syntax: 'condition')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfFalse:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'condition = false;')
Expression:
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Boolean) (Syntax: 'condition = false')
Left:
ILocalReferenceExpression: condition (OperationKind.LocalReferenceExpression, Type: System.Boolean) (Syntax: 'condition')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: False) (Syntax: 'false')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0162: Unreachable code detected
// condition = false;
Diagnostic(ErrorCode.WRN_UnreachableCode, "condition").WithLocation(13, 13),
// CS0219: The variable 'condition' is assigned but its value is never used
// bool condition = false;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "condition").WithArguments("condition").WithLocation(6, 14)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementSimpleIfWithConditionEvaluationTrue()
{
string source = @"
class P
{
private void M()
{
bool condition = false;
/*<bind>*/if (1 == 1)
{
condition = true;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (1 == 1) ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.Equals) (OperationKind.BinaryOperatorExpression, Type: System.Boolean, Constant: True) (Syntax: '1 == 1')
Left:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'condition = true;')
Expression:
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Boolean) (Syntax: 'condition = true')
Left:
ILocalReferenceExpression: condition (OperationKind.LocalReferenceExpression, Type: System.Boolean) (Syntax: 'condition')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfFalse:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0219: The variable 'condition' is assigned but its value is never used
// bool condition = false;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "condition").WithArguments("condition").WithLocation(6, 14)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementSimpleIfNested1()
{
string source = @"
using System;
class P
{
private void M()
{
int m = 12;
int n = 18;
/*<bind>*/if (m > 10)
{
if (n > 20)
Console.WriteLine(m);
}
else
{
Console.WriteLine(n);
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (m > 10) ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThan) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'm > 10')
Left:
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 10) (Syntax: '10')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (n > 20) ... iteLine(m);')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThan) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'n > 20')
Left:
ILocalReferenceExpression: n (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'n')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 20) (Syntax: '20')
IfTrue:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(m);')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.Int32 value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(m)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'm')
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
IfFalse:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(n);')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.Int32 value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(n)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'n')
ILocalReferenceExpression: n (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'n')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementSimpleIfNested2()
{
string source = @"
using System;
class P
{
private void M()
{
int m = 9;
int n = 7;
/*<bind>*/if (m > 10)
if (n > 20)
{
Console.WriteLine(m);
}
else
{
Console.WriteLine(n);
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (m > 10) ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThan) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'm > 10')
Left:
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 10) (Syntax: '10')
IfTrue:
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (n > 20) ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThan) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'n > 20')
Left:
ILocalReferenceExpression: n (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'n')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 20) (Syntax: '20')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(m);')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.Int32 value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(m)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'm')
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(n);')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.Int32 value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(n)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'n')
ILocalReferenceExpression: n (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'n')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithMultipleCondition()
{
string source = @"
using System;
class P
{
private void M()
{
int m = 9;
int n = 7;
int p = 5;
/*<bind>*/if (m >= n && m >= p)
{
Console.WriteLine(""Nothing is larger than m."");
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (m >= n ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.And) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'm >= n && m >= p')
Left:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'm >= n')
Left:
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
Right:
ILocalReferenceExpression: n (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'n')
Right:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'm >= p')
Left:
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
Right:
ILocalReferenceExpression: p (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'p')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.Wri ... than m."");')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.Wri ... r than m."")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '""Nothing is ... er than m.""')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""Nothing is larger than m."") (Syntax: '""Nothing is ... er than m.""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithElseIfCondition()
{
string source = @"
using System;
class P
{
private void M()
{
int m = 9;
int n = 7;
/*<bind>*/if (n > 20)
{
Console.WriteLine(""Result1"");
}
else if (m > 10)
{
Console.WriteLine(""Result2"");
}
else
{
Console.WriteLine(""Result3"");
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (n > 20) ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThan) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'n > 20')
Left:
ILocalReferenceExpression: n (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'n')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 20) (Syntax: '20')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.Wri ... ""Result1"");')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.Wri ... (""Result1"")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '""Result1""')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""Result1"") (Syntax: '""Result1""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (m > 10) ... }')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThan) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'm > 10')
Left:
ILocalReferenceExpression: m (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'm')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 10) (Syntax: '10')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.Wri ... ""Result2"");')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.Wri ... (""Result2"")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '""Result2""')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""Result2"") (Syntax: '""Result2""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.Wri ... ""Result3"");')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.Wri ... (""Result3"")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '""Result3""')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""Result3"") (Syntax: '""Result3""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithElseIfConditionOutVar()
{
string source = @"
class P
{
private void M()
{
var s = """";
/*<bind>*/if (int.TryParse(s, out var i))
System.Console.WriteLine($""i ={i}, s ={s}"");
else
System.Console.WriteLine($""i ={i}, s ={s}"");/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (int.Try ... , s ={s}"");')
Condition:
IInvocationExpression (System.Boolean System.Int32.TryParse(System.String s, out System.Int32 result)) (OperationKind.InvocationExpression, Type: System.Boolean) (Syntax: 'int.TryPars ... out var i)')
Instance Receiver:
null
Arguments(2):
IArgument (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument) (Syntax: 's')
ILocalReferenceExpression: s (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgument (ArgumentKind.Explicit, Matching Parameter: result) (OperationKind.Argument) (Syntax: 'out var i')
ILocalReferenceExpression: i (IsDeclaration: True) (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'var i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfTrue:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'System.Cons ... , s ={s}"");')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'System.Cons ... }, s ={s}"")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '$""i ={i}, s ={s}""')
IInterpolatedStringExpression (OperationKind.InterpolatedStringExpression, Type: System.String) (Syntax: '$""i ={i}, s ={s}""')
Parts(4):
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: 'i =')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""i ="") (Syntax: 'i =')
IInterpolation (OperationKind.Interpolation) (Syntax: '{i}')
Expression:
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i')
Alignment:
null
FormatString:
null
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: ', s =')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "", s ="") (Syntax: ', s =')
IInterpolation (OperationKind.Interpolation) (Syntax: '{s}')
Expression:
ILocalReferenceExpression: s (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 's')
Alignment:
null
FormatString:
null
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'System.Cons ... , s ={s}"");')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'System.Cons ... }, s ={s}"")')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: '$""i ={i}, s ={s}""')
IInterpolatedStringExpression (OperationKind.InterpolatedStringExpression, Type: System.String) (Syntax: '$""i ={i}, s ={s}""')
Parts(4):
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: 'i =')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""i ="") (Syntax: 'i =')
IInterpolation (OperationKind.Interpolation) (Syntax: '{i}')
Expression:
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i')
Alignment:
null
FormatString:
null
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: ', s =')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "", s ="") (Syntax: ', s =')
IInterpolation (OperationKind.Interpolation) (Syntax: '{s}')
Expression:
ILocalReferenceExpression: s (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 's')
Alignment:
null
FormatString:
null
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithOutVar()
{
string source = @"
class P
{
private void M()
{
/*<bind>*/if (true)
System.Console.WriteLine(A());/*</bind>*/
}
private int A()
{
var s = """";
if (int.TryParse(s, out var i))
{
return i;
}
else
{
return -1;
}
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... eLine(A());')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'System.Cons ... eLine(A());')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.Int32 value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'System.Cons ... teLine(A())')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'A()')
IInvocationExpression ( System.Int32 P.A()) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'A()')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: P, IsImplicit) (Syntax: 'A')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementExplictEmbeddedOutVar()
{
string source = @"
class P
{
private void M()
{
var s = ""data"";
/*<bind>*/if (true)
{
A(int.TryParse(s, out var i));
}/*</bind>*/
}
private void A(bool flag)
{
if (flag)
{
System.Console.WriteLine(""Result1"");
}
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... }')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IBlockStatement (1 statements, 1 locals) (OperationKind.BlockStatement) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 i
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'A(int.TryPa ... ut var i));')
Expression:
IInvocationExpression ( void P.A(System.Boolean flag)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'A(int.TryPa ... out var i))')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: P, IsImplicit) (Syntax: 'A')
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: flag) (OperationKind.Argument) (Syntax: 'int.TryPars ... out var i)')
IInvocationExpression (System.Boolean System.Int32.TryParse(System.String s, out System.Int32 result)) (OperationKind.InvocationExpression, Type: System.Boolean) (Syntax: 'int.TryPars ... out var i)')
Instance Receiver:
null
Arguments(2):
IArgument (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument) (Syntax: 's')
ILocalReferenceExpression: s (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgument (ArgumentKind.Explicit, Matching Parameter: result) (OperationKind.Argument) (Syntax: 'out var i')
ILocalReferenceExpression: i (IsDeclaration: True) (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'var i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementImplicitEmbeddedOutVar()
{
string source = @"
class Program
{
static void Main(string[] args)
{
object o = 25;
/*<bind>*/if (true)
A(o is int i, 1);/*</bind>*/
}
private static void A(bool flag, int number)
{
if (flag)
{
System.Console.WriteLine(new string('*', number));
}
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... int i, 1);')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IBlockStatement (1 statements, 1 locals) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'A(o is int i, 1);')
Locals: Local_1: System.Int32 i
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'A(o is int i, 1);')
Expression:
IInvocationExpression (void Program.A(System.Boolean flag, System.Int32 number)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'A(o is int i, 1)')
Instance Receiver:
null
Arguments(2):
IArgument (ArgumentKind.Explicit, Matching Parameter: flag) (OperationKind.Argument) (Syntax: 'o is int i')
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean) (Syntax: 'o is int i')
Expression:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'o')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 i) (OperationKind.DeclarationPattern) (Syntax: 'int i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgument (ArgumentKind.Explicit, Matching Parameter: number) (OperationKind.Argument) (Syntax: '1')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithConditionPattern()
{
string source = @"
using System;
class P
{
private void M()
{
object obj = ""pattern"";
/*<bind>*/if (obj is string str)
{
Console.WriteLine(str);
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (obj is ... }')
Condition:
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean) (Syntax: 'obj is string str')
Expression:
ILocalReferenceExpression: obj (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'obj')
Pattern:
IDeclarationPattern (Declared Symbol: System.String str) (OperationKind.DeclarationPattern) (Syntax: 'string str')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(str);')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(str)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'str')
ILocalReferenceExpression: str (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 'str')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithPattern()
{
string source = @"
class Program
{
static void Main(string[] args)
{
/*<bind>*/if (true)
A(25);/*</bind>*/
}
private static void A(object o)
{
if (o is null) return;
if (!(o is int i)) return;
System.Console.WriteLine(new string('*', i));
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... A(25);')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'A(25);')
Expression:
IInvocationExpression (void Program.A(System.Object o)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'A(25)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument) (Syntax: '25')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: '25')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 25) (Syntax: '25')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithEmbeddedPattern()
{
string source = @"
class Program
{
static void Main(string[] args)
{
object o = 25;
/*<bind>*/if (true)
{
A(o is int i, 1);
}/*</bind>*/
}
private static void A(bool flag, int number)
{
if (flag)
{
System.Console.WriteLine(new string('*', number));
}
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... }')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IBlockStatement (1 statements, 1 locals) (OperationKind.BlockStatement) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 i
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'A(o is int i, 1);')
Expression:
IInvocationExpression (void Program.A(System.Boolean flag, System.Int32 number)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'A(o is int i, 1)')
Instance Receiver:
null
Arguments(2):
IArgument (ArgumentKind.Explicit, Matching Parameter: flag) (OperationKind.Argument) (Syntax: 'o is int i')
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean) (Syntax: 'o is int i')
Expression:
ILocalReferenceExpression: o (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'o')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 i) (OperationKind.DeclarationPattern) (Syntax: 'int i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgument (ArgumentKind.Explicit, Matching Parameter: number) (OperationKind.Argument) (Syntax: '1')
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithElseMissing()
{
string source = @"
using System;
class P
{
private void M()
{
object obj = ""pattern"";
/*<bind>*/if (obj is string str)
{
Console.WriteLine(str);
}
else
/*</bind>*/ }
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement, IsInvalid) (Syntax: 'if (obj is ... else')
Condition:
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean) (Syntax: 'obj is string str')
Expression:
ILocalReferenceExpression: obj (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'obj')
Pattern:
IDeclarationPattern (Declared Symbol: System.String str) (OperationKind.DeclarationPattern) (Syntax: 'string str')
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(str);')
Expression:
IInvocationExpression (void System.Console.WriteLine(System.String value)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(str)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'str')
ILocalReferenceExpression: str (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 'str')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfFalse:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: '')
Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: null) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term '}'
// else
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}").WithLocation(14, 13),
// CS1002: ; expected
// else
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(14, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithConditionMissing()
{
string source = @"
using System;
class P
{
private void M()
{
int a = 1;
/*<bind>*/if ()
{
a = 2;
}
else
{
a = 3;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement, IsInvalid) (Syntax: 'if () ... }')
Condition:
IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '')
Children(0)
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'a = 2')
Left:
ILocalReferenceExpression: a (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2')
IfFalse:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'a = 3;')
Expression:
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'a = 3')
Left:
ILocalReferenceExpression: a (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ')'
// /*<bind>*/if ()
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 23),
// CS0219: The variable 'a' is assigned but its value is never used
// int a = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(8, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithStatementMissing()
{
string source = @"
using System;
class P
{
private void M()
{
int a = 1;
/*<bind>*/if (a == 1)
else
/*</bind>*/
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement, IsInvalid) (Syntax: 'if (a == 1) ... else')
Condition:
IBinaryOperatorExpression (BinaryOperatorKind.Equals) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'a == 1')
Left:
ILocalReferenceExpression: a (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
IfTrue:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: '')
Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: null) (Syntax: '')
Children(0)
IfFalse:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: '')
Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: null) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'else'
// /*<bind>*/if (a == 1)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("else").WithLocation(10, 30),
// CS1002: ; expected
// /*<bind>*/if (a == 1)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(10, 30),
// CS1525: Invalid expression term '}'
// else
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}").WithLocation(11, 13),
// CS1002: ; expected
// else
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithFuncCall()
{
string source = @"
using System;
class P
{
private void M()
{
/*<bind>*/if (true)
A();
else
B();/*</bind>*/
}
private void A()
{
Console.WriteLine(""A"");
}
private void B()
{
Console.WriteLine(""B"");
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (true) ... B();')
Condition:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True) (Syntax: 'true')
IfTrue:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'A();')
Expression:
IInvocationExpression ( void P.A()) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'A()')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: P, IsImplicit) (Syntax: 'A')
Arguments(0)
IfFalse:
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'B();')
Expression:
IInvocationExpression ( void P.B()) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'B()')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: P, IsImplicit) (Syntax: 'B')
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0162: Unreachable code detected
// B();/*</bind>*/
Diagnostic(ErrorCode.WRN_UnreachableCode, "B").WithLocation(11, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17601, "https://github.com/dotnet/roslyn/issues/17601")]
public void IIfstatementWithDynamic()
{
string source = @"
using System;
class C
{
public static int F<T>(dynamic d, Type t, T x) where T : struct
{
/*<bind>*/if (d.GetType() == t && ((T)d).Equals(x))
{
return 1;
}/*</bind>*/
return 2;
}
}
";
string expectedOperationTree = @"
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (d.GetTy ... }')
Condition:
IUnaryOperatorExpression (UnaryOperatorKind.True) (OperationKind.UnaryOperatorExpression, Type: System.Boolean, IsImplicit) (Syntax: 'd.GetType() ... ).Equals(x)')
Operand:
IBinaryOperatorExpression (BinaryOperatorKind.And) (OperationKind.BinaryOperatorExpression, Type: dynamic) (Syntax: 'd.GetType() ... ).Equals(x)')
Left:
IBinaryOperatorExpression (BinaryOperatorKind.Equals) (OperationKind.BinaryOperatorExpression, Type: dynamic) (Syntax: 'd.GetType() == t')
Left:
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'd.GetType()')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""GetType"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: dynamic) (Syntax: 'd.GetType')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
Arguments(0)
ArgumentNames(0)
ArgumentRefKinds(0)
Right:
IParameterReferenceExpression: t (OperationKind.ParameterReferenceExpression, Type: System.Type) (Syntax: 't')
Right:
IInvocationExpression (virtual System.Boolean System.ValueType.Equals(System.Object obj)) (OperationKind.InvocationExpression, Type: System.Boolean) (Syntax: '((T)d).Equals(x)')
Instance Receiver:
IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: T) (Syntax: '(T)d')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: obj) (OperationKind.Argument) (Syntax: 'x')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: T) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfTrue:
IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IReturnStatement (OperationKind.ReturnStatement) (Syntax: 'return 1;')
ReturnedValue:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
IfFalse:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IfStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// HttpRetry operations.
/// </summary>
public partial class HttpRetry : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRetry
{
/// <summary>
/// Initializes a new instance of the HttpRetry class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public HttpRetry(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 408 status code, then 200 after retry
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Head408WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head408", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/408").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Put500WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Put500", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/500").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Patch500WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Patch500", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/500").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 502 status code, then 200 after retry
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Get502WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get502", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/502").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Post503WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post503", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/503").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Delete503WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete503", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/503").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Put504WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Put504", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> Patch504WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Patch504", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias PDB;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.SymReaderInterop;
using Roslyn.Test.Utilities;
using Xunit;
using PDB::Roslyn.Test.MetadataUtilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class Scope
{
internal readonly int StartOffset;
internal readonly int EndOffset;
internal readonly ImmutableArray<string> Locals;
internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive)
{
this.StartOffset = startOffset;
this.EndOffset = endOffset + (isEndInclusive ? 1 : 0);
this.Locals = locals;
}
internal int Length
{
get { return this.EndOffset - this.StartOffset + 1; }
}
internal bool Contains(int offset)
{
return (offset >= this.StartOffset) && (offset < this.EndOffset);
}
}
internal static class ExpressionCompilerTestHelpers
{
internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName)
{
return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName));
}
internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName)
{
return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName));
}
internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName)
{
return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName));
}
internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames)
{
var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray();
Assert.True(expectedNames.SequenceEqual(actualNames));
}
internal static AssemblyName GetAssemblyName(this byte[] exeBytes)
{
using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes)))
{
var metadataReader = reader.GetMetadataReader();
var def = metadataReader.GetAssemblyDefinition();
var name = metadataReader.GetString(def.Name);
return new AssemblyName() { Name = name, Version = def.Version };
}
}
internal static Guid GetModuleVersionId(this byte[] exeBytes)
{
using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes)))
{
return reader.GetMetadataReader().GetModuleVersionId();
}
}
/// <summary>
/// Helper method to write the bytes to a file.
/// </summary>
[Conditional("DEBUG")]
internal static void WriteBytes(this ImmutableArray<byte> bytes, string path = null)
{
if (path == null)
{
path = Path.Combine(Path.GetTempPath(), "__ee_temp.dll");
}
File.WriteAllBytes(path, bytes.ToArray());
}
internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1)
{
var method = symReader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
return ImmutableArray<string>.Empty;
}
var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
method.GetAllScopes(scopes);
var names = ArrayBuilder<string>.GetInstance();
foreach (var scope in scopes)
{
var locals = scope.GetLocals();
foreach (var local in locals)
{
var name = local.GetName();
int slot;
local.GetAddressField1(out slot);
while (names.Count <= slot)
{
names.Add(null);
}
names[slot] = name;
}
}
scopes.Free();
return names.ToImmutableAndFree();
}
internal static void VerifyIL(
this ImmutableArray<byte> assembly,
string qualifiedName,
string expectedIL,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
var parts = qualifiedName.Split('.');
if (parts.Length != 2)
{
throw new NotImplementedException();
}
using (var module = new PEModule(new PEReader(assembly), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0))
{
var reader = module.MetadataReader;
var typeDef = reader.GetTypeDef(parts[0]);
var methodName = parts[1];
var methodHandle = reader.GetMethodDefHandle(typeDef, methodName);
var methodBody = module.GetMethodBodyOrThrow(methodHandle);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
var writer = new StringWriter(pooled.Builder);
var visualizer = new MetadataVisualizer(reader, writer);
visualizer.VisualizeMethodBody(methodBody, methodHandle, emitHeader: false);
var actualIL = pooled.ToStringAndFree();
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine);
}
}
internal static bool EmitAndGetReferences(
this Compilation compilation,
out byte[] exeBytes,
out byte[] pdbBytes,
out ImmutableArray<MetadataReference> references)
{
using (var pdbStream = new MemoryStream())
{
using (var exeStream = new MemoryStream())
{
var result = compilation.Emit(
peStream: exeStream,
pdbStream: pdbStream,
xmlDocumentationStream: null,
win32Resources: null,
manifestResources: null,
options: EmitOptions.Default,
testData: null,
cancellationToken: default(CancellationToken));
if (!result.Success)
{
result.Diagnostics.Verify();
exeBytes = null;
pdbBytes = null;
references = default(ImmutableArray<MetadataReference>);
return false;
}
exeBytes = exeStream.ToArray();
pdbBytes = pdbStream.ToArray();
}
}
// Determine the set of references that were actually used
// and ignore any references that were dropped in emit.
HashSet<string> referenceNames;
using (var metadata = ModuleMetadata.CreateFromImage(exeBytes))
{
var reader = metadata.MetadataReader;
referenceNames = new HashSet<string>(reader.AssemblyReferences.Select(h => GetAssemblyReferenceName(reader, h)));
}
references = ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames)));
return true;
}
internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive)
{
var method = symReader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
return ImmutableArray<Scope>.Empty;
}
var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
method.GetAllScopes(scopes);
var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), s.GetLocals().SelectAsArray(l => l.GetName()), isEndInclusive));
scopes.Free();
return result;
}
internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset)
{
Scope result = null;
foreach (var scope in scopes)
{
if (scope.Contains(offset))
{
if ((result == null) || (result.Length > scope.Length))
{
result = scope;
}
}
}
return result;
}
private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle)
{
var reference = reader.GetAssemblyReference(handle);
return reader.GetString(reference.Name);
}
private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames)
{
var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadata() as AssemblyMetadata;
if (assemblyMetadata == null)
{
// Netmodule. Assume it is referenced.
return true;
}
var name = assemblyMetadata.GetAssembly().Identity.Name;
return referenceNames.Contains(name);
}
/// <summary>
/// Verify the set of module metadata blocks
/// contains all blocks referenced by the set.
/// </summary>
internal static void VerifyAllModules(this ImmutableArray<ModuleInstance> modules)
{
var blocks = modules.SelectAsArray(m => m.MetadataBlock).SelectAsArray(b => ModuleMetadata.CreateFromMetadata(b.Pointer, b.Size));
var names = new HashSet<string>(blocks.Select(b => b.Name));
foreach (var block in blocks)
{
foreach (var name in block.GetModuleNames())
{
Assert.True(names.Contains(name));
}
}
}
internal static ModuleInstance ToModuleInstance(
this MetadataReference reference,
byte[] fullImage,
object symReader,
bool includeLocalSignatures = true)
{
var metadata = ((MetadataImageReference)reference).GetMetadata();
var assemblyMetadata = metadata as AssemblyMetadata;
Assert.True((assemblyMetadata == null) || (assemblyMetadata.GetModules().Length == 1));
var moduleMetadata = (assemblyMetadata == null) ? (ModuleMetadata)metadata : assemblyMetadata.GetModules()[0];
var moduleId = moduleMetadata.Module.GetModuleVersionIdOrThrow();
// The Expression Compiler expects metadata only, no headers or IL.
var metadataBytes = moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent().ToArray();
return new ModuleInstance(
reference,
moduleMetadata,
moduleId,
fullImage,
metadataBytes,
symReader,
includeLocalSignatures);
}
internal static void VerifyLocal<TMethodSymbol>(
this CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
DkmClrCompilationResultFlags expectedFlags,
Action<TMethodSymbol> verifyTypeParameters,
string expectedILOpt,
bool expectedGeneric,
string expectedValueSourcePath,
int expectedValueSourceLine)
where TMethodSymbol : IMethodSymbol
{
Assert.Equal(expectedLocalName, localAndMethod.LocalName);
Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters.
Assert.Equal(expectedFlags, localAndMethod.Flags);
var methodData = testData.GetMethodData(typeName + "." + expectedMethodName);
verifyTypeParameters((TMethodSymbol)methodData.Method);
if (expectedILOpt != null)
{
string actualIL = methodData.GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
expectedILOpt,
actualIL,
escapeQuotes: true,
expectedValueSourcePath: expectedValueSourcePath,
expectedValueSourceLine: expectedValueSourceLine);
}
Assert.Equal(((Cci.IMethodDefinition)methodData.Method).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default);
}
internal static ISymUnmanagedReader ConstructSymReaderWithImports(byte[] exeBytes, string methodName, params string[] importStrings)
{
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName));
var methodToken = metadataReader.GetToken(methodHandle);
return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfo>
{
{ methodToken, new MethodDebugInfo.Builder(new [] { importStrings }).Build() },
}.ToImmutableDictionary());
}
}
/// <summary>
/// Return MetadataReferences to the .winmd assemblies
/// for the given namespaces.
/// </summary>
internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces)
{
var paths = new HashSet<string>();
foreach (var @namespace in namespaces)
{
foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null))
{
paths.Add(path);
}
}
return ImmutableArray.CreateRange(paths.Select(GetAssembly));
}
private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319";
private const string Version1_3String = "WindowsRuntime 1.3";
private const string Version1_4String = "WindowsRuntime 1.4";
private static readonly int s_versionStringLength = Version1_3CLRString.Length;
private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength);
private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength);
private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength);
private static byte[] ToByteArray(string str, int length)
{
var bytes = new byte[length];
for (int i = 0; i < str.Length; i++)
{
bytes[i] = (byte)str[i];
}
return bytes;
}
internal static byte[] ToVersion1_3(byte[] bytes)
{
return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes);
}
internal static byte[] ToVersion1_4(byte[] bytes)
{
return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes);
}
private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to)
{
int n = bytes.Length;
var copy = new byte[n];
Array.Copy(bytes, copy, n);
int index = IndexOf(copy, from);
Array.Copy(to, 0, copy, index, to.Length);
return copy;
}
private static int IndexOf(byte[] a, byte[] b)
{
int m = b.Length;
int n = a.Length - m;
for (int x = 0; x < n; x++)
{
var matches = true;
for (int y = 0; y < m; y++)
{
if (a[x + y] != b[y])
{
matches = false;
break;
}
}
if (matches)
{
return x;
}
}
return -1;
}
private static MetadataReference GetAssembly(string path)
{
var bytes = File.ReadAllBytes(path);
var metadata = ModuleMetadata.CreateFromImage(bytes);
return metadata.GetReference(filePath: path);
}
internal static int GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber)
{
int ilOffset;
if (symReader == null)
{
ilOffset = 0;
}
else
{
var symMethod = symReader.GetMethod(methodToken);
if (symMethod == null)
{
ilOffset = 0;
}
else
{
var sequencePoints = symMethod.GetSequencePoints();
ilOffset = atLineNumber < 0
? sequencePoints.Where(sp => sp.StartLine != SequencePointList.HiddenSequencePointLine).Select(sp => sp.Offset).FirstOrDefault()
: sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset;
}
}
Assert.InRange(ilOffset, 0, int.MaxValue);
return ilOffset;
}
}
}
| |
using SolidEdgeSpy.Extensions;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Linq;
using System.Text;
namespace SolidEdgeSpy.InteropServices
{
public abstract class ComMemberInfo
{
internal ComTypeInfo _comTypeInfo;
internal string _name = String.Empty;
internal string _description = String.Empty;
internal int _helpContext = 0;
internal string _helpFile = String.Empty;
public ComMemberInfo(ComTypeInfo comTypeInfo)
{
_comTypeInfo = comTypeInfo;
}
public string Name { get { return _name; } }
public string Description { get { return _description; } }
public ComTypeInfo ComTypeInfo { get { return _comTypeInfo; } }
public override string ToString()
{
return _name;
}
}
public class ComFunctionInfo : ComMemberInfo
{
private IntPtr _pFuncDesc = IntPtr.Zero;
private System.Runtime.InteropServices.ComTypes.FUNCDESC _funcDesc;
private List<ComParameterInfo> _parameters = new List<ComParameterInfo>();
private ComParameterInfo _returnParameter;
public ComFunctionInfo(ComTypeInfo parent, IntPtr pFuncDesc)
: base(parent)
{
_pFuncDesc = pFuncDesc;
_funcDesc = pFuncDesc.ToStructure < System.Runtime.InteropServices.ComTypes.FUNCDESC>();
_comTypeInfo.GetITypeInfo().GetDocumentation(_funcDesc.memid, out _name, out _description, out _helpContext, out _helpFile);
if (_description == null) _description = String.Empty;
if (_helpFile == null) _helpFile = String.Empty;
LoadParameters();
}
public ComParameterInfo ReturnParameter { get { return _returnParameter; } }
public ComParameterInfo[] Parameters
{
get
{
if (_parameters == null)
{
LoadParameters();
}
return _parameters.ToArray();
}
}
public System.Runtime.InteropServices.ComTypes.FUNCFLAGS FunctionFlags { get { return (System.Runtime.InteropServices.ComTypes.FUNCFLAGS)_funcDesc.wFuncFlags; } }
public int DispId { get { return _funcDesc.memid; } }
public System.Runtime.InteropServices.ComTypes.INVOKEKIND InvokeKind { get { return _funcDesc.invkind; } }
public bool IsBindable { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FBINDABLE); } }
public bool IsDefaultBind { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FDEFAULTBIND); } }
public bool IsDefaultCollectionElemement { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FDEFAULTCOLLELEM); } }
public bool IsDisplayBindable { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FDISPLAYBIND); } }
public bool IsHidden { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FHIDDEN); } }
public bool IsImmediateBindable { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FIMMEDIATEBIND); } }
public bool IsNonBrowsable { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FNONBROWSABLE); } }
public bool IsReplaceable { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FREPLACEABLE); } }
public bool IsRequestEdit { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FREQUESTEDIT); } }
public bool IsRestricted { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED); } }
public bool IsSource { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FSOURCE); } }
public bool IsUiDefault { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FUIDEFAULT); } }
public bool SupportsGetLastError { get { return FunctionFlags.IsSet(System.Runtime.InteropServices.ComTypes.FUNCFLAGS.FUNCFLAG_FUSESGETLASTERROR); } }
private void LoadParameters()
{
_parameters = new List<ComParameterInfo>();
string[] rgBstrNames = new string[_funcDesc.cParams + 1];
int pcNames = 0;
_comTypeInfo.GetITypeInfo().GetNames(_funcDesc.memid, rgBstrNames, rgBstrNames.Length, out pcNames);
IntPtr pElemDesc = _funcDesc.lprgelemdescParam;
_returnParameter = new ComParameterInfo(this, rgBstrNames[0], _funcDesc.elemdescFunc);
if (_funcDesc.cParams > 0)
{
for (int cParams = 0; cParams < _funcDesc.cParams; cParams++)
{
System.Runtime.InteropServices.ComTypes.ELEMDESC elemDesc = (System.Runtime.InteropServices.ComTypes.ELEMDESC)Marshal.PtrToStructure(pElemDesc, typeof(System.Runtime.InteropServices.ComTypes.ELEMDESC));
_parameters.Add(new ComParameterInfo(this, rgBstrNames[cParams + 1], elemDesc));
pElemDesc = new IntPtr(pElemDesc.ToInt64() + Marshal.SizeOf(typeof(System.Runtime.InteropServices.ComTypes.ELEMDESC)));
}
}
else
{
//list.Add(new ElemDesc(this, m_funcDesc.elemdescFunc, rgBstrNames[0], -1));
}
//m_parameters = list.ToArray();
}
public System.Runtime.InteropServices.ComTypes.FUNCDESC FuncDesc { get { return this._funcDesc; } }
public override string ToString()
{
return Name;
}
public string ToString(bool includeParameters)
{
if (!includeParameters) return ToString();
StringBuilder sb = new StringBuilder();
sb.Append(_name);
if (_parameters.Count > 0)
{
sb.Append('(');
foreach (ComParameterInfo parameter in _parameters)
{
sb.Append(parameter.Name);
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2);
sb.Append(')');
}
else
{
sb.Append("()");
}
return sb.ToString();
}
}
public class ComPropertyInfo : ComMemberInfo
{
private List<ComFunctionInfo> _functions = new List<ComFunctionInfo>();
public ComPropertyInfo(ComTypeInfo parent, ComFunctionInfo[] functions)
: base(parent)
{
_functions.AddRange(functions);
_name = functions[0].Name;
_description = functions[0].Description;
}
public ComFunctionInfo GetFunction
{
get { return _functions.Where(x => x.InvokeKind == System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYGET).FirstOrDefault(); }
}
public ComFunctionInfo SetFunction
{
get
{
return _functions.Where(
x => x.InvokeKind != System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_FUNC).Where(
x => x.InvokeKind != System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYGET)
.FirstOrDefault();
}
}
public bool IsReadOnly
{
get
{
return ((GetFunction != null) && (SetFunction == null));
}
}
public bool IsWriteOnly
{
get
{
return ((SetFunction != null) && (GetFunction == null));
}
}
public bool IsReadWrite
{
get
{
return ((SetFunction != null) && (GetFunction != null));
}
}
public bool GetFunctionHasParameters
{
get
{
ComFunctionInfo getComFunctionInfo = GetFunction;
if (getComFunctionInfo != null)
{
return getComFunctionInfo.Parameters.Length > 0;
}
return false;
}
}
}
public class ComVariableInfo : ComMemberInfo
{
private System.Runtime.InteropServices.ComTypes.VARDESC _varDesc;
private object _constantValue;
public ComVariableInfo(ComTypeInfo parent, System.Runtime.InteropServices.ComTypes.VARDESC varDesc, object constantValue)
: base(parent)
{
_varDesc = varDesc;
_comTypeInfo.GetITypeInfo().GetDocumentation(_varDesc.memid, out _name, out _description, out _helpContext, out _helpFile);
_constantValue = constantValue;
if (_description == null) _description = String.Empty;
if (_helpFile == null) _helpFile = String.Empty;
}
public object ConstantValue { get { return _constantValue; } }
public System.Runtime.InteropServices.ComTypes.VARDESC VariableDescription { get { return _varDesc; } }
public System.Runtime.InteropServices.ComTypes.VARKIND VariableKind { get { return _varDesc.varkind; } }
public System.Runtime.InteropServices.ComTypes.VARFLAGS VariableFlags { get { return (System.Runtime.InteropServices.ComTypes.VARFLAGS)_varDesc.wVarFlags; } }
public bool IsBindable { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FBINDABLE); } }
public bool IsDefaultBind { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FDEFAULTBIND); } }
public bool IsDefaultCollectionElemement { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FDEFAULTCOLLELEM); } }
public bool IsDisplayBindable { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FDISPLAYBIND); } }
public bool IsHidden { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FHIDDEN); } }
public bool IsImmediateBindable { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FIMMEDIATEBIND); } }
public bool IsNonBrowsable { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FNONBROWSABLE); } }
public bool IsReadOnly { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FREADONLY); } }
public bool IsReplaceable { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FREPLACEABLE); } }
public bool IsRequestEdit { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FREQUESTEDIT); } }
public bool IsRestricted { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FRESTRICTED); } }
public bool IsSource { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FSOURCE); } }
public bool IsUiDefault { get { return VariableFlags.IsSet(System.Runtime.InteropServices.ComTypes.VARFLAGS.VARFLAG_FUIDEFAULT); } }
}
public class ComParameterInfo
{
private ComFunctionInfo _comFunctionInfo;
private string _name;
private System.Runtime.InteropServices.ComTypes.ELEMDESC _elemDesc;
public ComParameterInfo(ComFunctionInfo comFunctionInfo, string name, System.Runtime.InteropServices.ComTypes.ELEMDESC elemDesc)
{
_comFunctionInfo = comFunctionInfo;
_name = name;
_elemDesc = elemDesc;
}
public ComFunctionInfo ComFunctionInfo { get { return _comFunctionInfo; } }
public string Name { get { return _name; } }
public System.Runtime.InteropServices.ComTypes.ELEMDESC ELEMDESC { get { return _elemDesc; } }
public System.Runtime.InteropServices.VarEnum VariantType { get { return (System.Runtime.InteropServices.VarEnum)_elemDesc.tdesc.vt; } }
public bool IsIn { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FIN); } }
public bool IsOut { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FOUT); } }
public bool IsLcid { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FLCID); } }
public bool IsRetval { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FRETVAL); } }
public bool IsOptional { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FOPT); } }
public bool HasDefault { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FHASDEFAULT); } }
public bool HasCustomData { get { return _elemDesc.desc.paramdesc.wParamFlags.IsSet(System.Runtime.InteropServices.ComTypes.PARAMFLAG.PARAMFLAG_FHASCUSTDATA); } }
public override string ToString()
{
return _name;
}
}
}
| |
using YAF.Lucene.Net.Store;
using YAF.Lucene.Net.Util;
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Codecs
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Utility class for reading and writing versioned headers.
/// <para/>
/// Writing codec headers is useful to ensure that a file is in
/// the format you think it is.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CodecUtil
{
private CodecUtil() // no instance
{
}
/// <summary>
/// Constant to identify the start of a codec header.
/// </summary>
public static readonly int CODEC_MAGIC = 0x3fd76c17;
/// <summary>
/// Constant to identify the start of a codec footer.
/// </summary>
public static readonly int FOOTER_MAGIC = ~CODEC_MAGIC;
/// <summary>
/// Writes a codec header, which records both a string to
/// identify the file and a version number. This header can
/// be parsed and validated with
/// <see cref="CheckHeader(DataInput, string, int, int)"/>.
/// <para/>
/// CodecHeader --> Magic,CodecName,Version
/// <list type="bullet">
/// <item><description>Magic --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). this
/// identifies the start of the header. It is always <see cref="CODEC_MAGIC"/>.</description></item>
/// <item><description>CodecName --> String (<see cref="DataOutput.WriteString(string)"/>). this
/// is a string to identify this file.</description></item>
/// <item><description>Version --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). Records
/// the version of the file.</description></item>
/// </list>
/// <para/>
/// Note that the length of a codec header depends only upon the
/// name of the codec, so this length can be computed at any time
/// with <see cref="HeaderLength(string)"/>.
/// </summary>
/// <param name="out"> Output stream </param>
/// <param name="codec"> String to identify this file. It should be simple ASCII,
/// less than 128 characters in length. </param>
/// <param name="version"> Version number </param>
/// <exception cref="System.IO.IOException"> If there is an I/O error writing to the underlying medium. </exception>
public static void WriteHeader(DataOutput @out, string codec, int version)
{
BytesRef bytes = new BytesRef(codec);
if (bytes.Length != codec.Length || bytes.Length >= 128)
{
throw new System.ArgumentException("codec must be simple ASCII, less than 128 characters in length [got " + codec + "]");
}
@out.WriteInt32(CODEC_MAGIC);
@out.WriteString(codec);
@out.WriteInt32(version);
}
/// <summary>
/// Computes the length of a codec header.
/// </summary>
/// <param name="codec"> Codec name. </param>
/// <returns> Length of the entire codec header. </returns>
/// <seealso cref="WriteHeader(DataOutput, string, int)"/>
public static int HeaderLength(string codec)
{
return 9 + codec.Length;
}
/// <summary>
/// Reads and validates a header previously written with
/// <see cref="WriteHeader(DataOutput, string, int)"/>.
/// <para/>
/// When reading a file, supply the expected <paramref name="codec"/> and
/// an expected version range (<paramref name="minVersion"/> to <paramref name="maxVersion"/>).
/// </summary>
/// <param name="in"> Input stream, positioned at the point where the
/// header was previously written. Typically this is located
/// at the beginning of the file. </param>
/// <param name="codec"> The expected codec name. </param>
/// <param name="minVersion"> The minimum supported expected version number. </param>
/// <param name="maxVersion"> The maximum supported expected version number. </param>
/// <returns> The actual version found, when a valid header is found
/// that matches <paramref name="codec"/>, with an actual version
/// where <c>minVersion <= actual <= maxVersion</c>.
/// Otherwise an exception is thrown. </returns>
/// <exception cref="Index.CorruptIndexException"> If the first four bytes are not
/// <see cref="CODEC_MAGIC"/>, or if the actual codec found is
/// not <paramref name="codec"/>. </exception>
/// <exception cref="Index.IndexFormatTooOldException"> If the actual version is less
/// than <paramref name="minVersion"/>. </exception>
/// <exception cref="Index.IndexFormatTooNewException"> If the actual version is greater
/// than <paramref name="maxVersion"/>. </exception>
/// <exception cref="System.IO.IOException"> If there is an I/O error reading from the underlying medium. </exception>
/// <seealso cref="WriteHeader(DataOutput, string, int)"/>
public static int CheckHeader(DataInput @in, string codec, int minVersion, int maxVersion)
{
// Safety to guard against reading a bogus string:
int actualHeader = @in.ReadInt32();
if (actualHeader != CODEC_MAGIC)
{
throw new System.IO.IOException("codec header mismatch: actual header=" + actualHeader + " vs expected header=" + CODEC_MAGIC + " (resource: " + @in + ")");
}
return CheckHeaderNoMagic(@in, codec, minVersion, maxVersion);
}
/// <summary>
/// Like
/// <see cref="CheckHeader(DataInput,string,int,int)"/> except this
/// version assumes the first <see cref="int"/> has already been read
/// and validated from the input.
/// </summary>
public static int CheckHeaderNoMagic(DataInput @in, string codec, int minVersion, int maxVersion)
{
string actualCodec = @in.ReadString();
if (!actualCodec.Equals(codec, StringComparison.Ordinal))
{
throw new System.IO.IOException("codec mismatch: actual codec=" + actualCodec + " vs expected codec=" + codec + " (resource: " + @in + ")");
}
int actualVersion = @in.ReadInt32();
if (actualVersion < minVersion)
{
throw new System.IO.IOException("Version: " + actualVersion + " is not supported. Minimum Version number is " + minVersion + ".");
}
if (actualVersion > maxVersion)
{
throw new System.IO.IOException("Version: " + actualVersion + " is not supported. Maximum Version number is " + maxVersion + ".");
}
return actualVersion;
}
/// <summary>
/// Writes a codec footer, which records both a checksum
/// algorithm ID and a checksum. This footer can
/// be parsed and validated with
/// <see cref="CheckFooter(ChecksumIndexInput)"/>.
/// <para/>
/// CodecFooter --> Magic,AlgorithmID,Checksum
/// <list type="bullet">
/// <item><description>Magic --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). this
/// identifies the start of the footer. It is always <see cref="FOOTER_MAGIC"/>.</description></item>
/// <item><description>AlgorithmID --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). this
/// indicates the checksum algorithm used. Currently this is always 0,
/// for zlib-crc32.</description></item>
/// <item><description>Checksum --> Uint32 (<see cref="DataOutput.WriteInt64(long)"/>). The
/// actual checksum value for all previous bytes in the stream, including
/// the bytes from Magic and AlgorithmID.</description></item>
/// </list>
/// </summary>
/// <param name="out"> Output stream </param>
/// <exception cref="System.IO.IOException"> If there is an I/O error writing to the underlying medium. </exception>
public static void WriteFooter(IndexOutput @out)
{
@out.WriteInt32(FOOTER_MAGIC);
@out.WriteInt32(0);
@out.WriteInt64(@out.Checksum);
}
/// <summary>
/// Computes the length of a codec footer.
/// </summary>
/// <returns> Length of the entire codec footer. </returns>
/// <seealso cref="WriteFooter(IndexOutput)"/>
public static int FooterLength()
{
return 16;
}
/// <summary>
/// Validates the codec footer previously written by <see cref="WriteFooter(IndexOutput)"/>. </summary>
/// <returns> Actual checksum value. </returns>
/// <exception cref="System.IO.IOException"> If the footer is invalid, if the checksum does not match,
/// or if <paramref name="in"/> is not properly positioned before the footer
/// at the end of the stream. </exception>
public static long CheckFooter(ChecksumIndexInput @in)
{
ValidateFooter(@in);
long actualChecksum = @in.Checksum;
long expectedChecksum = @in.ReadInt64();
if (expectedChecksum != actualChecksum)
{
throw new System.IO.IOException("checksum failed (hardware problem?) : expected=" + expectedChecksum.ToString("x") + " actual=" + actualChecksum.ToString("x") + " (resource=" + @in + ")");
}
if (@in.GetFilePointer() != @in.Length)
{
throw new System.IO.IOException("did not read all bytes from file: read " + @in.GetFilePointer() + " vs size " + @in.Length + " (resource: " + @in + ")");
}
return actualChecksum;
}
/// <summary>
/// Returns (but does not validate) the checksum previously written by <see cref="CheckFooter(ChecksumIndexInput)"/>. </summary>
/// <returns> actual checksum value </returns>
/// <exception cref="System.IO.IOException"> If the footer is invalid. </exception>
public static long RetrieveChecksum(IndexInput @in)
{
@in.Seek(@in.Length - FooterLength());
ValidateFooter(@in);
return @in.ReadInt64();
}
private static void ValidateFooter(IndexInput @in)
{
int magic = @in.ReadInt32();
if (magic != FOOTER_MAGIC)
{
throw new System.IO.IOException("codec footer mismatch: actual footer=" + magic + " vs expected footer=" + FOOTER_MAGIC + " (resource: " + @in + ")");
}
int algorithmID = @in.ReadInt32();
if (algorithmID != 0)
{
throw new System.IO.IOException("codec footer mismatch: unknown algorithmID: " + algorithmID);
}
}
/// <summary>
/// Checks that the stream is positioned at the end, and throws exception
/// if it is not. </summary>
[Obsolete("Use CheckFooter(ChecksumIndexInput) instead, this should only used for files without checksums.")]
public static void CheckEOF(IndexInput @in)
{
if (@in.GetFilePointer() != @in.Length)
{
throw new System.IO.IOException("did not read all bytes from file: read " + @in.GetFilePointer() + " vs size " + @in.Length + " (resource: " + @in + ")");
}
}
/// <summary>
/// Clones the provided input, reads all bytes from the file, and calls <see cref="CheckFooter(ChecksumIndexInput)"/>
/// <para/>
/// Note that this method may be slow, as it must process the entire file.
/// If you just need to extract the checksum value, call <see cref="RetrieveChecksum(IndexInput)"/>.
/// </summary>
public static long ChecksumEntireFile(IndexInput input)
{
IndexInput clone = (IndexInput)input.Clone();
clone.Seek(0);
ChecksumIndexInput @in = new BufferedChecksumIndexInput(clone);
Debug.Assert(@in.GetFilePointer() == 0);
@in.Seek(@in.Length - FooterLength());
return CheckFooter(@in);
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace SoftLogik.Win.UI.Docking
{
public class DrawHelper
{
public static int bshift = 8;
public static void DrawTab(Graphics g, Rectangle r, Corners corner, GradientType gradient, Color darkColor, Color lightColor, Color edgeColor, bool closed)
{
//dims
Point[] points = null;
GraphicsPath path = null;
Region region = null;
LinearGradientBrush linearBrush = null;
Brush brush = null;
Pen pen = null;
r.Inflate(-1, -1);
//set brushes
switch (gradient)
{
case GradientType.Flat:
brush = new SolidBrush(darkColor);
break;
case GradientType.Linear:
brush = new LinearGradientBrush(r, darkColor, lightColor, LinearGradientMode.Vertical);
break;
case GradientType.Bell:
linearBrush = new LinearGradientBrush(r, darkColor, lightColor, LinearGradientMode.Vertical);
linearBrush.SetSigmaBellShape(0.17F, 0.67F);
brush = linearBrush;
break;
}
pen = new Pen(edgeColor, 1F);
//generic points
points = new Point[12] { new Point(r.Left, r.Bottom), new Point(r.Left, r.Bottom - bshift), new Point(r.Left, r.Top + bshift), new Point(r.Left, r.Top), new Point(r.Left + bshift, r.Top), new Point(r.Right - bshift, r.Top), new Point(r.Right, r.Top), new Point(r.Right, r.Top + bshift), new Point(r.Right, r.Bottom - bshift), new Point(r.Right, r.Bottom), new Point(r.Right - bshift, r.Bottom), new Point(r.Left + bshift, r.Bottom) };
path = new GraphicsPath();
switch (corner)
{
case Corners.LeftBottom:
path.AddLine(points[3], points[1]);
path.AddBezier(points[1], points[0], points[0], points[11]);
path.AddLine(points[11], points[9]);
path.AddLine(points[9], points[6]);
path.AddLine(points[6], points[3]);
region = new Region(path);
g.FillRegion(brush, region);
g.DrawLine(pen, points[3], points[1]);
g.DrawBezier(pen, points[1], points[0], points[0], points[11]);
g.DrawLine(pen, points[11], points[9]);
g.DrawLine(pen, points[9], points[6]);
if (closed)
{
g.DrawLine(pen, points[6], points[3]);
}
break;
case Corners.LeftTop:
path.AddLine(points[0], points[2]);
path.AddBezier(points[2], points[3], points[3], points[4]);
path.AddLine(points[4], points[6]);
path.AddLine(points[6], points[9]);
path.AddLine(points[9], points[0]);
region = new Region(path);
g.FillRegion(brush, region);
g.DrawLine(pen, points[0], points[2]);
g.DrawBezier(pen, points[2], points[3], points[3], points[4]);
g.DrawLine(pen, points[4], points[6]);
g.DrawLine(pen, points[6], points[9]);
if (closed)
{
g.DrawLine(pen, points[9], points[0]);
}
break;
case Corners.Bottom:
path.AddLine(points[1], points[3]);
path.AddBezier(points[1], points[0], points[0], points[11]);
path.AddLine(points[11], points[10]);
path.AddBezier(points[10], points[9], points[9], points[8]);
path.AddLine(points[8], points[6]);
path.AddLine(points[6], points[3]);
region = new Region(path);
g.FillRegion(brush, region);
g.DrawLine(pen, points[1], points[3]);
g.DrawBezier(pen, points[1], points[0], points[0], points[11]);
g.DrawLine(pen, points[11], points[10]);
g.DrawBezier(pen, points[10], points[9], points[9], points[8]);
g.DrawLine(pen, points[8], points[6]);
if (closed)
{
g.DrawLine(pen, points[6], points[3]);
}
break;
case Corners.Top:
path.AddLine(points[0], points[2]);
path.AddBezier(points[2], points[3], points[3], points[4]);
path.AddLine(points[4], points[5]);
path.AddBezier(points[5], points[6], points[6], points[7]);
path.AddLine(points[7], points[9]);
path.AddLine(points[9], points[0]);
region = new Region(path);
g.FillRegion(brush, region);
g.DrawLine(pen, points[0], points[2]);
g.DrawBezier(pen, points[2], points[3], points[3], points[4]);
g.DrawLine(pen, points[4], points[5]);
g.DrawBezier(pen, points[5], points[6], points[6], points[7]);
g.DrawLine(pen, points[7], points[9]);
if (closed)
{
g.DrawLine(pen, points[9], points[0]);
}
break;
case Corners.RightBottom:
path.AddLine(points[3], points[0]);
path.AddLine(points[0], points[10]);
path.AddBezier(points[10], points[9], points[9], points[8]);
path.AddLine(points[8], points[6]);
path.AddLine(points[6], points[3]);
region = new Region(path);
g.FillRegion(brush, region);
g.DrawLine(pen, points[3], points[0]);
g.DrawLine(pen, points[0], points[10]);
g.DrawBezier(pen, points[10], points[9], points[9], points[8]);
g.DrawLine(pen, points[8], points[6]);
if (closed)
{
g.DrawLine(pen, points[6], points[3]);
}
break;
case Corners.RightTop:
path.AddLine(points[0], points[3]);
path.AddLine(points[3], points[5]);
path.AddBezier(points[5], points[6], points[6], points[7]);
path.AddLine(points[7], points[9]);
path.AddLine(points[9], points[0]);
region = new Region(path);
g.FillRegion(brush, region);
g.DrawLine(pen, points[0], points[3]);
g.DrawLine(pen, points[3], points[5]);
g.DrawBezier(pen, points[5], points[6], points[6], points[7]);
g.DrawLine(pen, points[7], points[9]);
if (closed)
{
g.DrawLine(pen, points[9], points[0]);
}
break;
}
}
public static void DrawDocumentTab(Graphics g, Rectangle rect, Color backColorBegin, Color backColorEnd, Color edgeColor, TabDrawType tabType, bool closed)
{
GraphicsPath path = null;
Region region = null;
Brush brush = null;
Pen pen = null;
brush = new LinearGradientBrush(rect, backColorBegin, backColorEnd, LinearGradientMode.Vertical);
pen = new Pen(edgeColor, 1.0F);
path = new GraphicsPath();
if (tabType == TabDrawType.First)
{
path.AddLine(rect.Left + 1, rect.Bottom + 1, rect.Left + rect.Height, rect.Top + 2);
path.AddLine(rect.Left + rect.Height + 4, rect.Top, rect.Right - 3, rect.Top);
path.AddLine(rect.Right - 1, rect.Top + 2, rect.Right - 1, rect.Bottom + 1);
}
else
{
if (tabType == TabDrawType.Active)
{
path.AddLine(rect.Left + 1, rect.Bottom + 1, rect.Left + rect.Height, rect.Top + 2);
path.AddLine(rect.Left + rect.Height + 4, rect.Top, rect.Right - 3, rect.Top);
path.AddLine(rect.Right - 1, rect.Top + 2, rect.Right - 1, rect.Bottom + 1);
}
else
{
path.AddLine(rect.Left, rect.Top + 6, rect.Left + 4, rect.Top + 2);
path.AddLine(rect.Left + 8, rect.Top, rect.Right - 3, rect.Top);
path.AddLine(rect.Right - 1, rect.Top + 2, rect.Right - 1, rect.Bottom + 1);
path.AddLine(rect.Right - 1, rect.Bottom + 1, rect.Left, rect.Bottom + 1);
}
}
region = new Region(path);
g.FillRegion(brush, region);
g.DrawPath(pen, path);
}
}
public enum Corners : int
{
RightTop,
LeftTop,
LeftBottom,
RightBottom,
Bottom,
Top
}
public enum TabDrawType : int
{
First,
Active,
Inactive
}
public enum GradientType : int
{
Flat,
Linear,
Bell
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
/// <summary>
/// Version 2.01 - Very hacky compared to the original. Will fix original and release as 0.3 later.
/// </summary>
public class TreePopulatorModule : IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
public double m_tree_density = 50.0; // Aim for this many per region
public double m_tree_updates = 1000.0; // MS between updates
private bool m_active_trees = false;
private List<UUID> m_trees;
Timer CalculateTrees;
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IRegionModule>(this);
m_scene.AddCommand(
this, "tree plant", "tree plant", "Start populating trees", HandleTreeConsoleCommand);
m_scene.AddCommand(
this, "tree active", "tree active <boolean>", "Change activity state for trees module", HandleTreeConsoleCommand);
try
{
m_tree_density = config.Configs["Trees"].GetDouble("tree_density", m_tree_density);
m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
}
catch (Exception)
{
}
m_trees = new List<UUID>();
if (m_active_trees)
activeizeTreeze(true);
m_log.Debug("[TREES]: Initialised tree module");
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "TreePopulatorModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
/// <summary>
/// Handle a tree command from the console.
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
public void HandleTreeConsoleCommand(string module, string[] cmdparams)
{
if (m_scene.ConsoleScene() != null && m_scene.ConsoleScene() != m_scene)
return;
if (cmdparams[1] == "active")
{
if (cmdparams.Length <= 2)
{
if (m_active_trees)
m_log.InfoFormat("[TREES]: Trees are currently active");
else
m_log.InfoFormat("[TREES]: Trees are currently not active");
}
else if (cmdparams[2] == "true" && !m_active_trees)
{
m_log.InfoFormat("[TREES]: Activating Trees");
m_active_trees = true;
activeizeTreeze(m_active_trees);
}
else if (cmdparams[2] == "false" && m_active_trees)
{
m_log.InfoFormat("[TREES]: Trees no longer active, for now...");
m_active_trees = false;
activeizeTreeze(m_active_trees);
}
else
{
m_log.InfoFormat("[TREES]: When setting the tree module active via the console, you must specify true or false");
}
}
else if (cmdparams[1] == "plant")
{
m_log.InfoFormat("[TREES]: New tree planting");
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (uuid == UUID.Zero)
uuid = m_scene.RegionInfo.MasterAvatarAssignedUUID;
CreateTree(uuid, new Vector3(128.0f, 128.0f, 0.0f));
}
else
{
m_log.InfoFormat("[TREES]: Unknown command");
}
}
private void activeizeTreeze(bool activeYN)
{
if (activeYN)
{
CalculateTrees = new Timer(m_tree_updates);
CalculateTrees.Elapsed += CalculateTrees_Elapsed;
CalculateTrees.Start();
}
else
{
CalculateTrees.Stop();
}
}
private void growTrees()
{
foreach (UUID tree in m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart;
// 100 seconds to grow 1m
s_tree.Scale += new Vector3(0.1f, 0.1f, 0.1f);
s_tree.ScheduleFullUpdate();
//s_tree.ScheduleTerseUpdate();
}
else
{
m_trees.Remove(tree);
}
}
}
private void seedTrees()
{
foreach (UUID tree in m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart;
if (s_tree.Scale.X > 0.5)
{
if (Util.RandomClass.NextDouble() > 0.75)
{
SpawnChild(s_tree);
}
}
}
else
{
m_trees.Remove(tree);
}
}
}
private void killTrees()
{
foreach (UUID tree in m_trees)
{
double killLikelyhood = 0.0;
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart selectedTree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart;
double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
Math.Pow(selectedTree.Scale.Y, 2) +
Math.Pow(selectedTree.Scale.Z, 2));
foreach (UUID picktree in m_trees)
{
if (picktree != tree)
{
SceneObjectPart pickedTree = ((SceneObjectGroup) m_scene.Entities[picktree]).RootPart;
double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
Math.Pow(pickedTree.Scale.Y, 2) +
Math.Pow(pickedTree.Scale.Z, 2));
double pickedTreeDistance = Math.Sqrt(Math.Pow(Math.Abs(pickedTree.AbsolutePosition.X - selectedTree.AbsolutePosition.X), 2) +
Math.Pow(Math.Abs(pickedTree.AbsolutePosition.Y - selectedTree.AbsolutePosition.Y), 2) +
Math.Pow(Math.Abs(pickedTree.AbsolutePosition.Z - selectedTree.AbsolutePosition.Z), 2));
killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
}
}
if (Util.RandomClass.NextDouble() < killLikelyhood)
{
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
m_trees.Remove(selectedTree.ParentGroup.UUID);
m_scene.ForEachClient(delegate(IClientAPI controller)
{
controller.SendKillObject(m_scene.RegionInfo.RegionHandle,
selectedTree.LocalId);
});
break;
}
selectedTree.SetText(killLikelyhood.ToString(), new Vector3(1.0f, 1.0f, 1.0f), 1.0);
}
else
{
m_trees.Remove(tree);
}
}
}
private void SpawnChild(SceneObjectPart s_tree)
{
Vector3 position = new Vector3();
position.X = s_tree.AbsolutePosition.X + (1 * (-1 * Util.RandomClass.Next(1)));
if (position.X > 255)
position.X = 255;
if (position.X < 0)
position.X = 0;
position.Y = s_tree.AbsolutePosition.Y + (1 * (-1 * Util.RandomClass.Next(1)));
if (position.Y > 255)
position.Y = 255;
if (position.Y < 0)
position.Y = 0;
double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
position.X += (float) randX;
position.Y += (float) randY;
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (uuid == UUID.Zero)
uuid = m_scene.RegionInfo.MasterAvatarAssignedUUID;
CreateTree(uuid, position);
}
private void CreateTree(UUID uuid, Vector3 position)
{
position.Z = (float) m_scene.Heightmap[(int) position.X, (int) position.Y];
IVegetationModule module = m_scene.RequestModuleInterface<IVegetationModule>();
if (null == module)
return;
SceneObjectGroup tree
= module.AddTree(
uuid, UUID.Zero, new Vector3(0.1f, 0.1f, 0.1f), Quaternion.Identity, position, Tree.Cypress1, false);
m_trees.Add(tree.UUID);
tree.ScheduleGroupForFullUpdate();
}
private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
{
growTrees();
seedTrees();
killTrees();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Logging;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Script
{
public interface IPageResult {}
// Render a Template Page to the Response OutputStream
public class PageResult : IPageResult, IStreamWriterAsync, IHasOptions, IDisposable
{
/// <summary>
/// The Page to Render
/// </summary>
public SharpPage Page { get; }
/// <summary>
/// The Code Page to Render
/// </summary>
public SharpCodePage CodePage { get; }
/// <summary>
/// Use specified Layout
/// </summary>
public SharpPage LayoutPage { get; set; }
/// <summary>
/// Use Layout with specified name
/// </summary>
public string Layout { get; set; }
/// <summary>
/// Render without any Layout
/// </summary>
public bool NoLayout { get; set; }
/// <summary>
/// Extract Model Properties into Scope Args
/// </summary>
public object Model { get; set; }
/// <summary>
/// Add additional Args available to all pages
/// </summary>
public Dictionary<string, object> Args { get; set; }
/// <summary>
/// Add additional script methods available to all pages
/// </summary>
public List<ScriptMethods> ScriptMethods { get; set; }
[Obsolete("Use ScriptMethods")] public List<ScriptMethods> TemplateFilters => ScriptMethods;
/// <summary>
/// Add additional script blocks available to all pages
/// </summary>
public List<ScriptBlock> ScriptBlocks { get; set; }
[Obsolete("Use ScriptBlocks")] public List<ScriptBlock> TemplateBlocks => ScriptBlocks;
/// <summary>
/// Add additional partials available to all pages
/// </summary>
public Dictionary<string, SharpPage> Partials { get; set; }
/// <summary>
/// Return additional HTTP Headers in HTTP Requests
/// </summary>
public IDictionary<string, string> Options { get; set; }
/// <summary>
/// Specify the Content-Type of the Response
/// </summary>
public string ContentType
{
get => Options.TryGetValue(HttpHeaders.ContentType, out string contentType) ? contentType : null;
set => Options[HttpHeaders.ContentType] = value;
}
/// <summary>
/// Transform the Page output using a chain of stream transformers
/// </summary>
public List<Func<Stream, Task<Stream>>> PageTransformers { get; set; }
/// <summary>
/// Transform the entire output using a chain of stream transformers
/// </summary>
public List<Func<Stream, Task<Stream>>> OutputTransformers { get; set; }
/// <summary>
/// Available transformers that can transform context filter stream outputs
/// </summary>
public Dictionary<string, Func<Stream, Task<Stream>>> FilterTransformers { get; set; }
/// <summary>
/// Don't allow access to specified filters
/// </summary>
public HashSet<string> ExcludeFiltersNamed { get; } = new HashSet<string>();
/// <summary>
/// The last error thrown by a filter
/// </summary>
public Exception LastFilterError { get; set; }
/// <summary>
/// The StackTrace where the Last Error Occured
/// </summary>
public string[] LastFilterStackTrace { get; set; }
/// <summary>
/// What argument errors should be binded to
/// </summary>
public string AssignExceptionsTo { get; set; }
/// <summary>
/// Whether to skip execution of all page filters and just write page string fragments
/// </summary>
public bool SkipFilterExecution { get; set; }
/// <summary>
/// Overrides Context to specify whether to Ignore or Continue executing filters on error
/// </summary>
public bool? SkipExecutingFiltersIfError { get; set; }
/// <summary>
/// Whether to always rethrow Exceptions
/// </summary>
public bool RethrowExceptions { get; set; }
/// <summary>
/// Immediately halt execution of the page
/// </summary>
public bool HaltExecution { get; set; }
/// <summary>
/// Whether to disable buffering output and render directly to OutputStream
/// </summary>
public bool DisableBuffering { get; set; }
/// <summary>
/// The Return value of the page (if any)
/// </summary>
public ReturnValue ReturnValue { get; set; }
/// <summary>
/// The Current StackDepth
/// </summary>
public int StackDepth { get; internal set; }
/// <summary>
/// Can be used to track number of Evaluations
/// </summary>
public long Evaluations { get; private set; }
public void AssertNextEvaluation()
{
if (Evaluations++ >= Context.MaxEvaluations)
throw new NotSupportedException($"Exceeded Max Evaluations of {Context.MaxEvaluations}. \nMaxEvaluations can be changed in `ScriptContext.MaxEvaluations`.");
}
public void ResetIterations() => Evaluations = 0;
private readonly Stack<string> stackTrace = new Stack<string>();
private PageResult(PageFormat format)
{
Args = new Dictionary<string, object>();
ScriptMethods = new List<ScriptMethods>();
ScriptBlocks = new List<ScriptBlock>();
Partials = new Dictionary<string, SharpPage>();
PageTransformers = new List<Func<Stream, Task<Stream>>>();
OutputTransformers = new List<Func<Stream, Task<Stream>>>();
FilterTransformers = new Dictionary<string, Func<Stream, Task<Stream>>>();
Options = new Dictionary<string, string>
{
{HttpHeaders.ContentType, format?.ContentType},
};
}
public PageResult(SharpPage page) : this(page?.Format)
{
Page = page ?? throw new ArgumentNullException(nameof(page));
}
public PageResult(SharpCodePage page) : this(page?.Format)
{
CodePage = page ?? throw new ArgumentNullException(nameof(page));
var hasRequest = (CodePage as IRequiresRequest)?.Request;
if (hasRequest != null)
Args[ScriptConstants.Request] = hasRequest;
}
//entry point
public async Task WriteToAsync(Stream responseStream, CancellationToken token = default)
{
if (OutputTransformers.Count == 0)
{
var bufferOutput = !DisableBuffering && !(responseStream is MemoryStream);
if (bufferOutput)
{
using (var ms = MemoryStreamFactory.GetStream())
{
await WriteToAsyncInternal(ms, token);
ms.Position = 0;
await ms.WriteToAsync(responseStream, token);
}
}
else
{
await WriteToAsyncInternal(responseStream, token);
}
return;
}
//If PageResult has any OutputFilters Buffer and chain stream responses to each
using (var ms = MemoryStreamFactory.GetStream())
{
stackTrace.Push("OutputTransformer");
await WriteToAsyncInternal(ms, token);
Stream stream = ms;
foreach (var transformer in OutputTransformers)
{
stream.Position = 0;
stream = await transformer(stream);
}
using (stream)
{
stream.Position = 0;
await stream.WriteToAsync(responseStream, token);
}
stackTrace.Pop();
}
}
internal async Task WriteToAsyncInternal(Stream outputStream, CancellationToken token)
{
await Init();
if (!NoLayout)
{
if (LayoutPage != null)
{
await LayoutPage.Init();
if (CodePage != null)
InitIfNewPage(CodePage);
if (Page != null)
await InitIfNewPage(Page);
}
else
{
if (Page != null)
{
await InitIfNewPage(Page);
if (Page.LayoutPage != null)
{
LayoutPage = Page.LayoutPage;
await LayoutPage.Init();
}
}
else if (CodePage != null)
{
InitIfNewPage(CodePage);
if (CodePage.LayoutPage != null)
{
LayoutPage = CodePage.LayoutPage;
await LayoutPage.Init();
}
}
}
}
else
{
if (Page != null)
{
await InitIfNewPage(Page);
}
else if (CodePage != null)
{
InitIfNewPage(CodePage);
}
}
token.ThrowIfCancellationRequested();
var pageScope = CreatePageContext(null, outputStream);
if (!NoLayout && LayoutPage != null)
{
// sync impl with WriteFragmentsAsync
stackTrace.Push("Layout: " + LayoutPage.VirtualPath);
foreach (var fragment in LayoutPage.PageFragments)
{
if (HaltExecution)
break;
await WritePageFragmentAsync(pageScope, fragment, token);
}
stackTrace.Pop();
}
else
{
await WritePageAsync(Page, CodePage, pageScope, token);
}
}
internal async Task WriteFragmentsAsync(ScriptScopeContext scope, IEnumerable<PageFragment> fragments, string callTrace, CancellationToken token)
{
stackTrace.Push(callTrace);
foreach (var fragment in fragments)
{
if (HaltExecution)
return;
await WritePageFragmentAsync(scope, fragment, token);
}
stackTrace.Pop();
}
public async Task WritePageFragmentAsync(ScriptScopeContext scope, PageFragment fragment, CancellationToken token)
{
foreach (var scriptLanguage in Context.ScriptLanguagesArray)
{
if (ShouldSkipFilterExecution(fragment))
return;
if (await scriptLanguage.WritePageFragmentAsync(scope, fragment, token))
break;
}
}
public Task WriteStatementsAsync(ScriptScopeContext scope, IEnumerable<JsStatement> blockStatements, string callTrace, CancellationToken token)
{
try
{
stackTrace.Push(callTrace);
return WriteStatementsAsync(scope, blockStatements, token);
}
finally
{
stackTrace.Pop();
}
}
public async Task WriteStatementsAsync(ScriptScopeContext scope, IEnumerable<JsStatement> blockStatements, CancellationToken token)
{
foreach (var statement in blockStatements)
{
foreach (var scriptLanguage in Context.ScriptLanguagesArray)
{
if (HaltExecution || ShouldSkipFilterExecution(statement))
return;
if (await scriptLanguage.WriteStatementAsync(scope, statement, token))
break;
}
}
}
public bool ShouldSkipFilterExecution(PageVariableFragment var)
{
return HaltExecution || SkipFilterExecution && (var.Binding != null
? !Context.OnlyEvaluateFiltersWhenSkippingPageFilterExecution.Contains(var.Binding)
: var.InitialExpression?.Name == null ||
!Context.OnlyEvaluateFiltersWhenSkippingPageFilterExecution.Contains(var.InitialExpression.Name));
}
public bool ShouldSkipFilterExecution(PageFragment fragment) => !(fragment is PageStringFragment)
&& (fragment is PageVariableFragment var
? ShouldSkipFilterExecution(var)
: HaltExecution || SkipFilterExecution);
public bool ShouldSkipFilterExecution(JsStatement statement) => HaltExecution || SkipFilterExecution;
public ScriptContext Context => Page?.Context ?? CodePage.Context;
public PageFormat Format => Page?.Format ?? CodePage.Format;
public string VirtualPath => Page?.VirtualPath ?? CodePage.VirtualPath;
private bool hasInit;
public async Task<PageResult> Init()
{
if (hasInit)
return this;
if (!Context.HasInit)
throw new NotSupportedException($"{Context.GetType().Name} has not been initialized. Call 'Init()' to initialize Script Context.");
if (Model != null)
{
var explodeModel = Model.ToObjectDictionary();
foreach (var entry in explodeModel)
{
Args[entry.Key] = entry.Value ?? JsNull.Value;
}
}
Args[ScriptConstants.Model] = Model ?? JsNull.Value;
foreach (var scriptLanguage in Context.ScriptLanguages)
{
if (scriptLanguage is IConfigurePageResult configurePageResult)
{
configurePageResult.Configure(this);
}
}
foreach (var filter in ScriptMethods)
{
Context.InitMethod(filter);
}
foreach (var block in ScriptBlocks)
{
Context.InitBlock(block);
blocksMap[block.Name] = block;
}
if (Page != null)
{
await Page.Init();
InitPageArgs(Page.Args);
}
else
{
CodePage.Init();
InitPageArgs(CodePage.Args);
}
if (Layout != null && !NoLayout)
{
LayoutPage = Page != null
? Context.Pages.ResolveLayoutPage(Page, Layout)
: Context.Pages.ResolveLayoutPage(CodePage, Layout);
}
hasInit = true;
return this;
}
private void InitPageArgs(Dictionary<string, object> pageArgs)
{
if (pageArgs?.Count > 0)
{
NoLayout = (pageArgs.TryGetValue("ignore", out object ignore) && "template".Equals(ignore?.ToString())) ||
(pageArgs.TryGetValue("layout", out object layout) && "none".Equals(layout?.ToString()));
}
}
private Task InitIfNewPage(SharpPage page) => page != Page
? (Task) page.Init()
: TypeConstants.EmptyTask;
private void InitIfNewPage(SharpCodePage page)
{
if (page != CodePage)
page.Init();
}
private void AssertInit()
{
if (!hasInit)
throw new NotSupportedException("PageResult.Init() required for this operation.");
}
public Task WritePageAsync(SharpPage page, SharpCodePage codePage,
ScriptScopeContext scope, CancellationToken token = default(CancellationToken))
{
if (page != null)
return WritePageAsync(page, scope, token);
return WriteCodePageAsync(codePage, scope, token);
}
public async Task WritePageAsync(SharpPage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken))
{
if (PageTransformers.Count == 0)
{
await WritePageAsyncInternal(page, scope, token);
return;
}
//If PageResult has any PageFilters Buffer and chain stream responses to each
using (var ms = MemoryStreamFactory.GetStream())
{
stackTrace.Push("PageTransformer");
await WritePageAsyncInternal(page, new ScriptScopeContext(this, ms, scope.ScopedParams), token);
Stream stream = ms;
foreach (var transformer in PageTransformers)
{
stream.Position = 0;
stream = await transformer(stream);
}
using (stream)
{
stream.Position = 0;
await stream.WriteToAsync(scope.OutputStream, token);
}
stackTrace.Pop();
}
}
internal async Task WritePageAsyncInternal(SharpPage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken))
{
await page.Init(); //reload modified changes if needed
await WriteFragmentsAsync(scope, page.PageFragments, "Page: " + page.VirtualPath, token);
}
public async Task WriteCodePageAsync(SharpCodePage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken))
{
if (PageTransformers.Count == 0)
{
await WriteCodePageAsyncInternal(page, scope, token);
return;
}
//If PageResult has any PageFilters Buffer and chain stream responses to each
using (var ms = MemoryStreamFactory.GetStream())
{
await WriteCodePageAsyncInternal(page, new ScriptScopeContext(this, ms, scope.ScopedParams), token);
Stream stream = ms;
foreach (var transformer in PageTransformers)
{
stream.Position = 0;
stream = await transformer(stream);
}
using (stream)
{
stream.Position = 0;
await stream.WriteToAsync(scope.OutputStream, token);
}
}
}
internal Task WriteCodePageAsyncInternal(SharpCodePage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken))
{
page.Scope = scope;
if (!page.HasInit)
page.Init();
return page.WriteAsync(scope);
}
private string toDebugString(object instance)
{
using (JsConfig.With(new Config
{
ExcludeTypeInfo = true,
IncludeTypeInfo = false,
}))
{
if (instance is Dictionary<string, object> d)
return d.ToJsv();
if (instance is List<object> l)
return l.ToJsv();
if (instance is string s)
return '"' + s.Replace("\"", "\\\"") + '"';
return instance.ToJsv();
}
}
public async Task WriteVarAsync(ScriptScopeContext scope, PageVariableFragment var, CancellationToken token)
{
if (var.Binding != null)
stackTrace.Push($"Expression (binding): " + var.Binding);
else if (var.InitialExpression?.Name != null)
stackTrace.Push("Expression (filter): " + var.InitialExpression.Name);
else if (var.InitialValue != null)
stackTrace.Push($"Expression ({var.InitialValue.GetType().Name}): " + toDebugString(var.InitialValue).SubstringWithEllipsis(0, 200));
else
stackTrace.Push($"{var.Expression.GetType().Name}: " + var.Expression.ToRawString().SubstringWithEllipsis(0, 200));
var value = await EvaluateAsync(var, scope, token);
if (value != IgnoreResult.Value)
{
if (value != null)
{
var bytes = Format.EncodeValue(value).ToUtf8Bytes();
await scope.OutputStream.WriteAsync(bytes, token);
}
else
{
if (Context.OnUnhandledExpression != null)
{
var bytes = Context.OnUnhandledExpression(var);
if (bytes.Length > 0)
await scope.OutputStream.WriteAsync(bytes, token);
}
}
}
stackTrace.Pop();
}
private Func<Stream, Task<Stream>> GetFilterTransformer(string name)
{
return FilterTransformers.TryGetValue(name, out Func<Stream, Task<Stream>> fn)
? fn
: Context.FilterTransformers.TryGetValue(name, out fn)
? fn
: null;
}
private static Dictionary<string, object> GetPageParams(PageVariableFragment var)
{
Dictionary<string, object> scopedParams = null;
if (var != null && var.FilterExpressions.Length > 0)
{
if (var.FilterExpressions[0].Arguments.Length > 0)
{
var token = var.FilterExpressions[0].Arguments[0];
scopedParams = token.Evaluate(JS.CreateScope()) as Dictionary<string, object>;
}
}
return scopedParams;
}
private ScriptScopeContext CreatePageContext(PageVariableFragment var, Stream outputStream) => new ScriptScopeContext(this, outputStream, GetPageParams(var));
private async Task<object> EvaluateAsync(PageVariableFragment var, ScriptScopeContext scope, CancellationToken token=default(CancellationToken))
{
scope.ScopedParams[nameof(PageVariableFragment)] = var;
var value = var.Evaluate(scope);
if (value == null)
{
var handlesUnknownValue = Context.OnUnhandledExpression == null &&
var.FilterExpressions.Length > 0;
if (!handlesUnknownValue)
{
if (var.Expression is JsMemberExpression memberExpr)
{
//allow nested null bindings from an existing target to evaluate to an empty string
var targetValue = memberExpr.Object.Evaluate(scope);
if (targetValue != null)
return string.Empty;
}
if (var.Binding == null)
return null;
var hasFilterAsBinding = GetFilterAsBinding(var.Binding, out ScriptMethods filter);
if (hasFilterAsBinding != null)
{
value = InvokeFilter(hasFilterAsBinding, filter, new object[0], var.Binding);
}
else
{
var hasContextFilterAsBinding = GetContextFilterAsBinding(var.Binding, out filter);
if (hasContextFilterAsBinding != null)
{
value = InvokeFilter(hasContextFilterAsBinding, filter, new object[] { scope }, var.Binding);
}
else
{
return null;
}
}
}
}
if (value == JsNull.Value)
value = null;
value = EvaluateIfToken(value, scope);
for (var i = 0; i < var.FilterExpressions.Length; i++)
{
if (HaltExecution || value == StopExecution.Value)
break;
var expr = var.FilterExpressions[i];
try
{
var filterName = expr.Name;
var fnArgValues = JsCallExpression.EvaluateArgumentValues(scope, expr.Arguments);
var fnArgsLength = fnArgValues.Count;
var invoker = GetFilterInvoker(filterName, 1 + fnArgsLength, out ScriptMethods filter);
var contextFilterInvoker = invoker == null
? GetContextFilterInvoker(filterName, 2 + fnArgsLength, out filter)
: null;
var contextBlockInvoker = invoker == null && contextFilterInvoker == null
? GetContextBlockInvoker(filterName, 2 + fnArgsLength, out filter)
: null;
var delegateInvoker = invoker == null && contextFilterInvoker == null && contextBlockInvoker == null
? GetValue(filterName, scope) as Delegate
: null;
if (invoker == null && contextFilterInvoker == null && contextBlockInvoker == null && delegateInvoker == null)
{
if (i == 0)
return null; // ignore on server (i.e. assume it's on client) if first filter is missing
var errorMsg = CreateMissingFilterErrorMessage(filterName);
throw new NotSupportedException(errorMsg);
}
if (value is Task<object> valueObjectTask)
value = await valueObjectTask;
if (delegateInvoker != null)
{
value = JsCallExpression.InvokeDelegate(delegateInvoker, value, true, fnArgValues);
}
else if (invoker != null)
{
fnArgValues.Insert(0, value);
var args = fnArgValues.ToArray();
value = InvokeFilter(invoker, filter, args, expr.Name);
}
else if (contextFilterInvoker != null)
{
fnArgValues.Insert(0, scope);
fnArgValues.Insert(1, value); // filter target
var args = fnArgValues.ToArray();
value = InvokeFilter(contextFilterInvoker, filter, args, expr.Name);
}
else
{
var hasFilterTransformers = var.FilterExpressions.Length + i > 1;
var useScope = hasFilterTransformers
? scope.ScopeWithStream(MemoryStreamFactory.GetStream())
: scope;
fnArgValues.Insert(0, useScope);
fnArgValues.Insert(1, value); // filter target
var args = fnArgValues.ToArray();
try
{
var taskResponse = (Task)contextBlockInvoker(filter, args);
await taskResponse;
if (hasFilterTransformers)
{
using (useScope.OutputStream)
{
var stream = useScope.OutputStream;
//If Context Filter has any Filter Transformers Buffer and chain stream responses to each
for (var exprIndex = i + 1; exprIndex < var.FilterExpressions.Length; exprIndex++)
{
stream.Position = 0;
contextBlockInvoker = GetContextBlockInvoker(var.FilterExpressions[exprIndex].Name, 1 + var.FilterExpressions[exprIndex].Arguments.Length, out filter);
if (contextBlockInvoker != null)
{
args[0] = useScope;
for (var cmdIndex = 0; cmdIndex < var.FilterExpressions[exprIndex].Arguments.Length; cmdIndex++)
{
var arg = var.FilterExpressions[exprIndex].Arguments[cmdIndex];
var varValue = arg.Evaluate(scope);
args[1 + cmdIndex] = varValue;
}
await (Task)contextBlockInvoker(filter, args);
}
else
{
var transformer = GetFilterTransformer(var.FilterExpressions[exprIndex].Name);
if (transformer == null)
throw new NotSupportedException($"Could not find FilterTransformer '{var.FilterExpressions[exprIndex].Name}' in page '{Page.VirtualPath}'");
stream = await transformer(stream);
useScope = useScope.ScopeWithStream(stream);
}
}
if (stream.CanRead)
{
stream.Position = 0;
await stream.WriteToAsync(scope.OutputStream, token);
}
}
}
}
catch (StopFilterExecutionException) { throw; }
catch (Exception ex)
{
var rethrow = ScriptConfig.FatalExceptions.Contains(ex.GetType());
var exResult = Format.OnExpressionException(this, ex);
if (exResult != null)
await scope.OutputStream.WriteAsync(Format.EncodeValue(exResult).ToUtf8Bytes(), token);
else if (rethrow)
throw;
throw new TargetInvocationException($"Failed to invoke filter '{expr.GetDisplayName()}': {ex.Message}", ex);
}
return IgnoreResult.Value;
}
if (value is Task<object> valueTask)
value = await valueTask;
}
catch (StopFilterExecutionException ex)
{
LastFilterError = ex.InnerException;
LastFilterStackTrace = stackTrace.ToArray();
if (RethrowExceptions)
throw ex.InnerException;
var skipExecutingFilters = SkipExecutingFiltersIfError.GetValueOrDefault(Context.SkipExecutingFiltersIfError);
if (skipExecutingFilters)
this.SkipFilterExecution = true;
var rethrow = ScriptConfig.FatalExceptions.Contains(ex.InnerException.GetType());
if (!rethrow)
{
string errorBinding = null;
if (ex.Options is Dictionary<string, object> filterParams)
{
if (filterParams.TryGetValue(ScriptConstants.AssignError, out object assignError))
{
errorBinding = assignError as string;
}
else if (filterParams.TryGetValue(ScriptConstants.CatchError, out object catchError))
{
errorBinding = catchError as string;
SkipFilterExecution = false;
LastFilterError = null;
LastFilterStackTrace = null;
}
if (filterParams.TryGetValue(ScriptConstants.IfErrorReturn, out object ifErrorReturn))
{
SkipFilterExecution = false;
LastFilterError = null;
LastFilterStackTrace = null;
return ifErrorReturn;
}
}
if (errorBinding == null)
errorBinding = AssignExceptionsTo ?? Context.AssignExceptionsTo;
if (!string.IsNullOrEmpty(errorBinding))
{
scope.ScopedParams[errorBinding] = ex.InnerException;
scope.ScopedParams[errorBinding + "StackTrace"] = stackTrace.Map(x => " at " + x).Join(Environment.NewLine);
return string.Empty;
}
}
if (SkipExecutingFiltersIfError.HasValue || Context.SkipExecutingFiltersIfError)
return string.Empty;
// rethrow exceptions which aren't handled
var exResult = Format.OnExpressionException(this, ex);
if (exResult != null)
await scope.OutputStream.WriteAsync(Format.EncodeValue(exResult).ToUtf8Bytes(), token);
else if (rethrow)
throw ex.InnerException;
var filterName = expr.GetDisplayName();
if (filterName.StartsWith("throw"))
throw ex.InnerException;
throw new TargetInvocationException($"Failed to invoke filter '{filterName}': {ex.InnerException.Message}", ex.InnerException);
}
}
return UnwrapValue(value);
}
private static object UnwrapValue(object value)
{
if (value == null || value == JsNull.Value || value == StopExecution.Value)
return string.Empty; // treat as empty value if evaluated to null
return value;
}
internal string CreateMissingFilterErrorMessage(string filterName)
{
var registeredMethods = ScriptMethods.Union(Context.ScriptMethods).ToList();
var similarNonMatchingFilters = registeredMethods
.SelectMany(x => x.QueryFilters(filterName))
.Where(x => !(Context.ExcludeFiltersNamed.Contains(x.Name) || ExcludeFiltersNamed.Contains(x.Name)))
.ToList();
var sb = StringBuilderCache.Allocate()
.AppendLine($"Filter in '{VirtualPath}' named '{filterName}' was not found.");
if (similarNonMatchingFilters.Count > 0)
{
sb.Append("Check for correct usage in similar (but non-matching) filters:").AppendLine();
var normalFilters = similarNonMatchingFilters
.OrderBy(x => x.GetParameters().Length + (x.ReturnType == typeof(Task) ? 10 : 1))
.ToArray();
foreach (var mi in normalFilters)
{
var argsTypesWithoutContext = mi.GetParameters()
.Where(x => x.ParameterType != typeof(ScriptScopeContext))
.ToList();
sb.Append("{{ ");
if (argsTypesWithoutContext.Count == 0)
{
sb.Append($"{mi.Name} => {mi.ReturnType.Name}");
}
else
{
sb.Append($"{argsTypesWithoutContext[0].ParameterType.Name} | {mi.Name}(");
var piCount = 0;
foreach (var pi in argsTypesWithoutContext.Skip(1))
{
if (piCount++ > 0)
sb.Append(", ");
sb.Append(pi.ParameterType.Name);
}
var returnType = mi.ReturnType == typeof(Task)
? "(Stream)"
: mi.ReturnType.Name;
sb.Append($") => {returnType}");
}
sb.AppendLine(" }}");
}
}
else
{
var registeredFilterNames = registeredMethods.Map(x => $"'{x.GetType().Name}'").Join(", ");
sb.Append($"No similar filters named '{filterName}' were found in registered filter(s): {registeredFilterNames}.");
}
return StringBuilderCache.ReturnAndFree(sb);
}
// Filters with no args can be used in-place of bindings
private MethodInvoker GetFilterAsBinding(string name, out ScriptMethods filter) => GetFilterInvoker(name, 0, out filter);
private MethodInvoker GetContextFilterAsBinding(string name, out ScriptMethods filter) => GetContextFilterInvoker(name, 1, out filter);
internal object InvokeFilter(MethodInvoker invoker, ScriptMethods filter, object[] args, string binding)
{
if (invoker == null)
throw new NotSupportedException(CreateMissingFilterErrorMessage(binding.LeftPart('(')));
try
{
return invoker(filter, args);
}
catch (StopFilterExecutionException) { throw; }
catch (Exception ex)
{
var exResult = Format.OnExpressionException(this, ex);
if (exResult != null)
return exResult;
if (binding.StartsWith("throw"))
throw;
throw new TargetInvocationException($"Failed to invoke filter '{binding}': {ex.Message}", ex);
}
}
public ReadOnlySpan<char> ParseJsExpression(ScriptScopeContext scope, ReadOnlySpan<char> literal, out JsToken token)
{
try
{
return literal.ParseJsExpression(out token);
}
catch (ArgumentException e)
{
if (scope.ScopedParams.TryGetValue(nameof(PageVariableFragment), out var oVar)
&& oVar is PageVariableFragment var && !var.OriginalText.IsNullOrEmpty())
{
throw new Exception($"Invalid literal: {literal.ToString()} in '{var.OriginalText}'", e);
}
throw;
}
}
private readonly Dictionary<string, ScriptBlock> blocksMap = new Dictionary<string, ScriptBlock>();
public ScriptBlock TryGetBlock(string name) => blocksMap.TryGetValue(name, out var block) ? block : Context.GetBlock(name);
public ScriptBlock GetBlock(string name)
{
var block = TryGetBlock(name);
if (block == null)
throw new NotSupportedException($"Block in '{VirtualPath}' named '{name}' was not found.");
return block;
}
public ScriptScopeContext CreateScope(Stream outputStream=null) =>
new ScriptScopeContext(this, outputStream ?? MemoryStreamFactory.GetStream(), null);
internal MethodInvoker GetFilterInvoker(string name, int argsCount, out ScriptMethods filter) => GetInvoker(name, argsCount, InvokerType.Filter, out filter);
internal MethodInvoker GetContextFilterInvoker(string name, int argsCount, out ScriptMethods filter) => GetInvoker(name, argsCount, InvokerType.ContextFilter, out filter);
internal MethodInvoker GetContextBlockInvoker(string name, int argsCount, out ScriptMethods filter) => GetInvoker(name, argsCount, InvokerType.ContextBlock, out filter);
private MethodInvoker GetInvoker(string name, int argsCount, InvokerType invokerType, out ScriptMethods filter)
{
if (!Context.ExcludeFiltersNamed.Contains(name) && !ExcludeFiltersNamed.Contains(name))
{
foreach (var tplFilter in ScriptMethods)
{
var invoker = tplFilter?.GetInvoker(name, argsCount, invokerType);
if (invoker != null)
{
filter = tplFilter;
return invoker;
}
}
foreach (var tplFilter in Context.ScriptMethods)
{
var invoker = tplFilter?.GetInvoker(name, argsCount, invokerType);
if (invoker != null)
{
filter = tplFilter;
return invoker;
}
}
}
filter = null;
return null;
}
public object EvaluateIfToken(object value, ScriptScopeContext scope)
{
if (value is JsToken token)
return token.Evaluate(scope);
return value;
}
internal bool TryGetValue(string name, ScriptScopeContext scope, out object value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
MethodInvoker invoker;
var ret = true;
value = scope.ScopedParams != null && scope.ScopedParams.TryGetValue(name, out object obj)
? obj
: Args.TryGetValue(name, out obj)
? obj
: Page != null && Page.Args.TryGetValue(name, out obj)
? obj
: CodePage != null && CodePage.Args.TryGetValue(name, out obj)
? obj
: LayoutPage != null && LayoutPage.Args.TryGetValue(name, out obj)
? obj
: Context.Args.TryGetValue(name, out obj)
? obj
: (invoker = GetFilterAsBinding(name, out ScriptMethods filter)) != null
? InvokeFilter(invoker, filter, new object[0], name)
: (invoker = GetContextFilterAsBinding(name, out filter)) != null
? InvokeFilter(invoker, filter, new object[]{ scope }, name)
: ((ret = false) ? (object)null : null);
return ret;
}
internal object GetValue(string name, ScriptScopeContext scope)
{
TryGetValue(name, scope, out var value);
return value;
}
public string ResultOutput => resultOutput;
private string resultOutput;
public string Result
{
get
{
try
{
if (resultOutput != null)
return resultOutput;
Init().Wait();
resultOutput = this.RenderToStringAsync().Result;
return resultOutput;
}
catch (AggregateException e)
{
var ex = e.UnwrapIfSingleException();
throw ex;
}
}
}
public PageResult Execute()
{
var render = Result;
return this;
}
public PageResult Clone(SharpPage page)
{
return new PageResult(page)
{
Args = Args,
ScriptMethods = ScriptMethods,
ScriptBlocks = ScriptBlocks,
FilterTransformers = FilterTransformers,
};
}
public void Dispose()
{
CodePage?.Dispose();
}
}
public class BindingExpressionException : Exception
{
public string Expression { get; }
public string Member { get; }
public BindingExpressionException(string message, string member, string expression, Exception inner=null)
: base(message, inner)
{
Expression = expression;
Member = member;
}
}
public class SyntaxErrorException : ArgumentException
{
public SyntaxErrorException() { }
public SyntaxErrorException(string message) : base(message) { }
public SyntaxErrorException(string message, Exception innerException) : base(message, innerException) { }
}
}
| |
// 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 CompareEqualUInt16()
{
var test = new SimpleBinaryOpTest__CompareEqualUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualUInt16 testClass)
{
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareEqualUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__CompareEqualUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.CompareEqual(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.CompareEqual(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareEqualUInt16();
var result = Avx2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareEqualUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] == right[0]) ? unchecked((ushort)(-1)) : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((ushort)(-1)) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SmartLMS.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright 2003-2004 DigitalCraftsmen - http://www.digitalcraftsmen.com.br/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.ManagementExtensions
{
using System;
using System.Text;
using System.Collections;
using System.Runtime.Serialization;
/// <summary>
/// Represents a ManagedObject's Name.
/// TODO: Supports query semantic.
/// </summary>
[Serializable]
public class ManagedObjectName : ISerializable
{
protected String domain;
protected String literalProperties = String.Empty;
protected Hashtable properties;
protected bool allProperties;
/// <summary>
/// Creates a ManagedObjectName using a name pattern like
/// "domain:key=value,key2=value2"
/// </summary>
/// <param name="name">Complete name</param>
public ManagedObjectName(String name)
{
Setup(name);
}
/// <summary>
/// Creates a ManagedObjectName with specified domain and
/// properties.
/// </summary>
/// <param name="domain">Domain name</param>
/// <param name="properties">Property list.</param>
public ManagedObjectName(String domain, String properties)
{
SetupDomain(domain);
SetupProperties(properties);
}
/// <summary>
/// Creates a ManagedObjectName with specified domain and
/// properties.
/// </summary>
/// <param name="domain">Domain name</param>
/// <param name="properties">Property list.</param>
public ManagedObjectName(String domain, Hashtable properties)
{
SetupDomain(domain);
SetupProperties(properties);
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public ManagedObjectName(SerializationInfo info, StreamingContext context)
{
String domain = info.GetString("domain");
String props = info.GetString("props");
SetupDomain(domain);
if (props != String.Empty)
{
SetupProperties(props);
}
}
/// <summary>
/// Parses the full name extracting the domain and properties.
/// </summary>
/// <param name="name">Full name.</param>
protected virtual void Setup(String name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.IndexOf(':') != -1)
{
String[] splitted = name.Split(new char[] { ':' });
SetupDomain(splitted[0]);
SetupProperties(splitted[1]);
}
else
{
SetupDomain(name);
}
}
/// <summary>
/// Sets up the domain. Can be empty but can't be null.
/// </summary>
/// <param name="domain"></param>
protected virtual void SetupDomain(String domain)
{
if (domain == null)
{
throw new ArgumentNullException("domain");
}
this.domain = domain;
}
/// <summary>
/// Parses and validate a properties list string like
/// "key=value,key2=value2" and so on.
/// </summary>
/// <param name="properties">Property list.</param>
protected virtual void SetupProperties(String properties)
{
if (properties == null)
{
throw new ArgumentNullException("properties");
}
if (properties.Equals("*"))
{
literalProperties = "*";
allProperties = true;
return;
}
String [] props = properties.Split( new char[] { ',' } );
Hashtable propsHash = new Hashtable(
CaseInsensitiveHashCodeProvider.Default,
CaseInsensitiveComparer.Default);
foreach(String chunk in props)
{
if (chunk.IndexOf('=') == -1)
{
throw new InvalidManagedObjectName("Invalid properties.");
}
String[] keyvalue = chunk.Split( new char[] { '=' } );
String key = keyvalue[0];
String value = keyvalue[1];
propsHash.Add(key, value);
}
SetupProperties(propsHash);
}
/// <summary>
/// Validates a properties Hashtable.
/// </summary>
/// <param name="properties">Property list.</param>
protected virtual void SetupProperties(Hashtable properties)
{
StringBuilder sb = new StringBuilder();
foreach(DictionaryEntry entry in properties)
{
if (sb.Length != 0)
{
sb.Append(",");
}
String key = null;
try
{
key = (String) entry.Key;
}
catch(InvalidCastException)
{
throw new InvalidManagedObjectName("Key is not a String.");
}
String value = null;
try
{
value = (String) entry.Value;
}
catch(InvalidCastException)
{
throw new InvalidManagedObjectName("Value is not a String.");
}
sb.AppendFormat("{0}={1}", key, value);
}
this.literalProperties = sb.ToString();
this.properties = new Hashtable(properties);
}
public String Domain
{
get
{
return domain;
}
}
public String LiteralProperties
{
get
{
return literalProperties;
}
}
public String this[ String key ]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
return (String) this.properties[key];
}
}
public override bool Equals(object obj)
{
ManagedObjectName other = obj as ManagedObjectName;
if (other != null)
{
return other.domain.Equals(domain) &&
other.literalProperties.Equals(literalProperties);
}
return false;
}
public override int GetHashCode()
{
return domain.GetHashCode() ^ literalProperties.GetHashCode();
}
public override string ToString()
{
return
String.Format("Domain: {0} Properties: {1}",
domain, literalProperties);
}
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("domain", domain);
info.AddValue("props", literalProperties);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotVVM.Framework.Compilation;
using DotVVM.Framework.Compilation.Binding;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Compilation.Parser;
using DotVVM.Framework.Compilation.Styles;
using DotVVM.Framework.Compilation.Validation;
using Newtonsoft.Json;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Routing;
using DotVVM.Framework.ResourceManagement;
using DotVVM.Framework.Runtime;
using DotVVM.Framework.Runtime.Filters;
using DotVVM.Framework.Security;
using DotVVM.Framework.ResourceManagement.ClientGlobalize;
using DotVVM.Framework.ViewModel;
using DotVVM.Framework.ViewModel.Serialization;
using DotVVM.Framework.ViewModel.Validation;
using System.Globalization;
using System.Reflection;
using DotVVM.Framework.Hosting.Middlewares;
using DotVVM.Framework.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using DotVVM.Framework.Runtime.Tracing;
using DotVVM.Framework.Compilation.Javascript;
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace DotVVM.Framework.Configuration
{
public sealed class DotvvmConfiguration
{
private bool isFrozen;
public const string DotvvmControlTagPrefix = "dot";
/// <summary>
/// Gets or sets the application physical path.
/// </summary>
[JsonProperty("applicationPhysicalPath")]
[DefaultValue(".")]
public string ApplicationPhysicalPath
{
get { return _applicationPhysicalPath; }
set { ThrowIfFrozen(); _applicationPhysicalPath = value; }
}
private string _applicationPhysicalPath = "."; // defaults to current working directory. In practice this gets overridden by app initializer
/// <summary>
/// Gets the settings of the markup.
/// </summary>
[JsonProperty("markup")]
public DotvvmMarkupConfiguration Markup { get; private set; }
/// <summary>
/// Gets the route table.
/// </summary>
[JsonProperty("routes")]
[JsonConverter(typeof(RouteTableJsonConverter))]
public DotvvmRouteTable RouteTable { get; private set; }
/// <summary>
/// Gets the configuration of resources.
/// </summary>
[JsonProperty("resources")]
[JsonConverter(typeof(ResourceRepositoryJsonConverter))]
public DotvvmResourceRepository Resources { get; private set; } = new DotvvmResourceRepository();
/// <summary>
/// Gets the security configuration.
/// </summary>
[JsonProperty("security")]
public DotvvmSecurityConfiguration Security { get; private set; } = new DotvvmSecurityConfiguration();
/// <summary>
/// Gets the runtime configuration.
/// </summary>
[JsonProperty("runtime")]
public DotvvmRuntimeConfiguration Runtime { get; private set; } = new DotvvmRuntimeConfiguration();
/// <summary>
/// Gets or sets the default culture.
/// </summary>
[JsonProperty("defaultCulture")]
public string DefaultCulture
{
get { return _defaultCulture; }
set { ThrowIfFrozen(); _defaultCulture = value; }
}
private string _defaultCulture;
/// <summary>
/// Gets or sets whether the client side validation rules should be enabled.
/// </summary>
[JsonProperty("clientSideValidation", DefaultValueHandling = DefaultValueHandling.Ignore)]
[DefaultValue(true)]
public bool ClientSideValidation
{
get { return _clientSideValidation; }
set { ThrowIfFrozen(); _clientSideValidation = value; }
}
private bool _clientSideValidation = true;
/// <summary>
/// Gets or sets whether navigation in the SPA pages should use History API. Always true
/// </summary>
[JsonIgnore]
[Obsolete("The UseHistoryApiSpaNavigation property is not supported - the classic SPA mode (URLs with #/) was removed from DotVVM, and the History API is the default and only option now. See https://www.dotvvm.com/docs/3.0/pages/concepts/layout/single-page-applications-spa#changes-to-spas-in-dotvvm-30 for more details.")]
public bool UseHistoryApiSpaNavigation => true;
/// <summary>
/// Gets or sets the configuration for experimental features.
/// </summary>
[JsonProperty("experimentalFeatures")]
public DotvvmExperimentalFeaturesConfiguration ExperimentalFeatures
{
get => _experimentalFeatures;
set { ThrowIfFrozen(); _experimentalFeatures = value; }
}
private DotvvmExperimentalFeaturesConfiguration _experimentalFeatures = new DotvvmExperimentalFeaturesConfiguration();
/// <summary>
/// Gets or sets whether the application should run in debug mode.
/// For ASP.NET Core check out <see href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments" />
/// </summary>
[JsonProperty("debug", DefaultValueHandling = DefaultValueHandling.Include)]
public bool Debug
{
get => _debug;
set { ThrowIfFrozen(); _debug = value; }
}
private bool _debug;
/// <summary>
/// Gets or sets the configuration for diagnostic features useful during the development of an application.
/// </summary>
[JsonProperty("diagnostics")]
public DotvvmDiagnosticsConfiguration Diagnostics
{
get { return _diagnostics; }
set { ThrowIfFrozen(); _diagnostics = value; }
}
private DotvvmDiagnosticsConfiguration _diagnostics = new();
private void ThrowIfFrozen()
{
if (isFrozen)
throw new InvalidOperationException("DotvvmConfiguration cannot be modified after initialization by IDotvvmStartup.");
}
/// <summary>
/// Prevent from changes.
/// </summary>
public void Freeze()
{
isFrozen = true;
Markup.Freeze();
RouteTable.Freeze();
Resources.Freeze();
Runtime.Freeze();
Security.Freeze();
ExperimentalFeatures.Freeze();
_routeConstraints.Freeze();
Styles.Freeze();
FreezableList.Freeze(ref _compiledViewsAssemblies);
}
[JsonIgnore]
public IDictionary<string, IRouteParameterConstraint> RouteConstraints => _routeConstraints;
private readonly FreezableDictionary<string, IRouteParameterConstraint> _routeConstraints = new FreezableDictionary<string, IRouteParameterConstraint>();
/// <summary>
/// Whether DotVVM compiler should generate runtime debug info for bindings. It can be useful, but may also cause unexpected problems.
/// </summary>
[JsonIgnore]
public bool AllowBindingDebugging
{
get { return _allowBindingDebugging; }
set { ThrowIfFrozen(); _allowBindingDebugging = value; }
}
private bool _allowBindingDebugging;
/// <summary>
/// Gets an instance of the service locator component.
/// </summary>
[JsonIgnore]
[Obsolete("You probably want to use ServiceProvider")]
public ServiceLocator ServiceLocator { get; private set; }
[JsonIgnore]
public IServiceProvider ServiceProvider { get; private set; }
[JsonIgnore]
public StyleRepository Styles
{
get { return _styles; }
set { ThrowIfFrozen(); _styles = value; }
}
private StyleRepository _styles;
[JsonProperty("compiledViewsAssemblies")]
public IList<string> CompiledViewsAssemblies
{
get { return _compiledViewsAssemblies; }
set { ThrowIfFrozen(); _compiledViewsAssemblies = value; }
}
private IList<string> _compiledViewsAssemblies = new FreezableList<string>() { "CompiledViews.dll" };
/// <summary> must be there for serialization </summary>
internal DotvvmConfiguration(): this(new ServiceLocator(CreateDefaultServiceCollection().BuildServiceProvider()).GetServiceProvider())
{ }
/// <summary>
/// Initializes a new instance of the <see cref="DotvvmConfiguration"/> class.
/// </summary>
internal DotvvmConfiguration(IServiceProvider services)
{
ServiceProvider = services;
#pragma warning disable
ServiceLocator = new ServiceLocator(services);
#pragma warning restore
_defaultCulture = CultureInfo.CurrentCulture.Name;
Markup = new DotvvmMarkupConfiguration(new Lazy<JavascriptTranslatorConfiguration>(() => ServiceProvider.GetRequiredService<IOptions<JavascriptTranslatorConfiguration>>().Value));
RouteTable = new DotvvmRouteTable(this);
_styles = new StyleRepository(this);
}
private static ServiceCollection CreateDefaultServiceCollection()
{
var services = new ServiceCollection();
DotvvmServiceCollectionExtensions.RegisterDotVVMServices(services);
return services;
}
/// <summary>
/// Creates the default configuration and optionally registers additional application services.
/// </summary>
/// <param name="registerServices">An action to register additional services.</param>
/// <param name="serviceProviderFactoryMethod">Register factory method to create your own instance of IServiceProvider.</param>
public static DotvvmConfiguration CreateDefault(Action<IServiceCollection>? registerServices = null, Func<IServiceCollection, IServiceProvider>? serviceProviderFactoryMethod = null)
{
var services = CreateDefaultServiceCollection();
registerServices?.Invoke(services);
return new ServiceLocator(services, serviceProviderFactoryMethod).GetService<DotvvmConfiguration>();
}
/// <summary>
/// Creates the default configuration using the given service provider.
/// </summary>
/// <param name="serviceProvider">The service provider to resolve services from.</param>
public static DotvvmConfiguration CreateDefault(IServiceProvider serviceProvider)
{
var config = new DotvvmConfiguration(serviceProvider);
config.Runtime.GlobalFilters.Add(new ModelValidationFilterAttribute());
config.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "dot", Namespace = "DotVVM.Framework.Controls", Assembly = "DotVVM.Framework" });
RegisterConstraints(config);
RegisterResources(config);
ConfigureOptions(config.RouteTable, serviceProvider);
ConfigureOptions(config.Markup, serviceProvider);
ConfigureOptions(config.Resources, serviceProvider);
ConfigureOptions(config.Runtime, serviceProvider);
ConfigureOptions(config.Security, serviceProvider);
ConfigureOptions(config.Styles, serviceProvider);
ConfigureOptions(config, serviceProvider);
return config;
}
/// <summary>
/// Creates a configuration with fake services in place of hosting-specific components.
/// </summary>
internal static DotvvmConfiguration CreateInternal(Action<IServiceCollection> registerServices)
{
return CreateDefault(services =>
{
services.TryAddSingleton<IViewModelProtector, FakeViewModelProtector>();
services.TryAddSingleton<ICsrfProtector, FakeCsrfProtector>();
registerServices(services);
});
}
private static void ConfigureOptions<T>(T obj, IServiceProvider serviceProvider)
where T : class
{
foreach (var conf in serviceProvider.GetServices<IConfigureOptions<T>>())
{
conf.Configure(obj);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
static void RegisterConstraints(DotvvmConfiguration configuration)
{
configuration.RouteConstraints.Add("alpha", GenericRouteParameterType.Create("[a-zA-Z]*?"));
configuration.RouteConstraints.Add("bool", GenericRouteParameterType.Create<bool>("true|false", bool.TryParse));
configuration.RouteConstraints.Add("decimal", GenericRouteParameterType.Create<decimal>("-?[0-9.e]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("double", GenericRouteParameterType.Create<double>("-?[0-9.e]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("float", GenericRouteParameterType.Create<float>("-?[0-9.e]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("guid", GenericRouteParameterType.Create<Guid>("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", Guid.TryParse));
configuration.RouteConstraints.Add("int", GenericRouteParameterType.Create<int>("-?[0-9]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("posint", GenericRouteParameterType.Create<int>("[0-9]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("length", new GenericRouteParameterType(p => "[^/]{" + p + "}"));
configuration.RouteConstraints.Add("long", GenericRouteParameterType.Create<long>("-?[0-9]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("max", new GenericRouteParameterType(p => "-?[0-9.e]*?", (valueString, parameter) => {
if (parameter is null) throw new Exception("The `max` route constraint must have a numeric parameter.");
double value;
if (!Invariant.TryParse(valueString, out value)) return ParameterParseResult.Failed;
if (double.Parse(parameter, CultureInfo.InvariantCulture) < value) return ParameterParseResult.Failed;
return ParameterParseResult.Create(value);
}));
configuration.RouteConstraints.Add("min", new GenericRouteParameterType(p => "-?[0-9.e]*?", (valueString, parameter) => {
if (parameter is null) throw new Exception("The `min` route constraint must have a numeric parameter.");
double value;
if (!Invariant.TryParse(valueString, out value)) return ParameterParseResult.Failed;
if (double.Parse(parameter, CultureInfo.InvariantCulture) > value) return ParameterParseResult.Failed;
return ParameterParseResult.Create(value);
}));
configuration.RouteConstraints.Add("range", new GenericRouteParameterType(p => "-?[0-9.e]*?", (valueString, parameter) => {
if (parameter is null) throw new Exception("The `range` route constraint must have two numeric parameters.");
double value;
if (!Invariant.TryParse(valueString, out value)) return ParameterParseResult.Failed;
var split = parameter.Split(',');
if (double.Parse(split[0], CultureInfo.InvariantCulture) > value || double.Parse(split[1], CultureInfo.InvariantCulture) < value) return ParameterParseResult.Failed;
return ParameterParseResult.Create(value);
}));
configuration.RouteConstraints.Add("maxLength", new GenericRouteParameterType(p => "[^/]{0," + p + "}"));
configuration.RouteConstraints.Add("minLength", new GenericRouteParameterType(p => "[^/]{" + p + ",}"));
configuration.RouteConstraints.Add("regex", new GenericRouteParameterType(p => {
if (p is null) throw new Exception("The `regex` route constraint must have a parameter.");
if (p.StartsWith("^")) throw new ArgumentException("Regex in route constraint should not start with `^`, it's always looking for full-match.");
if (p.EndsWith("$")) throw new ArgumentException("Regex in route constraint should not end with `$`, it's always looking for full-match.");
return p;
}));
}
private static void RegisterResources(DotvvmConfiguration configuration)
{
configuration.Resources.RegisterScript(ResourceConstants.KnockoutJSResourceName,
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.Resources.Scripts.knockout-latest.js",
debugName: "DotVVM.Framework.Resources.Scripts.knockout-latest.debug.js"));
configuration.Resources.RegisterScript(ResourceConstants.DotvvmResourceName + ".internal",
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.obj.javascript.root_only.dotvvm-root.js",
debugName: "DotVVM.Framework.obj.javascript.root_only_debug.dotvvm-root.js"),
dependencies: new[] { ResourceConstants.KnockoutJSResourceName },
module: true);
configuration.Resources.RegisterScript(ResourceConstants.DotvvmResourceName + ".internal-spa",
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.obj.javascript.root_spa.dotvvm-root.js",
debugName: "DotVVM.Framework.obj.javascript.root_spa_debug.dotvvm-root.js"),
dependencies: new[] { ResourceConstants.KnockoutJSResourceName },
module: true);
configuration.Resources.Register(ResourceConstants.DotvvmResourceName,
new InlineScriptResource(@"", ResourceRenderPosition.Anywhere, defer: true) {
Dependencies = new[] { ResourceConstants.DotvvmResourceName + ".internal" }
});
configuration.Resources.RegisterScript(ResourceConstants.DotvvmDebugResourceName,
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.Resources.Scripts.DotVVM.Debug.js"),
dependencies: new[] { ResourceConstants.DotvvmResourceName });
configuration.Resources.RegisterStylesheet(ResourceConstants.DotvvmFileUploadCssResourceName,
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.Resources.Styles.DotVVM.FileUpload.css"));
configuration.Resources.RegisterStylesheet(ResourceConstants.DotvvmInternalCssResourceName,
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.Resources.Styles.DotVVM.Internal.css"));
RegisterGlobalizeResources(configuration);
}
private static void RegisterGlobalizeResources(DotvvmConfiguration configuration)
{
configuration.Resources.RegisterScript(ResourceConstants.GlobalizeResourceName,
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.Resources.Scripts.Globalize.globalize.min.js"));
configuration.Resources.RegisterNamedParent("globalize", new JQueryGlobalizeResourceRepository());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using Microsoft.DotNet.Cli.Build.Framework;
using Microsoft.DotNet.InternalAbstractions;
using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers;
namespace Microsoft.DotNet.Cli.Build
{
public class DebTargets
{
[Target(nameof(GenerateSharedHostDeb),
nameof(GenerateSharedFrameworkDeb),
nameof(GenerateSdkDeb))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult GenerateDebs(BuildTargetContext c)
{
return c.Success();
}
[Target(nameof(InstallSharedFramework))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult GenerateSdkDeb(BuildTargetContext c)
{
var channel = c.BuildContext.Get<string>("Channel").ToLower();
var packageName = Monikers.GetSdkDebianPackageName(c);
var version = c.BuildContext.Get<BuildVersion>("BuildVersion").NuGetVersion;
var debFile = c.BuildContext.Get<string>("SdkInstallerFile");
var manPagesDir = Path.Combine(Dirs.RepoRoot, "Documentation", "manpages");
var previousVersionURL = $"https://dotnetcli.blob.core.windows.net/dotnet/{channel}/Installers/Latest/dotnet-ubuntu-x64.latest.deb";
var sdkPublishRoot = c.BuildContext.Get<string>("CLISDKRoot");
var sharedFxDebianPackageName = Monikers.GetDebianSharedFrameworkPackageName(c);
var objRoot = Path.Combine(Dirs.Output, "obj", "debian", "sdk");
if (Directory.Exists(objRoot))
{
Directory.Delete(objRoot, true);
}
Directory.CreateDirectory(objRoot);
Cmd(Path.Combine(Dirs.RepoRoot, "scripts", "package", "package-debian.sh"),
"-v", version,
"-i", sdkPublishRoot,
"-o", debFile,
"-p", packageName,
"-b", Monikers.CLISdkBrandName,
"-m", manPagesDir,
"--framework-debian-package-name", sharedFxDebianPackageName,
"--framework-nuget-name", Monikers.SharedFrameworkName,
"--framework-nuget-version", c.BuildContext.Get<string>("SharedFrameworkNugetVersion"),
"--previous-version-url", previousVersionURL,
"--obj-root", objRoot)
.Execute()
.EnsureSuccessful();
return c.Success();
}
[Target]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult GenerateSharedHostDeb(BuildTargetContext c)
{
var packageName = Monikers.GetDebianSharedHostPackageName(c);
var version = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostVersion;
var inputRoot = c.BuildContext.Get<string>("SharedHostPublishRoot");
var debFile = c.BuildContext.Get<string>("SharedHostInstallerFile");
var objRoot = Path.Combine(Dirs.Output, "obj", "debian", "sharedhost");
var manPagesDir = Path.Combine(Dirs.RepoRoot, "Documentation", "manpages");
if (Directory.Exists(objRoot))
{
Directory.Delete(objRoot, true);
}
Directory.CreateDirectory(objRoot);
Cmd(Path.Combine(Dirs.RepoRoot, "scripts", "package", "package-sharedhost-debian.sh"),
"--input", inputRoot, "--output", debFile, "-b", Monikers.SharedHostBrandName,
"--obj-root", objRoot, "--version", version, "-m", manPagesDir)
.Execute()
.EnsureSuccessful();
return c.Success();
}
[Target(nameof(InstallSharedHost))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult GenerateSharedFrameworkDeb(BuildTargetContext c)
{
var packageName = Monikers.GetDebianSharedFrameworkPackageName(c);
var version = c.BuildContext.Get<string>("SharedFrameworkNugetVersion");
var inputRoot = c.BuildContext.Get<string>("SharedFrameworkPublishRoot");
var debFile = c.BuildContext.Get<string>("SharedFrameworkInstallerFile");
var objRoot = Path.Combine(Dirs.Output, "obj", "debian", "sharedframework");
if (Directory.Exists(objRoot))
{
Directory.Delete(objRoot, true);
}
Directory.CreateDirectory(objRoot);
Cmd(Path.Combine(Dirs.RepoRoot, "scripts", "package", "package-sharedframework-debian.sh"),
"--input", inputRoot, "--output", debFile, "--package-name", packageName, "-b", Monikers.SharedFxBrandName,
"--framework-nuget-name", Monikers.SharedFrameworkName,
"--framework-nuget-version", c.BuildContext.Get<string>("SharedFrameworkNugetVersion"),
"--obj-root", objRoot, "--version", version)
.Execute()
.EnsureSuccessful();
return c.Success();
}
[Target(nameof(InstallSDK),
nameof(RunE2ETest),
nameof(RemovePackages))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult TestDebInstaller(BuildTargetContext c)
{
return c.Success();
}
[Target]
public static BuildTargetResult InstallSharedHost(BuildTargetContext c)
{
InstallPackage(c.BuildContext.Get<string>("SharedHostInstallerFile"));
return c.Success();
}
[Target(nameof(InstallSharedHost))]
public static BuildTargetResult InstallSharedFramework(BuildTargetContext c)
{
InstallPackage(c.BuildContext.Get<string>("SharedFrameworkInstallerFile"));
return c.Success();
}
[Target(nameof(InstallSharedFramework))]
public static BuildTargetResult InstallSDK(BuildTargetContext c)
{
InstallPackage(c.BuildContext.Get<string>("SdkInstallerFile"));
return c.Success();
}
[Target]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult RunE2ETest(BuildTargetContext c)
{
Directory.SetCurrentDirectory(Path.Combine(Dirs.RepoRoot, "test", "EndToEnd"));
Cmd("dotnet", "build")
.Execute()
.EnsureSuccessful();
var testResultsPath = Path.Combine(Dirs.Output, "obj", "debian", "test", "debian-endtoend-testResults.xml");
Cmd("dotnet", "test", "-xml", testResultsPath)
.Execute()
.EnsureSuccessful();
return c.Success();
}
[Target]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult RemovePackages(BuildTargetContext c)
{
IEnumerable<string> orderedPackageNames = new List<string>()
{
Monikers.GetSdkDebianPackageName(c),
Monikers.GetDebianSharedFrameworkPackageName(c),
Monikers.GetDebianSharedHostPackageName(c)
};
foreach(var packageName in orderedPackageNames)
{
RemovePackage(packageName);
}
return c.Success();
}
private static void InstallPackage(string packagePath)
{
Cmd("sudo", "dpkg", "-i", packagePath)
.Execute()
.EnsureSuccessful();
}
private static void RemovePackage(string packageName)
{
Cmd("sudo", "dpkg", "-r", packageName)
.Execute()
.EnsureSuccessful();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using ComplexTestSupport;
using Xunit;
namespace System.Numerics.Tests
{
public class arithmaticOperation_BinaryPlus_AddTest
{
private static void VerifyBinaryPlusResult(double realFirst, double imgFirst, double realSecond, double imgSecond)
{
// Create complex numbers
Complex cFirst = new Complex(realFirst, imgFirst);
Complex cSecond = new Complex(realSecond, imgSecond);
// calculate the expected results
double realExpectedResult = realFirst + realSecond;
double imgExpectedResult = imgFirst + imgSecond;
// local variable
Complex cResult;
// arithmetic addition operation
cResult = cFirst + cSecond;
// verify the result
Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult,
string.Format("Binary Plus test = ({0}, {1}) + ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond));
// arithmetic static addition operation
cResult = Complex.Add(cFirst, cSecond);
// verify the result
Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult,
string.Format("Add test = ({0}, {1}) + ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond));
}
[Fact]
public static void RunTests_Zero()
{
double real = Support.GetRandomDoubleValue(false);
double imaginary = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(0.0, 0.0, real, imaginary); // Verify 0+x=0
VerifyBinaryPlusResult(real, imaginary, 0.0, 0.0); // Verify 0+x=0
}
[Fact]
public static void RunTests_BoundaryValues()
{
double real;
double img;
// test with 'Max' + (Positive, Positive)
real = Support.GetRandomDoubleValue(false);
img = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(double.MaxValue, double.MaxValue, real, img);
// test with 'Max' + (Negative, Negative)
real = Support.GetRandomDoubleValue(true);
img = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(double.MaxValue, double.MaxValue, real, img);
// test with 'Min' + (Positive, Positive)
real = Support.GetRandomDoubleValue(false);
img = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(double.MinValue, double.MinValue, real, img);
// test with 'Min' + (Negative, Negative)
real = Support.GetRandomDoubleValue(true);
img = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(double.MinValue, double.MinValue, real, img);
}
[Fact]
public static void RunTests_RandomValidValues()
{
// Verify test results with ComplexInFirstQuad + ComplexInFirstQuad
double realFirst = Support.GetRandomDoubleValue(false);
double imgFirst = Support.GetRandomDoubleValue(false);
double realSecond = Support.GetRandomDoubleValue(false);
double imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInFirstQuad + ComplexInSecondQuad
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInFirstQuad + ComplexInThirdQuad
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInFirstQuad + ComplexInFourthQuad
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInSecondQuad + ComplexInSecondQuad
realFirst = Support.GetRandomDoubleValue(true);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInSecondQuad + ComplexInThirdQuad
realFirst = Support.GetRandomDoubleValue(true);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInSecondQuad + ComplexInFourthQuad
realFirst = Support.GetRandomDoubleValue(true);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInThirdQuad + ComplexInThirdQuad
realFirst = Support.GetRandomDoubleValue(true);
imgFirst = Support.GetRandomDoubleValue(true);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInThirdQuad + ComplexInFourthQuad
realFirst = Support.GetRandomDoubleValue(true);
imgFirst = Support.GetRandomDoubleValue(true);
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify test results with ComplexInFourthQuad + ComplexInFourthQuad
realFirst = Support.GetRandomDoubleValue(true);
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
}
[Fact]
public static void RunTests_InvalidImaginaryValues()
{
double realFirst;
double imgFirst;
double realSecond;
double imgSecond;
// Verify with (valid, PositiveInfinity) + (valid, PositiveValid)
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = double.PositiveInfinity;
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (valid, PositiveInfinity) + (valid, NegativeValid)
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = double.PositiveInfinity;
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (valid, NegativeInfinity) + (valid, PositiveValid)
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = double.NegativeInfinity;
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (valid, NegativeInfinity) + (valid, NegativeValid)
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = double.NegativeInfinity;
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(true);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (valid, NaN) + (valid, Valid)
realFirst = Support.GetRandomDoubleValue(false);
imgFirst = double.NaN;
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
}
[Fact]
public static void RunTests_InvalidRealValues()
{
double realFirst;
double imgFirst;
double realSecond;
double imgSecond;
// Verify with (PositiveInfinity, valid) + (PositiveValid, valid)
realFirst = double.PositiveInfinity;
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (PositiveInfinity, valid) + (NegativeValid, valid)
realFirst = double.PositiveInfinity;
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (NegativeInfinity, valid) + (PositiveValid, valid)
realFirst = double.NegativeInfinity;
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (NegativeInfinity, valid) + (NegativeValid, valid)
realFirst = double.NegativeInfinity;
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(true);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
// Verify with (NaN, valid) + (valid, valid)
realFirst = double.NaN;
imgFirst = Support.GetRandomDoubleValue(false);
realSecond = Support.GetRandomDoubleValue(false);
imgSecond = Support.GetRandomDoubleValue(false);
VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolymorphicrecursiveOperations operations.
/// </summary>
internal partial class PolymorphicrecursiveOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IPolymorphicrecursiveOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphicrecursiveOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolymorphicrecursiveOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<FishInner>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<FishInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<FishInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "fishtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "fishtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(FishInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiAreaTestApp.Areas.HelpPage.SampleGeneration
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using Axiom.MathLib;
using Axiom.Core;
namespace Axiom.SceneManagers.Multiverse
{
public delegate void MosaicModificationStateChangedHandler(Mosaic mosaic, bool state);
public delegate void MosaicChangedHandler(Mosaic mosaic, MosaicTile tile, int worldXMeters, int worldZMeters, int sizeXMeters, int sizeZMeters);
public abstract class Mosaic
{
public bool Modified
{
get
{
return m_modified;
}
protected set
{
if (m_modified == value)
{
return;
}
m_modified = value;
if (MosaicModificationStateChanged != null)
{
MosaicModificationStateChanged(this, m_modified);
}
}
}
public event MosaicModificationStateChangedHandler MosaicModificationStateChanged;
public event MosaicChangedHandler MosaicChanged;
public MosaicDescription MosaicDesc
{
get
{
return desc;
}
}
protected MosaicDescription desc;
// the radius (in tiles) from the camera that should be preloaded
protected int preloadRadius;
public object BaseName { get; private set; }
// the location of the camera
protected Vector3 cameraLocation;
protected int cameraTileX = int.MaxValue;
protected int cameraTileZ = int.MaxValue;
protected MosaicTile[,] tiles;
protected int sizeXTiles;
protected int sizeZTiles;
protected int tileShift;
protected int tileMask;
protected int xWorldOffsetMeters;
protected int zWorldOffsetMeters;
protected abstract MosaicTile NewTile(int tileX, int tileZ, Vector3 worldLocMM);
//todo: change modifiedTiles to a HashSet when we can use .Net 3.0
private readonly List<MosaicTile> modifiedTiles = new List<MosaicTile>();
private bool m_modified;
protected Mosaic(string baseName, int preloadRadius, MosaicDescription desc)
{
this.desc = desc;
//todo: save description into MMF file using baseName
BaseName = baseName;
this.preloadRadius = preloadRadius;
Init();
}
protected Mosaic(string baseName, int preloadRadius)
{
Stream s = ResourceManager.FindCommonResourceData(string.Format("{0}.mmf", baseName));
desc = new MosaicDescription(s);
BaseName = baseName;
this.preloadRadius = preloadRadius;
Init();
}
private /*sealed*/ void Init()
{
sizeXTiles = desc.SizeXTiles;
sizeZTiles = desc.SizeZTiles;
// Center the map on the world origin
int pageSize = TerrainManager.Instance.PageSize;
int centerXMeters = (desc.SizeXPixels * desc.MetersPerSample) / 2;
int centerZMeters = (desc.SizeZPixels * desc.MetersPerSample) / 2;
centerXMeters = (centerXMeters / pageSize) * pageSize;
centerZMeters = (centerZMeters / pageSize) * pageSize;
xWorldOffsetMeters = centerXMeters;
zWorldOffsetMeters = centerZMeters;
tiles = new MosaicTile[sizeXTiles, sizeZTiles];
for (int tileX = 0; tileX < sizeXTiles; tileX++)
{
for (int tileZ = 0; tileZ < sizeZTiles; tileZ++)
{
float worldTileSizeMM = desc.TileSizeSamples * desc.MetersPerSample * TerrainManager.oneMeter;
Vector3 worldLocMM = new Vector3(tileX * worldTileSizeMM - xWorldOffsetMeters * TerrainManager.oneMeter, 0, tileZ * worldTileSizeMM - zWorldOffsetMeters * TerrainManager.oneMeter);
MosaicTile tile = NewTile(tileX, tileZ, worldLocMM);
tile.TileModificationStateChanged += UpdateModifiedState;
tile.TileChanged += Tile_OnTileChanged;
tiles[tileX, tileZ] = tile;
}
}
TerrainManager.Instance.SettingCameraLocation += CameraLocationPreChange;
int tileSize = desc.TileSizeSamples;
tileMask = tileSize - 1;
tileShift = 0;
while (tileSize > 1)
{
tileSize = tileSize >> 1;
tileShift++;
}
// ensure its a power of 2
Debug.Assert((1 << tileShift) == desc.TileSizeSamples);
}
private void Tile_OnTileChanged(MosaicTile tile, int tileXSample, int tileZSample, int sizeXSamples, int sizeZSamples)
{
if (MosaicChanged != null)
{
// Convert samples coordinates & size to world coordinates & size in meters
int tileSizeMeters = desc.MetersPerSample * desc.TileSizeSamples;
// Calculate the upper left corner of the tile in world coordinates
int worldXMeters = tileXSample * desc.MetersPerSample - xWorldOffsetMeters;
int worldZMeters = tileZSample * desc.MetersPerSample - zWorldOffsetMeters;
// Adjust for the tile-specific coordinate
worldXMeters += tile.tileX * tileSizeMeters;
worldZMeters += tile.tileZ * tileSizeMeters;
// Calculate the size of the modified area in meters
int sizeXMeters = sizeXSamples * desc.MetersPerSample;
int sizeZMeters = sizeZSamples * desc.MetersPerSample;
// Generate the notification
MosaicChanged(this, tile, worldXMeters, worldZMeters, sizeXMeters, sizeZMeters);
}
}
private void UpdateModifiedState(MosaicTile tile, bool state)
{
bool contained = modifiedTiles.Contains(tile);
//todo: change modifiedTiles to a HashSet when we can use .Net 3.0
//todo: this would simplify the logic to simply adding or removing based on state
if (contained && !state)
{
modifiedTiles.Remove(tile);
}
else if (!contained && state)
{
modifiedTiles.Add(tile);
}
Modified = modifiedTiles.Count > 0 || desc.Modified;
}
private void Preload()
{
cameraTileX = (int)Math.Floor((cameraLocation.x + xWorldOffsetMeters * TerrainManager.oneMeter) / (desc.TileSizeSamples * desc.MetersPerSample * TerrainManager.oneMeter));
cameraTileZ = (int)Math.Floor((cameraLocation.z + zWorldOffsetMeters * TerrainManager.oneMeter) / (desc.TileSizeSamples * desc.MetersPerSample * TerrainManager.oneMeter));
// compute preload area using current camera tile and the preload radius
int startX = cameraTileX - preloadRadius;
int endX = cameraTileX + preloadRadius;
int startZ = cameraTileZ - preloadRadius;
int endZ = cameraTileZ + preloadRadius;
// clip to tile area
if (startX < 0)
{
startX = 0;
}
if (endX >= sizeXTiles)
{
endX = sizeXTiles - 1;
}
if (startZ < 0)
{
startZ = 0;
}
if (endZ >= sizeZTiles)
{
endZ = sizeZTiles - 1;
}
// load all tiles in the preload area
for (int x = startX; x <= endX; x++)
{
for (int z = startZ; z <= endZ; z++)
{
tiles[x, z].Load();
}
}
}
private void CameraLocationPreChange(object sender, CameraLocationEventArgs args)
{
cameraLocation = args.newLocation;
int newCameraTileX = (int)Math.Floor(cameraLocation.x / (desc.TileSizeSamples * TerrainManager.oneMeter));
int newCameraTileZ = (int)Math.Floor(cameraLocation.z / (desc.TileSizeSamples * TerrainManager.oneMeter));
if ((cameraTileX != newCameraTileX) || (cameraTileZ != newCameraTileZ))
{
cameraTileX = newCameraTileX;
cameraTileZ = newCameraTileZ;
Preload();
}
}
public virtual void Save(bool force)
{
desc.Save(force);
if (force)
{
for (int z=0; z < sizeZTiles; z++)
{
for (int x=0; x < sizeXTiles; x++)
{
tiles[x,z].Save(force);
}
}
}
else
{
// We need to create a copy because Saving tiles will updated
// the modifiedTiles list.
List<MosaicTile> listCopy = new List<MosaicTile>(modifiedTiles);
foreach (MosaicTile tile in listCopy)
{
tile.Save(force);
}
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("DudeWorld/Swordz Player")]
public class SwordzPlayer : MonoBehaviour
{
public int humanPlayer;
public BlockMeter lifeMeter;
public GUIText statusText;
public Color playerColor;
public string characterFile;
public bool mouseControls = false;
public int simultaneousAttackers = 2;
private Dude dude;
//private DudeController controller;
private SwordzDude swordzDude;
private Damageable damageable;
private Detector detector;
private int healthPerBlock = 10;
private List<GameObject> attackers;
private float lastAttackTime = 0.0f;
private bool arcadeTwoButtons = false;
private CharacterController character;
private Vector3 lastSafePosition;
private float safePositionUpdateRate = 1.0f;
private float lastSafePositionUpdate = 0.0f;
private float runbuttonTime = 0.0f;
private float sprintDelay = 0.6f;
// urverden stuff
public Vector3 LastSafePosition
{
get { return lastSafePosition; }
}
void Awake() {
character = GetComponent<CharacterController>();
dude = gameObject.GetComponent<Dude>();
swordzDude = gameObject.GetComponent<SwordzDude>();
damageable = gameObject.GetComponent<Damageable>();
detector = gameObject.GetComponentInChildren<Detector>();
//controller = gameObject.GetComponent(typeof(DudeController)) as DudeController;
attackers = new List<GameObject>();
}
// Use this for initialization
void Start () {
//healthPerBlock = dude.maxHealth / lifeMeter.maxBlocks;
if(mouseControls) Screen.showCursor = true;
}
void FixedUpdate()
{
if(transform.position.y >= 0.0f && (Time.fixedTime - lastSafePositionUpdate) >= safePositionUpdateRate)
{
lastSafePosition = transform.position + (Vector3.up * 0.1f);
lastSafePositionUpdate = Time.fixedTime;
}
}
void OnFall()
{
var respawnPrefab = Resources.Load("Effects/boom_enemy_spawn") as GameObject;
Instantiate(respawnPrefab, lastSafePosition, Quaternion.identity);
transform.position = lastSafePosition;
}
void Update ()
{
// if there are joysticks connected while in singleplayer mode (mouse controls), then disable them
if(mouseControls && Input.GetJoystickNames().Length > 0)
{
mouseControls = false;
}
/*
if(mouseControls &&
Input.GetAxis("Horizontal_"+humanPlayer) == 0.0f && Input.GetAxis("Vertical_"+humanPlayer) == 0.0f)
{
gameObject.SendMessage("LookAtMouse");
}
*/
// snap look if player is performing an action
/*
if(Input.GetButtonDown("Attack_"+humanPlayer) ||
Input.GetButtonDown("Dodge_"+humanPlayer) ||
Input.GetButtonDown("Block_"+humanPlayer))
{
dude.Look(controller.GetMoveVec());
}
*/
bool canLook = !swordzDude.status.attacking && !swordzDude.status.attackingRecovery;
// allow players to cancel into other actions
if(Input.GetButtonDown("Block_"+humanPlayer) ||
Input.GetButtonDown("Dodge_"+humanPlayer))
{
swordzDude.OnCancel();
}
if(Input.GetButtonDown("Attack_"+humanPlayer))
{
LookInAttackDirection();
gameObject.SendMessage("OnAttack");
//if(dude.blocking)
// gameObject.BroadcastMessage("OnBash");
lastAttackTime = Time.time;
}
// dodging and sprinting
if(Input.GetButtonUp("Dodge_"+humanPlayer))
{
if(swordzDude.status.running)
{
gameObject.BroadcastMessage("OnSprintEnd");
}
else if(!Input.GetButton("Attack_"+humanPlayer) && !swordzDude.status.running)
{
dude.Look();
gameObject.BroadcastMessage("OnDodge");
}
}
else if(Input.GetButtonDown("Dodge_"+humanPlayer))
{
runbuttonTime = Time.time;
}
else if((Input.GetButton("Dodge_"+humanPlayer) && runbuttonTime != 0.0f &&
Time.time - runbuttonTime >= sprintDelay))
{
gameObject.BroadcastMessage("OnSprint");
runbuttonTime = 0.0f;
}
if((Input.GetButton("Block_"+humanPlayer) && !Input.GetButton("Attack_"+humanPlayer)))
{
if(!dude.blocking) {
if(canLook)
{
if(mouseControls) gameObject.SendMessage("LookAtMouse");
else dude.Look();
}
gameObject.SendMessage("OnBlock");
}
}
else if(Input.GetButtonUp("Block_"+humanPlayer)) {
gameObject.BroadcastMessage("OnBlockEnd");
}
if((Input.GetButton("Block_"+humanPlayer)) && canLook && mouseControls) {
gameObject.SendMessage("LookAtMouse");
}
/*
if(Input.GetButtonDown("Fire4_"+humanPlayer)) {
gameObject.SendMessage("OnDisarm");
}
*/
if(lifeMeter != null)
{
lifeMeter.SetMaxBlocks( (int)Mathf.Ceil(damageable.maxHealth / healthPerBlock) );
lifeMeter.SetBlocks(damageable.GetHealth()/healthPerBlock);
}
}
/*void OnSetPlayer(int playerNum)
{
humanPlayer = playerNum;
}*/
void OnShotHit(DamageEvent data)
{
// we send damagedealt in Dude now ... that might not be a good idea
//Director.GetSingleton().SendMessage("OnDamageDealt", data);
}
void OnKill()
{
//swordzDude.OnDisarm();
//lifeMeter.SetBlocks(0);
//Director.GetSingleton().SendMessage("OnPlayerDeath", humanPlayer);
}
void OnRequestAttack(GameObject requestor)
{
attackers.RemoveAll(item => item == null);
if(attackers.Count < simultaneousAttackers)
{
if(!attackers.Contains(requestor))
attackers.Add(requestor);
requestor.SendMessage("OnAllowAttack", gameObject);
//Debug.Log("Attack accepted, current attackers: " + attackers.Count);
}
else
{
//Debug.Log("Attack REJECTED, current attackers: " + attackers.Count);
}
}
void OnCancelAttack(GameObject requestor)
{
attackers.Remove(requestor);
}
void OnFollowUp()
{
if(detector.target != null)
{
LookAtTarget();
}
else if(mouseControls)
{
gameObject.SendMessage("LookAtMouse");
}
else
{
//dude.Look(currentFacing);
}
}
// FIXME: this function and the next look amazingly similar
void LookAtTarget()
{
if(detector.target != null)
{
var lookVec = detector.target.position - transform.position;
if(Vector3.Angle(transform.forward, lookVec) < 90.0f)
dude.Look(lookVec);
else if(mouseControls)
gameObject.SendMessage("LookAtMouse");
else
dude.Look();
}
}
public void LookInAttackDirection()
{
bool canLook = !swordzDude.status.attacking && !swordzDude.status.attackingRecovery;
if(canLook)
{
if(detector.target != null)
{
LookAtTarget();
}
else if(mouseControls) gameObject.SendMessage("LookAtMouse");
else dude.Look();
}
}
void OnDrawGizmos()
{
if(attackers != null)
{
foreach(var attacker in attackers)
{
if(attacker != null)
{
Gizmos.color = Color.magenta;
Gizmos.DrawWireSphere(attacker.transform.position, 1.0f);
}
}
}
if(lastSafePosition != null)
{
Gizmos.DrawWireCube(lastSafePosition, Vector3.one * 0.1f);
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* 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>
/// CouponResponse
/// </summary>
[DataContract]
public partial class CouponResponse : IEquatable<CouponResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CouponResponse" /> class.
/// </summary>
/// <param name="coupon">coupon.</param>
/// <param name="error">error.</param>
/// <param name="itemsInvalidForCoupons">Items invalid for coupons. These will display as warnings within the UI..</param>
/// <param name="metadata">metadata.</param>
/// <param name="success">Indicates if API call was successful.</param>
/// <param name="warning">warning.</param>
public CouponResponse(Coupon coupon = default(Coupon), Error error = default(Error), List<string> itemsInvalidForCoupons = default(List<string>), ResponseMetadata metadata = default(ResponseMetadata), bool? success = default(bool?), Warning warning = default(Warning))
{
this.Coupon = coupon;
this.Error = error;
this.ItemsInvalidForCoupons = itemsInvalidForCoupons;
this.Metadata = metadata;
this.Success = success;
this.Warning = warning;
}
/// <summary>
/// Gets or Sets Coupon
/// </summary>
[DataMember(Name="coupon", EmitDefaultValue=false)]
public Coupon Coupon { get; set; }
/// <summary>
/// Gets or Sets Error
/// </summary>
[DataMember(Name="error", EmitDefaultValue=false)]
public Error Error { get; set; }
/// <summary>
/// Items invalid for coupons. These will display as warnings within the UI.
/// </summary>
/// <value>Items invalid for coupons. These will display as warnings within the UI.</value>
[DataMember(Name="items_invalid_for_coupons", EmitDefaultValue=false)]
public List<string> ItemsInvalidForCoupons { get; set; }
/// <summary>
/// Gets or Sets Metadata
/// </summary>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public ResponseMetadata Metadata { get; set; }
/// <summary>
/// Indicates if API call was successful
/// </summary>
/// <value>Indicates if API call was successful</value>
[DataMember(Name="success", EmitDefaultValue=false)]
public bool? Success { get; set; }
/// <summary>
/// Gets or Sets Warning
/// </summary>
[DataMember(Name="warning", EmitDefaultValue=false)]
public Warning Warning { 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 CouponResponse {\n");
sb.Append(" Coupon: ").Append(Coupon).Append("\n");
sb.Append(" Error: ").Append(Error).Append("\n");
sb.Append(" ItemsInvalidForCoupons: ").Append(ItemsInvalidForCoupons).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" Success: ").Append(Success).Append("\n");
sb.Append(" Warning: ").Append(Warning).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 CouponResponse);
}
/// <summary>
/// Returns true if CouponResponse instances are equal
/// </summary>
/// <param name="input">Instance of CouponResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CouponResponse input)
{
if (input == null)
return false;
return
(
this.Coupon == input.Coupon ||
(this.Coupon != null &&
this.Coupon.Equals(input.Coupon))
) &&
(
this.Error == input.Error ||
(this.Error != null &&
this.Error.Equals(input.Error))
) &&
(
this.ItemsInvalidForCoupons == input.ItemsInvalidForCoupons ||
this.ItemsInvalidForCoupons != null &&
this.ItemsInvalidForCoupons.SequenceEqual(input.ItemsInvalidForCoupons)
) &&
(
this.Metadata == input.Metadata ||
(this.Metadata != null &&
this.Metadata.Equals(input.Metadata))
) &&
(
this.Success == input.Success ||
(this.Success != null &&
this.Success.Equals(input.Success))
) &&
(
this.Warning == input.Warning ||
(this.Warning != null &&
this.Warning.Equals(input.Warning))
);
}
/// <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.Coupon != null)
hashCode = hashCode * 59 + this.Coupon.GetHashCode();
if (this.Error != null)
hashCode = hashCode * 59 + this.Error.GetHashCode();
if (this.ItemsInvalidForCoupons != null)
hashCode = hashCode * 59 + this.ItemsInvalidForCoupons.GetHashCode();
if (this.Metadata != null)
hashCode = hashCode * 59 + this.Metadata.GetHashCode();
if (this.Success != null)
hashCode = hashCode * 59 + this.Success.GetHashCode();
if (this.Warning != null)
hashCode = hashCode * 59 + this.Warning.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) 2015, InWorldz Halcyon Developers
* 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 halcyon 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 log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace OpenSim.Region.Framework.AvatarTransit.SendStates
{
internal class SendAvatarState : TransitStateBase
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private InTransitAvatar _avatar;
public SendAvatarState(InTransitAvatar _avatar, TransitStateBase progenitor)
{
this._avatar = _avatar;
this.Progenitor = progenitor;
}
public override async Task StateEntry()
{
await _avatar.TriggerOnTransitStageChanged(TransitStage.SendEstablishChildPresence, _avatar.RideOnPrims);
SimpleRegionInfo destination = _avatar.TransitArgs.DestinationRegion;
//do we have a presence on the destination?
if (!_avatar.ScenePresence.RemotePresences.HasPresenceOnRegion(destination.RegionHandle))
{
//no, we need to establish a new presence
Tuple<EstablishPresenceResult, string> result =
await _avatar.ScenePresence.RemotePresences.EstablishPresenceOnRegionLocked(destination, false, true);
if (result.Item1 != EstablishPresenceResult.Success)
{
//something broke
_avatar.ScenePresence.ControllingClient.SendAlertMessage(
"Unable to complete transfer to new region: " + result.Item2);
throw new SendAvatarException(
String.Format("Could not establish presence on remote region: {0}", result.Item2));
}
RollbackActions.Push(() => { _avatar.ScenePresence.RemotePresences.DropRemotePresenceLocked(destination, true).Wait(); });
}
AvatarRemotePresence remotePresence = null;
_avatar.ScenePresence.RemotePresences.TryGetRemotePresenceLocked(destination.RegionHandle,
(AvatarRemotePresence pres) =>
{
remotePresence = pres;
}
);
if (remotePresence == null)
{
//something is horked
throw new SendAvatarException(
String.Format("Presence could not be established on new region for {0}", _avatar.ScenePresence.Name));
}
//we have a presence now, we can send the child agent update
await _avatar.TriggerOnTransitStageChanged(TransitStage.SendAvatarHandoff, _avatar.RideOnPrims);
//the ChildAgentUpdate below will always stop attachment scripts to transmit their state
//if anything from this point on fails, we need to start the scripts running again
RollbackActions.Push(() =>
{
List<SceneObjectGroup> attachments = _avatar.ScenePresence.GetAttachments();
foreach (var att in attachments)
{
att.EndTransit(false);
}
}
);
// Invoke the agent2 entry point
ChildAgentUpdate2Response rc = this.SendChildAgentUpdate2();
switch (rc)
{
case ChildAgentUpdate2Response.Ok:
break; // continue normally
case ChildAgentUpdate2Response.AccessDenied:
throw new SendAvatarException(
String.Format("Region entry denied for {0}", _avatar.ScenePresence.Name));
case ChildAgentUpdate2Response.MethodNotAvailalble:
throw new SendAvatarException(
String.Format("Region change not available for {0}", _avatar.ScenePresence.Name));
case ChildAgentUpdate2Response.Error:
default:
throw new SendAvatarException(
String.Format("Region change failed for {0}", _avatar.ScenePresence.Name));
}
//this avatar is now considered a child agent
_avatar.ScenePresence.MakeChildAgent(_avatar.TransitArgs.DestinationRegion.RegionHandle);
//if there is a failure, we will need to restore the user as a root agent
Vector3 restorePos = _avatar.ScenePresence.AbsolutePosition;
Util.ForceValidRegionXY(ref restorePos);
RollbackActions.Push(() => { _avatar.ScenePresence.MakeRootAgent(restorePos); });
//the user is ready to be transfered
IEventQueue eq = _avatar.ScenePresence.Scene.RequestModuleInterface<IEventQueue>();
bool eventWasQueued = false;
switch (_avatar.TransitArgs.Type)
{
case TransitType.OutboundCrossing:
eventWasQueued = eq.CrossRegion(_avatar.TransitArgs.DestinationRegion.RegionHandle,
_avatar.TransitArgs.LocationInDestination,
_avatar.ScenePresence.Velocity,
_avatar.TransitArgs.DestinationRegion.ExternalEndPoint,
remotePresence.PresenceInfo.FullCapsSeedURL,
_avatar.ScenePresence.UUID,
_avatar.ScenePresence.ControllingClient.SessionId);
break;
case TransitType.OutboundTeleport:
eventWasQueued = eq.TeleportFinishEvent(_avatar.TransitArgs.DestinationRegion.RegionHandle,
13,
_avatar.TransitArgs.DestinationRegion.ExternalEndPoint,
4,
(uint)_avatar.TransitArgs.TeleportFlags,
remotePresence.PresenceInfo.FullCapsSeedURL,
_avatar.ScenePresence.UUID);
break;
default:
throw new SendAvatarException(String.Format("Invalid transit type {0} for sending avatar {1}",
_avatar.TransitArgs.Type));
}
if (!eventWasQueued)
{
throw new SendAvatarException(String.Format("Unable to enqueue transfer event for {0}",
_avatar.ScenePresence.Name));
}
//wait for confirmation of avatar on the other side
await _avatar.WaitForRelease();
//matching endtransit for all attachments
List<SceneObjectGroup> sentAttachments = _avatar.ScenePresence.GetAttachments();
foreach (var att in sentAttachments)
{
att.EndTransit(true);
}
_avatar.ScenePresence.AttachmentsCrossedToNewRegion();
//unsit the SP if appropriate
if (_avatar.TransitArgs.RideOnPart != null)
{
_avatar.TransitArgs.RideOnPart.SetAvatarOnSitTarget(UUID.Zero, false);
}
//this avatar is history.
_avatar.ScenePresence.Reset(_avatar.TransitArgs.DestinationRegion);
// the user may change their profile information in other region,
// so the userinfo in UserProfileCache is not reliable any more, delete it
if (_avatar.ScenePresence.Scene.NeedSceneCacheClear(_avatar.UserId))
{
_avatar.ScenePresence.Scene.CommsManager.UserProfileCacheService.RemoveUser(_avatar.UserId);
}
_avatar.ScenePresence.Scene.EventManager.TriggerAvatarLeavingRegion(_avatar.ScenePresence,
_avatar.TransitArgs.DestinationRegion);
}
private ChildAgentUpdate2Response SendChildAgentUpdate2()
{
ScenePresence agent = _avatar.ScenePresence;
SceneObjectGroup sceneObjectGroup = _avatar.TransitArgs.RideOnGroup;
SceneObjectPart part = _avatar.TransitArgs.RideOnPart;
ulong newRegionHandle = _avatar.TransitArgs.DestinationRegion.RegionHandle;
SimpleRegionInfo neighbourRegion = _avatar.TransitArgs.DestinationRegion;
Vector3 pos = _avatar.TransitArgs.LocationInDestination;
AgentLocomotionFlags locomotionFlags = 0 ;
if (_avatar.TransitArgs.Type == TransitType.OutboundCrossing)
{
locomotionFlags = AgentLocomotionFlags.Crossing;
}
else if (_avatar.TransitArgs.Type == TransitType.OutboundTeleport)
{
locomotionFlags = AgentLocomotionFlags.Teleport;
}
AgentData cAgent = new AgentData();
agent.CopyToForRootAgent(cAgent);
if (part != null)
{
cAgent.Position = part.AbsolutePosition;
cAgent.SatOnPrim = part.UUID;
cAgent.SatOnPrimOffset = part.SitTargetPosition;
}
else
{
cAgent.Position = pos;
}
if (sceneObjectGroup != null)
cAgent.SatOnGroup = sceneObjectGroup.UUID;
cAgent.LocomotionState = 1;
cAgent.LocomotionFlags = locomotionFlags;
List<SceneObjectGroup> attachments = agent.CollectAttachmentsForCrossing();
//try the new comms first
var engine = ProviderRegistry.Instance.Get<ISerializationEngine>();
if (engine == null)
{
_log.ErrorFormat("[SCENE COMM]: Cannot send child agent update to {0}, Serialization engine is missing!",
neighbourRegion.RegionHandle);
return ChildAgentUpdate2Response.Error;
}
List<byte[]> serializedAttachments = new List<byte[]>();
foreach (var att in attachments)
{
//mark the SOG in-transit. this along with the serialization below sends a disable to the script engine, but they are not cumulative
att.StartTransit();
//we are stopping the scripts as part of the serialization process here
//this means that later on, should the remote creation call fail, we need to re-enable them
//reenabling is done via EndTransit with success==false
byte[] sogBytes = engine.SceneObjectSerializer.SerializeGroupToBytes(att, SerializationFlags.FromCrossing | SerializationFlags.StopScripts | SerializationFlags.SerializeScriptBytecode);
serializedAttachments.Add(sogBytes);
}
cAgent.SerializedAttachments = serializedAttachments;
var scene = agent.Scene;
cAgent.CallbackURI = scene.RegionInfo.InsecurePublicHTTPServerURI +
"/agent/" + agent.UUID.ToString() + "/" + agent.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
ChildAgentUpdate2Response resp = scene.InterregionComms.SendChildAgentUpdate2(neighbourRegion, cAgent);
if (resp == ChildAgentUpdate2Response.Error)
{
_log.ErrorFormat("[SCENE COMM]: Error sending child agent update to {0}", neighbourRegion.RegionHandle);
}
else if (resp == ChildAgentUpdate2Response.MethodNotAvailalble)
{
_log.ErrorFormat("[SCENE COMM]: Error sending child agent update to {0}, ChildAgentUpdate2 not available. Falling back to old method", neighbourRegion.RegionHandle);
}
return resp;
}
}
}
| |
// 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 AndNotInt32()
{
var test = new SimpleBinaryOpTest__AndNotInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable;
static SimpleBinaryOpTest__AndNotInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.AndNot(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.AndNot(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotInt32();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.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(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, 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 = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.Zelig.Test;
namespace Microsoft.Zelig.Test
{
public class StructsTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
string testName = "Structs";
result |= Assert.CheckFailed(Structs01_Test(), testName, 1);
result |= Assert.CheckFailed(Structs04_Test(), testName, 4);
result |= Assert.CheckFailed(Structs11_Test(), testName, 11);
result |= Assert.CheckFailed(Structs12_Test(), testName, 12);
result |= Assert.CheckFailed(Structs13_Test(), testName, 13);
result |= Assert.CheckFailed(Structs14_Test(), testName, 14);
result |= Assert.CheckFailed(Structs15_Test(), testName, 15);
result |= Assert.CheckFailed(Structs19_Test(), testName, 19);
result |= Assert.CheckFailed(Structs21_Test(), testName, 21);
result |= Assert.CheckFailed(Structs23_Test(), testName, 23);
result |= Assert.CheckFailed(Structs24_Test(), testName, 24);
result |= Assert.CheckFailed(Structs26_Test(), testName, 26);
result |= Assert.CheckFailed(Structs28_Test(), testName, 28);
result |= Assert.CheckFailed(Structs29_Test(), testName, 29);
result |= Assert.CheckFailed(Structs32_Test(), testName, 32);
result |= Assert.CheckFailed(Structs33_Test(), testName, 33);
result |= Assert.CheckFailed(Structs34_Test(), testName, 34);
result |= Assert.CheckFailed(Structs35_Test(), testName, 35);
result |= Assert.CheckFailed(Structs36_Test(), testName, 36);
result |= Assert.CheckFailed(Structs37_Test(), testName, 37);
result |= Assert.CheckFailed(Structs38_Test(), testName, 38);
result |= Assert.CheckFailed(Structs40_Test(), testName, 40);
result |= Assert.CheckFailed(Structs41_Test(), testName, 41);
result |= Assert.CheckFailed(Structs42_Test(), testName, 42);
result |= Assert.CheckFailed(Structs43_Test(), testName, 43);
result |= Assert.CheckFailed(Structs44_Test(), testName, 44);
result |= Assert.CheckFailed(Structs55_Test(), testName, 55);
return result;
}
//Structs Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Structs
//Test Case Calls
[TestMethod]
public TestResult Structs01_Test()
{
StructsTestClass_01_Notes.Note();
if (StructsTestClass_01.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs04_Test()
{
StructsTestClass_04_Notes.Note();
if (StructsTestClass_04.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs11_Test()
{
StructsTestClass_11_Notes.Note();
if (StructsTestClass_11.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs12_Test()
{
StructsTestClass_12_Notes.Note();
if (StructsTestClass_12.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs13_Test()
{
StructsTestClass_13_Notes.Note();
if (StructsTestClass_13.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs14_Test()
{
StructsTestClass_14_Notes.Note();
if (StructsTestClass_14.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs15_Test()
{
StructsTestClass_15_Notes.Note();
if (StructsTestClass_15.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs19_Test()
{
StructsTestClass_19_Notes.Note();
if (StructsTestClass_19.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs21_Test()
{
StructsTestClass_21_Notes.Note();
if (StructsTestClass_21.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs23_Test()
{
StructsTestClass_23_Notes.Note();
if (StructsTestClass_23.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs24_Test()
{
StructsTestClass_24_Notes.Note();
if (StructsTestClass_24.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs26_Test()
{
StructsTestClass_26_Notes.Note();
if (StructsTestClass_26.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs28_Test()
{
StructsTestClass_28_Notes.Note();
if (StructsTestClass_28.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs29_Test()
{
StructsTestClass_29_Notes.Note();
if (StructsTestClass_29.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs32_Test()
{
StructsTestClass_32_Notes.Note();
if (StructsTestClass_32.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs33_Test()
{
StructsTestClass_33_Notes.Note();
if (StructsTestClass_33.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs34_Test()
{
StructsTestClass_34_Notes.Note();
if (StructsTestClass_34.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs35_Test()
{
StructsTestClass_35_Notes.Note();
if (StructsTestClass_35.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs36_Test()
{
StructsTestClass_36_Notes.Note();
if (StructsTestClass_36.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs37_Test()
{
StructsTestClass_37_Notes.Note();
if (StructsTestClass_37.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs38_Test()
{
StructsTestClass_38_Notes.Note();
if (StructsTestClass_38.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs40_Test()
{
StructsTestClass_40_Notes.Note();
if (StructsTestClass_40.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs41_Test()
{
StructsTestClass_41_Notes.Note();
if (StructsTestClass_41.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs42_Test()
{
StructsTestClass_42_Notes.Note();
if (StructsTestClass_42.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs43_Test()
{
StructsTestClass_43_Notes.Note();
if (StructsTestClass_43.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs44_Test()
{
StructsTestClass_44_Notes.Note();
if (StructsTestClass_44.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Structs55_Test()
{
StructsTestClass_55_Notes.Note();
if (StructsTestClass_55.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
//Compiled Test Cases
class StructsTestClass_01_Notes
{
public static void Note()
{
Log.Comment(" Declaring a struct with and without a trailing semicolon. ");
}
}
struct StructsTestClass_01_Struct1 {
public int i;
}
struct StructsTestClass_01_Struct2 {
public int i;
};
public class StructsTestClass_01
{
public static bool testMethod()
{
StructsTestClass_01_Struct1 s1;
StructsTestClass_01_Struct2 s2;
s1.i = 1;
s2.i = 1;
return( 0 == (s1.i-s2.i));
}
}
class StructsTestClass_04_Notes {
public static void Note()
{
Log.Comment(" Verify all valid protection levels for members and methods");
}
}
struct StructsTestClass_04_Struct1 {
public int pub;
private int priv;
internal int intern;
public int StructsTestClass_04PubPriv()
{
return StructsTestClass_04Priv();
}
private int StructsTestClass_04Priv()
{
pub = 1;
priv = 2;
return(pub + priv);
}
internal int StructsTestClass_04Intern()
{
intern = 3;
return(intern);
}
public int GetPrivate()
{
return(priv);
}
}
public class StructsTestClass_04
{
public static bool testMethod()
{
StructsTestClass_04_Struct1 s1 = new StructsTestClass_04_Struct1();
int result;
result = s1.StructsTestClass_04PubPriv();
result += s1.StructsTestClass_04Intern();
result -= s1.intern;
result -= s1.pub;
result -= s1.GetPrivate();
return(result == 0);
}
}
class StructsTestClass_11_Notes {
public static void Note()
{
Log.Comment(" Verify struct can implement an interface.");
}
}
interface Inter1 {
int Return42();
}
struct StructsTestClass_11_Struct1 : Inter1 {
public int Return42() { return(42); }
}
public class StructsTestClass_11
{
public static bool testMethod()
{
Inter1 i1 = new StructsTestClass_11_Struct1();
return(0 == (i1.Return42() - 42));
}
}
class StructsTestClass_12_Notes {
public static void Note()
{
Log.Comment(" Verify struct can implement multiple interfaces.");
}
}
interface StructsTestClass_12_Inter1 {
int Return42();
}
interface StructsTestClass_12_Inter2 {
int Return20();
}
interface StructsTestClass_12_Inter3 {
int Return22();
}
struct StructsTestClass_12_Struct1 : StructsTestClass_12_Inter1, StructsTestClass_12_Inter2, StructsTestClass_12_Inter3 {
public int Return42() { return(42); }
public int Return20() { return(20); }
public int Return22() { return(22); }
}
public class StructsTestClass_12
{
public static bool testMethod()
{
StructsTestClass_12_Inter1 i1 = new StructsTestClass_12_Struct1();
return (0 == (i1.Return42() - ((StructsTestClass_12_Inter2)i1).Return20() - ((StructsTestClass_12_Inter3)i1).Return22()));
}
}
class StructsTestClass_13_Notes {
public static void Note()
{
Log.Comment(" Verify struct can implement multiple interfaces that contain methods with identical signatures.");
}
}
interface StructsTestClass_13_Inter1 {
int Return42();
}
interface StructsTestClass_13_Inter2 {
int Return42();
}
interface StructsTestClass_13_Inter3 {
int Return0();
}
struct StructsTestClass_13_Struct1 : StructsTestClass_13_Inter1, StructsTestClass_13_Inter2, StructsTestClass_13_Inter3 {
int StructsTestClass_13_Inter1.Return42() { return(42); }
int StructsTestClass_13_Inter2.Return42() { return(42); }
int StructsTestClass_13_Inter3.Return0() { return(0); }
}
public class StructsTestClass_13
{
public static int Main_old()
{
StructsTestClass_13_Inter1 i1 = new StructsTestClass_13_Struct1();
return (i1.Return42() - ((StructsTestClass_13_Inter2)i1).Return42() - ((StructsTestClass_13_Inter3)i1).Return0());
}
public static bool testMethod()
{
try
{
return (Main_old() == 0);
}
catch
{
return false;
}
}
}
class StructsTestClass_14_Notes {
public static void Note()
{
Log.Comment(" Verify that a struct can contain a class");
}
}
class StructsTestClass_14_Class1 {
};
struct StructsTestClass_14_Struct1 {
public StructsTestClass_14_Class1 c;
}
public class StructsTestClass_14
{
public static int Main_old()
{
StructsTestClass_14_Struct1 s1 = new StructsTestClass_14_Struct1();
int result = s1.c == null ? 0 : 1;
return(result);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_15_Notes {
public static void Note()
{
Log.Comment(" Verify that a struct can contain another sruct");
}
}
struct StructsTestClass_15_Struct1 {
public int i;
};
struct StructsTestClass_15_Struct2 {
public StructsTestClass_15_Struct1 s;
public int i;
}
public class StructsTestClass_15
{
public static int Main_old()
{
StructsTestClass_15_Struct2 s2 = new StructsTestClass_15_Struct2();
return(s2.s.i);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_19_Notes {
public static void Note()
{
Log.Comment("Attempt to use an empty StructsTestClass_19_Struct");
}
}
struct StructsTestClass_19_Struct1 {
}
public class StructsTestClass_19
{
public static int Main_old()
{
StructsTestClass_19_Struct1 s = new StructsTestClass_19_Struct1();
return(0);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_21_Notes {
public static void Note()
{
Log.Comment("attempt to return a struct");
}
}
public struct StructsTestClass_21_Struct1 {
int a;
public void Set(int val) { a = val; }
public int Get() { return(a); }
}
public class StructsTestClass_21
{
public static int Main_old()
{
if (callQuick().Get() != 0)
return(1);
return(call().Get()-42);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
public static StructsTestClass_21_Struct1 callQuick()
{
return(new StructsTestClass_21_Struct1());
}
public static StructsTestClass_21_Struct1 call()
{
StructsTestClass_21_Struct1 s = new StructsTestClass_21_Struct1();
s.Set(42);
return(s);
}
}
class StructsTestClass_23_Notes {
public static void Note()
{
Log.Comment("struct like an object");
}
}
struct StructsTestClass_23_Struct1 {
public int i;
}
public class StructsTestClass_23
{
public static int Main_old()
{
StructsTestClass_23_Struct1 s = new StructsTestClass_23_Struct1();
s.i = 42;
return(0);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_24_Notes {
public static void Note()
{
Log.Comment(" struct values aren't changed when boxed and passed as interfaces.");
}
}
public interface Interface1 {
void SetInt(int val);
int GetInt();
};
public struct StructsTestClass_24_Struct1 : Interface1 {
public int i;
public void SetInt(int val) { i = val; }
public int GetInt() { return(i); }
}
public class StructsTestClass_24
{
public static int Main_old()
{
StructsTestClass_24_Struct1 s = new StructsTestClass_24_Struct1();
s.i = 42;
Call(s);
return(s.i == 42 ? 0 : 1);
}
public static void Call(Interface1 iface)
{
if (iface.GetInt() != 42) {
throw new System.Exception();
throw new System.Exception("expected i == 42");
}
iface.SetInt(99);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_26_Notes {
public static void Note()
{
Log.Comment(" StructsTestClass_26_A ttempt to make a parameterized conStructsTestClass_26_Structor for a StructsTestClass_?_Struct.");
}
}
struct StructsTestClass_26_Struct1 {
public StructsTestClass_26_Struct1(int j) { i = j; }
public int i;
}
public class StructsTestClass_26
{
public static int Main_old()
{
StructsTestClass_26_Struct1 s = new StructsTestClass_26_Struct1(42);
return(s.i - 42);
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_28_Notes {
public static void Note()
{
Log.Comment(" Explicit test of object boxing conversions to and from a StructsTestClass_28_Struct.");
}
}
struct StructsTestClass_28_Struct1 {
public int i;
}
public class StructsTestClass_28
{
static public int Main_old()
{
StructsTestClass_28_Struct1 s1 = new StructsTestClass_28_Struct1();
Object converter = s1;
StructsTestClass_28_Struct1 s2 = (StructsTestClass_28_Struct1) converter;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_29_Notes {
public static void Note()
{
Log.Comment(" StructsTestClass_29 conStructsTestClass_29_Structor forwarding works for StructsTestClass_?_Structs");
}
}
struct Foo {
public Foo(int x): this(5, 6) {
}
public Foo(int x, int y) {
m_x = x;
m_y = y;
}
public int m_x;
public int m_y;
}
public class StructsTestClass_29
{
static public int Main_old()
{
Foo s1 = new Foo(1);
if (s1.m_x != 5)
return(1);
if (s1.m_y != 6)
return(1);
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class StructsTestClass_32_Notes {
public static void Note()
{
Log.Comment(" nested struct should work");
}
}
public struct StructsTestClass_32_Struct{
public struct Nested{
public int i;
}
public Nested n;
}
public class StructsTestClass_32
{
public static bool testMethod()
{
StructsTestClass_32_Struct s = new StructsTestClass_32_Struct();
StructsTestClass_32_Struct.Nested nn = new StructsTestClass_32_Struct.Nested();
nn.i = 10;
s.n = nn; //value copy
if(s.n.i == nn.i)
return true;
else
return false;
}
}
class StructsTestClass_33_Notes {
public static void Note()
{
Log.Comment(" nested class inside struct should work");
}
}
public struct StructsTestClass_33_Struct{
public class Nested{
public int i;
}
public Nested n;
}
public class StructsTestClass_33
{
public static bool testMethod()
{
StructsTestClass_33_Struct s = new StructsTestClass_33_Struct();
StructsTestClass_33_Struct.Nested nn = new StructsTestClass_33_Struct.Nested();
nn.i = 10;
s.n = nn; //value copy
if(s.n.i == nn.i)
return true;
else
return false;
}
}
class StructsTestClass_34_Notes {
public static void Note()
{
Log.Comment(" nested struct should work");
}
}
public struct StructsTestClass_34_Struct
{
public struct Nested
{
public struct NestedNested
{
public int i;
}
public int i; //in different scope
}
public Nested n;
}
public class StructsTestClass_34
{
public static bool testMethod()
{
StructsTestClass_34_Struct s = new StructsTestClass_34_Struct();
StructsTestClass_34_Struct.Nested nn = new StructsTestClass_34_Struct.Nested();
nn.i = 10;
s.n = nn; //value copy
StructsTestClass_34_Struct.Nested.NestedNested nnn = new StructsTestClass_34_Struct.Nested.NestedNested();
if(s.n.i != nn.i)
return false;
nnn.i = 20;
s.n.i = nnn.i;
if(nn.i == 10 && s.n.i == nnn.i)//check nn.i did not changed
return true;
else
return false;
}
}
class StructsTestClass_35_Notes {
public static void Note()
{
Log.Comment(" cast struct to inherited interface type");
}
}
public interface StructsTestClass_35_Interface
{
int foo();
}
public struct StructsTestClass_35_A : StructsTestClass_35_Interface
{
public int foo()
{
return 10;
}
}
public class StructsTestClass_35
{
public static bool testMethod()
{
StructsTestClass_35_Interface a = new StructsTestClass_35_A ();
if(a.foo() != 10)
return false;
else
return true;
}
}
class StructsTestClass_36_Notes {
public static void Note()
{
Log.Comment(" cast struct to inherited interface type");
}
}
public interface StructsTestClass_36_Interface
{
int foo();
}
public struct StructsTestClass_36_A : StructsTestClass_36_Interface
{
public int foo()
{
return 10;
}
}
public class StructsTestClass_36
{
public static bool testMethod()
{
StructsTestClass_36_Interface a = new StructsTestClass_36_A ();
if(a.foo() != 10)
return false;
else
return true;
}
}
class StructsTestClass_37_Notes {
public static void Note()
{
Log.Comment(" cast struct to inherited interface type");
}
}
public interface StructsTestClass_37_Interface
{
int foo();
}
public struct StructsTestClass_37_A : StructsTestClass_37_Interface
{
public int foo()
{
return 10;
}
}
public class StructsTestClass_37
{
public static bool testMethod()
{
StructsTestClass_37_A a = new StructsTestClass_37_A ();
object o = a; //boxing
bool b = o is StructsTestClass_37_Interface ;
if(!b)
return false;
if((a as StructsTestClass_37_Interface ) == null)
return false;
if(a.foo() != 10)
return false;
else
return true;
}
}
class StructsTestClass_38_Notes {
public static void Note()
{
Log.Comment(" cast struct to inherited interface type through function");
}
}
public interface StructsTestClass_38_Interface
{
int foo();
}
public struct StructsTestClass_38_A : StructsTestClass_38_Interface
{
public StructsTestClass_38_Interface GetI()
{
this.i = 10;
return this;
}
public int foo()
{
return i;
}
public int i;
}
public class StructsTestClass_38
{
public static bool testMethod()
{
StructsTestClass_38_A a = new StructsTestClass_38_A ();
object o = a; //boxing
bool b = o is StructsTestClass_38_Interface ;
if(!b)
return false;
if((a as StructsTestClass_38_Interface ) == null)
return false;
if(a.GetI().foo() != 10)
return false;
else
return true;
}
}
class StructsTestClass_40_Notes {
public static void Note()
{
Log.Comment(" property in struct");
}
}
public struct StructsTestClass_40_Struct
{
public int Foo
{
get
{
return 10;
}
}
}
public class StructsTestClass_40
{
public static bool testMethod()
{
StructsTestClass_40_Struct a = new StructsTestClass_40_Struct();
if(a.Foo == 10)
return true;
else
return false;
}
}
class StructsTestClass_41_Notes {
public static void Note()
{
Log.Comment(" indexer in struct");
}
}
public struct StructsTestClass_41_Struct
{
public int this[int index]
{
get
{
return index;
}
}
}
public class StructsTestClass_41
{
public static bool testMethod()
{
StructsTestClass_41_Struct a = new StructsTestClass_41_Struct();
if(a[10] == 10)
return true;
else
return false;
}
}
class StructsTestClass_42_Notes {
public static void Note()
{
Log.Comment(" interface indexer in StructsTestClass_42_Struct");
}
}
public interface StructsTestClass_42_Interface
{
int this[int index]{get;}
}
public struct StructsTestClass_42_A : StructsTestClass_42_Interface
{
public int this[int index]
{
get
{
return index;
}
}
}
public class StructsTestClass_42
{
public static bool testMethod()
{
StructsTestClass_42_Interface a = new StructsTestClass_42_A ();
if(a[10] == 10)
return true;
else
return false;
}
}
class StructsTestClass_43_Notes {
public static void Note()
{
Log.Comment(" delegate in struct");
}
}
public struct StructsTestClass_43_Struct
{
public delegate int foo();
public int boo()
{
return 10;
}
}
public class StructsTestClass_43
{
public static bool testMethod()
{
StructsTestClass_43_Struct a = new StructsTestClass_43_Struct();
StructsTestClass_43_Struct.foo d = new StructsTestClass_43_Struct.foo(a.boo);
if(d() == 10)
return true;
else
return false;
}
}
class StructsTestClass_44_Notes {
public static void Note()
{
Log.Comment(" delegate in struct assing interface as a delegate argument");
}
}
public interface StructsTestClass_44_Interface
{
int boo();
}
public struct StructsTestClass_44_A : StructsTestClass_44_Interface
{
public delegate int foo();
public int boo()
{
return 10;
}
}
public class StructsTestClass_44
{
public static bool testMethod()
{
StructsTestClass_44_Interface a = new StructsTestClass_44_A();
StructsTestClass_44_A .foo d = new StructsTestClass_44_A .foo(a.boo);
if(d() == 10)
return true;
else
return false;
}
}
class StructsTestClass_55_Notes {
public static void Note()
{
Log.Comment("The this object cannot be used before all of its fields are assigned to");
}
}
public struct StructsTestClass_55
{
public int i;
static void foo(){}
StructsTestClass_55(int i)
{
this.i = i;
foo();
}
public static bool testMethod()
{
StructsTestClass_55 s = new StructsTestClass_55(101);
return (0 == s.i - 101);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
namespace NUnit.Framework.Constraints.Tests
{
[TestFixture]
public class CollectionContainsConstraintTests
{
[Test]
public void CanTestContentsOfArray()
{
object item = "xyz";
object[] c = new object[] { 123, item, "abc" };
Assert.That(c, new CollectionContainsConstraint(item));
}
#if !SILVERLIGHT
[Test]
public void CanTestContentsOfArrayList()
{
object item = "xyz";
ArrayList list = new ArrayList(new object[] { 123, item, "abc" });
Assert.That(list, new CollectionContainsConstraint(item));
}
[Test]
public void CanTestContentsOfSortedList()
{
object item = "xyz";
SortedList list = new SortedList();
list.Add("a", 123);
list.Add("b", item);
list.Add("c", "abc");
Assert.That(list.Values, new CollectionContainsConstraint(item));
Assert.That(list.Keys, new CollectionContainsConstraint("b"));
}
#endif
[Test]
public void CanTestContentsOfCollectionNotImplementingIList()
{
SimpleObjectCollection ints = new SimpleObjectCollection(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
Assert.That(ints, new CollectionContainsConstraint(9));
}
[Test]
public void IgnoreCaseIsHonored()
{
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("WORLD").IgnoreCase);
}
[Test]
public void UsesProvidedIComparer()
{
MyComparer comparer = new MyComparer();
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("World").Using(comparer));
Assert.That(comparer.Called, "Comparer was not called");
}
class MyComparer : IComparer
{
public bool Called;
public int Compare(object x, object y)
{
Called = true;
return 0;
}
}
#if CLR_2_0 || CLR_4_0
[Test]
public void UsesProvidedEqualityComparer()
{
MyEqualityComparer comparer = new MyEqualityComparer();
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("World").Using(comparer));
Assert.That(comparer.Called, "Comparer was not called");
}
class MyEqualityComparer : IEqualityComparer
{
public bool Called;
bool IEqualityComparer.Equals(object x, object y)
{
Called = true;
return x == y;
}
int IEqualityComparer.GetHashCode(object x)
{
return x.GetHashCode();
}
}
[Test]
public void UsesProvidedEqualityComparerOfT()
{
MyEqualityComparerOfT<string> comparer = new MyEqualityComparerOfT<string>();
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("World").Using(comparer));
Assert.That(comparer.Called, "Comparer was not called");
}
class MyEqualityComparerOfT<T> : IEqualityComparer<T>
{
public bool Called;
bool IEqualityComparer<T>.Equals(T x, T y)
{
Called = true;
return Comparer<T>.Default.Compare(x, y) == 0;
}
int IEqualityComparer<T>.GetHashCode(T x)
{
return x.GetHashCode();
}
}
[Test]
public void UsesProvidedComparerOfT()
{
MyComparer<string> comparer = new MyComparer<string>();
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("World").Using(comparer));
Assert.That(comparer.Called, "Comparer was not called");
}
class MyComparer<T> : IComparer<T>
{
public bool Called;
public int Compare(T x, T y)
{
Called = true;
return Comparer<T>.Default.Compare(x, y);
}
}
[Test]
public void UsesProvidedComparisonOfT()
{
MyComparison<string> comparer = new MyComparison<string>();
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("World").Using(new Comparison<string>(comparer.Compare)));
Assert.That(comparer.Called, "Comparer was not called");
}
class MyComparison<T>
{
public bool Called;
public int Compare(T x, T y)
{
Called = true;
return Comparer<T>.Default.Compare(x, y);
}
}
[Test]
public void ContainsWithRecursiveStructure()
{
SelfRecursiveEnumerable item = new SelfRecursiveEnumerable();
SelfRecursiveEnumerable[] container = new SelfRecursiveEnumerable[] { new SelfRecursiveEnumerable(), item };
Assert.That(container, new CollectionContainsConstraint(item));
}
class SelfRecursiveEnumerable : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return this;
}
}
#if !NETCF_2_0
[Test]
public void UsesProvidedLambdaExpression()
{
Assert.That(new string[] { "Hello", "World" },
new CollectionContainsConstraint("WORLD").Using<string>((x, y) => StringUtil.Compare(x, y, true)));
}
#endif
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Mvc.JQuery.Datatables.DynamicLinq
{
internal class ExpressionParser
{
struct Token
{
public TokenId id;
public string text;
public int pos;
}
enum TokenId
{
Unknown,
End,
Identifier,
StringLiteral,
IntegerLiteral,
RealLiteral,
Exclamation,
Percent,
Amphersand,
OpenParen,
CloseParen,
Asterisk,
Plus,
Comma,
Minus,
Dot,
Slash,
Colon,
LessThan,
Equal,
GreaterThan,
Question,
OpenBracket,
CloseBracket,
Bar,
ExclamationEqual,
DoubleAmphersand,
LessThanEqual,
LessGreater,
DoubleEqual,
GreaterThanEqual,
DoubleBar
}
interface ILogicalSignatures
{
void F(bool x, bool y);
void F(bool? x, bool? y);
}
interface IArithmeticSignatures
{
void F(int x, int y);
void F(uint x, uint y);
void F(long x, long y);
void F(ulong x, ulong y);
void F(float x, float y);
void F(double x, double y);
void F(decimal x, decimal y);
void F(int? x, int? y);
void F(uint? x, uint? y);
void F(long? x, long? y);
void F(ulong? x, ulong? y);
void F(float? x, float? y);
void F(double? x, double? y);
void F(decimal? x, decimal? y);
}
interface IRelationalSignatures : IArithmeticSignatures
{
void F(string x, string y);
void F(char x, char y);
void F(DateTime x, DateTime y);
void F(DateTimeOffset x, DateTimeOffset y);
void F(TimeSpan x, TimeSpan y);
void F(char? x, char? y);
void F(DateTime? x, DateTime? y);
void F(DateTimeOffset? x, DateTimeOffset? y);
void F(TimeSpan? x, TimeSpan? y);
}
interface IEqualitySignatures : IRelationalSignatures
{
void F(bool x, bool y);
void F(bool? x, bool? y);
void F(Guid x, Guid y);
void F(Guid? x, Guid? y);
}
interface IAddSignatures : IArithmeticSignatures
{
void F(DateTime x, TimeSpan y);
void F(TimeSpan x, TimeSpan y);
void F(DateTime? x, TimeSpan? y);
void F(TimeSpan? x, TimeSpan? y);
}
interface ISubtractSignatures : IAddSignatures
{
void F(DateTime x, DateTime y);
void F(DateTime? x, DateTime? y);
}
interface INegationSignatures
{
void F(int x);
void F(long x);
void F(float x);
void F(double x);
void F(decimal x);
void F(int? x);
void F(long? x);
void F(float? x);
void F(double? x);
void F(decimal? x);
}
interface INotSignatures
{
void F(bool x);
void F(bool? x);
}
interface IEnumerableSignatures
{
void Where(bool predicate);
void Any();
void Any(bool predicate);
void All(bool predicate);
void Count();
void Count(bool predicate);
void Min(object selector);
void Max(object selector);
void Sum(int selector);
void Sum(int? selector);
void Sum(long selector);
void Sum(long? selector);
void Sum(float selector);
void Sum(float? selector);
void Sum(double selector);
void Sum(double? selector);
void Sum(decimal selector);
void Sum(decimal? selector);
void Average(int selector);
void Average(int? selector);
void Average(long selector);
void Average(long? selector);
void Average(float selector);
void Average(float? selector);
void Average(double selector);
void Average(double? selector);
void Average(decimal selector);
void Average(decimal? selector);
}
static readonly Type[] predefinedTypes = {
typeof(Object),
typeof(Boolean),
typeof(Char),
typeof(String),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(TimeSpan),
typeof(Guid),
typeof(Math),
typeof(Convert)
};
static readonly Expression trueLiteral = Expression.Constant(true);
static readonly Expression falseLiteral = Expression.Constant(false);
static readonly Expression nullLiteral = Expression.Constant(null);
static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";
static Dictionary<string, object> keywords;
Dictionary<string, object> symbols;
IDictionary<string, object> externals;
Dictionary<Expression, string> literals;
ParameterExpression it;
string text;
int textPos;
int textLen;
char ch;
Token token;
private Type _interfaceType = null;
private Type _baseType = null;
public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values)
{
if (expression == null) throw new ArgumentNullException("expression");
if (keywords == null) keywords = CreateKeywords();
symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
literals = new Dictionary<Expression, string>();
if (parameters != null) ProcessParameters(parameters);
if (values != null) ProcessValues(values);
text = expression;
textLen = text.Length;
SetTextPos(0);
NextToken();
}
void ProcessParameters(ParameterExpression[] parameters)
{
foreach (ParameterExpression pe in parameters)
if (!String.IsNullOrEmpty(pe.Name))
AddSymbol(pe.Name, pe);
if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name))
it = parameters[0];
}
void ProcessValues(object[] values)
{
for (int i = 0; i < values.Length; i++)
{
object value = values[i];
if (i == values.Length - 1 && value is IDictionary<string, object>)
{
externals = (IDictionary<string, object>)value;
}
else
{
AddSymbol("@" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), value);
}
}
}
void AddSymbol(string name, object value)
{
if (symbols.ContainsKey(name))
throw ParseError(Res.DuplicateIdentifier, name);
symbols.Add(name, value);
}
public Expression Parse(Type resultType, Type baseType = null)
{
//Update base resultType
_interfaceType = resultType;
_baseType = baseType;
int exprPos = token.pos;
Expression expr = ParseExpression(resultType);
if (resultType != null)
if ((expr = PromoteExpression(expr, resultType, true)) == null)
throw ParseError(exprPos, Res.ExpressionTypeMismatch, GetTypeName(resultType));
ValidateToken(TokenId.End, Res.SyntaxError);
return expr;
}
#pragma warning disable 0219
public IEnumerable<DynamicOrdering> ParseOrdering()
{
List<DynamicOrdering> orderings = new List<DynamicOrdering>();
while (true)
{
Expression expr = ParseExpression();
bool ascending = true;
if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending"))
{
NextToken();
}
else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending"))
{
NextToken();
ascending = false;
}
orderings.Add(new DynamicOrdering { Selector = expr, Ascending = ascending });
if (token.id != TokenId.Comma) break;
NextToken();
}
ValidateToken(TokenId.End, Res.SyntaxError);
return orderings;
}
#pragma warning restore 0219
// ?: operator
Expression ParseExpression(Type resultType = null)
{
int errorPos = token.pos;
Expression expr = ParseLogicalOr(resultType);
if (token.id == TokenId.Question)
{
NextToken();
Expression expr1 = ParseExpression(resultType);
ValidateToken(TokenId.Colon, Res.ColonExpected);
NextToken();
Expression expr2 = ParseExpression(resultType);
expr = GenerateConditional(expr, expr1, expr2, errorPos);
}
return expr;
}
// ||, or operator
Expression ParseLogicalOr(Type resultType = null)
{
Expression left = ParseLogicalAnd(resultType);
while (token.id == TokenId.DoubleBar || TokenIdentifierIs("or"))
{
Token op = token;
NextToken();
Expression right = ParseLogicalAnd(resultType);
CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
left = Expression.OrElse(left, right);
}
return left;
}
// &&, and operator
Expression ParseLogicalAnd(Type resultType = null)
{
Expression left = ParseComparison(resultType);
while (token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and"))
{
Token op = token;
NextToken();
Expression right = ParseComparison(resultType);
CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
left = Expression.AndAlso(left, right);
}
return left;
}
// =, ==, !=, <>, >, >=, <, <= operators
Expression ParseComparison(Type resultType = null)
{
Expression left = ParseAdditive(resultType);
while (token.id == TokenId.Equal || token.id == TokenId.DoubleEqual ||
token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater ||
token.id == TokenId.GreaterThan || token.id == TokenId.GreaterThanEqual ||
token.id == TokenId.LessThan || token.id == TokenId.LessThanEqual)
{
Token op = token;
NextToken();
Expression right = ParseAdditive(resultType);
bool isEquality = op.id == TokenId.Equal || op.id == TokenId.DoubleEqual ||
op.id == TokenId.ExclamationEqual || op.id == TokenId.LessGreater;
if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType)
{
if (left.Type != right.Type)
{
if (left.Type.IsAssignableFrom(right.Type))
{
right = Expression.Convert(right, left.Type);
}
else if (right.Type.IsAssignableFrom(left.Type))
{
left = Expression.Convert(left, right.Type);
}
else
{
throw IncompatibleOperandsError(op.text, left, right, op.pos);
}
}
}
else if (IsEnumType(left.Type) || IsEnumType(right.Type))
{
if (left.Type != right.Type)
{
Expression e;
if ((e = PromoteExpression(right, left.Type, true)) != null)
{
right = e;
}
else if ((e = PromoteExpression(left, right.Type, true)) != null)
{
left = e;
}
else
{
throw IncompatibleOperandsError(op.text, left, right, op.pos);
}
}
}
else
{
CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures),
op.text, ref left, ref right, op.pos);
}
switch (op.id)
{
case TokenId.Equal:
case TokenId.DoubleEqual:
left = GenerateEqual(left, right);
break;
case TokenId.ExclamationEqual:
case TokenId.LessGreater:
left = GenerateNotEqual(left, right);
break;
case TokenId.GreaterThan:
left = GenerateGreaterThan(left, right);
break;
case TokenId.GreaterThanEqual:
left = GenerateGreaterThanEqual(left, right);
break;
case TokenId.LessThan:
left = GenerateLessThan(left, right);
break;
case TokenId.LessThanEqual:
left = GenerateLessThanEqual(left, right);
break;
}
}
return left;
}
// +, -, & operators
Expression ParseAdditive(Type resultType = null)
{
Expression left = ParseMultiplicative(resultType);
while (token.id == TokenId.Plus || token.id == TokenId.Minus ||
token.id == TokenId.Amphersand)
{
Token op = token;
NextToken();
Expression right = ParseMultiplicative(resultType);
switch (op.id)
{
case TokenId.Plus:
if (left.Type == typeof(string) || right.Type == typeof(string))
goto case TokenId.Amphersand;
CheckAndPromoteOperands(typeof(IAddSignatures), op.text, ref left, ref right, op.pos);
left = GenerateAdd(left, right);
break;
case TokenId.Minus:
CheckAndPromoteOperands(typeof(ISubtractSignatures), op.text, ref left, ref right, op.pos);
left = GenerateSubtract(left, right);
break;
case TokenId.Amphersand:
left = GenerateStringConcat(left, right);
break;
}
}
return left;
}
// *, /, %, mod operators
Expression ParseMultiplicative(Type resultType = null)
{
Expression left = ParseUnary(resultType);
while (token.id == TokenId.Asterisk || token.id == TokenId.Slash ||
token.id == TokenId.Percent || TokenIdentifierIs("mod"))
{
Token op = token;
NextToken();
Expression right = ParseUnary(resultType);
CheckAndPromoteOperands(typeof(IArithmeticSignatures), op.text, ref left, ref right, op.pos);
switch (op.id)
{
case TokenId.Asterisk:
left = Expression.Multiply(left, right);
break;
case TokenId.Slash:
left = Expression.Divide(left, right);
break;
case TokenId.Percent:
case TokenId.Identifier:
left = Expression.Modulo(left, right);
break;
}
}
return left;
}
// -, !, not unary operators
Expression ParseUnary(Type resultType = null)
{
if (token.id == TokenId.Minus || token.id == TokenId.Exclamation ||
TokenIdentifierIs("not"))
{
Token op = token;
NextToken();
if (op.id == TokenId.Minus && (token.id == TokenId.IntegerLiteral ||
token.id == TokenId.RealLiteral))
{
token.text = "-" + token.text;
token.pos = op.pos;
return ParsePrimary(resultType);
}
Expression expr = ParseUnary(resultType);
if (op.id == TokenId.Minus)
{
CheckAndPromoteOperand(typeof(INegationSignatures), op.text, ref expr, op.pos);
expr = Expression.Negate(expr);
}
else
{
CheckAndPromoteOperand(typeof(INotSignatures), op.text, ref expr, op.pos);
expr = Expression.Not(expr);
}
return expr;
}
return ParsePrimary(resultType);
}
Expression ParsePrimary(Type resultType = null)
{
Expression expr = ParsePrimaryStart(resultType);
while (true)
{
if (token.id == TokenId.Dot)
{
NextToken();
expr = ParseMemberAccess(null, expr);
}
else if (token.id == TokenId.OpenBracket)
{
expr = ParseElementAccess(expr);
}
else
{
break;
}
}
return expr;
}
Expression ParsePrimaryStart(Type resultType = null)
{
switch (token.id)
{
case TokenId.Identifier:
return ParseIdentifier(resultType);
case TokenId.StringLiteral:
return ParseStringLiteral(resultType);
case TokenId.IntegerLiteral:
return ParseIntegerLiteral(resultType);
case TokenId.RealLiteral:
return ParseRealLiteral(resultType);
case TokenId.OpenParen:
return ParseParenExpression(resultType);
default:
throw ParseError(Res.ExpressionExpected);
}
}
Expression ParseStringLiteral(Type resultType = null)
{
ValidateToken(TokenId.StringLiteral);
char quote = token.text[0];
string s = token.text.Substring(1, token.text.Length - 2);
int start = 0;
while (true)
{
int i = s.IndexOf(quote, start);
if (i < 0) break;
s = s.Remove(i, 1);
start = i + 1;
}
if (quote == '\'')
{
if (s.Length != 1)
throw ParseError(Res.InvalidCharacterLiteral);
NextToken();
return CreateLiteral(s[0], s);
}
NextToken();
return CreateLiteral(s, s);
}
Expression ParseIntegerLiteral(Type resultType = null)
{
ValidateToken(TokenId.IntegerLiteral);
string text = token.text;
if (text[0] != '-')
{
ulong value;
if (!UInt64.TryParse(text, out value))
throw ParseError(Res.InvalidIntegerLiteral, text);
NextToken();
if (value <= (ulong)Int32.MaxValue) return CreateLiteral((int)value, text);
if (value <= (ulong)UInt32.MaxValue) return CreateLiteral((uint)value, text);
if (value <= (ulong)Int64.MaxValue) return CreateLiteral((long)value, text);
return CreateLiteral(value, text);
}
else
{
long value;
if (!Int64.TryParse(text, out value))
throw ParseError(Res.InvalidIntegerLiteral, text);
NextToken();
if (value >= Int32.MinValue && value <= Int32.MaxValue)
return CreateLiteral((int)value, text);
return CreateLiteral(value, text);
}
}
Expression ParseRealLiteral(Type resultType = null)
{
ValidateToken(TokenId.RealLiteral);
string text = token.text;
object value = null;
char last = text[text.Length - 1];
if (last == 'F' || last == 'f')
{
float f;
if (Single.TryParse(text.Substring(0, text.Length - 1), out f)) value = f;
}
else
{
double d;
if (Double.TryParse(text, out d)) value = d;
}
if (value == null) throw ParseError(Res.InvalidRealLiteral, text);
NextToken();
return CreateLiteral(value, text);
}
Expression CreateLiteral(object value, string text)
{
ConstantExpression expr = Expression.Constant(value);
literals.Add(expr, text);
return expr;
}
Expression ParseParenExpression(Type resultType = null)
{
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
Expression e = ParseExpression();
ValidateToken(TokenId.CloseParen, Res.CloseParenOrOperatorExpected);
NextToken();
return e;
}
Expression ParseIdentifier(Type resultType = null)
{
ValidateToken(TokenId.Identifier);
object value;
if (keywords.TryGetValue(token.text, out value))
{
if (value is Type) return ParseTypeAccess((Type)value);
if (value == (object)keywordIt) return ParseIt(resultType);
if (value == (object)keywordIif) return ParseIif(resultType);
if (value == (object)keywordNew) return ParseNew(resultType);
NextToken();
return (Expression)value;
}
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value))
{
Expression expr = value as Expression;
if (expr == null)
{
expr = Expression.Constant(value);
}
else
{
LambdaExpression lambda = expr as LambdaExpression;
if (lambda != null) return ParseLambdaInvocation(lambda);
}
NextToken();
return expr;
}
if (it != null) return ParseMemberAccess(null, it);
throw ParseError(Res.UnknownIdentifier, token.text);
}
Expression ParseIt(Type resultType = null)
{
if (it == null)
throw ParseError(Res.NoItInScope);
NextToken();
return it;
}
Expression ParseIif(Type resultType = null)
{
int errorPos = token.pos;
NextToken();
Expression[] args = ParseArgumentList();
if (args.Length != 3)
throw ParseError(errorPos, Res.IifRequiresThreeArgs);
return GenerateConditional(args[0], args[1], args[2], errorPos);
}
Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos)
{
if (test.Type != typeof(bool))
throw ParseError(errorPos, Res.FirstExprMustBeBool);
if (expr1.Type != expr2.Type)
{
Expression expr1as2 = expr2 != nullLiteral ? PromoteExpression(expr1, expr2.Type, true) : null;
Expression expr2as1 = expr1 != nullLiteral ? PromoteExpression(expr2, expr1.Type, true) : null;
if (expr1as2 != null && expr2as1 == null)
{
expr1 = expr1as2;
}
else if (expr2as1 != null && expr1as2 == null)
{
expr2 = expr2as1;
}
else
{
string type1 = expr1 != nullLiteral ? expr1.Type.Name : "null";
string type2 = expr2 != nullLiteral ? expr2.Type.Name : "null";
if (expr1as2 != null && expr2as1 != null)
throw ParseError(errorPos, Res.BothTypesConvertToOther, type1, type2);
throw ParseError(errorPos, Res.NeitherTypeConvertsToOther, type1, type2);
}
}
return Expression.Condition(test, expr1, expr2);
}
Expression ParseNew(Type resultType = null)
{
NextToken();
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
List<DynamicProperty> properties = new List<DynamicProperty>();
List<Expression> expressions = new List<Expression>();
while (true)
{
int exprPos = token.pos;
Expression expr = ParseExpression();
string propName;
if (TokenIdentifierIs("as"))
{
NextToken();
propName = GetIdentifier();
NextToken();
}
else
{
MemberExpression me = expr as MemberExpression;
if (me == null) throw ParseError(exprPos, Res.MissingAsClause);
propName = me.Member.Name;
}
expressions.Add(expr);
properties.Add(new DynamicProperty(propName, expr.Type));
if (token.id != TokenId.Comma) break;
NextToken();
}
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
NextToken();
Type type = null;
if (_interfaceType != null)
type = DynamicExpression.CreateClass(properties, _interfaceType, _baseType);
else
type = DynamicExpression.CreateClass(properties);
MemberBinding[] bindings = new MemberBinding[properties.Count];
for (int i = 0; i < bindings.Length; i++)
bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
return Expression.MemberInit(Expression.New(type), bindings);
}
Expression ParseLambdaInvocation(LambdaExpression lambda)
{
int errorPos = token.pos;
NextToken();
Expression[] args = ParseArgumentList();
MethodBase method;
if (FindMethod(lambda.Type, "Invoke", false, args, out method) != 1)
throw ParseError(errorPos, Res.ArgsIncompatibleWithLambda);
return Expression.Invoke(lambda, args);
}
Expression ParseTypeAccess(Type type)
{
int errorPos = token.pos;
NextToken();
if (token.id == TokenId.Question)
{
if (!type.IsValueType || IsNullableType(type))
throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type));
type = typeof(Nullable<>).MakeGenericType(type);
NextToken();
}
if (token.id == TokenId.OpenParen)
{
Expression[] args = ParseArgumentList();
MethodBase method;
switch (FindBestMethod(type.GetConstructors(), args, out method))
{
case 0:
if (args.Length == 1)
return GenerateConversion(args[0], type, errorPos);
throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type));
case 1:
return Expression.New((ConstructorInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type));
}
}
ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected);
NextToken();
return ParseMemberAccess(type, null);
}
Expression GenerateConversion(Expression expr, Type type, int errorPos)
{
Type exprType = expr.Type;
if (exprType == type) return expr;
if (exprType.IsValueType && type.IsValueType)
{
if ((IsNullableType(exprType) || IsNullableType(type)) &&
GetNonNullableType(exprType) == GetNonNullableType(type))
return Expression.Convert(expr, type);
if ((IsNumericType(exprType) || IsEnumType(exprType)) &&
(IsNumericType(type)) || IsEnumType(type))
return Expression.ConvertChecked(expr, type);
}
if (exprType.IsAssignableFrom(type) || type.IsAssignableFrom(exprType) ||
exprType.IsInterface || type.IsInterface)
return Expression.Convert(expr, type);
throw ParseError(errorPos, Res.CannotConvertValue,
GetTypeName(exprType), GetTypeName(type));
}
Expression ParseMemberAccess(Type type, Expression instance)
{
if (instance != null) type = instance.Type;
int errorPos = token.pos;
string id = GetIdentifier();
NextToken();
if (token.id == TokenId.OpenParen)
{
if (instance != null && type != typeof(string))
{
Type enumerableType = FindGenericType(typeof(IEnumerable<>), type);
if (enumerableType != null)
{
Type elementType = enumerableType.GetGenericArguments()[0];
return ParseAggregate(instance, elementType, id, errorPos);
}
}
Expression[] args = ParseArgumentList();
MethodBase mb;
switch (FindMethod(type, id, instance == null, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableMethod,
id, GetTypeName(type));
case 1:
MethodInfo method = (MethodInfo)mb;
//HM removed this as it seemed to be breaking stuff
//if (!IsPredefinedType(method.DeclaringType))
// throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
if (method.ReturnType == typeof(void))
throw ParseError(errorPos, Res.MethodIsVoid,
id, GetTypeName(method.DeclaringType));
return Expression.Call(instance, (MethodInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
id, GetTypeName(type));
}
}
else
{
MemberInfo member = FindPropertyOrField(type, id, instance == null);
if (member == null)
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
return member is System.Reflection.PropertyInfo ?
Expression.Property(instance, (System.Reflection.PropertyInfo)member) :
Expression.Field(instance, (FieldInfo)member);
}
}
static Type FindGenericType(Type generic, Type type)
{
while (type != null && type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type;
if (generic.IsInterface)
{
foreach (Type intfType in type.GetInterfaces())
{
Type found = FindGenericType(generic, intfType);
if (found != null) return found;
}
}
type = type.BaseType;
}
return null;
}
Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
{
ParameterExpression outerIt = it;
ParameterExpression innerIt = Expression.Parameter(elementType, "");
it = innerIt;
Expression[] args = ParseArgumentList();
it = outerIt;
MethodBase signature;
if (FindMethod(typeof(IEnumerableSignatures), methodName, false, args, out signature) != 1)
throw ParseError(errorPos, Res.NoApplicableAggregate, methodName);
Type[] typeArgs;
if (signature.Name == "Min" || signature.Name == "Max")
{
typeArgs = new Type[] { elementType, args[0].Type };
}
else
{
typeArgs = new Type[] { elementType };
}
if (args.Length == 0)
{
args = new Expression[] { instance };
}
else
{
args = new Expression[] { instance, Expression.Lambda(args[0], innerIt) };
}
return Expression.Call(typeof(Enumerable), signature.Name, typeArgs, args);
}
Expression[] ParseArgumentList()
{
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
Expression[] args = token.id != TokenId.CloseParen ? ParseArguments() : new Expression[0];
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
NextToken();
return args;
}
Expression[] ParseArguments()
{
List<Expression> argList = new List<Expression>();
while (true)
{
argList.Add(ParseExpression());
if (token.id != TokenId.Comma) break;
NextToken();
}
return argList.ToArray();
}
Expression ParseElementAccess(Expression expr)
{
int errorPos = token.pos;
ValidateToken(TokenId.OpenBracket, Res.OpenParenExpected);
NextToken();
Expression[] args = ParseArguments();
ValidateToken(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected);
NextToken();
if (expr.Type.IsArray)
{
if (expr.Type.GetArrayRank() != 1 || args.Length != 1)
throw ParseError(errorPos, Res.CannotIndexMultiDimArray);
Expression index = PromoteExpression(args[0], typeof(int), true);
if (index == null)
throw ParseError(errorPos, Res.InvalidIndex);
return Expression.ArrayIndex(expr, index);
}
else
{
MethodBase mb;
switch (FindIndexer(expr.Type, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableIndexer,
GetTypeName(expr.Type));
case 1:
return Expression.Call(expr, (MethodInfo)mb, args);
default:
throw ParseError(errorPos, Res.AmbiguousIndexerInvocation,
GetTypeName(expr.Type));
}
}
}
static bool IsPredefinedType(Type type)
{
foreach (Type t in predefinedTypes) if (t == type) return true;
return false;
}
static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
static Type GetNonNullableType(Type type)
{
return IsNullableType(type) ? type.GetGenericArguments()[0] : type;
}
static string GetTypeName(Type type)
{
Type baseType = GetNonNullableType(type);
string s = baseType.Name;
if (type != baseType) s += '?';
return s;
}
static bool IsNumericType(Type type)
{
return GetNumericTypeKind(type) != 0;
}
static bool IsSignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 2;
}
static bool IsUnsignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 3;
}
static int GetNumericTypeKind(Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum) return 0;
switch (Type.GetTypeCode(type))
{
case TypeCode.Char:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return 1;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
return 2;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return 3;
default:
return 0;
}
}
static bool IsEnumType(Type type)
{
return GetNonNullableType(type).IsEnum;
}
void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos)
{
Expression[] args = new Expression[] { expr };
MethodBase method;
if (FindMethod(signatures, "F", false, args, out method) != 1)
throw ParseError(errorPos, Res.IncompatibleOperand,
opName, GetTypeName(args[0].Type));
expr = args[0];
}
void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos)
{
Expression[] args = new Expression[] { left, right };
MethodBase method;
if (FindMethod(signatures, "F", false, args, out method) != 1)
throw IncompatibleOperandsError(opName, left, right, errorPos);
left = args[0];
right = args[1];
}
Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos)
{
return ParseError(pos, Res.IncompatibleOperands,
opName, GetTypeName(left.Type), GetTypeName(right.Type));
}
MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
(staticAccess ? BindingFlags.Static : BindingFlags.Instance);
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field,
flags, Type.FilterNameIgnoreCase, memberName);
if (members.Length != 0) return members[0];
}
return null;
}
int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
(staticAccess ? BindingFlags.Static : BindingFlags.Instance);
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.FindMembers(MemberTypes.Method,
flags, Type.FilterNameIgnoreCase, methodName);
int count = FindBestMethod(members.Cast<MethodBase>(), args, out method);
if (count != 0) return count;
}
method = null;
return 0;
}
int FindIndexer(Type type, Expression[] args, out MethodBase method)
{
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.GetDefaultMembers();
if (members.Length != 0)
{
IEnumerable<MethodBase> methods = members.
OfType<System.Reflection.PropertyInfo>().
Select(p => (MethodBase)p.GetGetMethod()).
Where(m => m != null);
int count = FindBestMethod(methods, args, out method);
if (count != 0) return count;
}
}
method = null;
return 0;
}
static IEnumerable<Type> SelfAndBaseTypes(Type type)
{
if (type.IsInterface)
{
List<Type> types = new List<Type>();
AddInterface(types, type);
return types;
}
return SelfAndBaseClasses(type);
}
static IEnumerable<Type> SelfAndBaseClasses(Type type)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
static void AddInterface(List<Type> types, Type type)
{
if (!types.Contains(type))
{
types.Add(type);
foreach (Type t in type.GetInterfaces()) AddInterface(types, t);
}
}
class MethodData
{
public MethodBase MethodBase;
public ParameterInfo[] Parameters;
public Expression[] Args;
}
int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method)
{
MethodData[] applicable = methods.
Select(m => new MethodData { MethodBase = m, Parameters = m.GetParameters() }).
Where(m => IsApplicable(m, args)).
ToArray();
if (applicable.Length > 1)
{
applicable = applicable.
Where(m => applicable.All(n => m == n || IsBetterThan(args, m, n))).
ToArray();
}
if (applicable.Length == 1)
{
MethodData md = applicable[0];
for (int i = 0; i < args.Length; i++) args[i] = md.Args[i];
method = md.MethodBase;
}
else
{
method = null;
}
return applicable.Length;
}
bool IsApplicable(MethodData method, Expression[] args)
{
if (method.Parameters.Length != args.Length) return false;
Expression[] promotedArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++)
{
ParameterInfo pi = method.Parameters[i];
if (pi.IsOut) return false;
Expression promoted = PromoteExpression(args[i], pi.ParameterType, false);
if (promoted == null) return false;
promotedArgs[i] = promoted;
}
method.Args = promotedArgs;
return true;
}
Expression PromoteExpression(Expression expr, Type type, bool exact)
{
if (expr.Type == type) return expr;
if (expr is ConstantExpression)
{
ConstantExpression ce = (ConstantExpression)expr;
if (ce == nullLiteral)
{
if (!type.IsValueType || IsNullableType(type))
return Expression.Constant(null, type);
}
else
{
string text;
if (literals.TryGetValue(ce, out text))
{
Type target = GetNonNullableType(type);
Object value = null;
switch (Type.GetTypeCode(ce.Type))
{
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
value = ParseNumber(text, target);
break;
case TypeCode.Double:
if (target == typeof(decimal)) value = ParseNumber(text, target);
break;
case TypeCode.String:
value = ParseEnum(text, target);
break;
}
if (value != null)
return Expression.Constant(value, type);
}
}
}
if (IsCompatibleWith(expr.Type, type))
{
if (type.IsValueType || exact) return Expression.Convert(expr, type);
return expr;
}
return null;
}
public static object ParseNumber(string text, TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.SByte:
sbyte sb;
if (sbyte.TryParse(text, out sb)) return sb;
break;
case TypeCode.Byte:
byte b;
if (byte.TryParse(text, out b)) return b;
break;
case TypeCode.Int16:
short s;
if (short.TryParse(text, out s)) return s;
break;
case TypeCode.UInt16:
ushort us;
if (ushort.TryParse(text, out us)) return us;
break;
case TypeCode.Int32:
int i;
if (int.TryParse(text, out i)) return i;
break;
case TypeCode.UInt32:
uint ui;
if (uint.TryParse(text, out ui)) return ui;
break;
case TypeCode.Int64:
long l;
if (long.TryParse(text, out l)) return l;
break;
case TypeCode.UInt64:
ulong ul;
if (ulong.TryParse(text, out ul)) return ul;
break;
case TypeCode.Single:
float f;
if (float.TryParse(text, out f)) return f;
break;
case TypeCode.Double:
double d;
if (double.TryParse(text, out d)) return d;
break;
case TypeCode.Decimal:
decimal e;
if (decimal.TryParse(text, out e)) return e;
break;
}
return null;
}
public static object ParseNumber(string text, Type type)
{
return ParseNumber(text, Type.GetTypeCode(GetNonNullableType(type)));
}
static object ParseEnum(string name, Type type)
{
if (type.IsEnum)
{
MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field,
BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static,
Type.FilterNameIgnoreCase, name);
if (memberInfos.Length != 0) return ((FieldInfo)memberInfos[0]).GetValue(null);
}
return null;
}
static bool IsCompatibleWith(Type source, Type target)
{
if (source == target) return true;
if (!target.IsValueType) return target.IsAssignableFrom(source);
Type st = GetNonNullableType(source);
Type tt = GetNonNullableType(target);
if (st != source && tt == target) return false;
TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st);
TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt);
switch (sc)
{
case TypeCode.SByte:
switch (tc)
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Byte:
switch (tc)
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int16:
switch (tc)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt16:
switch (tc)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int32:
switch (tc)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt32:
switch (tc)
{
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int64:
switch (tc)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt64:
switch (tc)
{
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Single:
switch (tc)
{
case TypeCode.Single:
case TypeCode.Double:
return true;
}
break;
default:
if (st == tt) return true;
break;
}
return false;
}
static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2)
{
bool better = false;
for (int i = 0; i < args.Length; i++)
{
int c = CompareConversions(args[i].Type,
m1.Parameters[i].ParameterType,
m2.Parameters[i].ParameterType);
if (c < 0) return false;
if (c > 0) better = true;
}
return better;
}
// Return 1 if s -> t1 is a better conversion than s -> t2
// Return -1 if s -> t2 is a better conversion than s -> t1
// Return 0 if neither conversion is better
static int CompareConversions(Type s, Type t1, Type t2)
{
if (t1 == t2) return 0;
if (s == t1) return 1;
if (s == t2) return -1;
bool t1t2 = IsCompatibleWith(t1, t2);
bool t2t1 = IsCompatibleWith(t2, t1);
if (t1t2 && !t2t1) return 1;
if (t2t1 && !t1t2) return -1;
if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1;
if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1;
return 0;
}
Expression GenerateEqual(Expression left, Expression right)
{
return Expression.Equal(left, right);
}
Expression GenerateNotEqual(Expression left, Expression right)
{
return Expression.NotEqual(left, right);
}
Expression GenerateGreaterThan(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.GreaterThan(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.GreaterThan(left, right);
}
Expression GenerateGreaterThanEqual(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.GreaterThanOrEqual(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.GreaterThanOrEqual(left, right);
}
Expression GenerateLessThan(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.LessThan(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.LessThan(left, right);
}
Expression GenerateLessThanEqual(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.LessThanOrEqual(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.LessThanOrEqual(left, right);
}
Expression GenerateAdd(Expression left, Expression right)
{
if (left.Type == typeof(string) && right.Type == typeof(string))
{
return GenerateStaticMethodCall("Concat", left, right);
}
return Expression.Add(left, right);
}
Expression GenerateSubtract(Expression left, Expression right)
{
return Expression.Subtract(left, right);
}
Expression GenerateStringConcat(Expression left, Expression right)
{
return Expression.Call(
null,
typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
new[] { left, right });
}
MethodInfo GetStaticMethod(string methodName, Expression left, Expression right)
{
return left.Type.GetMethod(methodName, new[] { left.Type, right.Type });
}
Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right)
{
return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right });
}
void SetTextPos(int pos)
{
textPos = pos;
ch = textPos < textLen ? text[textPos] : '\0';
}
void NextChar()
{
if (textPos < textLen) textPos++;
ch = textPos < textLen ? text[textPos] : '\0';
}
void NextToken()
{
while (Char.IsWhiteSpace(ch)) NextChar();
TokenId t;
int tokenPos = textPos;
switch (ch)
{
case '!':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.ExclamationEqual;
}
else
{
t = TokenId.Exclamation;
}
break;
case '%':
NextChar();
t = TokenId.Percent;
break;
case '&':
NextChar();
if (ch == '&')
{
NextChar();
t = TokenId.DoubleAmphersand;
}
else
{
t = TokenId.Amphersand;
}
break;
case '(':
NextChar();
t = TokenId.OpenParen;
break;
case ')':
NextChar();
t = TokenId.CloseParen;
break;
case '*':
NextChar();
t = TokenId.Asterisk;
break;
case '+':
NextChar();
t = TokenId.Plus;
break;
case ',':
NextChar();
t = TokenId.Comma;
break;
case '-':
NextChar();
t = TokenId.Minus;
break;
case '.':
NextChar();
t = TokenId.Dot;
break;
case '/':
NextChar();
t = TokenId.Slash;
break;
case ':':
NextChar();
t = TokenId.Colon;
break;
case '<':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.LessThanEqual;
}
else if (ch == '>')
{
NextChar();
t = TokenId.LessGreater;
}
else
{
t = TokenId.LessThan;
}
break;
case '=':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.DoubleEqual;
}
else
{
t = TokenId.Equal;
}
break;
case '>':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.GreaterThanEqual;
}
else
{
t = TokenId.GreaterThan;
}
break;
case '?':
NextChar();
t = TokenId.Question;
break;
case '[':
NextChar();
t = TokenId.OpenBracket;
break;
case ']':
NextChar();
t = TokenId.CloseBracket;
break;
case '|':
NextChar();
if (ch == '|')
{
NextChar();
t = TokenId.DoubleBar;
}
else
{
t = TokenId.Bar;
}
break;
case '"':
case '\'':
char quote = ch;
do
{
NextChar();
while (textPos < textLen && ch != quote) NextChar();
if (textPos == textLen)
throw ParseError(textPos, Res.UnterminatedStringLiteral);
NextChar();
} while (ch == quote);
t = TokenId.StringLiteral;
break;
default:
if (Char.IsLetter(ch) || ch == '@' || ch == '_')
{
do
{
NextChar();
} while (Char.IsLetterOrDigit(ch) || ch == '_');
t = TokenId.Identifier;
break;
}
if (Char.IsDigit(ch))
{
t = TokenId.IntegerLiteral;
do
{
NextChar();
} while (Char.IsDigit(ch));
if (ch == '.')
{
t = TokenId.RealLiteral;
NextChar();
ValidateDigit();
do
{
NextChar();
} while (Char.IsDigit(ch));
}
if (ch == 'E' || ch == 'e')
{
t = TokenId.RealLiteral;
NextChar();
if (ch == '+' || ch == '-') NextChar();
ValidateDigit();
do
{
NextChar();
} while (Char.IsDigit(ch));
}
if (ch == 'F' || ch == 'f') NextChar();
break;
}
if (textPos == textLen)
{
t = TokenId.End;
break;
}
throw ParseError(textPos, Res.InvalidCharacter, ch);
}
token.id = t;
token.text = text.Substring(tokenPos, textPos - tokenPos);
token.pos = tokenPos;
}
bool TokenIdentifierIs(string id)
{
return token.id == TokenId.Identifier && String.Equals(id, token.text, StringComparison.OrdinalIgnoreCase);
}
string GetIdentifier()
{
ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
string id = token.text;
if (id.Length > 1 && id[0] == '@') id = id.Substring(1);
return id;
}
void ValidateDigit()
{
if (!Char.IsDigit(ch)) throw ParseError(textPos, Res.DigitExpected);
}
void ValidateToken(TokenId t, string errorMessage)
{
if (token.id != t) throw ParseError(errorMessage);
}
void ValidateToken(TokenId t)
{
if (token.id != t) throw ParseError(Res.SyntaxError);
}
Exception ParseError(string format, params object[] args)
{
return ParseError(token.pos, format, args);
}
Exception ParseError(int pos, string format, params object[] args)
{
return new ParseException(string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args), pos);
}
static Dictionary<string, object> CreateKeywords()
{
Dictionary<string, object> d = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
d.Add("true", trueLiteral);
d.Add("false", falseLiteral);
d.Add("null", nullLiteral);
d.Add(keywordIt, keywordIt);
d.Add(keywordIif, keywordIif);
d.Add(keywordNew, keywordNew);
foreach (Type type in predefinedTypes) d.Add(type.Name, type);
return d;
}
}
}
| |
#if !UNITY_WSA && !UNITY_WP8
using System;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using PlayFab.SharedModels;
#if !DISABLE_PLAYFABCLIENT_API
using PlayFab.ClientModels;
#endif
using PlayFab.Json;
namespace PlayFab.Internal
{
public class PlayFabWebRequest : IPlayFabHttp
{
private static readonly Queue<Action> ResultQueue = new Queue<Action>();
private static readonly Queue<Action> _tempActions = new Queue<Action>();
private static readonly List<CallRequestContainer> ActiveRequests = new List<CallRequestContainer>();
private static Thread _requestQueueThread;
private static readonly object _ThreadLock = new object();
private static readonly TimeSpan ThreadKillTimeout = TimeSpan.FromSeconds(60);
private static DateTime _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; // Kill the thread after 1 minute of inactivity
private static bool _isApplicationPlaying;
private static int _activeCallCount;
private static string _unityVersion;
private static string _authKey;
private static bool _sessionStarted;
public bool SessionStarted { get { return _sessionStarted; } set { _sessionStarted = value; } }
public string AuthKey { get { return _authKey; } set { _authKey = value; } }
public void InitializeHttp()
{
SetupCertificates();
_isApplicationPlaying = true;
_unityVersion = Application.unityVersion;
}
public void OnDestroy()
{
_isApplicationPlaying = false;
lock (ResultQueue)
{
ResultQueue.Clear();
}
lock (ActiveRequests)
{
ActiveRequests.Clear();
}
lock (_ThreadLock)
{
_requestQueueThread = null;
}
}
private void SetupCertificates()
{
// These are performance Optimizations for HttpWebRequests.
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.Expect100Continue = false;
//Support for SSL
var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true
ServicePointManager.ServerCertificateValidationCallback = rcvc;
}
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
public void MakeApiCall(CallRequestContainer reqContainer)
{
reqContainer.HttpState = HttpRequestState.Idle;
lock (ActiveRequests)
{
ActiveRequests.Insert(0, reqContainer);
}
ActivateThreadWorker();
}
private static void ActivateThreadWorker()
{
lock (_ThreadLock)
{
if (_requestQueueThread != null)
{
return;
}
_requestQueueThread = new Thread(WorkerThreadMainLoop);
_requestQueueThread.Start();
}
}
private static void WorkerThreadMainLoop()
{
try
{
bool active;
lock (_ThreadLock)
{
// Kill the thread after 1 minute of inactivity
_threadKillTime = DateTime.UtcNow + ThreadKillTimeout;
}
List<CallRequestContainer> localActiveRequests = new List<CallRequestContainer>();
do
{
//process active requests
lock (ActiveRequests)
{
localActiveRequests.AddRange(ActiveRequests);
ActiveRequests.Clear();
_activeCallCount = localActiveRequests.Count;
}
var activeCalls = localActiveRequests.Count;
for (var i = activeCalls - 1; i >= 0; i--) // We must iterate backwards, because we remove at index i in some cases
{
switch (localActiveRequests[i].HttpState)
{
case HttpRequestState.Error:
localActiveRequests.RemoveAt(i); break;
case HttpRequestState.Idle:
Post(localActiveRequests[i]); break;
case HttpRequestState.Sent:
if (localActiveRequests[i].HttpRequest.HaveResponse) // Else we'll try again next tick
ProcessHttpResponse(localActiveRequests[i]);
break;
case HttpRequestState.Received:
ProcessJsonResponse(localActiveRequests[i]);
localActiveRequests.RemoveAt(i);
break;
}
}
#region Expire Thread.
// Check if we've been inactive
lock (_ThreadLock)
{
var now = DateTime.UtcNow;
if (activeCalls > 0 && _isApplicationPlaying)
{
// Still active, reset the _threadKillTime
_threadKillTime = now + ThreadKillTimeout;
}
// Kill the thread after 1 minute of inactivity
active = now <= _threadKillTime;
if (!active)
{
_requestQueueThread = null;
}
// This thread will be stopped, so null this now, inside lock (_threadLock)
}
#endregion
Thread.Sleep(1);
} while (active);
}
catch (Exception e)
{
Debug.LogException(e);
_requestQueueThread = null;
}
}
private static void Post(CallRequestContainer reqContainer)
{
try
{
reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl);
reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion;
reqContainer.HttpRequest.SendChunked = false;
reqContainer.HttpRequest.Proxy = null;
// Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's.
reqContainer.HttpRequest.Headers.Add("X-ReportErrorAsSuccess", "true");
// Without this, we have to catch WebException instead, and manually decode the result
reqContainer.HttpRequest.Headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString);
switch (reqContainer.AuthKey)
{
#if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API
case AuthType.DevSecretKey: reqContainer.HttpRequest.Headers.Add("X-SecretKey", PlayFabSettings.DeveloperSecretKey); break;
#endif
case AuthType.LoginSession: reqContainer.HttpRequest.Headers.Add("X-Authorization", _authKey); break;
}
reqContainer.HttpRequest.ContentType = "application/json";
reqContainer.HttpRequest.Method = "POST";
reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive;
reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout;
reqContainer.HttpRequest.AllowWriteStreamBuffering = false;
reqContainer.HttpRequest.Proxy = null;
reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength;
reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout;
//Debug.Log("Get Stream");
// Get Request Stream and send data in the body.
using (var stream = reqContainer.HttpRequest.GetRequestStream())
{
//Debug.Log("Post Stream");
stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
//Debug.Log("After Post stream");
}
reqContainer.HttpState = HttpRequestState.Sent;
}
catch (WebException e)
{
reqContainer.JsonResponse = ResponseToString(e.Response) ?? e.Status + ": WebException making http request to: " + reqContainer.FullUrl;
var enhancedError = new WebException(reqContainer.JsonResponse, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
catch (Exception e)
{
reqContainer.JsonResponse = "Unhandled exception in Post : " + reqContainer.FullUrl;
var enhancedError = new Exception(reqContainer.JsonResponse, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
private static void ProcessHttpResponse(CallRequestContainer reqContainer)
{
try
{
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif
// Get and check the response
var httpResponse = (HttpWebResponse)reqContainer.HttpRequest.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
reqContainer.JsonResponse = ResponseToString(httpResponse);
}
if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(reqContainer.JsonResponse))
{
reqContainer.JsonResponse = reqContainer.JsonResponse ?? "No response from server";
QueueRequestError(reqContainer);
return;
}
else
{
// Response Recieved Successfully, now process.
}
reqContainer.HttpState = HttpRequestState.Received;
}
catch (Exception e)
{
var msg = "Unhandled exception in ProcessHttpResponse : " + reqContainer.FullUrl;
reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
var enhancedError = new Exception(msg, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
/// <summary>
/// Set the reqContainer into an error state, and queue it to invoke the ErrorCallback for that request
/// </summary>
private static void QueueRequestError(CallRequestContainer reqContainer)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData); // Decode the server-json error
reqContainer.HttpState = HttpRequestState.Error;
lock (ResultQueue)
{
//Queue The result callbacks to run on the main thread.
ResultQueue.Enqueue(() =>
{
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
if (reqContainer.ErrorCallback != null)
reqContainer.ErrorCallback(reqContainer.Error);
});
}
}
private static void ProcessJsonResponse(CallRequestContainer reqContainer)
{
try
{
var httpResult = JsonWrapper.DeserializeObject<HttpResponseObject>(reqContainer.JsonResponse);
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif
//This would happen if playfab returned a 500 internal server error or a bad json response.
if (httpResult == null || httpResult.code != 200)
{
QueueRequestError(reqContainer);
return;
}
reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data);
reqContainer.DeserializeResultJson(); // Assigns Result with a properly typed object
reqContainer.ApiResult.Request = reqContainer.ApiRequest;
reqContainer.ApiResult.CustomData = reqContainer.CustomData;
#if !DISABLE_PLAYFABCLIENT_API
ClientModels.UserSettings userSettings = null;
var res = reqContainer.ApiResult as ClientModels.LoginResult;
var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult;
if (res != null)
{
userSettings = res.SettingsForUser;
_authKey = res.SessionTicket;
}
else if (regRes != null)
{
userSettings = regRes.SettingsForUser;
_authKey = regRes.SessionTicket;
}
if (userSettings != null && _authKey != null && userSettings.NeedsAttribution)
{
lock (ResultQueue)
{
ResultQueue.Enqueue(PlayFabIdfa.OnPlayFabLogin);
}
}
#endif
lock (ResultQueue)
{
//Queue The result callbacks to run on the main thread.
ResultQueue.Enqueue(() =>
{
#if PLAYFAB_REQUEST_TIMING
reqContainer.Stopwatch.Stop();
reqContainer.Timing.MainThreadRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
PlayFabHttp.SendRequestTiming(reqContainer.Timing);
#endif
try
{
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
reqContainer.InvokeSuccessCallback();
}
catch (Exception e)
{
Debug.LogException(e); // Log the user's callback exception back to them without halting PlayFabHttp
}
});
}
}
catch (Exception e)
{
var msg = "Unhandled exception in ProcessJsonResponse : " + reqContainer.FullUrl;
reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
var enhancedError = new Exception(msg, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
public void Update()
{
lock (ResultQueue)
{
while (ResultQueue.Count > 0)
{
var actionToQueue = ResultQueue.Dequeue();
_tempActions.Enqueue(actionToQueue);
}
}
while (_tempActions.Count > 0)
{
var finishedRequest = _tempActions.Dequeue();
finishedRequest();
}
}
private static string ResponseToString(WebResponse webResponse)
{
if (webResponse == null)
return null;
try
{
using (var responseStream = webResponse.GetResponseStream())
{
if (responseStream == null)
return null;
using (var stream = new StreamReader(responseStream))
{
return stream.ReadToEnd();
}
}
}
catch (WebException webException)
{
try
{
using (var responseStream = webException.Response.GetResponseStream())
{
if (responseStream == null)
return null;
using (var stream = new StreamReader(responseStream))
{
return stream.ReadToEnd();
}
}
}
catch (Exception e)
{
Debug.LogException(e);
return null;
}
}
catch (Exception e)
{
Debug.LogException(e);
return null;
}
}
public int GetPendingMessages()
{
var count = 0;
lock (ActiveRequests)
count += ActiveRequests.Count + _activeCallCount;
lock (ResultQueue)
count += ResultQueue.Count;
return count;
}
}
}
#endif
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using NLog.Time;
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
private static int globalSequenceId;
private readonly object layoutCacheLock = new object();
private string formattedMessage;
private string message;
private object[] parameters;
private IFormatProvider formatProvider;
private IDictionary<Layout, string> layoutCache;
private IDictionary<object, object> properties;
private IDictionary eventContextAdapter;
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
this.TimeStamp = TimeSource.Current.Time;
this.SequenceID = Interlocked.Increment(ref globalSequenceId);
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception): this()
{
this.Level = level;
this.LoggerName = loggerName;
this.Message = message;
this.Parameters = parameters;
this.FormatProvider = formatProvider;
this.Exception = exception;
if (NeedToPreformatMessage(parameters))
{
this.CalcFormattedMessage();
}
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")]
public int SequenceID { get; private set; }
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace
{
get { return this.StackTrace != null; }
}
/// <summary>
/// Gets the stack frame of the method that did the logging.
/// </summary>
public StackFrame UserStackFrame
{
get { return (this.StackTrace != null) ? this.StackTrace.GetFrame(this.UserStackFrameNumber) : null; }
}
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber { get; private set; }
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace { get; private set; }
/// <summary>
/// Gets or sets the exception information.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
public string LoggerName { get; set; }
/// <summary>
/// Gets the logger short name.
/// </summary>
[Obsolete("This property should not be used.")]
public string LoggerShortName
{
get
{
int lastDot = this.LoggerName.LastIndexOf('.');
if (lastDot >= 0)
{
return this.LoggerName.Substring(lastDot + 1);
}
return this.LoggerName;
}
}
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message
{
get { return message; }
set
{
message = value;
ResetFormattedMessage();
}
}
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")]
public object[] Parameters
{
get { return parameters; }
set
{
parameters = value;
ResetFormattedMessage();
}
}
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider
{
get { return formatProvider; }
set
{
if (formatProvider != value)
{
formatProvider = value;
ResetFormattedMessage();
}
}
}
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (this.formattedMessage == null)
{
this.CalcFormattedMessage();
}
return this.formattedMessage;
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties
{
get
{
if (this.properties == null)
{
this.InitEventContext();
}
return this.properties;
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
[Obsolete("Use LogEventInfo.Properties instead.", true)]
public IDictionary Context
{
get
{
if (this.eventContextAdapter == null)
{
this.InitEventContext();
}
return this.eventContextAdapter;
}
}
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message });
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
[Obsolete("use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message)")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception)
{
return new LogEventInfo(logLevel, loggerName, null, message, null, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message)
{
return Create(logLevel, loggerName, exception, formatProvider, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName,formatProvider, message, parameters, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return "Log Event: Logger='" + this.LoggerName + "' Level=" + this.Level + " Message='" + this.FormattedMessage + "' SequenceID=" + this.SequenceID;
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
this.StackTrace = stackTrace;
this.UserStackFrameNumber = userStackFrame;
}
internal string AddCachedLayoutValue(Layout layout, string value)
{
lock (this.layoutCacheLock)
{
if (this.layoutCache == null)
{
this.layoutCache = new Dictionary<Layout, string>();
}
this.layoutCache[layout] = value;
}
return value;
}
internal bool TryGetCachedLayoutValue(Layout layout, out string value)
{
lock (this.layoutCacheLock)
{
if (this.layoutCache == null || this.layoutCache.Count == 0)
{
value = null;
return false;
}
return this.layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters == null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 3)
{
// too many parameters, too costly to check
return true;
}
if (!IsSafeToDeferFormatting(parameters[0]))
{
return true;
}
if (parameters.Length >= 2)
{
if (!IsSafeToDeferFormatting(parameters[1]))
{
return true;
}
}
if (parameters.Length >= 3)
{
if (!IsSafeToDeferFormatting(parameters[2]))
{
return true;
}
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
if (value == null)
{
return true;
}
return value.GetType().IsPrimitive || (value is string);
}
private void CalcFormattedMessage()
{
if (this.Parameters == null || this.Parameters.Length == 0)
{
this.formattedMessage = this.Message;
}
else
{
try
{
this.formattedMessage = string.Format(this.FormatProvider ?? CultureInfo.CurrentCulture, this.Message, this.Parameters);
}
catch (Exception exception)
{
this.formattedMessage = this.Message;
InternalLogger.Warn(exception, "Error when formatting a message.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
private void ResetFormattedMessage()
{
this.formattedMessage = null;
}
private void InitEventContext()
{
this.properties = new Dictionary<object, object>();
this.eventContextAdapter = new DictionaryAdapter<object, object>(this.properties);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AGO.Core;
using AGO.Core.Controllers;
using AGO.Core.Controllers.Security;
using AGO.Core.DataAccess;
using AGO.Core.Filters;
using AGO.Core.Json;
using AGO.Core.Localization;
using AGO.Core.Model;
using AGO.Core.Model.Processing;
using AGO.Core.Model.Projects;
using AGO.Core.Model.Security;
using AGO.Core.Security;
using AGO.Tasks.Model.Task;
using Common.Logging;
using NHibernate;
using NHibernate.Criterion;
namespace AGO.Tasks.Controllers
{
public class AbstractTasksController : AbstractController
{
protected AbstractTasksController(
IJsonService jsonService,
IFilteringService filteringService,
ILocalizationService localizationService,
IModelProcessingService modelProcessingService,
AuthController authController,
ISecurityService securityService,
ISessionProviderRegistry registry,
DaoFactory factory)
: base(jsonService, filteringService, localizationService, modelProcessingService, authController, securityService, registry, factory)
{
}
protected ICriteria PrepareLookup<TModel>(string project, string term, int page,
Expression<Func<TModel, string>> textProperty,
Expression<Func<TModel, string>> searchProperty = null,
params Expression<Func<TModel, object>>[] sorters)
where TModel : class, IProjectBoundModel, IIdentifiedModel<Guid>
{
var projectFilter = _FilteringService.Filter<TModel>().Where(m => m.ProjectCode == project);
//term search predicate
IModelFilterNode termFilter = null;
if (!term.IsNullOrWhiteSpace())
{
termFilter = _FilteringService.Filter<TModel>()
.WhereString(searchProperty ?? textProperty).Like(term.TrimSafe(), true, true);
}
//concat with security predicates
var filter = ApplyReadConstraint<TModel>(project, projectFilter, termFilter);
//get executable criteria
var criteria = _FilteringService.CompileFilter(filter, typeof(TModel)).GetExecutableCriteria(ProjectSession(project));
//add needed sorting
var objTextProp = textProperty.Cast<TModel, string, object>();
if (sorters == null || !sorters.Any())
{
criteria.AddOrder(Order.Asc(Projections.Property(objTextProp).PropertyName));
}
else
{
foreach (var s in sorters)
{
criteria.AddOrder(Order.Asc(Projections.Property(s).PropertyName));
}
}
return DaoFactory.CreateProjectCrudDao(project).PagedCriteria(criteria, page);
}
protected IEnumerable<LookupEntry> Lookup<TModel>(string project, string term, int page,
Expression<Func<TModel, string>> textProperty,
Expression<Func<TModel, string>> searchProperty = null,
params Expression<Func<TModel, object>>[] sorters)
where TModel: class, IProjectBoundModel, IIdentifiedModel<Guid>
{
try
{
var objTextProp = textProperty.Cast<TModel, string, object>();
return PrepareLookup(project, term, page, textProperty, searchProperty, sorters)
.LookupModelsList(objTextProp);
}
catch (NoSuchProjectMemberException)
{
Log.WarnFormat("Lookup from not project member catched. User '{0}' for type '{1}'", CurrentUser.Email, typeof(TModel).AssemblyQualifiedName);
return Enumerable.Empty<LookupEntry>();
}
}
protected UpdateResult<TDTO> Edit<TModel, TDTO>(Guid id, string project,
Action<TModel, ValidationResult> update,
Func<TModel, TDTO> convert,
Func<TModel> factory = null) where TDTO: class
where TModel: CoreModel<Guid>, new()
{
var result = new UpdateResult<TDTO> {Validation = new ValidationResult()};
Func<TModel> defaultFactory = () =>
{
var m = new TModel();
var secureModel = m as ISecureModel;
if (secureModel != null)
{
var member = CurrentUserToMember(project);
secureModel.Creator = member;
secureModel.LastChanger = member;
secureModel.LastChangeTime = DateTime.UtcNow;
}
var projectBoundModel = m as IProjectBoundModel;
if (projectBoundModel != null)
projectBoundModel.ProjectCode = project;
return m;
};
Func<TModel, TModel> postFactory = model =>
{
var secureModel = model as ISecureModel;
if (secureModel != null)
{
secureModel.LastChanger = CurrentUserToMember(project);
secureModel.LastChangeTime = DateTime.UtcNow;
}
return model;
};
try
{
ICrudDao dao;
ISession session;
if (typeof (ProjectModel).IsAssignableFrom(typeof (TModel)))
{
dao = DaoFactory.CreateMainCrudDao();
session = MainSession;
}
else
{
dao = DaoFactory.CreateProjectCrudDao(project);
session = ProjectSession(project);
}
var persistentModel = postFactory(default(Guid).Equals(id)
? (factory ?? defaultFactory)()
: dao.Get<TModel>(id));
if (persistentModel == null)
throw new NoSuchEntityException();
TModel original = null;
if (!persistentModel.IsNew())
original = (TModel) persistentModel.Clone();
update(persistentModel, result.Validation);
//validate model
_ModelProcessingService.ValidateModelSaving(persistentModel, result.Validation, session);
if (!result.Validation.Success)
return result;
//test permissions
DemandUpdate(persistentModel, project);
//persist
dao.Store(persistentModel);
if (original != null)
_ModelProcessingService.AfterModelUpdated(persistentModel, original);
else
_ModelProcessingService.AfterModelCreated(persistentModel);
result.Model = convert(persistentModel);
}
catch (Exception e)
{
LogManager.GetLogger(GetType()).Error(e.GetBaseException().Message, e);
var msg = _LocalizationService.MessageForException(e) ?? "Unexpected error";
result.Validation.AddErrors(msg);
}
return result;
}
protected IModelFilterNode ApplyReadConstraint<TModel>(string project, params IModelFilterNode[] filter)
{
return SecurityService.ApplyReadConstraint<TModel>(project, CurrentUser.Id, ProjectSession(project), filter);
}
protected void DemandUpdate(IdentifiedModel model, string project)
{
SecurityService.DemandUpdate(model, project, CurrentUser.Id, ProjectSession(project));
}
protected void DemandDelete(IdentifiedModel model, string project)
{
SecurityService.DemandDelete(model, project, CurrentUser.Id, ProjectSession(project));
}
protected TModel SecureFind<TModel>(string project, Guid id) where TModel : class, IProjectBoundModel, IIdentifiedModel<Guid>
{
var fb = _FilteringService.Filter<TModel>();
var predicate = ApplyReadConstraint<TModel>(project, fb.Where(m =>
m.ProjectCode == project && m.Id == id));
var model = DaoFactory.CreateProjectFilteringDao(project).Find<TModel>(predicate);
if (model == null)
throw new NoSuchEntityException();
return model;
}
protected TaskModel SecureFindTask(string project, string numpp)
{
var fb = _FilteringService.Filter<TaskModel>();
var predicate = ApplyReadConstraint<TaskModel>(project, fb.Where(m =>
m.ProjectCode == project && m.SeqNumber == numpp));
var model = DaoFactory.CreateProjectFilteringDao(project).Find<TaskModel>(predicate);
if (model == null)
throw new NoSuchEntityException();
return model;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
namespace Epi.Data
{
/// <summary>
/// Provides base implementation of IDbDriver implementation
/// </summary>
public abstract class DbDriverBase : IDbDriver
{
#region Public Events
#endregion Public Events
#region Public Properties
/// <summary>
/// Gets the default schema prefix if applicable (ex. dbo for SQL Server)
/// </summary>
public abstract string SchemaPrefix
{
get;
}
/// <summary>
/// Property to specify if the same operation will be called multiple times. Data driver should use this to optimize code.
/// </summary>
public abstract bool IsBulkOperation
{
get;
set;
}
/// <summary>
/// Returns the full name of the data source. Typically used for display purposes
/// </summary>
public abstract string FullName
{
get;
}
/// <summary>
/// Gets/sets the Database name
/// </summary>
public abstract string DbName
{
get;
set;
}
/// <summary>
/// Gets the database connection string
/// </summary>
public abstract string ConnectionString
{
get;
set;
}
/// <summary>
/// Returns the maximum number of columns a table can have.
/// </summary>
public abstract int TableColumnMax
{
get;
}
/// <summary>
/// Gets an OLE-compatible connection string.
/// This is needed by Epi Map, as ESRI does not understand .NET connection strings.
/// See http://www.ConnectionStrings.com for an OLE-compatible connection string for
/// your database.
/// </summary>
public abstract string OleConnectionString
{
get;
}
/// <summary>
/// What is this?
/// </summary>
public abstract string DataSource
{
get;
}
/// <summary>
/// Gets a user-friendly description of the otherwise bewildering connection string
/// </summary>
public abstract string ConnectionDescription
{
get;
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Gets whether or not the database format is valid. Used for error checking on file-based database types.
/// </summary>
/// <param name="validationMessage">Any associated validation error messages</param>
/// <returns>bool</returns>
public virtual bool IsDatabaseFormatValid(ref string validationMessage)
{
return true;
}
/// <summary>
/// Change the data type of the column in current database
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="columnName">name of the column</param>
/// <param name="newColumnType">new data type of the column</param>
/// <returns>Boolean</returns>
public abstract bool AlterColumnType(string tableName, string columnName, string newColumnType);
/// <summary>
/// Adds a column to the table
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="column">The column</param>
/// <returns>Boolean</returns>
public abstract bool AddColumn(string tableName, TableColumn column);
/// <summary>
/// Test database connectivity
/// </summary>
/// <returns>Returns true if connection can be made successfully</returns>
public abstract bool TestConnection();
/// <summary>
/// Creates a table with the given columns
/// </summary>
/// <param name="tableName">The table to be created</param>
/// <param name="columns">List of columns</param>
public abstract void CreateTable(string tableName, List<TableColumn> columns);
///// <summary>
///// Gets a database engine specific connection string builder dialog for a database that already exists.
///// </summary>
///// <returns>IConnectionStringBuilder</returns>
//public abstract IConnectionStringGui GetConnectionStringGuiForExistingDb();
///// <summary>
///// Gets a database engine specific connection string builder dialog for a database that does not exist yet.
///// </summary>
///// <returns>IConnectionStringBuilder</returns>
//public abstract IConnectionStringGui GetConnectionStringGuiForNewDb();
///// <summary>
///// Gets a database engine specific connection
///// </summary>
///// <param name="fileName">File name and path of the project</param>
///// <returns>IConnectionStringBuilder</returns>
//public abstract ConnectionStringInfo RequestNewConnection(string fileName);
///// <summary>
///// Creates a physical database
///// </summary>
//public abstract void CreateDatabase(string databaseName);
/// <summary>
/// GetTableSchema()
/// </summary>
/// <returns>Table Schema</returns>
public abstract DataSets.TableSchema.TablesDataTable GetTableSchema();
/// <summary>
/// Returns the count of tables
/// </summary>
/// <returns>int</returns>
public abstract int GetTableCount();
/// <summary>
/// Return the number of colums in the specified table
/// </summary>
/// <remarks>
/// Originaly intended to be used to keep view tables from getting to wide.
/// </remarks>
/// <param name="tableName"></param>
/// <returns>the number of columns in the </returns>
public abstract int GetTableColumnCount(string tableName);
/// <summary>
/// Executes a sql query to select records into a data table
/// </summary>
/// <param name="selectQuery"></param>
/// <returns></returns>
public abstract DataTable Select(Query selectQuery);
/// <summary>
/// Executes a SELECT statement against the database and returns a disconnected data table. NOTE: Use this overload to work with Typed DataSets.
/// </summary>
/// <param name="selectQuery">The query to be executed against the database</param>
/// <param name="table">Table that will contain the result</param>
/// <returns>A DataTable containing the results of the query</returns>
public abstract DataTable Select(Query selectQuery, DataTable table);
/// <summary>
/// Gets a value indicating whether or not a specific column exists for a table in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <param name="columnName">Name of the column</param>
/// <returns>Boolean</returns>
public abstract bool ColumnExists(string tableName, string columnName);
/// <summary>
/// Compact the database
/// << may only apply to Access databases >>
/// </summary>
public abstract bool CompactDatabase();
/// <summary>
/// Executes a SQL statement that does not return anything.
/// </summary>
/// <param name="nonQueryStatement">The query to be executed against the database</param>
public abstract int ExecuteNonQuery(Query nonQueryStatement);
/// <summary>
/// Executes a SQL non-query within a transaction.
/// </summary>
/// <param name="nonQueryStatement">The query to be executed against the database</param>
/// <param name="transaction">The transaction object</param>
public abstract int ExecuteNonQuery(Query nonQueryStatement, IDbTransaction transaction);
/// <summary>
/// Executes a scalar query against the database
/// </summary>
/// <param name="scalarStatement">The query to be executed against the database</param>
/// <returns>object</returns>
public abstract object ExecuteScalar(Query scalarStatement);
/// <summary>
/// Executes a scalar query against the database using an existing transaction
/// </summary>
/// <param name="scalarStatement">The query to be executed against the database</param>
/// <param name="transaction">The existing transaction within which to execute</param>
/// <returns>object</returns>
public abstract object ExecuteScalar(Query scalarStatement, IDbTransaction transaction);
/// <summary>
/// Delete a specific table in current database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Boolean</returns>
public abstract bool DeleteTable(string tableName);
/// <summary>
/// Delete a specific column in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <param name="columnName">Name of the column</param>
/// <returns>Boolean</returns>
public abstract bool DeleteColumn(string tableName, string columnName);
/// <summary>
/// Gets a value indicating whether or not a specific table exists in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Boolean</returns>
public abstract bool TableExists(string tableName);
/// <summary>
/// Gets primary_key schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
public abstract DataSets.TableColumnSchema.ColumnsDataTable GetTableColumnSchema(string tableName);
/// <summary>
/// Gets primary_key schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
public abstract DataSets.ANSI.TableColumnSchema.ColumnsDataTable GetTableColumnSchemaANSI(string tableName);
/// <summary>
/// Gets Primary_Keys schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
public abstract DataSets.TableKeysSchema.Primary_KeysDataTable GetTableKeysSchema(string tableName);
/// <summary>
/// Gets the contents of a table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Datatable containing the table data</returns>
public abstract DataTable GetTableData(string tableName);
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames">
/// Comma delimited string of column names and ASC/DESC order
/// </param>
/// <returns>DataTable that has been sorted by criteria specified</returns>
public abstract DataTable GetTableData(string tableName, string columnNames);
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames"></param>
/// <param name="sortCriteria">
/// Comma delimited string of column names and ASC/DESC order
/// </param>
/// <returns>Ordered DataTable</returns>
public abstract DataTable GetTableData(string tableName, string columnNames, string sortCriteria);
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames">List of column names to select. Column names should not be bracketed; this method will add brackets.</param>
/// <returns>DataTable</returns>
public virtual DataTable GetTableData(string tableName, List<string> columnNames)
{
WordBuilder wb = new WordBuilder(",");
foreach (string s in columnNames)
{
wb.Add(this.InsertInEscape(s));
}
return GetTableData(tableName, wb.ToString(), string.Empty);
}
/// <summary>
/// Returns contents of a table with only the top two rows.
/// </summary>
/// <param name="tableName">The name of the table to query</param>
/// <returns>DataTable</returns>
public abstract DataTable GetTopTwoTable(string tableName);
/// <summary>
/// Create a DataReader on the specified table
/// </summary>
/// <param name="tableName"></param>
/// <returns>An instance of an object that implements IDataReader</returns>
public abstract IDataReader GetTableDataReader(string tableName);
/// <summary>
/// Create a DataReader on the specified table
/// </summary>
/// <param name="selectQuery"></param>
/// <param name="commandBehavior"></param>
/// <returns>An instance of an object that implements IDataReader</returns>
public abstract IDataReader ExecuteReader(Query selectQuery, CommandBehavior commandBehavior);
/// <summary>
/// Create a DataReader on the specified table
/// </summary>
/// <param name="selectQuery"></param>
/// <returns>An instance of an object that implements IDataReader</returns>
public abstract IDataReader ExecuteReader(Query selectQuery);
/// <summary>
/// return the column names of the specified table as a generic List<string>
/// </summary>
/// <param name="tableName"></param>
/// <returns>Generic list of column names</returns>
public abstract List<string> GetTableColumnNames(string tableName);
public abstract Dictionary<string, int> GetTableColumnNameTypePairs(string tableName);
/// <summary>
/// Returns a DataView that contains the names of columns that have a dtatype of "text"
/// </summary>
/// <param name="tableName"></param>
/// <returns>DataView</returns>
public abstract DataView GetTextColumnNames(string tableName);
/// <summary>
/// Begins a database transaction
/// </summary>
/// <returns>A specialized transaction object based on the current database engine type</returns>
public abstract IDbTransaction OpenTransaction();
/// <summary>
/// Begins a database transaction
/// </summary>
/// <param name="isolationLevel">The transaction locking behavior for the connection</param>
/// <returns>A specialized transaction object based on the current database engine type</returns>
public abstract IDbTransaction OpenTransaction(IsolationLevel isolationLevel);
/// <summary>
/// Closes a database transaction connection. Developer should commit or rollback transaction prior to calling this method.
/// </summary>
/// <returns>A specialized transaction object based on the current database engine type</returns>
public abstract void CloseTransaction(IDbTransaction transaction);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="dataTable"></param>
/// <param name="tableName"></param>
/// <param name="insertQuery"></param>
/// <param name="updateQuery"></param>
public abstract void Update(DataTable dataTable, string tableName, Query insertQuery, Query updateQuery);
/// <summary>
/// Updates the GUIDs of a child table with those of the parent via a uniquekey/fkey relationship
/// </summary>
public abstract void UpdateGUIDs(string childTableName, string parentTableName);
/// <summary>
/// Updates the foreign and unique keys of a child table with those of the parent via the original keys that existed prior to an import from an Epi Info 3.5.x project.
/// </summary>
public abstract void UpdateKeys(string childTableName, string parentTableName);
/// <summary>
/// Disposes the object
/// </summary>
public virtual void Dispose()
{
}
/// <summary>
/// Gets the names of all tables in the database
/// </summary>
/// <returns>Names of all tables in the database</returns>
public abstract List<string> GetTableNames();
/// <summary>
/// Query class abstract factory which returns different type of query instance for different type of database
/// </summary>
/// <param name="ansiSqlStatement"></param>
/// <returns></returns>
public abstract Query CreateQuery(string ansiSqlStatement);
#endregion Public Methods
#region IDbDriver Members
/// <summary>
/// Determines the level of rights the user has on the SQL database
/// </summary>
public virtual ProjectPermissions GetPermissions()
{
return new ProjectPermissions();
}
/// <summary>
/// Get the code table names for the project
/// </summary>
/// <param name="project">The project</param>
/// <returns>DataTable of code table names</returns>
public abstract DataTable GetCodeTableNamesForProject(Project project);
/// <summary>
/// Get the code table list
/// </summary>
/// <param name="db">IDbDriver</param>
/// <returns>Epi.DataSets.TableSchema.TablesDataTable</returns>
public abstract Epi.DataSets.TableSchema.TablesDataTable GetCodeTableList(IDbDriver db);
/// <summary>
/// Determine the type of database in use.
/// Warning: This is not the ideal OO way of handling this. Once drivers are updated, this may be removed.
/// </summary>
/// <returns>String representation of the database type</returns>
public abstract string IdentifyDatabase();
/// <summary>
/// Inserts the string in escape characters. [] for SQL server and `` for MySQL etc.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public abstract string InsertInEscape(string str);
/// <summary>
/// Inserts all strings in the list in escape sequence
/// </summary>
/// <param name="strings"></param>
/// <returns></returns>
public List<string> InsertInEscape(List<string> strings)
{
List<string> newList = new List<string>();
foreach (string str in strings)
{
newList.Add(InsertInEscape(str));
}
return newList;
}
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public virtual string FormatDate(DateTime dt)
{
return Util.InsertInSingleQuotes(dt.ToShortDateString());
}
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public virtual string FormatDateTime(DateTime dt)
{
return Util.InsertInSingleQuotes(dt.ToString());
}
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public virtual string FormatTime(DateTime dt)
{
return Util.InsertInSingleQuotes(dt.ToString());
}
/// <summary>
/// Returns database sepecific column type
/// </summary>
/// <param name="dataType"></param>
/// <returns></returns>
public abstract string GetDbSpecificColumnType(GenericDbColumnType dataType);
public abstract string SyntaxTrue
{
get;
}
public abstract string SyntaxFalse
{
get;
}
public abstract System.Data.Common.DbDataAdapter GetDbAdapter(string p);
public abstract System.Data.IDbConnection GetConnection();
public abstract System.Data.Common.DbCommand GetCommand(string pKeyString, DataTable pDataTable);
public abstract System.Data.Common.DbCommandBuilder GetDbCommandBuilder(System.Data.Common.DbDataAdapter Adapter);
public abstract bool InsertBulkRows(string pSelectSQL, System.Data.Common.DbDataReader pDataReader, SetGadgetStatusHandler pStatusDelegate = null, CheckForCancellationHandler pCancellationDelegate = null);
public abstract bool Insert_1_Row(string pSelectSQL, System.Data.Common.DbDataReader pDataReader);
public abstract bool Update_1_Row(string pSelectSQL, string pKeyString, System.Data.Common.DbDataReader pDataReader);
public abstract bool CheckDatabaseTableExistance(string pFileString, string pTableName, bool pIsConnectionString = false);
public abstract bool CreateDataBase(string pFileString);
public abstract bool CheckDatabaseExistance(string pFileString, string pTableName, bool pIsConnectionString = false);
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReadonlypropertyOperations operations.
/// </summary>
internal partial class ReadonlypropertyOperations : IServiceOperations<AzureCompositeModel>, IReadonlypropertyOperations
{
/// <summary>
/// Initializes a new instance of the ReadonlypropertyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReadonlypropertyOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that have readonly properties
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ReadonlyObjInner>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ReadonlyObjInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ReadonlyObjInner>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that have readonly properties
/// </summary>
/// <param name='size'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(int? size = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ReadonlyObjInner complexBody = new ReadonlyObjInner();
if (size != null)
{
complexBody.Size = size;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright (c) 2007-2009 SlimDX Group
*
* 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.Globalization;
using System.Text;
using System.Windows.Forms;
using SlimDX;
using SlimDX.DirectInput;
using System.Collections.Generic;
namespace MouseTest
{
public partial class MainForm : Form
{
Mouse mouse;
void CreateDevice()
{
// make sure that DirectInput has been initialized
DirectInput dinput = new DirectInput();
// build up cooperative flags
CooperativeLevel cooperativeLevel;
if (exclusiveRadio.Checked)
cooperativeLevel = CooperativeLevel.Exclusive;
else
cooperativeLevel = CooperativeLevel.Nonexclusive;
if (foregroundRadio.Checked)
cooperativeLevel |= CooperativeLevel.Foreground;
else
cooperativeLevel |= CooperativeLevel.Background;
// create the device
try
{
mouse = new Mouse(dinput);
mouse.SetCooperativeLevel(this, cooperativeLevel);
}
catch (DirectInputException e)
{
MessageBox.Show(e.Message);
return;
}
if (!immediateRadio.Checked)
{
// since we want to use buffered data, we need to tell DirectInput
// to set up a buffer for the data
mouse.Properties.BufferSize = 8;
}
// acquire the device
mouse.Acquire();
// set the timer to go off 12 times a second to read input
// NOTE: Normally applications would read this much faster.
// This rate is for demonstration purposes only.
timer.Interval = 1000 / 12;
timer.Start();
}
void ReadImmediateData()
{
if (mouse.Acquire().IsFailure)
return;
if (mouse.Poll().IsFailure)
return;
MouseState state = mouse.GetCurrentState();
if (Result.Last.IsFailure)
return;
StringBuilder data = new StringBuilder();
data.AppendFormat(CultureInfo.CurrentCulture, "(X={0} Y={1} Z={2})", state.X, state.Y, state.Z);
for (int i = 0; i < 8; i++)
{
data.Append(" B");
data.Append(i);
data.Append("=");
if (state.IsPressed(i))
data.Append("1");
else
data.Append("0");
}
dataBox.Text = data.ToString();
}
void ReadBufferedData()
{
if (mouse.Acquire().IsFailure)
return;
if (mouse.Poll().IsFailure)
return;
IList<MouseState> bufferedData = mouse.GetBufferedData();
if (Result.Last.IsFailure || bufferedData.Count == 0)
return;
StringBuilder data = new StringBuilder();
MouseState result = new MouseState();
foreach (MouseState packet in bufferedData)
{
result.X += packet.X;
result.Y += packet.Y;
result.Z += packet.Z;
}
data.AppendFormat(CultureInfo.CurrentCulture, "(X={0} Y={1} Z={2})", result.X, result.Y, result.Z);
for (int i = 0; i < 8; i++)
{
data.Append(" B");
data.Append(i);
data.Append("=");
if (bufferedData[bufferedData.Count - 1].IsPressed(i))
data.Append("1");
else
data.Append("0");
}
dataBox.Text = data.ToString();
}
void ReleaseDevice()
{
timer.Stop();
if (mouse != null)
{
mouse.Unacquire();
mouse.Dispose();
}
mouse = null;
}
#region Boilerplate
public MainForm()
{
InitializeComponent();
UpdateUI();
}
private void exclusiveRadio_Click(object sender, EventArgs e)
{
exclusiveRadio.Checked = true;
nonexclusiveRadio.Checked = false;
UpdateUI();
}
private void foregroundRadio_Click(object sender, EventArgs e)
{
foregroundRadio.Checked = true;
backgroundRadio.Checked = false;
UpdateUI();
}
private void nonexclusiveRadio_Click(object sender, EventArgs e)
{
nonexclusiveRadio.Checked = true;
exclusiveRadio.Checked = false;
UpdateUI();
}
private void backgroundRadio_Click(object sender, EventArgs e)
{
backgroundRadio.Checked = true;
foregroundRadio.Checked = false;
UpdateUI();
}
private void immediateRadio_CheckedChanged(object sender, EventArgs e)
{
UpdateUI();
}
private void bufferedRadio_CheckedChanged(object sender, EventArgs e)
{
UpdateUI();
}
private void createButton_Click(object sender, EventArgs e)
{
if (mouse == null)
CreateDevice();
else
ReleaseDevice();
UpdateUI();
}
private void exitButton_Click(object sender, EventArgs e)
{
ReleaseDevice();
Close();
}
private void timer_Tick(object sender, EventArgs e)
{
if (immediateRadio.Checked)
ReadImmediateData();
else
ReadBufferedData();
}
void UpdateUI()
{
if (mouse != null)
{
createButton.Text = "Release Device";
dataBox.Text = "";
exclusiveRadio.Enabled = false;
nonexclusiveRadio.Enabled = false;
foregroundRadio.Enabled = false;
backgroundRadio.Enabled = false;
immediateRadio.Enabled = false;
bufferedRadio.Enabled = false;
if (exclusiveRadio.Checked)
helpLabel.Text = "Press Enter to release the mouse device and display the cursor again.";
}
else
{
createButton.Text = "Create Device";
dataBox.Text = "Device not created. Choose settings and click 'Create Device' then type to see results";
helpLabel.Text = "";
exclusiveRadio.Enabled = true;
nonexclusiveRadio.Enabled = true;
foregroundRadio.Enabled = true;
backgroundRadio.Enabled = true;
immediateRadio.Enabled = true;
bufferedRadio.Enabled = true;
}
StringBuilder text = new StringBuilder();
if (!foregroundRadio.Checked && exclusiveRadio.Checked)
{
text.Append("For security reasons, background exclusive mouse access ");
text.Append("is not allowed.");
text.AppendLine();
text.AppendLine();
}
else
{
if (foregroundRadio.Checked)
{
text.Append("Foreground cooperative level means that the ");
text.Append("application has access to data only when in the ");
text.Append("foreground or, in other words, has the input focus. ");
text.Append("If the application moves to the background, the device ");
text.Append("is automatically unacquired, or made unavailable.");
text.AppendLine();
text.AppendLine();
}
else
{
text.Append("Background cooperative level really mean foreground and ");
text.Append("background. A device with a background cooperative level ");
text.Append("can be acquired and used by an application at any time.");
text.AppendLine();
text.AppendLine();
}
if (exclusiveRadio.Checked)
{
text.Append("Exclusive mode prevents other application from also acquiring ");
text.Append("the device exclusively. The fact that your application is using ");
text.Append("a device at the exclusive level does not mean that other ");
text.Append("application cannot get data from the device. Windows itself ");
text.Append("requires exclusive access to the mouse because mouse events such ");
text.Append("as clicking on an inactive window could force an application to ");
text.Append("unacquire the device, with potentially harmful results, such as ");
text.Append("a loss of data from the input buffer. Therefore, when an application ");
text.Append("has exclusive access to the mouse, Windows is not allowed any access ");
text.Append("at all. No mouse messages are generated. A further side effect is ");
text.Append("that the cursor disappears.");
text.AppendLine();
text.AppendLine();
}
else
{
text.Append("Nonexclusive mode means that other applications can acquire ");
text.Append("the device in exclusive or nonexclusive mode.");
text.AppendLine();
text.AppendLine();
}
if (immediateRadio.Checked)
{
text.Append("Immediate data is a snapshot of the current state of a device. ");
text.Append("It provides no data about what has happened with the device since ");
text.Append("the last call, apart from implicit information that you can derive ");
text.Append("by comparing the current state with the last one. ");
text.Append("Events in between calls are lost.");
text.AppendLine();
text.AppendLine();
}
else
{
text.Append("Buffered data is a record of events that are stored until an ");
text.Append("application retrieves them. With buffered data, events are ");
text.Append("stored until you are ready to deal with them. If the ");
text.Append("buffer overflows, new data is lost.");
text.AppendLine();
text.AppendLine();
}
text.Append("The sample will read the mouse 12 times a second. Typically ");
text.Append("an application would poll the mouse much faster than this, ");
text.Append("but this slow rate is simply for the purposes of demonstration.");
}
behaviorLabel.Text = text.ToString();
}
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
ReleaseDevice();
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
namespace TMPro
{
[ExecuteInEditMode]
[DisallowMultipleComponent]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[AddComponentMenu("Mesh/TextMeshPro - Text")]
public partial class TextMeshPro : TMP_Text, ILayoutElement
{
// Public Properties and Serializable Properties
/// <summary>
/// Sets the Renderer's sorting Layer ID
/// </summary>
public int sortingLayerID
{
get { return m_renderer.sortingLayerID; }
set { m_renderer.sortingLayerID = value; }
}
/// <summary>
/// Sets the Renderer's sorting order within the assigned layer.
/// </summary>
public int sortingOrder
{
get { return m_renderer.sortingOrder; }
set { m_renderer.sortingOrder = value; }
}
/// <summary>
/// Determines if the size of the text container will be adjusted to fit the text object when it is first created.
/// </summary>
public override bool autoSizeTextContainer
{
get { return m_autoSizeTextContainer; }
set { if (m_autoSizeTextContainer == value) return; m_autoSizeTextContainer = value; if (m_autoSizeTextContainer) { TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this); SetLayoutDirty(); } }
}
/// <summary>
/// Returns a reference to the Text Container
/// </summary>
[Obsolete("The TextContainer is now obsolete. Use the RectTransform instead.")]
public TextContainer textContainer
{
get
{
return null;
}
}
/// <summary>
/// Returns a reference to the Transform
/// </summary>
public new Transform transform
{
get
{
if (m_transform == null)
m_transform = GetComponent<Transform>();
return m_transform;
}
}
#pragma warning disable 0108
/// <summary>
/// Returns the rendered assigned to the text object.
/// </summary>
public Renderer renderer
{
get
{
if (m_renderer == null)
m_renderer = GetComponent<Renderer>();
return m_renderer;
}
}
/// <summary>
/// Returns the mesh assigned to the text object.
/// </summary>
public override Mesh mesh
{
get
{
if (m_mesh == null)
{
m_mesh = new Mesh();
m_mesh.hideFlags = HideFlags.HideAndDontSave;
this.meshFilter.mesh = m_mesh;
}
return m_mesh;
}
}
/// <summary>
/// Returns the Mesh Filter of the text object.
/// </summary>
public MeshFilter meshFilter
{
get
{
if (m_meshFilter == null)
m_meshFilter = GetComponent<MeshFilter>();
return m_meshFilter;
}
}
// MASKING RELATED PROPERTIES
/// <summary>
/// Sets the mask type
/// </summary>
public MaskingTypes maskType
{
get { return m_maskType; }
set { m_maskType = value; SetMask(m_maskType); }
}
/// <summary>
/// Function used to set the mask type and coordinates in World Space
/// </summary>
/// <param name="type"></param>
/// <param name="maskCoords"></param>
public void SetMask(MaskingTypes type, Vector4 maskCoords)
{
SetMask(type);
SetMaskCoordinates(maskCoords);
}
/// <summary>
/// Function used to set the mask type, coordinates and softness
/// </summary>
/// <param name="type"></param>
/// <param name="maskCoords"></param>
/// <param name="softnessX"></param>
/// <param name="softnessY"></param>
public void SetMask(MaskingTypes type, Vector4 maskCoords, float softnessX, float softnessY)
{
SetMask(type);
SetMaskCoordinates(maskCoords, softnessX, softnessY);
}
/// <summary>
/// Schedule rebuilding of the text geometry.
/// </summary>
public override void SetVerticesDirty()
{
//Debug.Log("SetVerticesDirty()");
if (m_verticesAlreadyDirty || this == null || !this.IsActive())
return;
TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this);
m_verticesAlreadyDirty = true;
}
/// <summary>
///
/// </summary>
public override void SetLayoutDirty()
{
m_isPreferredWidthDirty = true;
m_isPreferredHeightDirty = true;
if (m_layoutAlreadyDirty || this == null || !this.IsActive())
return;
//TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this);
m_layoutAlreadyDirty = true;
//LayoutRebuilder.MarkLayoutForRebuild(this.rectTransform);
m_isLayoutDirty = true;
}
/// <summary>
/// Schedule updating of the material used by the text object.
/// </summary>
public override void SetMaterialDirty()
{
//Debug.Log("SetMaterialDirty()");
//if (!this.IsActive())
// return;
//m_isMaterialDirty = true;
UpdateMaterial();
//TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this);
}
/// <summary>
///
/// </summary>
public override void SetAllDirty()
{
m_isInputParsingRequired = true;
SetLayoutDirty();
SetVerticesDirty();
SetMaterialDirty();
}
/// <summary>
///
/// </summary>
/// <param name="update"></param>
public override void Rebuild(CanvasUpdate update)
{
if (this == null) return;
if (update == CanvasUpdate.Prelayout)
{
if (m_autoSizeTextContainer)
{
m_rectTransform.sizeDelta = GetPreferredValues(Mathf.Infinity, Mathf.Infinity);
}
}
else if (update == CanvasUpdate.PreRender)
{
this.OnPreRenderObject();
m_verticesAlreadyDirty = false;
m_layoutAlreadyDirty = false;
if (!m_isMaterialDirty) return;
UpdateMaterial();
m_isMaterialDirty = false;
}
}
/// <summary>
///
/// </summary>
protected override void UpdateMaterial()
{
//Debug.Log("*** UpdateMaterial() ***");
//if (!this.IsActive())
// return;
if (m_sharedMaterial == null)
return;
if (m_renderer == null) m_renderer = this.renderer;
// Only update the material if it has changed.
if (m_renderer.sharedMaterial.GetInstanceID() != m_sharedMaterial.GetInstanceID())
m_renderer.sharedMaterial = m_sharedMaterial;
}
/// <summary>
/// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script.
/// </summary>
public override void UpdateMeshPadding()
{
m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
m_havePropertiesChanged = true;
checkPaddingRequired = false;
// Return if text object is not awake yet.
if (m_textInfo == null) return;
// Update sub text objects
for (int i = 1; i < m_textInfo.materialCount; i++)
m_subTextObjects[i].UpdateMeshPadding(m_enableExtraPadding, m_isUsingBold);
}
/// <summary>
/// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
public override void ForceMeshUpdate()
{
//Debug.Log("ForceMeshUpdate() called.");
m_havePropertiesChanged = true;
OnPreRenderObject();
}
/// <summary>
/// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
/// <param name="ignoreInactive">If set to true, the text object will be regenerated regardless of is active state.</param>
public override void ForceMeshUpdate(bool ignoreInactive)
{
m_havePropertiesChanged = true;
m_ignoreActiveState = true;
OnPreRenderObject();
}
/// <summary>
/// Function used to evaluate the length of a text string.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public override TMP_TextInfo GetTextInfo(string text)
{
StringToCharArray(text, ref m_char_buffer);
SetArraySizes(m_char_buffer);
m_renderMode = TextRenderFlags.DontRender;
ComputeMarginSize();
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
return this.textInfo;
}
/// <summary>
/// Function to clear the geometry of the Primary and Sub Text objects.
/// </summary>
public override void ClearMesh(bool updateMesh)
{
if (m_textInfo.meshInfo[0].mesh == null) m_textInfo.meshInfo[0].mesh = m_mesh;
m_textInfo.ClearMeshInfo(updateMesh);
}
/// <summary>
/// Function to force the regeneration of the text object.
/// </summary>
/// <param name="flags"> Flags to control which portions of the geometry gets uploaded.</param>
//public override void ForceMeshUpdate(TMP_VertexDataUpdateFlags flags) { }
/// <summary>
/// Function to update the geometry of the main and sub text objects.
/// </summary>
/// <param name="mesh"></param>
/// <param name="index"></param>
public override void UpdateGeometry(Mesh mesh, int index)
{
mesh.RecalculateBounds();
}
/// <summary>
/// Function to upload the updated vertex data and renderer.
/// </summary>
public override void UpdateVertexData(TMP_VertexDataUpdateFlags flags)
{
int materialCount = m_textInfo.materialCount;
for (int i = 0; i < materialCount; i++)
{
Mesh mesh;
if (i == 0)
mesh = m_mesh;
else
{
// Clear unused vertices
// TODO: Causes issues when sorting geometry as last vertex data attribute get wiped out.
//m_textInfo.meshInfo[i].ClearUnusedVertices();
mesh = m_subTextObjects[i].mesh;
}
//mesh.MarkDynamic();
if ((flags & TMP_VertexDataUpdateFlags.Vertices) == TMP_VertexDataUpdateFlags.Vertices)
mesh.vertices = m_textInfo.meshInfo[i].vertices;
if ((flags & TMP_VertexDataUpdateFlags.Uv0) == TMP_VertexDataUpdateFlags.Uv0)
mesh.uv = m_textInfo.meshInfo[i].uvs0;
if ((flags & TMP_VertexDataUpdateFlags.Uv2) == TMP_VertexDataUpdateFlags.Uv2)
mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//if ((flags & TMP_VertexDataUpdateFlags.Uv4) == TMP_VertexDataUpdateFlags.Uv4)
// mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
if ((flags & TMP_VertexDataUpdateFlags.Colors32) == TMP_VertexDataUpdateFlags.Colors32)
mesh.colors32 = m_textInfo.meshInfo[i].colors32;
mesh.RecalculateBounds();
}
}
/// <summary>
/// Function to upload the updated vertex data and renderer.
/// </summary>
public override void UpdateVertexData()
{
int materialCount = m_textInfo.materialCount;
for (int i = 0; i < materialCount; i++)
{
Mesh mesh;
if (i == 0)
mesh = m_mesh;
else
{
// Clear unused vertices
m_textInfo.meshInfo[i].ClearUnusedVertices();
mesh = m_subTextObjects[i].mesh;
}
//mesh.MarkDynamic();
mesh.vertices = m_textInfo.meshInfo[i].vertices;
mesh.uv = m_textInfo.meshInfo[i].uvs0;
mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
mesh.colors32 = m_textInfo.meshInfo[i].colors32;
mesh.RecalculateBounds();
}
}
public void UpdateFontAsset()
{
LoadFontAsset();
}
private bool m_currentAutoSizeMode;
public void CalculateLayoutInputHorizontal()
{
//Debug.Log("*** CalculateLayoutInputHorizontal() ***");
if (!this.gameObject.activeInHierarchy)
return;
//IsRectTransformDriven = true;
m_currentAutoSizeMode = m_enableAutoSizing;
if (m_isCalculateSizeRequired || m_rectTransform.hasChanged)
{
//Debug.Log("Calculating Layout Horizontal");
//m_LayoutPhase = AutoLayoutPhase.Horizontal;
//m_isRebuildingLayout = true;
m_minWidth = 0;
m_flexibleWidth = 0;
//m_renderMode = TextRenderFlags.GetPreferredSizes; // Set Text to not Render and exit early once we have new width values.
if (m_enableAutoSizing)
{
m_fontSize = m_fontSizeMax;
}
// Set Margins to Infinity
m_marginWidth = k_LargePositiveFloat;
m_marginHeight = k_LargePositiveFloat;
if (m_isInputParsingRequired || m_isTextTruncated)
ParseInputText();
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
//m_preferredWidth = (int)m_preferredWidth + 1f;
ComputeMarginSize();
//Debug.Log("Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect);
m_isLayoutDirty = true;
}
}
public void CalculateLayoutInputVertical()
{
//Debug.Log("*** CalculateLayoutInputVertical() ***");
// Check if object is active
if (!this.gameObject.activeInHierarchy) // || IsRectTransformDriven == false)
return;
//IsRectTransformDriven = true;
if (m_isCalculateSizeRequired || m_rectTransform.hasChanged)
{
//Debug.Log("Calculating Layout InputVertical");
//m_LayoutPhase = AutoLayoutPhase.Vertical;
//m_isRebuildingLayout = true;
m_minHeight = 0;
m_flexibleHeight = 0;
//m_renderMode = TextRenderFlags.GetPreferredSizes;
if (m_enableAutoSizing)
{
m_currentAutoSizeMode = true;
m_enableAutoSizing = false;
}
m_marginHeight = k_LargePositiveFloat;
GenerateTextMesh();
m_enableAutoSizing = m_currentAutoSizeMode;
m_renderMode = TextRenderFlags.Render;
//m_preferredHeight = (int)m_preferredHeight + 1f;
ComputeMarginSize();
//Debug.Log("Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect);
m_isLayoutDirty = true;
}
m_isCalculateSizeRequired = false;
}
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.GtkSharp.Drawing;
namespace Eto.GtkSharp.Forms.Controls
{
public class TextAreaHandler : TextAreaHandler<Gtk.TextView, TextArea, TextArea.ICallback>
{
}
public class TextAreaHandler<TControl, TWidget, TCallback> : GtkControl<TControl, TWidget, TCallback>, TextArea.IHandler
where TControl: Gtk.TextView, new()
where TWidget: TextArea
where TCallback: TextArea.ICallback
{
bool sendSelectionChanged = true;
readonly Gtk.ScrolledWindow scroll;
Gtk.TextTag tag;
public override Gtk.Widget ContainerControl
{
get { return scroll; }
}
public override Size DefaultSize { get { return new Size(100, 60); } }
public TextAreaHandler()
{
scroll = new Gtk.ScrolledWindow();
scroll.ShadowType = Gtk.ShadowType.In;
Control = new TControl();
Size = new Size(100, 60);
scroll.Add(Control);
Wrap = true;
}
public override void AttachEvent(string id)
{
switch (id)
{
case TextControl.TextChangedEvent:
Control.Buffer.Changed += Connector.HandleBufferChanged;
break;
case TextArea.SelectionChangedEvent:
Control.Buffer.MarkSet += Connector.HandleSelectionChanged;
break;
case TextArea.CaretIndexChangedEvent:
Control.Buffer.MarkSet += Connector.HandleCaretIndexChanged;
break;
default:
base.AttachEvent(id);
break;
}
}
protected new TextAreaConnector Connector { get { return (TextAreaConnector)base.Connector; } }
protected override WeakConnector CreateConnector()
{
return new TextAreaConnector();
}
protected class TextAreaConnector : GtkControlConnector
{
Range<int> lastSelection;
int? lastCaretIndex;
public new TextAreaHandler<TControl, TWidget, TCallback> Handler { get { return (TextAreaHandler<TControl, TWidget, TCallback>)base.Handler; } }
public void HandleBufferChanged(object sender, EventArgs e)
{
Handler.Callback.OnTextChanged(Handler.Widget, EventArgs.Empty);
}
public void HandleSelectionChanged(object o, Gtk.MarkSetArgs args)
{
var handler = Handler;
var selection = handler.Selection;
if (handler.sendSelectionChanged && selection != lastSelection)
{
handler.Callback.OnSelectionChanged(handler.Widget, EventArgs.Empty);
lastSelection = selection;
}
}
public void HandleCaretIndexChanged(object o, Gtk.MarkSetArgs args)
{
var handler = Handler;
var caretIndex = handler.CaretIndex;
if (handler.sendSelectionChanged && caretIndex != lastCaretIndex)
{
handler.Callback.OnCaretIndexChanged(handler.Widget, EventArgs.Empty);
lastCaretIndex = caretIndex;
}
}
public void HandleApplyTag(object sender, EventArgs e)
{
var buffer = Handler.Control.Buffer;
var tag = Handler.tag;
buffer.ApplyTag(tag, buffer.StartIter, buffer.EndIter);
}
}
public override string Text
{
get { return Control.Buffer.Text; }
set
{
Control.Buffer.Text = value;
if (tag != null)
Control.Buffer.ApplyTag(tag, Control.Buffer.StartIter, Control.Buffer.EndIter);
}
}
public virtual Color TextColor
{
get { return Control.GetForeground(); }
set
{
Control.SetForeground(value);
Control.SetTextColor(value);
}
}
public override Color BackgroundColor
{
get
{
return Control.GetBase();
}
set
{
Control.SetBackground(value);
Control.SetBase(value);
}
}
public bool ReadOnly
{
get { return !Control.Editable; }
set { Control.Editable = !value; }
}
public bool Wrap
{
get { return Control.WrapMode != Gtk.WrapMode.None; }
set { Control.WrapMode = value ? Gtk.WrapMode.WordChar : Gtk.WrapMode.None; }
}
public void Append(string text, bool scrollToCursor)
{
var end = Control.Buffer.EndIter;
Control.Buffer.Insert(ref end, text);
if (scrollToCursor)
{
var mark = Control.Buffer.CreateMark(null, end, false);
Control.ScrollToMark(mark, 0, false, 0, 0);
}
}
public string SelectedText
{
get
{
Gtk.TextIter start, end;
if (Control.Buffer.GetSelectionBounds(out start, out end))
{
return Control.Buffer.GetText(start, end, false);
}
return null;
}
set
{
sendSelectionChanged = false;
Gtk.TextIter start, end;
if (Control.Buffer.GetSelectionBounds(out start, out end))
{
var startOffset = start.Offset;
Control.Buffer.Delete(ref start, ref end);
if (value != null)
{
Control.Buffer.Insert(ref start, value);
start = Control.Buffer.GetIterAtOffset(startOffset);
end = Control.Buffer.GetIterAtOffset(startOffset + value.Length);
Control.Buffer.SelectRange(start, end);
}
}
else if (value != null)
Control.Buffer.InsertAtCursor(value);
if (tag != null)
Control.Buffer.ApplyTag(tag, Control.Buffer.StartIter, Control.Buffer.EndIter);
Callback.OnSelectionChanged(Widget, EventArgs.Empty);
sendSelectionChanged = true;
}
}
public Range<int> Selection
{
get
{
Gtk.TextIter start, end;
if (Control.Buffer.GetSelectionBounds(out start, out end))
return new Range<int>(start.Offset, end.Offset - 1);
return new Range<int>(Control.Buffer.CursorPosition, 0);
}
set
{
sendSelectionChanged = false;
var start = Control.Buffer.GetIterAtOffset(value.Start);
var end = Control.Buffer.GetIterAtOffset(value.End + 1);
Control.Buffer.SelectRange(start, end);
Callback.OnSelectionChanged(Widget, EventArgs.Empty);
sendSelectionChanged = true;
}
}
public void SelectAll()
{
Control.Buffer.SelectRange(Control.Buffer.StartIter, Control.Buffer.EndIter);
}
public int CaretIndex
{
get { return Control.Buffer.GetIterAtMark(Control.Buffer.InsertMark).Offset; }
set
{
var ins = Control.Buffer.GetIterAtOffset(value);
Control.Buffer.SelectRange(ins, ins);
}
}
public bool AcceptsTab
{
get { return Control.AcceptsTab; }
set { Control.AcceptsTab = value; }
}
bool acceptsReturn = true;
public bool AcceptsReturn
{
get { return acceptsReturn; }
set
{
if (value != acceptsReturn)
{
if (!acceptsReturn)
Widget.KeyDown -= HandleKeyDown;
//Control.KeyPressEvent -= PreventEnterKey;
acceptsReturn = value;
if (!acceptsReturn)
Widget.KeyDown += HandleKeyDown;
//Control.KeyPressEvent += PreventEnterKey;
}
}
}
void HandleKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
e.Handled = true;
}
static void PreventEnterKey(object o, Gtk.KeyPressEventArgs args)
{
if (args.Event.Key == Gdk.Key.Return)
args.RetVal = false;
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
if (value != null)
{
if (tag == null)
{
tag = new Gtk.TextTag("font");
Control.Buffer.TagTable.Add(tag);
Control.Buffer.Changed += Connector.HandleApplyTag;
Control.Buffer.ApplyTag(tag, Control.Buffer.StartIter, Control.Buffer.EndIter);
}
value.Apply(tag);
}
else
{
Control.Buffer.RemoveAllTags(Control.Buffer.StartIter, Control.Buffer.EndIter);
}
}
}
public TextAlignment TextAlignment
{
get { return Control.Justification.ToEto(); }
set { Control.Justification = value.ToGtk(); }
}
public bool SpellCheck
{
get { return false; }
set { }
}
public bool SpellCheckIsSupported { get { return false; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.Utilities;
using UnityEngine;
namespace UnityEngine.InputNew
{
public class Gamepad
: Joystick
{
enum GamepadControl
{
// Standardized.
LeftStickX,
LeftStickY,
LeftStickButton,
RightStickX,
RightStickY,
RightStickButton,
DPadLeft,
DPadRight,
DPadUp,
DPadDown,
Action1,
Action2,
Action3,
Action4,
LeftTrigger,
RightTrigger,
LeftBumper,
RightBumper,
// Compound controls.
LeftStick,
RightStick,
DPad,
// Not standardized, but provided for convenience.
Back,
Start,
Select,
System,
Pause,
Menu,
Share,
View,
Options,
TiltX,
TiltY,
TiltZ,
ScrollWheel,
TouchPadTap,
TouchPadXAxis,
TouchPadYAxis,
// Not standardized.
Analog0,
Analog1,
Analog2,
Analog3,
Analog4,
Analog5,
Analog6,
Analog7,
Analog8,
Analog9,
Analog10,
Analog11,
Analog12,
Analog13,
Analog14,
Analog15,
Analog16,
Analog17,
Analog18,
Analog19,
Button0,
Button1,
Button2,
Button3,
Button4,
Button5,
Button6,
Button7,
Button8,
Button9,
Button10,
Button11,
Button12,
Button13,
Button14,
Button15,
Button16,
Button17,
Button18,
Button19,
}
#region Constructors
public Gamepad()
: this("Gamepad", null) {}
public Gamepad(string deviceName, List<InputControlData> additionalControls)
{
this.deviceName = deviceName;
var controlCount = EnumHelpers.GetValueCount<GamepadControl>();
var controls = Enumerable.Repeat(new InputControlData(), controlCount).ToList();
// Compounds.
controls[(int)GamepadControl.LeftStick] = new InputControlData
{
name = "Left Stick"
, controlType = InputControlType.Vector2
, componentControlIndices = new[] { (int)GamepadControl.LeftStickX, (int)GamepadControl.LeftStickY }
};
controls[(int)GamepadControl.RightStick] = new InputControlData
{
name = "Right Stick"
, controlType = InputControlType.Vector2
, componentControlIndices = new[] { (int)GamepadControl.RightStickX, (int)GamepadControl.RightStickY }
};
////TODO: dpad (more complicated as the source is buttons which need to be translated into a vector)
// Buttons.
controls[(int)GamepadControl.Action1] = new InputControlData { name = "Action 1", controlType = InputControlType.Button };
controls[(int)GamepadControl.Action2] = new InputControlData { name = "Action 2", controlType = InputControlType.Button };
controls[(int)GamepadControl.Action3] = new InputControlData { name = "Action 3", controlType = InputControlType.Button };
controls[(int)GamepadControl.Action4] = new InputControlData { name = "Action 4", controlType = InputControlType.Button };
controls[(int)GamepadControl.Start] = new InputControlData { name = "Start", controlType = InputControlType.Button };
controls[(int)GamepadControl.Back] = new InputControlData { name = "Back", controlType = InputControlType.Button };
controls[(int)GamepadControl.LeftStickButton] = new InputControlData { name = "Left Stick Button", controlType = InputControlType.Button };
controls[(int)GamepadControl.RightStickButton] = new InputControlData { name = "Right Stick Button", controlType = InputControlType.Button };
controls[(int)GamepadControl.DPadUp] = new InputControlData { name = "DPad Up", controlType = InputControlType.Button };
controls[(int)GamepadControl.DPadDown] = new InputControlData { name = "DPad Down", controlType = InputControlType.Button };
controls[(int)GamepadControl.DPadLeft] = new InputControlData { name = "DPad Left", controlType = InputControlType.Button };
controls[(int)GamepadControl.DPadRight] = new InputControlData { name = "DPad Right", controlType = InputControlType.Button };
controls[(int)GamepadControl.LeftBumper] = new InputControlData { name = "Left Bumper", controlType = InputControlType.Button };
controls[(int)GamepadControl.RightBumper] = new InputControlData { name = "Right Bumper", controlType = InputControlType.Button };
// Axes.
controls[(int)GamepadControl.LeftStickX] = new InputControlData { name = "Left Stick X", controlType = InputControlType.AbsoluteAxis };
controls[(int)GamepadControl.LeftStickY] = new InputControlData { name = "Left Stick Y", controlType = InputControlType.AbsoluteAxis };
controls[(int)GamepadControl.RightStickX] = new InputControlData { name = "Right Stick X", controlType = InputControlType.AbsoluteAxis };
controls[(int)GamepadControl.RightStickY] = new InputControlData { name = "Right Stick Y", controlType = InputControlType.AbsoluteAxis };
controls[(int)GamepadControl.LeftTrigger] = new InputControlData { name = "Left Trigger", controlType = InputControlType.AbsoluteAxis };
controls[(int)GamepadControl.RightTrigger] = new InputControlData { name = "Right Trigger", controlType = InputControlType.AbsoluteAxis };
if (additionalControls != null)
controls.AddRange(additionalControls);
SetControls(controls);
}
#endregion
public AxisInputControl leftStickX { get { return (AxisInputControl)this[(int)GamepadControl.LeftStickX]; } }
public AxisInputControl leftStickY { get { return (AxisInputControl)this[(int)GamepadControl.LeftStickY]; } }
public ButtonInputControl leftStickButton { get { return (ButtonInputControl)this[(int)GamepadControl.LeftStickButton]; } }
public AxisInputControl rightStickX { get { return (AxisInputControl)this[(int)GamepadControl.RightStickX]; } }
public AxisInputControl rightStickY { get { return (AxisInputControl)this[(int)GamepadControl.RightStickY]; } }
public ButtonInputControl rightStickButton { get { return (ButtonInputControl)this[(int)GamepadControl.RightStickButton]; } }
public ButtonInputControl dPadLeft { get { return (ButtonInputControl)this[(int)GamepadControl.DPadLeft]; } }
public ButtonInputControl dPadRight { get { return (ButtonInputControl)this[(int)GamepadControl.DPadRight]; } }
public ButtonInputControl dPadUp { get { return (ButtonInputControl)this[(int)GamepadControl.DPadUp]; } }
public ButtonInputControl dPadDown { get { return (ButtonInputControl)this[(int)GamepadControl.DPadDown]; } }
public ButtonInputControl action1 { get { return (ButtonInputControl)this[(int)GamepadControl.Action1]; } }
public ButtonInputControl action2 { get { return (ButtonInputControl)this[(int)GamepadControl.Action2]; } }
public ButtonInputControl action3 { get { return (ButtonInputControl)this[(int)GamepadControl.Action3]; } }
public ButtonInputControl action4 { get { return (ButtonInputControl)this[(int)GamepadControl.Action4]; } }
public AxisInputControl leftTrigger { get { return (AxisInputControl)this[(int)GamepadControl.LeftTrigger]; } }
public AxisInputControl rightTrigger { get { return (AxisInputControl)this[(int)GamepadControl.RightTrigger]; } }
public ButtonInputControl leftBumper { get { return (ButtonInputControl)this[(int)GamepadControl.LeftBumper]; } }
public ButtonInputControl rightBumper { get { return (ButtonInputControl)this[(int)GamepadControl.RightBumper]; } }
// Compound controls.
public Vector2InputControl leftStick { get { return (Vector2InputControl)this[(int)GamepadControl.LeftStick]; } }
public Vector2InputControl rightStick { get { return (Vector2InputControl)this[(int)GamepadControl.RightStick]; } }
public Vector2InputControl dPad { get { return (Vector2InputControl)this[(int)GamepadControl.DPad]; } }
// Not standardized, but provided for convenience.
public ButtonInputControl back { get { return (ButtonInputControl)this[(int)GamepadControl.Back]; } }
public ButtonInputControl start { get { return (ButtonInputControl)this[(int)GamepadControl.Start]; } }
public ButtonInputControl select { get { return (ButtonInputControl)this[(int)GamepadControl.Select]; } }
public ButtonInputControl system { get { return (ButtonInputControl)this[(int)GamepadControl.System]; } }
public ButtonInputControl pause { get { return (ButtonInputControl)this[(int)GamepadControl.Pause]; } }
public ButtonInputControl menu { get { return (ButtonInputControl)this[(int)GamepadControl.Menu]; } }
public ButtonInputControl share { get { return (ButtonInputControl)this[(int)GamepadControl.Share]; } }
public ButtonInputControl view { get { return (ButtonInputControl)this[(int)GamepadControl.View]; } }
public ButtonInputControl options { get { return (ButtonInputControl)this[(int)GamepadControl.Options]; } }
public AxisInputControl tiltX { get { return (AxisInputControl)this[(int)GamepadControl.TiltX]; } }
public AxisInputControl tiltY { get { return (AxisInputControl)this[(int)GamepadControl.TiltY]; } }
public AxisInputControl tiltZ { get { return (AxisInputControl)this[(int)GamepadControl.TiltZ]; } }
public AxisInputControl scrollWheel { get { return (AxisInputControl)this[(int)GamepadControl.ScrollWheel]; } }
public ButtonInputControl touchPadTap { get { return (ButtonInputControl)this[(int)GamepadControl.TouchPadTap]; } }
public AxisInputControl touchPadXAxis { get { return (AxisInputControl)this[(int)GamepadControl.TouchPadXAxis]; } }
public AxisInputControl touchPadYAxis { get { return (AxisInputControl)this[(int)GamepadControl.TouchPadYAxis]; } }
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
namespace Tests.ExtractorTests
{
/// <summary>
/// Unit tests for ExtractorTests
/// </summary>
public class ExtractorTests
{
private readonly ITestOutputHelper _testOutputHelper;
public ExtractorTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
private static IEnumerable<Options> ExtractorTestData
{
get
{
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1080.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: true);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1078.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1000.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1001.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1002.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { @"System.Core.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1003.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1004.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1005.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1006.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1008.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1009.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1010.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1011.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1012.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1013.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1014.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1015.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: @"/optimize",
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1016.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CheckerErrors.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
}
}
public static IEnumerable<object> ExtractorTest
{
get
{
return Enumerable.Range(0, ExtractorTestData.Count()).Select(i => new object[] { i });
}
}
[Theory]
[MemberData("ExtractorTest")]
[Trait("Category", "Runtime")]
[Trait("Category", "CoreTest")]
[Trait("Category", "V4.0")]
[Trait("Category", "Short")]
public void ExtractorFailures(int testIndex)
{
Options options = ExtractorTestData.ElementAt(testIndex);
options.ContractFramework = @".NetFramework\v4.0";
options.BuildFramework = @".NetFramework\v4.0";
options.FoxtrotOptions = options.FoxtrotOptions + " /nologo /verbose:4 /iw:-";
TestDriver.BuildExtractExpectFailureOrWarnings(_testOutputHelper, options);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace YAF.Lucene.Net.Search.Payloads
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext;
using IBits = YAF.Lucene.Net.Util.IBits;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using NearSpansOrdered = YAF.Lucene.Net.Search.Spans.NearSpansOrdered;
using NearSpansUnordered = YAF.Lucene.Net.Search.Spans.NearSpansUnordered;
using Similarity = YAF.Lucene.Net.Search.Similarities.Similarity;
using SpanNearQuery = YAF.Lucene.Net.Search.Spans.SpanNearQuery;
using SpanQuery = YAF.Lucene.Net.Search.Spans.SpanQuery;
using Spans = YAF.Lucene.Net.Search.Spans.Spans;
using SpanScorer = YAF.Lucene.Net.Search.Spans.SpanScorer;
using SpanWeight = YAF.Lucene.Net.Search.Spans.SpanWeight;
using ToStringUtils = YAF.Lucene.Net.Util.ToStringUtils;
/// <summary>
/// This class is very similar to
/// <see cref="Lucene.Net.Search.Spans.SpanNearQuery"/> except that it factors
/// in the value of the payloads located at each of the positions where the
/// <see cref="Lucene.Net.Search.Spans.TermSpans"/> occurs.
/// <para/>
/// NOTE: In order to take advantage of this with the default scoring implementation
/// (<see cref="Similarities.DefaultSimilarity"/>), you must override <see cref="Similarities.DefaultSimilarity.ScorePayload(int, int, int, BytesRef)"/>,
/// which returns 1 by default.
/// <para/>
/// Payload scores are aggregated using a pluggable <see cref="PayloadFunction"/>.
/// </summary>
/// <seealso cref="Lucene.Net.Search.Similarities.Similarity.SimScorer.ComputePayloadFactor(int, int, int, BytesRef)"/>
public class PayloadNearQuery : SpanNearQuery
{
protected string m_fieldName;
protected PayloadFunction m_function;
public PayloadNearQuery(SpanQuery[] clauses, int slop, bool inOrder)
: this(clauses, slop, inOrder, new AveragePayloadFunction())
{
}
public PayloadNearQuery(SpanQuery[] clauses, int slop, bool inOrder, PayloadFunction function)
: base(clauses, slop, inOrder)
{
m_fieldName = clauses[0].Field; // all clauses must have same field
this.m_function = function;
}
public override Weight CreateWeight(IndexSearcher searcher)
{
return new PayloadNearSpanWeight(this, this, searcher);
}
public override object Clone()
{
int sz = m_clauses.Count;
SpanQuery[] newClauses = new SpanQuery[sz];
for (int i = 0; i < sz; i++)
{
newClauses[i] = (SpanQuery)m_clauses[i].Clone();
}
PayloadNearQuery boostingNearQuery = new PayloadNearQuery(newClauses, m_slop, m_inOrder, m_function);
boostingNearQuery.Boost = Boost;
return boostingNearQuery;
}
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("payloadNear([");
bool hasCommaSpace = false;
foreach (SpanQuery clause in m_clauses)
{
buffer.Append(clause.ToString(field));
buffer.Append(", ");
hasCommaSpace = true;
}
if (hasCommaSpace)
buffer.Remove(buffer.Length - 2, 2);
buffer.Append("], ");
buffer.Append(m_slop);
buffer.Append(", ");
buffer.Append(m_inOrder);
buffer.Append(")");
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + ((m_fieldName == null) ? 0 : m_fieldName.GetHashCode());
result = prime * result + ((m_function == null) ? 0 : m_function.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
PayloadNearQuery other = (PayloadNearQuery)obj;
if (m_fieldName == null)
{
if (other.m_fieldName != null)
{
return false;
}
}
else if (!m_fieldName.Equals(other.m_fieldName, StringComparison.Ordinal))
{
return false;
}
if (m_function == null)
{
if (other.m_function != null)
{
return false;
}
}
else if (!m_function.Equals(other.m_function))
{
return false;
}
return true;
}
public class PayloadNearSpanWeight : SpanWeight
{
private readonly PayloadNearQuery outerInstance;
public PayloadNearSpanWeight(PayloadNearQuery outerInstance, SpanQuery query, IndexSearcher searcher)
: base(query, searcher)
{
this.outerInstance = outerInstance;
}
public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
{
return new PayloadNearSpanScorer(outerInstance, m_query.GetSpans(context, acceptDocs, m_termContexts), this, m_similarity, m_similarity.GetSimScorer(m_stats, context));
}
public override Explanation Explain(AtomicReaderContext context, int doc)
{
PayloadNearSpanScorer scorer = (PayloadNearSpanScorer)GetScorer(context, (context.AtomicReader).LiveDocs);
if (scorer != null)
{
int newDoc = scorer.Advance(doc);
if (newDoc == doc)
{
float freq = scorer.Freq;
Similarity.SimScorer docScorer = m_similarity.GetSimScorer(m_stats, context);
Explanation expl = new Explanation();
expl.Description = "weight(" + Query + " in " + doc + ") [" + m_similarity.GetType().Name + "], result of:";
Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.AddDetail(scoreExplanation);
expl.Value = scoreExplanation.Value;
string field = ((SpanQuery)Query).Field;
// now the payloads part
Explanation payloadExpl = outerInstance.m_function.Explain(doc, field, scorer.payloadsSeen, scorer.m_payloadScore);
// combined
ComplexExplanation result = new ComplexExplanation();
result.AddDetail(expl);
result.AddDetail(payloadExpl);
result.Value = expl.Value * payloadExpl.Value;
result.Description = "PayloadNearQuery, product of:";
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
}
public class PayloadNearSpanScorer : SpanScorer
{
private readonly PayloadNearQuery outerInstance;
internal Spans spans;
protected internal float m_payloadScore;
internal int payloadsSeen;
protected internal PayloadNearSpanScorer(PayloadNearQuery outerInstance, Spans spans, Weight weight, Similarity similarity, Similarity.SimScorer docScorer)
: base(spans, weight, docScorer)
{
this.outerInstance = outerInstance;
this.spans = spans;
}
// Get the payloads associated with all underlying subspans
public virtual void GetPayloads(Spans[] subSpans)
{
for (var i = 0; i < subSpans.Length; i++)
{
var span = subSpans[i] as NearSpansOrdered;
if (span != null)
{
if (span.IsPayloadAvailable)
{
ProcessPayloads(span.GetPayload(), subSpans[i].Start, subSpans[i].End);
}
GetPayloads(span.SubSpans);
}
else
{
var unordered = subSpans[i] as NearSpansUnordered;
if (unordered != null)
{
if (unordered.IsPayloadAvailable)
{
ProcessPayloads(unordered.GetPayload(), subSpans[i].Start, subSpans[i].End);
}
GetPayloads(unordered.SubSpans);
}
}
}
}
// TODO change the whole spans api to use bytesRef, or nuke spans
internal BytesRef scratch = new BytesRef();
/// <summary>
/// By default, uses the <see cref="PayloadFunction"/> to score the payloads, but
/// can be overridden to do other things.
/// </summary>
/// <param name="payLoads"> The payloads </param>
/// <param name="start"> The start position of the span being scored </param>
/// <param name="end"> The end position of the span being scored
/// </param>
/// <seealso cref="Spans.Spans"/>
protected virtual void ProcessPayloads(ICollection<byte[]> payLoads, int start, int end)
{
foreach (var thePayload in payLoads)
{
scratch.Bytes = thePayload;
scratch.Offset = 0;
scratch.Length = thePayload.Length;
m_payloadScore = outerInstance.m_function.CurrentScore(m_doc, outerInstance.m_fieldName, start, end, payloadsSeen, m_payloadScore, m_docScorer.ComputePayloadFactor(m_doc, spans.Start, spans.End, scratch));
++payloadsSeen;
}
}
//
protected override bool SetFreqCurrentDoc()
{
if (!m_more)
{
return false;
}
m_doc = spans.Doc;
m_freq = 0.0f;
m_payloadScore = 0;
payloadsSeen = 0;
do
{
int matchLength = spans.End - spans.Start;
m_freq += m_docScorer.ComputeSlopFactor(matchLength);
Spans[] spansArr = new Spans[1];
spansArr[0] = spans;
GetPayloads(spansArr);
m_more = spans.Next();
} while (m_more && (m_doc == spans.Doc));
return true;
}
public override float GetScore()
{
return base.GetScore() * outerInstance.m_function.DocScore(m_doc, outerInstance.m_fieldName, payloadsSeen, m_payloadScore);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace System.Drawing
{
public sealed class TextureBrush : Brush
{
// When creating a texture brush from a metafile image, the dstRect
// is used to specify the size that the metafile image should be
// rendered at in the device units of the destination graphics.
// It is NOT used to crop the metafile image, so only the width
// and height values matter for metafiles.
public TextureBrush(Image bitmap) : this(bitmap, WrapMode.Tile)
{
}
public TextureBrush(Image image, WrapMode wrapMode)
{
if (image == null)
{
throw new ArgumentNullException(nameof(image));
}
if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateTexture(new HandleRef(image, image.nativeImage),
(int)wrapMode,
out brush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(brush);
}
public TextureBrush(Image image, WrapMode wrapMode, RectangleF dstRect)
{
if (image == null)
{
throw new ArgumentNullException(nameof(image));
}
if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateTexture2(new HandleRef(image, image.nativeImage),
unchecked((int)wrapMode),
dstRect.X,
dstRect.Y,
dstRect.Width,
dstRect.Height,
out brush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(brush);
}
public TextureBrush(Image image, WrapMode wrapMode, Rectangle dstRect)
{
if (image == null)
{
throw new ArgumentNullException(nameof(image));
}
if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateTexture2I(new HandleRef(image, image.nativeImage),
unchecked((int)wrapMode),
dstRect.X,
dstRect.Y,
dstRect.Width,
dstRect.Height,
out brush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(brush);
}
public TextureBrush(Image image, RectangleF dstRect) : this(image, dstRect, null) { }
public TextureBrush(Image image, RectangleF dstRect, ImageAttributes imageAttr)
{
if (image == null)
{
throw new ArgumentNullException(nameof(image));
}
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateTextureIA(new HandleRef(image, image.nativeImage),
new HandleRef(imageAttr, (imageAttr == null) ?
IntPtr.Zero : imageAttr.nativeImageAttributes),
dstRect.X,
dstRect.Y,
dstRect.Width,
dstRect.Height,
out brush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(brush);
}
public TextureBrush(Image image, Rectangle dstRect) : this(image, dstRect, null) { }
public TextureBrush(Image image, Rectangle dstRect, ImageAttributes imageAttr)
{
if (image == null)
{
throw new ArgumentNullException(nameof(image));
}
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateTextureIAI(new HandleRef(image, image.nativeImage),
new HandleRef(imageAttr, (imageAttr == null) ?
IntPtr.Zero : imageAttr.nativeImageAttributes),
dstRect.X,
dstRect.Y,
dstRect.Width,
dstRect.Height,
out brush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(brush);
}
internal TextureBrush(IntPtr nativeBrush)
{
Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null.");
SetNativeBrushInternal(nativeBrush);
}
public override object Clone()
{
IntPtr cloneBrush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out cloneBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
return new TextureBrush(cloneBrush);
}
public Matrix Transform
{
get
{
var matrix = new Matrix();
int status = SafeNativeMethods.Gdip.GdipGetTextureTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix));
SafeNativeMethods.Gdip.CheckStatus(status);
return matrix;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int status = SafeNativeMethods.Gdip.GdipSetTextureTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.nativeMatrix));
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public WrapMode WrapMode
{
get
{
int mode = 0;
int status = SafeNativeMethods.Gdip.GdipGetTextureWrapMode(new HandleRef(this, NativeBrush), out mode);
SafeNativeMethods.Gdip.CheckStatus(status);
return (WrapMode)mode;
}
set
{
if (value < WrapMode.Tile || value > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(WrapMode));
}
int status = SafeNativeMethods.Gdip.GdipSetTextureWrapMode(new HandleRef(this, NativeBrush), unchecked((int)value));
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public Image Image
{
get
{
IntPtr image;
int status = SafeNativeMethods.Gdip.GdipGetTextureImage(new HandleRef(this, NativeBrush), out image);
SafeNativeMethods.Gdip.CheckStatus(status);
return Image.CreateImageObject(image);
}
}
public void ResetTransform()
{
int status = SafeNativeMethods.Gdip.GdipResetTextureTransform(new HandleRef(this, NativeBrush));
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend);
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
{
throw new ArgumentNullException(nameof(matrix));
}
// Multiplying the transform by a disposed matrix is a nop in GDI+, but throws
// with the libgdiplus backend. Simulate a nop for compatability with GDI+.
if (matrix.nativeMatrix == IntPtr.Zero)
{
return;
}
int status = SafeNativeMethods.Gdip.GdipMultiplyTextureTransform(new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.nativeMatrix),
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend);
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipTranslateTextureTransform(new HandleRef(this, NativeBrush),
dx,
dy,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend);
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipScaleTextureTransform(new HandleRef(this, NativeBrush),
sx,
sy,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend);
public void RotateTransform(float angle, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipRotateTextureTransform(new HandleRef(this, NativeBrush),
angle,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
}
| |
// 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.ComponentModel;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Text;
using System.Xml;
namespace System.ServiceModel
{
public class NetHttpBinding : HttpBindingBase
{
private BinaryMessageEncodingBindingElement _binaryMessageEncodingBindingElement;
private NetHttpMessageEncoding _messageEncoding;
private BasicHttpSecurity _basicHttpSecurity;
public NetHttpBinding()
: this(BasicHttpSecurityMode.None)
{
}
public NetHttpBinding(BasicHttpSecurityMode securityMode)
: base()
{
this.Initialize();
_basicHttpSecurity.Mode = securityMode;
}
public NetHttpBinding(string configurationName)
: base()
{
this.Initialize();
}
private NetHttpBinding(BasicHttpSecurity security)
: base()
{
this.Initialize();
_basicHttpSecurity = security;
}
[DefaultValue(NetHttpMessageEncoding.Binary)]
public NetHttpMessageEncoding MessageEncoding
{
get { return _messageEncoding; }
set { _messageEncoding = value; }
}
public BasicHttpSecurity Security
{
get
{
return _basicHttpSecurity;
}
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
_basicHttpSecurity = value;
}
}
public WebSocketTransportSettings WebSocketSettings
{
get
{
return this.InternalWebSocketSettings;
}
}
internal override BasicHttpSecurity BasicHttpSecurity
{
get
{
return _basicHttpSecurity;
}
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingParameterCollection parameters)
{
if ((this.BasicHttpSecurity.Mode == BasicHttpSecurityMode.Transport ||
this.BasicHttpSecurity.Mode == BasicHttpSecurityMode.TransportCredentialOnly) &&
this.BasicHttpSecurity.Transport.ClientCredentialType == HttpClientCredentialType.InheritedFromHost)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.HttpClientCredentialTypeInvalid, this.BasicHttpSecurity.Transport.ClientCredentialType)));
}
return base.BuildChannelFactory<TChannel>(parameters);
}
public override BindingElementCollection CreateBindingElements()
{
this.CheckSettings();
// return collection of BindingElements
BindingElementCollection bindingElements = new BindingElementCollection();
// order of BindingElements is important
// add security (*optional)
SecurityBindingElement messageSecurity = this.BasicHttpSecurity.CreateMessageSecurity();
if (messageSecurity != null)
{
bindingElements.Add(messageSecurity);
}
// add encoding
switch (this.MessageEncoding)
{
case NetHttpMessageEncoding.Text:
bindingElements.Add(this.TextMessageEncodingBindingElement);
break;
case NetHttpMessageEncoding.Mtom:
throw ExceptionHelper.PlatformNotSupported();
default:
bindingElements.Add(_binaryMessageEncodingBindingElement);
break;
}
// add transport (http or https)
bindingElements.Add(this.GetTransport());
return bindingElements.Clone();
}
internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
{
binding = null;
if (elements.Count > 4)
{
return false;
}
SecurityBindingElement securityElement = null;
MessageEncodingBindingElement encoding = null;
HttpTransportBindingElement transport = null;
foreach (BindingElement element in elements)
{
if (element is SecurityBindingElement)
{
securityElement = element as SecurityBindingElement;
}
else if (element is TransportBindingElement)
{
transport = element as HttpTransportBindingElement;
}
else if (element is MessageEncodingBindingElement)
{
encoding = element as MessageEncodingBindingElement;
}
else
{
return false;
}
}
if (transport == null || transport.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Always)
{
return false;
}
HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement;
if ((securityElement != null) && (httpsTransport != null) && (httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate))
{
return false;
}
// process transport binding element
UnifiedSecurityMode mode;
HttpTransportSecurity transportSecurity = new HttpTransportSecurity();
if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode))
{
return false;
}
if (encoding == null)
{
return false;
}
if (!(encoding is TextMessageEncodingBindingElement ||
encoding is BinaryMessageEncodingBindingElement))
{
return false;
}
if (encoding.MessageVersion != MessageVersion.Soap12WSAddressing10)
{
return false;
}
BasicHttpSecurity security;
if (!TryCreateSecurity(securityElement, mode, transportSecurity, out security))
{
return false;
}
NetHttpBinding netHttpBinding = new NetHttpBinding(security);
netHttpBinding.InitializeFrom(transport, encoding);
// make sure all our defaults match
if (!netHttpBinding.IsBindingElementsMatch(transport, encoding))
{
return false;
}
binding = netHttpBinding;
return true;
}
internal override void SetReaderQuotas(XmlDictionaryReaderQuotas readerQuotas)
{
readerQuotas.CopyTo(_binaryMessageEncodingBindingElement.ReaderQuotas);
}
internal override EnvelopeVersion GetEnvelopeVersion()
{
return EnvelopeVersion.Soap12;
}
internal override void CheckSettings()
{
base.CheckSettings();
// In the Win8 profile, Mtom is not supported.
if ((this.MessageEncoding == NetHttpMessageEncoding.Mtom)
)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedBindingProperty, "MessageEncoding", this.MessageEncoding)));
}
}
private void Initialize()
{
_messageEncoding = NetHttpBindingDefaults.MessageEncoding;
_binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement() { MessageVersion = MessageVersion.Soap12WSAddressing10 };
this.TextMessageEncodingBindingElement.MessageVersion = MessageVersion.Soap12WSAddressing10;
this.WebSocketSettings.TransportUsage = NetHttpBindingDefaults.TransportUsage;
this.WebSocketSettings.SubProtocol = WebSocketTransportSettings.SoapSubProtocol;
_basicHttpSecurity = new BasicHttpSecurity();
}
internal override void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding)
{
base.InitializeFrom(transport, encoding);
if (encoding is BinaryMessageEncodingBindingElement)
{
_messageEncoding = NetHttpMessageEncoding.Binary;
BinaryMessageEncodingBindingElement binary = (BinaryMessageEncodingBindingElement)encoding;
this.ReaderQuotas = binary.ReaderQuotas;
}
if (encoding is TextMessageEncodingBindingElement)
{
_messageEncoding = NetHttpMessageEncoding.Text;
}
}
private bool IsBindingElementsMatch(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding)
{
switch (this.MessageEncoding)
{
case NetHttpMessageEncoding.Text:
if (!this.TextMessageEncodingBindingElement.IsMatch(encoding))
{
return false;
}
break;
case NetHttpMessageEncoding.Mtom:
return false;
default: // NetHttpMessageEncoding.Binary
if (!_binaryMessageEncodingBindingElement.IsMatch(encoding))
{
return false;
}
break;
}
if (!this.GetTransport().IsMatch(transport))
{
return false;
}
return true;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.LogReceiverService;
using NLog.Config;
using NLog.Targets;
using Xunit;
using NLog.Targets.Wrappers;
using System.Threading;
public class LogReceiverWebServiceTargetTests : NLogTestBase
{
[Fact]
public void LogReceiverWebServiceTargetSingleEventTest()
{
var logger = LogManager.GetLogger("loggerName");
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
SimpleConfigurator.ConfigureForTargetLogging(target);
logger.Info("message text");
var payload = target.LastPayload;
Assert.Equal(2, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
Assert.Equal(3, payload.Strings.Count);
Assert.Equal(1, payload.Events.Length);
Assert.Equal("message text", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("loggerName", payload.Strings[payload.Events[0].LoggerOrdinal]);
}
[Fact]
public void LogReceiverWebServiceTargetMultipleEventTest()
{
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
var exceptions = new List<Exception>();
var events = new[]
{
LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add),
};
var configuration = new LoggingConfiguration();
target.Initialize(configuration);
target.WriteAsyncLogEvents(events);
// with multiple events, we should get string caching
var payload = target.LastPayload;
Assert.Equal(2, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
// 7 strings instead of 9 since 'logger1' and 'message2' are being reused
Assert.Equal(7, payload.Strings.Count);
Assert.Equal(3, payload.Events.Length);
Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]);
Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]);
Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]);
Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]);
Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]);
Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal);
}
[Fact]
public void LogReceiverWebServiceTargetMultipleEventWithPerEventPropertiesTest()
{
var target = new MyLogReceiverWebServiceTarget();
target.IncludeEventProperties = true;
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
var exceptions = new List<Exception>();
var events = new[]
{
LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add),
};
events[0].LogEvent.Properties["prop1"] = "value1";
events[1].LogEvent.Properties["prop1"] = "value2";
events[2].LogEvent.Properties["prop1"] = "value3";
events[0].LogEvent.Properties["prop2"] = "value2a";
var configuration = new LoggingConfiguration();
target.Initialize(configuration);
target.WriteAsyncLogEvents(events);
// with multiple events, we should get string caching
var payload = target.LastPayload;
// 4 layout names - 2 from Parameters, 2 from unique properties in events
Assert.Equal(4, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
Assert.Equal("prop1", payload.LayoutNames[2]);
Assert.Equal("prop2", payload.LayoutNames[3]);
Assert.Equal(12, payload.Strings.Count);
Assert.Equal(3, payload.Events.Length);
Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]);
Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]);
Assert.Equal("value1", payload.Strings[payload.Events[0].ValueIndexes[2]]);
Assert.Equal("value2", payload.Strings[payload.Events[1].ValueIndexes[2]]);
Assert.Equal("value3", payload.Strings[payload.Events[2].ValueIndexes[2]]);
Assert.Equal("value2a", payload.Strings[payload.Events[0].ValueIndexes[3]]);
Assert.Equal("", payload.Strings[payload.Events[1].ValueIndexes[3]]);
Assert.Equal("", payload.Strings[payload.Events[2].ValueIndexes[3]]);
Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]);
Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]);
Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]);
Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal);
}
[Fact]
public void NoEmptyEventLists()
{
var configuration = new LoggingConfiguration();
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Initialize(configuration);
var asyncTarget = new AsyncTargetWrapper(target)
{
Name = "NoEmptyEventLists_wrapper"
};
try
{
asyncTarget.Initialize(configuration);
asyncTarget.WriteAsyncLogEvents(new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(ex => { }) });
Thread.Sleep(1000);
Assert.Equal(1, target.SendCount);
}
finally
{
asyncTarget.Close();
target.Close();
}
}
public class MyLogReceiverWebServiceTarget : LogReceiverWebServiceTarget
{
public NLogEvents LastPayload;
public int SendCount;
protected internal override bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations)
{
this.LastPayload = events;
++this.SendCount;
foreach (var ac in asyncContinuations)
{
ac.Continuation(null);
}
return false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Diagnostics.Tracing;
using Azure.Core.Diagnostics;
namespace Azure.Messaging.EventHubs.Processor.Diagnostics
{
/// <summary>
/// EventSource for Azure-Messaging-EventHubs-Processor-BlobEventStore traces.
/// </summary>
///
/// <remarks>
/// When defining Start/Stop tasks, the StopEvent.Id must be exactly StartEvent.Id + 1.
///
/// Do not explicitly include the Guid here, since EventSource has a mechanism to automatically
/// map to an EventSource Guid based on the Name (Azure-Messaging-EventHubs-Processor-BlobEventStore).
/// </remarks>
///
[EventSource(Name = EventSourceName)]
internal class BlobEventStoreEventSource : EventSource
{
/// <summary>The name to use for the event source.</summary>
private const string EventSourceName = "Azure-Messaging-EventHubs-Processor-BlobEventStore";
/// <summary>
/// Provides a singleton instance of the event source for callers to
/// use for logging.
/// </summary>
///
public static BlobEventStoreEventSource Log { get; } = new BlobEventStoreEventSource(EventSourceName);
/// <summary>
/// Prevents an instance of the <see cref="BlobEventStoreEventSource" /> class from being created
/// outside the scope of this library. Exposed for testing purposes only.
/// </summary>
///
protected BlobEventStoreEventSource()
{
}
/// <summary>
/// Prevents an instance of the <see cref="BlobEventStoreEventSource" /> class from being created
/// outside the scope of this library. Exposed for testing purposes only.
/// </summary>
///
/// <param name="eventSourceName">The name to assign to the event source.</param>
///
private BlobEventStoreEventSource(string eventSourceName) : base(eventSourceName, EventSourceSettings.Default, AzureEventSourceListener.TraitName, AzureEventSourceListener.TraitValue)
{
}
/// <summary>
/// Indicates that a <see cref="BlobsCheckpointStore" /> was created.
/// </summary>
///
/// <param name="typeName">The type name for the checkpoint store.</param>
/// <param name="accountName">The Storage account name corresponding to the associated container client.</param>
/// <param name="containerName">The name of the associated container client.</param>
///
[Event(20, Level = EventLevel.Verbose, Message = "{0} created. AccountName: '{1}'; ContainerName: '{2}'.")]
public virtual void BlobsCheckpointStoreCreated(string typeName,
string accountName,
string containerName)
{
if (IsEnabled())
{
WriteEvent(20, typeName, accountName ?? string.Empty, containerName ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of ownership has started.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
///
[Event(21, Level = EventLevel.Informational, Message = "Starting to list ownership for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'.")]
public virtual void ListOwnershipStart(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(21, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of ownership has completed.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
/// <param name="ownershipCount">The amount of ownership received from the storage service.</param>
///
[Event(22, Level = EventLevel.Informational, Message = "Completed listing ownership for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'. There were {3} ownership entries were found.")]
public virtual void ListOwnershipComplete(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
int ownershipCount)
{
if (IsEnabled())
{
WriteEvent(22, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownershipCount);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while retrieving a list of ownership.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(23, Level = EventLevel.Error, Message = "An exception occurred when listing ownership for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; ErrorMessage: '{3}'.")]
public virtual void ListOwnershipError(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(23, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to claim a partition ownership has started.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
///
[Event(24, Level = EventLevel.Informational, Message = "Starting to claim ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'.")]
public virtual void ClaimOwnershipStart(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier)
{
if (IsEnabled())
{
WriteEvent(24, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve claim partition ownership has completed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
///
[Event(25, Level = EventLevel.Informational, Message = "Completed the attempt to claim ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'.")]
public virtual void ClaimOwnershipComplete(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier)
{
if (IsEnabled())
{
WriteEvent(25, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty);
}
}
/// <summary>
/// Indicates that an exception was encountered while attempting to retrieve claim partition ownership.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(26, Level = EventLevel.Error, Message = "An exception occurred when claiming ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'. ErrorMessage: '{5}'.")]
public virtual void ClaimOwnershipError(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(26, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that ownership was unable to be claimed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
/// <param name="message">The message for the failure.</param>
///
[Event(27, Level = EventLevel.Informational, Message = "Unable to claim ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'. Message: '{5}'.")]
public virtual void OwnershipNotClaimable(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier,
string message)
{
if (IsEnabled())
{
WriteEvent(27, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty, message ?? string.Empty);
}
}
/// <summary>
/// Indicates that ownership was successfully claimed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
///
[Event(28, Level = EventLevel.Informational, Message = "Successfully claimed ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'.")]
public virtual void OwnershipClaimed(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier)
{
if (IsEnabled())
{
WriteEvent(28, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of checkpoints has started.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoints are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoints are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoints are associated with.</param>
///
[Event(29, Level = EventLevel.Informational, Message = "Starting to list checkpoints for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'.")]
public virtual void ListCheckpointsStart(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(29, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of checkpoints has completed.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoints are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoints are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoints are associated with.</param>
/// <param name="checkpointCount">The amount of checkpoints received from the storage service.</param>
///
[Event(30, Level = EventLevel.Informational, Message = "Completed listing checkpoints for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'. There were '{3}' checkpoints found.")]
public virtual void ListCheckpointsComplete(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
int checkpointCount)
{
if (IsEnabled())
{
WriteEvent(30, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, checkpointCount);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while retrieving a list of checkpoints.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoints are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoints are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(31, Level = EventLevel.Error, Message = "An exception occurred when listing checkpoints for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; ErrorMessage: '{3}'.")]
public virtual void ListCheckpointsError(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(31, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to create/update a checkpoint has started.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being checkpointed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
///
[Event(32, Level = EventLevel.Informational, Message = "Starting to create/update a checkpoint for partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'.")]
public virtual void UpdateCheckpointStart(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(32, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to update a checkpoint has completed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being checkpointed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
///
[Event(33, Level = EventLevel.Informational, Message = "Completed the attempt to create/update a checkpoint for partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'.")]
public virtual void UpdateCheckpointComplete(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(33, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while updating a checkpoint.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being checkpointed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(34, Level = EventLevel.Error, Message = "An exception occurred when creating/updating a checkpoint for partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'. ErrorMessage: '{4}'.")]
public virtual void UpdateCheckpointError(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(34, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that invalid checkpoint data was found during an attempt to retrieve a list of checkpoints.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition the data is associated with.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the data is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the data is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the data is associated with.</param>
///
[Event(35, Level = EventLevel.Warning, Message = "An invalid checkpoint was found for partition: '{0}' of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'. This checkpoint is not valid and will be ignored.")]
public virtual void InvalidCheckpointFound(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(35, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a checkpoint has started.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="partitionId">The partition id the specific checkpoint is associated with.</param>
///
[Event(36, Level = EventLevel.Informational, Message = "Starting to retrieve checkpoint for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; PartitionId: '{3}'.")]
public virtual void GetCheckpointStart(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string partitionId)
{
if (IsEnabled())
{
WriteEvent(36, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, partitionId ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a checkpoint has completed.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="partitionId">The partition id the specific checkpoint is associated with.</param>
///
[Event(37, Level = EventLevel.Informational, Message = "Completed retrieving checkpoint for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'. PartitionId: '{3}'.")]
public virtual void GetCheckpointComplete(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string partitionId)
{
if (IsEnabled())
{
WriteEvent(37, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, partitionId);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while retrieving a checkpoint.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="partitionId">The partition id the specific checkpoint is associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(38, Level = EventLevel.Error, Message = "An exception occurred when retrieving checkpoint for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; PartitionId: '{3}'; ErrorMessage: '{4}'.")]
public virtual void GetCheckpointError(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string partitionId,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(38, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, partitionId ?? string.Empty, errorMessage ?? string.Empty);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TransferConfigurations.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using ClientLibraryConstants = Microsoft.Azure.Storage.Shared.Protocol.Constants;
/// <summary>
/// TransferConfigurations class.
/// </summary>
public class TransferConfigurations
{
/// <summary>
/// Stores the BlockSize to use for Windows Azure Storage transfers to block blob(s).
/// It must be between 4MB and 100MB and be multiple of 4MB.
/// </summary>
private int blockSize;
/// <summary>
/// How many work items to process in parallel.
/// </summary>
private int parallelOperations;
/// <summary>
/// Maximum amount of cache memory to use in bytes.
/// </summary>
private long maximumCacheSize;
/// <summary>
/// How many listings can be performed in parallel.
/// </summary>
private int? maxListingConcurrency;
/// <summary>
/// Instance to call native methods to get current memory status.
/// </summary>
private GlobalMemoryStatusNativeMethods memStatus = new GlobalMemoryStatusNativeMethods();
/// <summary>
/// Initializes a new instance of the
/// <see cref="TransferConfigurations" /> class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public TransferConfigurations()
{
// setup default values.
this.blockSize = Constants.DefaultTransferChunkSize;
this.parallelOperations = Environment.ProcessorCount * 8;
this.MemoryChunkSize = Constants.DefaultMemoryChunkSize;
this.UpdateMaximumCacheSize(this.blockSize);
this.SupportUncPath = false;
if (Interop.CrossPlatformHelpers.IsWindows)
{
try
{
LongPath.GetFullPath("\\\\?\\F:");
this.SupportUncPath = true;
}
catch (Exception)
{
}
}
}
/// <summary>
/// Gets or sets a value indicating how many work items to process
/// concurrently. Downloading or uploading a single blob can consist
/// of a large number of work items.
/// </summary>
/// <value>How many work items to process concurrently.</value>
public int ParallelOperations
{
get
{
return this.parallelOperations;
}
set
{
if (value <= 0)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
Resources.ParallelCountNotPositiveException));
}
this.parallelOperations = value;
this.UpdateMaximumCacheSize(this.blockSize);
}
}
/// <summary>
/// Gets or sets a value indicating how many listing works to process concurrently.
/// When source is an Azure File directory or local file directory, DataMovement Library would list the directory in parallel.
/// This value is to indicate the maximum number of listing works to process in parallel.
/// </summary>
/// <value>How many listing works to process concurrently.</value>
public int? MaxListingConcurrency
{
get
{
return this.maxListingConcurrency;
}
set
{
if (value <= 0)
throw new ArgumentException(string.Format((IFormatProvider) CultureInfo.CurrentCulture, Resources.MaxListingConcurrencyNotPositiveException));
this.maxListingConcurrency = value;
}
}
/// <summary>
/// Gets or sets the BlockSize to use for Windows Azure Storage transfers to block blob(s).
/// It must be between 4MB and 100MB and be multiple of 4MB.
///
/// Currently, the max block count of a block blob is limited to 50000.
/// When transfering a big file and the BlockSize provided is smaller than the minimum value - (size/50000),
/// it'll be reset to a value which is greater than the minimum value and multiple of 4MB for this file.
/// </summary>
/// <value>BlockSize to use for Windows Azure Storage transfers.</value>
public int BlockSize
{
get
{
return this.blockSize;
}
set
{
if (Constants.MinBlockSize > value || value > Constants.MaxBlockSize)
{
string errorMessage = string.Format(
CultureInfo.CurrentCulture,
Resources.BlockSizeOutOfRangeException,
Utils.BytesToHumanReadableSize(Constants.MinBlockSize),
Utils.BytesToHumanReadableSize(Constants.MaxBlockSize));
throw new ArgumentOutOfRangeException("value", value, errorMessage);
}
if (value % Constants.DefaultTransferChunkSize != 0)
{
throw new ArgumentException(Resources.BlockSizeMustBeMultipleOf4MB, "value");
}
this.blockSize = value;
this.UpdateMaximumCacheSize(this.blockSize);
}
}
/// <summary>
/// Gets or sets the user agent prefix
/// </summary>
public string UserAgentPrefix
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating how much memory we can cache
/// during upload/download.
/// </summary>
/// <value>Maximum amount of cache memory to use in bytes.</value>
internal long MaximumCacheSize
{
get
{
return this.maximumCacheSize;
}
set
{
if (value < Constants.DefaultTransferChunkSize)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
Resources.SmallMemoryCacheSizeLimitationException,
Utils.BytesToHumanReadableSize(Constants.DefaultTransferChunkSize)));
}
if (0 == this.memStatus.AvailablePhysicalMemory)
{
this.maximumCacheSize = Math.Min(value, Constants.MemoryCacheMaximum);
}
else
{
#if DOTNET5_4
if (8 == Marshal.SizeOf(new IntPtr()))
#else
if (Environment.Is64BitProcess)
#endif
{
this.maximumCacheSize = Math.Min(value, (long) (this.memStatus.AvailablePhysicalMemory * Constants.MemoryCacheMultiplier));
}
else
{
this.maximumCacheSize = Math.Min(value,
Math.Min((long) (this.memStatus.AvailablePhysicalMemory*Constants.MemoryCacheMultiplier), Constants.MemoryCacheMaximum));
}
}
TransferManager.SetMemoryLimitation(this.maximumCacheSize);
}
}
/// <summary>
/// To indicate whether the process environment supports UNC path.
///
/// On Windows, it requires to use UNC path to access files/directories with long path.
/// In some environment, the .Net Framework only supports legacy path without UNC path support.
/// DataMovement Library will detect whether .Net Framework supports UNC path in the process environment
/// to determine whether to use UNC path in the following transfers.
/// </summary>
internal bool SupportUncPath { get; private set; }
/// <summary>
/// The size of memory chunk of memory pool
/// </summary>
internal int MemoryChunkSize { get; private set; }
/// <summary>
/// Update the memory pool size according to the block size
/// </summary>
/// <param name="newBlockSize"></param>
internal void UpdateMaximumCacheSize(int newBlockSize)
{
this.MaximumCacheSize = (long)3 * newBlockSize * this.ParallelOperations;
}
}
}
| |
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.VersioningAndUnification.AppConfig
{
public sealed class SpecificVersionPrimary : ResolveAssemblyReferenceTestFixture
{
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void Exists()
{
// This WriteLine is a hack. On a slow machine, the Tasks unittest fails because remoting
// times out the object used for remoting console writes. Adding a write in the middle of
// keeps remoting from timing out the object.
Console.WriteLine("Performing VersioningAndUnification.Prerequisite.SpecificVersionPrimary.Exists() test");
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
AssertNoCase(@"{Registry:Software\Microsoft\.NetFramework,v2.0,AssemblyFoldersEx}", t.ResolvedFiles[0].GetMetadata("ResolvedFrom"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes a *different* assembly version name from
// 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void ExistsDifferentName()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='DontUnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from range 0.0.0.0-1.5.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void ExistsOldVersionRange()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-1.5.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 4.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 4.0.0.0 of the file *does not* exist.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void HighVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='4.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 0.5.0.0
/// - An app.config was passed in that promotes assembly version from 0.0.0.0-2.0.0.0 to 2.0.0.0
/// - Version 0.5.0.0 of the file *does not* exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The reference is not resolved.
/// Rationale:
/// Primary references are never unified--even those that don't exist on disk. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void LowVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=0.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(0, t.ResolvedFiles.Length);
// Cleanup.
File.Delete(appConfigFile);
}
}
}
| |
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 DalSoft.WebApi.HelpPage.SampleGeneration
{
/// <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 System;
using System.ServiceModel;
namespace OpenRiaServices.DomainServices.Hosting.OData
{
#region Namespaces
using System.ComponentModel;
using System.Net;
using System.Reflection;
using System.ServiceModel.Dispatcher;
using OpenRiaServices.DomainServices.Server;
using System.Web;
#endregion
/// <summary>Base class for all operation invokers supported on the domain data service endpoint.</summary>
internal abstract class DomainDataServiceOperationInvoker : IOperationInvoker
{
/// <summary>Operation type.</summary>
private readonly DomainOperationType operationType;
/// <summary>Constructs an invoker instance.</summary>
/// <param name="operationType">Operation type.</param>
internal DomainDataServiceOperationInvoker(DomainOperationType operationType)
{
this.operationType = operationType;
}
/// <summary>
/// Gets a value that specifies whether the Invoke or InvokeBegin method is called by the dispatcher.
/// </summary>
public bool IsSynchronous
{
get
{
return true;
}
}
/// <summary>
/// Returns an array of parameter objects.
/// </summary>
/// <returns>The parameters that are to be used as arguments to the operation.</returns>
public abstract object[] AllocateInputs();
/// <summary>
/// Returns an object and a set of output objects from an instance and set of input objects.
/// </summary>
/// <param name="instance">The object to be invoked.</param>
/// <param name="inputs">The inputs to the method.</param>
/// <param name="outputs">The outputs from the method.</param>
/// <returns>The return value.</returns>
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
object result = null;
DomainService domainService = null;
try
{
// Instantiate the domain service.
domainService = this.GetDomainService(instance);
// Validate the requst.
DomainDataServiceOperationInvoker.VerifyRequest(domainService);
// Obtain the result.
this.ConvertInputs(inputs);
result = this.InvokeCore(domainService, inputs, out outputs);
result = this.ConvertReturnValue(result);
}
catch (DomainDataServiceException)
{
// if the exception has already been transformed to DomainDataServiceException just rethrow it.
throw;
}
catch (Exception ex)
{
if (ex.IsFatal())
{
throw;
}
else
{
// We need to ensure that any time an exception is thrown by the service it is transformed to a
// properly sanitized/configured DomainDataService exception.
throw new DomainDataServiceException(Resource.DomainDataService_General_Error, ex);
}
}
return result;
}
/// <summary>
/// Converts input parameters in place.
/// </summary>
/// <param name="inputs">Input parameters.</param>
protected virtual void ConvertInputs(object[] inputs)
{
}
/// <summary>
/// Converts the return value.
/// </summary>
/// <param name="returnValue">Return value.</param>
/// <returns>Converted return value.</returns>
protected virtual object ConvertReturnValue(object returnValue)
{
return returnValue;
}
/// <summary>
/// Derived classes override this method to provide custom invocation behavior.
/// </summary>
/// <param name="instance">Instance to invoke the invoker against.</param>
/// <param name="inputs">Input parameters post conversion.</param>
/// <param name="outputs">Optional out parameters.</param>
/// <returns>Result of invocation.</returns>
protected abstract object InvokeCore(object instance, object[] inputs, out object[] outputs);
/// <summary>
/// An asynchronous implementation of the Invoke method.
/// </summary>
/// <param name="instance">The object to be invoked.</param>
/// <param name="inputs">The inputs to the method.</param>
/// <param name="callback">The asynchronous callback object.</param>
/// <param name="state">Associated state data.</param>
/// <returns>A System.IAsyncResult used to complete the asynchronous call.</returns>
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// The asynchronous end method.
/// </summary>
/// <param name="instance">The object invoked.</param>
/// <param name="outputs">The outputs from the method.</param>
/// <param name="result">The System.IAsyncResult object.</param>
/// <returns>The return value.</returns>
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
throw new NotSupportedException();
}
/// <summary>
/// Validate the current request.
/// </summary>
/// <param name="domainService">Domain service instance for which request was sent.</param>
private static void VerifyRequest(DomainService domainService)
{
EnableClientAccessAttribute ecaAttribute = (EnableClientAccessAttribute)TypeDescriptor.GetAttributes(domainService)[typeof(EnableClientAccessAttribute)];
System.Diagnostics.Debug.Assert(ecaAttribute != null, "The OData Endpoint shouldn't be created if EnableClientAccess attribute is missing on the domain service type.");
if (ecaAttribute.RequiresSecureEndpoint)
{
if (HttpContext.Current != null)
{
if (HttpContext.Current.Request.IsSecureConnection)
{
return;
}
}
else if (OperationContext.Current != null)
{
// DEVNOTE(wbasheer): See what the RIA people do here and match.
}
throw new DomainDataServiceException((int)HttpStatusCode.Forbidden, Resource.DomainDataService_Enable_Client_Access_Require_Secure_Connection);
}
}
/// <summary>
/// Instatiates a DomainService instance along with the DomainServiceContext.
/// </summary>
/// <param name="instance">Wrapper representing the instance passed to invocation.</param>
/// <returns>New DomainService instance.</returns>
private DomainService GetDomainService(object instance)
{
// Create and initialize the DomainService for this request.
DomainDataServiceContractBehavior.DomainDataServiceInstanceInfo instanceInfo =
(DomainDataServiceContractBehavior.DomainDataServiceInstanceInfo)instance;
IServiceProvider serviceProvider = (IServiceProvider)OperationContext.Current.Host;
DomainServiceContext context = new DomainServiceContext(serviceProvider, this.operationType);
try
{
DomainService domainService = DomainService.Factory.CreateDomainService(instanceInfo.DomainServiceType, context);
instanceInfo.DomainServiceInstance = domainService;
return domainService;
}
catch (TargetInvocationException tie)
{
// If the exception has already been transformed to a DomainServiceException just rethrow it.
if (tie.InnerException != null)
{
throw new DomainDataServiceException(Resource.DomainDataService_General_Error, tie.InnerException);
}
throw new DomainDataServiceException(Resource.DomainDataService_General_Error, tie);
}
catch (Exception ex)
{
if (ex.IsFatal())
{
throw;
}
else
{
// We need to ensure that any time an exception is thrown by the service it is transformed to a
// properly sanitized/configured DomainDataService exception.
throw new DomainDataServiceException(Resource.DomainDataService_General_Error, ex);
}
}
}
}
}
| |
#region Copyright (c) 2009 S. van Deursen
/* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent
* manner.
*
* To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/
*
* Copyright (c) 2009 S. van Deursen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
// NOTE: This file a copy of ValidatorExtensionTests.Compare.Base.cs with all occurrences of 'xxx' replaced
// with 'Int64'.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CuttingEdge.Conditions.UnitTests.CompareTests
{
[TestClass]
public class CompareInt64Tests
{
private static readonly Int64 One = 1;
private static readonly Int64 Two = 2;
private static readonly Int64 Three = 3;
private static readonly Int64 Four = 4;
private static readonly Int64 Five = 5;
#region IsInt64InRange
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsInRange on Int64 x with 'lower bound > x < upper bound' should fail.")]
public void IsInt64InRangeTest01()
{
Int64 a = One;
Condition.Requires(a).IsInRange(Two, Four);
}
[TestMethod]
[Description("Calling IsInRange on Int64 x with 'lower bound = x < upper bound' should pass.")]
public void IsInt64InRangeTest02()
{
Int64 a = Two;
Condition.Requires(a).IsInRange(Two, Four);
}
[TestMethod]
[Description("Calling IsInRange on Int64 x with 'lower bound < x < upper bound' should pass.")]
public void IsInt64InRangeTest03()
{
Int64 a = Three;
Condition.Requires(a).IsInRange(Two, Four);
}
[TestMethod]
[Description("Calling IsInRange on Int64 x with 'lower bound < x = upper bound' should pass.")]
public void IsInt64InRangeTest04()
{
Int64 a = Four;
Condition.Requires(a).IsInRange(Two, Four);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsInRange on Int64 x with 'lower bound < x > upper bound' should fail.")]
public void IsInt64InRangeTest05()
{
Int64 a = Five;
Condition.Requires(a).IsInRange(Two, Four);
}
[TestMethod]
[Description("Calling IsInRange on Int64 x with conditionDescription should pass.")]
public void IsInt64InRangeTest06()
{
Int64 a = Four;
Condition.Requires(a).IsInRange(Two, Four, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsInRange on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64InRangeTest07()
{
Int64 a = Five;
try
{
Condition.Requires(a, "a").IsInRange(Two, Four, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsInRange on Int64 x with 'lower bound > x < upper bound' should succeed when exceptions are suppressed.")]
public void IsInt64InRangeTest08()
{
Int64 a = One;
Condition.Requires(a).SuppressExceptionsForTest().IsInRange(Two, Four);
}
#endregion // IsInt64InRange
#region IsInt64NotInRange
[TestMethod]
[Description("Calling IsNotInRange on Int64 x with 'lower bound > x < upper bound' should pass.")]
public void IsInt64NotInRangeTest01()
{
Int64 a = One;
Condition.Requires(a).IsNotInRange(Two, Four);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotInRange on Int64 x with 'lower bound = x < upper bound' should fail.")]
public void IsInt64NotInRangeTest02()
{
Int64 a = Two;
Condition.Requires(a).IsNotInRange(Two, Four);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotInRange on Int64 x with 'lower bound < x < upper bound' should fail.")]
public void IsInt64NotInRangeTest03()
{
Int64 a = Three;
Condition.Requires(a).IsNotInRange(Two, Four);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotInRange on Int64 x with 'lower bound < x = upper bound' should fail.")]
public void IsInt64NotInRangeTest04()
{
Int64 a = Four;
Condition.Requires(a).IsNotInRange(Two, Four);
}
[TestMethod]
[Description("Calling IsNotInRange on Int64 x with 'lower bound < x > upper bound' should pass.")]
public void IsInt64NotInRangeTest05()
{
Int64 a = Five;
Condition.Requires(a).IsNotInRange(Two, Four);
}
[TestMethod]
[Description("Calling IsNotInRange on Int64 x with conditionDescription should pass.")]
public void IsInt64NotInRangeTest06()
{
Int64 a = Five;
Condition.Requires(a).IsNotInRange(Two, Four, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsNotInRange on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64NotInRangeTest07()
{
Int64 a = Four;
try
{
Condition.Requires(a, "a").IsNotInRange(Two, Four, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsNotInRange on Int64 x with 'lower bound = x < upper bound' should succeed when exceptions are suppressed.")]
public void IsInt64NotInRangeTest08()
{
Int64 a = Two;
Condition.Requires(a).SuppressExceptionsForTest().IsNotInRange(Two, Four);
}
#endregion // IsInt64NotInRange
#region IsInt64GreaterThan
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsGreaterThan on Int64 x with 'lower bound < x' should fail.")]
public void IsInt64GreaterThanTest01()
{
Int64 a = One;
Condition.Requires(a).IsGreaterThan(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsGreaterThan on Int64 x with 'lower bound = x' should fail.")]
public void IsInt64GreaterThanTest02()
{
Int64 a = Two;
Condition.Requires(a).IsGreaterThan(Two);
}
[TestMethod]
[Description("Calling IsGreaterThan on Int64 x with 'lower bound < x' should pass.")]
public void IsInt64GreaterThanTest03()
{
Int64 a = Three;
Condition.Requires(a).IsGreaterThan(Two);
}
[TestMethod]
[Description("Calling IsGreaterThan on Int64 x with conditionDescription should pass.")]
public void IsInt64GreaterThanTest04()
{
Int64 a = Three;
Condition.Requires(a).IsGreaterThan(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsGreaterThan on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64GreaterThanTest05()
{
Int64 a = Three;
try
{
Condition.Requires(a, "a").IsGreaterThan(Three, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsGreaterThan on Int64 x with 'lower bound < x' should succeed when exceptions are suppressed.")]
public void IsInt64GreaterThanTest06()
{
Int64 a = One;
Condition.Requires(a).SuppressExceptionsForTest().IsGreaterThan(Two);
}
#endregion // IsInt64GreaterThan
#region IsInt64NotGreaterThan
[TestMethod]
[Description("Calling IsNotGreaterThan on Int64 x with 'x < upper bound' should pass.")]
public void IsInt64NotGreaterThanTest01()
{
Int64 a = One;
Condition.Requires(a).IsNotGreaterThan(Two);
}
[TestMethod]
[Description("Calling IsNotGreaterThan on Int64 x with 'x = upper bound' should pass.")]
public void IsInt64NotGreaterThanTest02()
{
Int64 a = Two;
Condition.Requires(a).IsNotGreaterThan(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsNotGreaterThan on Int64 x with 'x > upper bound' should fail.")]
public void IsInt64NotGreaterThanTest03()
{
Int64 a = Three;
Condition.Requires(a).IsNotGreaterThan(Two);
}
[TestMethod]
[Description("Calling IsNotGreaterThan on Int64 x with conditionDescription should pass.")]
public void IsInt64NotGreaterThanTest04()
{
Int64 a = Two;
Condition.Requires(a).IsNotGreaterThan(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsNotGreaterThan on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64NotGreaterThanTest05()
{
Int64 a = Three;
try
{
Condition.Requires(a, "a").IsNotGreaterThan(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsNotGreaterThan on Int64 x with 'x > upper bound' should succeed when exceptions are suppressed.")]
public void IsInt64NotGreaterThanTest06()
{
Int64 a = Three;
Condition.Requires(a).SuppressExceptionsForTest().IsNotGreaterThan(Two);
}
#endregion // IsInt64NotGreaterThan
#region IsInt64GreaterOrEqual
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsGreaterOrEqual on Int64 x with 'lower bound > x' should fail.")]
public void IsInt64GreaterOrEqualTest01()
{
Int64 a = One;
Condition.Requires(a).IsGreaterOrEqual(Two);
}
[TestMethod]
[Description("Calling IsGreaterOrEqual on Int64 x with 'lower bound = x' should pass.")]
public void IsInt64GreaterOrEqualTest02()
{
Int64 a = Two;
Condition.Requires(a).IsGreaterOrEqual(Two);
}
[TestMethod]
[Description("Calling IsGreaterOrEqual on Int64 x with 'lower bound < x' should pass.")]
public void IsInt64GreaterOrEqualTest03()
{
Int64 a = Three;
Condition.Requires(a).IsGreaterOrEqual(Two);
}
[TestMethod]
[Description("Calling IsGreaterOrEqual on Int64 x with conditionDescription should pass.")]
public void IsInt64GreaterOrEqualTest04()
{
Int64 a = Three;
Condition.Requires(a).IsGreaterOrEqual(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsGreaterOrEqual on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64GreaterOrEqualTest05()
{
Int64 a = One;
try
{
Condition.Requires(a, "a").IsGreaterOrEqual(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsGreaterOrEqual on Int64 x with 'lower bound > x' should succeed when exceptions are suppressed.")]
public void IsInt64GreaterOrEqualTest06()
{
Int64 a = One;
Condition.Requires(a).SuppressExceptionsForTest().IsGreaterOrEqual(Two);
}
#endregion // IsInt64GreaterOrEqual
#region IsInt64NotGreaterOrEqual
[TestMethod]
[Description("Calling IsNotGreaterOrEqual on Int64 x with 'x < upper bound' should pass.")]
public void IsInt64NotGreaterOrEqualTest01()
{
Int64 a = One;
Condition.Requires(a).IsNotGreaterOrEqual(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsNotGreaterOrEqual on Int64 x with 'x = upper bound' should fail.")]
public void IsInt64NotGreaterOrEqualTest02()
{
Int64 a = Two;
Condition.Requires(a).IsNotGreaterOrEqual(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsNotGreaterOrEqual on Int64 x with 'x > upper bound' should fail.")]
public void IsInt64NotGreaterOrEqualTest03()
{
Int64 a = Three;
Condition.Requires(a).IsNotGreaterOrEqual(Two);
}
[TestMethod]
[Description("Calling IsNotGreaterOrEqual on Int64 x with conditionDescription should pass.")]
public void IsInt64NotGreaterOrEqualTest04()
{
Int64 a = One;
Condition.Requires(a).IsNotGreaterOrEqual(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsNotGreaterOrEqual on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64NotGreaterOrEqualTest05()
{
Int64 a = Three;
try
{
Condition.Requires(a, "a").IsNotGreaterOrEqual(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsNotGreaterOrEqual on Int64 x with 'x = upper bound' should succeed when exceptions are suppressed.")]
public void IsInt64NotGreaterOrEqualTest06()
{
Int64 a = Two;
Condition.Requires(a).SuppressExceptionsForTest().IsNotGreaterOrEqual(Two);
}
#endregion // IsInt64NotGreaterOrEqual
#region IsInt64LessThan
[TestMethod]
[Description("Calling IsLessThan on Int64 x with 'x < upper bound' should pass.")]
public void IsInt64LessThanTest01()
{
Int64 a = One;
Condition.Requires(a).IsLessThan(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsLessThan on Int64 x with 'x = upper bound' should fail.")]
public void IsInt64LessThanTest02()
{
Int64 a = Two;
Condition.Requires(a).IsLessThan(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsLessThan on Int64 x with 'x > upper bound' should fail.")]
public void IsInt64LessThanTest03()
{
Int64 a = Three;
Condition.Requires(a).IsLessThan(Two);
}
[TestMethod]
[Description("Calling IsLessThan on Int64 x with conditionDescription should pass.")]
public void IsInt64LessThanTest04()
{
Int64 a = Two;
Condition.Requires(a).IsLessThan(Three, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsLessThan on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64LessThanTest05()
{
Int64 a = Three;
try
{
Condition.Requires(a, "a").IsLessThan(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsLessThan on Int64 x with 'x = upper bound' should succeed when exceptions are suppressed.")]
public void IsInt64LessThanTest06()
{
Int64 a = Two;
Condition.Requires(a).SuppressExceptionsForTest().IsLessThan(Two);
}
#endregion // IsInt64LessThan
#region IsInt64NotLessThan
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsNotLessThan on Int64 x with 'lower bound > x' should fail.")]
public void IsInt64NotLessThanTest01()
{
Int64 a = One;
Condition.Requires(a).IsNotLessThan(Two);
}
[TestMethod]
[Description("Calling IsNotLessThan on Int64 x with 'lower bound = x' should pass.")]
public void IsInt64NotLessThanTest02()
{
Int64 a = Two;
Condition.Requires(a).IsNotLessThan(Two);
}
[TestMethod]
[Description("Calling IsNotLessThan on Int64 x with 'lower bound < x' should pass.")]
public void IsInt64NotLessThanTest03()
{
Int64 a = Three;
Condition.Requires(a).IsNotLessThan(Two);
}
[TestMethod]
[Description("Calling IsNotLessThan on Int64 x with conditionDescription should pass.")]
public void IsInt64NotLessThanTest04()
{
Int64 a = Two;
Condition.Requires(a).IsNotLessThan(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsNotLessThan on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64NotLessThanTest05()
{
Int64 a = Two;
try
{
Condition.Requires(a, "a").IsNotLessThan(Three, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsNotLessThan on Int64 x with 'lower bound > x' should succeed when exceptions are suppressed.")]
public void IsInt64NotLessThanTest06()
{
Int64 a = One;
Condition.Requires(a).SuppressExceptionsForTest().IsNotLessThan(Two);
}
#endregion // IsInt64NotLessThan
#region IsInt64LessOrEqual
[TestMethod]
[Description("Calling IsLessOrEqual on Int64 x with 'x < upper bound' should pass.")]
public void IsInt64LessOrEqualTest01()
{
Int64 a = One;
Condition.Requires(a).IsLessOrEqual(Two);
}
[TestMethod]
[Description("Calling IsLessOrEqual on Int64 x with 'x = upper bound' should pass.")]
public void IsInt64LessOrEqualTest02()
{
Int64 a = Two;
Condition.Requires(a).IsLessOrEqual(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsLessOrEqual on Int64 x with 'x > upper bound' should fail.")]
public void IsInt64LessOrEqualTest03()
{
Int64 a = Three;
Condition.Requires(a).IsLessOrEqual(Two);
}
[TestMethod]
[Description("Calling IsLessOrEqual on Int64 x with conditionDescription should pass.")]
public void IsInt64LessOrEqualTest04()
{
Int64 a = Two;
Condition.Requires(a).IsLessOrEqual(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsLessOrEqual on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64LessOrEqualTest05()
{
Int64 a = Three;
try
{
Condition.Requires(a, "a").IsLessOrEqual(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsLessOrEqual on Int64 x with 'x > upper bound' should succeed when exceptions are suppressed.")]
public void IsInt64LessOrEqualTest06()
{
Int64 a = Three;
Condition.Requires(a).SuppressExceptionsForTest().IsLessOrEqual(Two);
}
#endregion // IsInt64LessOrEqual
#region IsInt64NotLessOrEqual
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsNotLessOrEqual on Int64 x with 'lower bound > x' should fail.")]
public void IsInt64NotLessOrEqualTest01()
{
Int64 a = One;
Condition.Requires(a).IsNotLessOrEqual(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Calling IsNotLessOrEqual on Int64 x with 'lower bound = x' should fail.")]
public void IsInt64NotLessOrEqualTest02()
{
Int64 a = Two;
Condition.Requires(a).IsNotLessOrEqual(Two);
}
[TestMethod]
[Description("Calling IsNotLessOrEqual on Int64 x with 'lower bound < x' should pass.")]
public void IsInt64NotLessOrEqualTest03()
{
Int64 a = Three;
Condition.Requires(a).IsNotLessOrEqual(Two);
}
[TestMethod]
[Description("Calling IsNotLessOrEqual on Int64 x with conditionDescription should pass.")]
public void IsInt64NotLessOrEqualTest04()
{
Int64 a = Three;
Condition.Requires(a).IsNotLessOrEqual(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsNotLessOrEqual on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64NotLessOrEqualTest05()
{
Int64 a = Two;
try
{
Condition.Requires(a, "a").IsNotLessOrEqual(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsNotLessOrEqual on Int64 x with 'lower bound > x' should succeed when exceptions are suppressed.")]
public void IsInt64NotLessOrEqualTest06()
{
Int64 a = One;
Condition.Requires(a).SuppressExceptionsForTest().IsNotLessOrEqual(Two);
}
#endregion // IsNotLessOrEqual
#region IsInt64EqualTo
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsEqualTo on Int64 x with 'x < other' should fail.")]
public void IsInt64EqualToTest01()
{
Int64 a = One;
Condition.Requires(a).IsEqualTo(Two);
}
[TestMethod]
[Description("Calling IsEqualTo on Int64 x with 'x = other' should pass.")]
public void IsInt64EqualToTest02()
{
Int64 a = Two;
Condition.Requires(a).IsEqualTo(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsEqualTo on Int64 x with 'x > other' should fail.")]
public void IsInt64EqualToTest03()
{
Int64 a = Three;
Condition.Requires(a).IsEqualTo(Two);
}
[TestMethod]
[Description("Calling IsEqualTo on Int64 x with conditionDescription should pass.")]
public void IsInt64EqualToTest04()
{
Int64 a = Two;
Condition.Requires(a).IsEqualTo(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsEqualTo on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64EqualToTest05()
{
Int64 a = Three;
try
{
Condition.Requires(a, "a").IsEqualTo(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsEqualTo on Int64 x with 'x < other' should succeed when exceptions are suppressed.")]
public void IsInt64EqualToTest06()
{
Int64 a = One;
Condition.Requires(a).SuppressExceptionsForTest().IsEqualTo(Two);
}
#endregion // IsInt64EqualTo
#region IsInt64NotEqualTo
[TestMethod]
[Description("Calling IsNotEqualTo on Int64 x with 'x < other' should pass.")]
public void IsInt64NotEqualToTest01()
{
Int64 a = One;
Condition.Requires(a).IsNotEqualTo(Two);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotEqualTo on Int64 x with 'x = other' should fail.")]
public void IsInt64NotEqualToTest02()
{
Int64 a = Two;
Condition.Requires(a).IsNotEqualTo(Two);
}
[TestMethod]
[Description("Calling IsNotEqualTo on Int64 x with 'x > other' should pass.")]
public void IsInt64NotEqualToTest03()
{
Int64 a = Three;
Condition.Requires(a).IsNotEqualTo(Two);
}
[TestMethod]
[Description("Calling IsNotEqualTo on Int64 x with conditionDescription should pass.")]
public void IsInt64NotEqualToTest04()
{
Int64 a = Three;
Condition.Requires(a).IsNotEqualTo(Two, string.Empty);
}
[TestMethod]
[Description("Calling a failing IsNotEqualTo on Int64 should throw an Exception with an exception message that contains the given parameterized condition description argument.")]
public void IsInt64NotEqualToTest05()
{
Int64 a = Two;
try
{
Condition.Requires(a, "a").IsNotEqualTo(Two, "abc {0} xyz");
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc a xyz"));
}
}
[TestMethod]
[Description("Calling IsNotEqualTo on Int64 x with 'x = other' should succeed when exceptions are suppressed.")]
public void IsInt64NotEqualToTest06()
{
Int64 a = Two;
Condition.Requires(a).SuppressExceptionsForTest().IsNotEqualTo(Two);
}
#endregion // IsInt64NotEqualTo
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Cross.DbFactory;
namespace Cross.DbFactory.Migrations
{
[DbContext(typeof(CrossContext))]
[Migration("20151223125758_Cross")]
partial class Cross
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("Cross.Entities.Task", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreateTime");
b.Property<int?>("CreateUserId");
b.Property<DateTime>("FinishedTime");
b.HasKey("Id");
});
modelBuilder.Entity("Cross.Entities.TaskSet", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CreateUserId");
b.Property<int>("ImageTaskCount");
b.Property<DateTime>("LastEditTime");
b.Property<int>("StoryTaskCount");
b.Property<int>("VideoTaskCount");
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "Role");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<int>("RoleId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "RoleClaim");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "User");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<int>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "UserClaim");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<int>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<int>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "UserLogin");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>", b =>
{
b.Property<int>("UserId");
b.Property<int>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "UserInRole");
});
modelBuilder.Entity("Cross.Entities.Task", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("CreateUserId");
});
modelBuilder.Entity("Cross.Entities.TaskSet", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("CreateUserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole<int>")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole<int>")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableArrayExtensionsTest
{
private static readonly ImmutableArray<int> emptyDefault = default(ImmutableArray<int>);
private static readonly ImmutableArray<int> empty = ImmutableArray.Create<int>();
private static readonly ImmutableArray<int> oneElement = ImmutableArray.Create(1);
private static readonly ImmutableArray<int> manyElements = ImmutableArray.Create(1, 2, 3);
private static readonly ImmutableArray<GenericParameterHelper> oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1));
private static readonly ImmutableArray<string> twoElementRefTypeWithNull = ImmutableArray.Create("1", null);
[Fact]
public void Select()
{
Assert.Equal(new[] { 4, 5, 6 }, ImmutableArrayExtensions.Select(manyElements, n => n + 3));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(manyElements, null));
}
[Fact]
public void SelectEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select<int, bool>(emptyDefault, null));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select(emptyDefault, n => true));
}
[Fact]
public void SelectEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(empty, null));
Assert.False(ImmutableArrayExtensions.Select(empty, n => true).Any());
}
[Fact]
public void Where()
{
Assert.Equal(new[] { 2, 3 }, ImmutableArrayExtensions.Where(manyElements, n => n > 1));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(manyElements, null));
}
[Fact]
public void WhereEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(emptyDefault, null));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(emptyDefault, n => true));
}
[Fact]
public void WhereEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(empty, null));
Assert.False(ImmutableArrayExtensions.Where(empty, n => true).Any());
}
[Fact]
public void Any()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(oneElement, null));
Assert.True(ImmutableArrayExtensions.Any(oneElement));
Assert.True(ImmutableArrayExtensions.Any(manyElements, n => n == 2));
Assert.False(ImmutableArrayExtensions.Any(manyElements, n => n == 4));
}
[Fact]
public void AnyEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(emptyDefault, n => true));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(emptyDefault, null));
}
[Fact]
public void AnyEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(empty, null));
Assert.False(ImmutableArrayExtensions.Any(empty));
Assert.False(ImmutableArrayExtensions.Any(empty, n => true));
}
[Fact]
public void All()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(oneElement, null));
Assert.False(ImmutableArrayExtensions.All(manyElements, n => n == 2));
Assert.True(ImmutableArrayExtensions.All(manyElements, n => n > 0));
}
[Fact]
public void AllEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(emptyDefault, n => true));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(emptyDefault, null));
}
[Fact]
public void AllEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(empty, null));
Assert.True(ImmutableArrayExtensions.All(empty, n => { Assert.True(false); return false; })); // predicate should never be invoked.
}
[Fact]
public void SequenceEqual()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(oneElement, (IEnumerable<int>)null));
Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, manyElements));
Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, manyElements.ToArray()));
Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, oneElement));
Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, oneElement.ToArray()));
Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, manyElements, (a, b) => true));
Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, ImmutableArray.Create(manyElements.ToArray()), (a, b) => false));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(oneElement, oneElement, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(oneElement, emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(emptyDefault, empty));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(emptyDefault, emptyDefault));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(emptyDefault, emptyDefault, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmpty()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(empty, (IEnumerable<int>)null));
Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty));
Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty.ToArray()));
Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty, (a, b) => true));
Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty, (a, b) => false));
}
[Fact]
public void Aggregate()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(oneElement, null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(oneElement, 1, null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(oneElement, 1, null, null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(oneElement, 1, (a, b) => a + b, null));
Assert.Equal(Enumerable.Aggregate(manyElements, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(manyElements, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(manyElements, 5, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(manyElements, 5, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(manyElements, 5, (a, b) => a * b, a => -a), ImmutableArrayExtensions.Aggregate(manyElements, 5, (a, b) => a * b, a => -a));
}
[Fact]
public void AggregateEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(emptyDefault, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(emptyDefault, 1, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(emptyDefault, 1, (a, b) => a + b, a => a));
}
[Fact]
public void AggregateEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.Aggregate(empty, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate(empty, 1, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate<int, int, int>(empty, 1, (a, b) => a + b, a => a));
}
[Fact]
public void ElementAt()
{
// Basis for some assertions that follow
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(manyElements, -1));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAt(emptyDefault, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(manyElements, -1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAt(oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAt(manyElements, 2));
}
[Fact]
public void ElementAtOrDefault()
{
Assert.Equal(Enumerable.ElementAtOrDefault(manyElements, -1), ImmutableArrayExtensions.ElementAtOrDefault(manyElements, -1));
Assert.Equal(Enumerable.ElementAtOrDefault(manyElements, 3), ImmutableArrayExtensions.ElementAtOrDefault(manyElements, 3));
Assert.Throws<InvalidOperationException>(() => Enumerable.ElementAtOrDefault(emptyDefault, 0));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAtOrDefault(emptyDefault, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(empty, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(empty, 1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAtOrDefault(oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAtOrDefault(manyElements, 2));
}
[Fact]
public void First()
{
Assert.Equal(Enumerable.First(oneElement), ImmutableArrayExtensions.First(oneElement));
Assert.Equal(Enumerable.First(manyElements), ImmutableArrayExtensions.First(manyElements));
}
[Fact]
public void FirstEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(empty, null));
}
[Fact]
public void FirstEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(emptyDefault, null));
}
[Fact]
public void FirstOrDefault()
{
Assert.Equal(Enumerable.FirstOrDefault(oneElement), ImmutableArrayExtensions.FirstOrDefault(oneElement));
Assert.Equal(Enumerable.FirstOrDefault(manyElements), ImmutableArrayExtensions.FirstOrDefault(manyElements));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(oneElement, null));
}
[Fact]
public void FirstOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(empty));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(empty, null));
}
[Fact]
public void FirstOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(emptyDefault, null));
}
[Fact]
public void Last()
{
Assert.Equal(Enumerable.Last(oneElement), ImmutableArrayExtensions.Last(oneElement));
Assert.Equal(Enumerable.Last(manyElements), ImmutableArrayExtensions.Last(manyElements));
}
[Fact]
public void LastEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(empty, null));
}
[Fact]
public void LastEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(emptyDefault, null));
}
[Fact]
public void LastOrDefault()
{
Assert.Equal(Enumerable.LastOrDefault(oneElement), ImmutableArrayExtensions.LastOrDefault(oneElement));
Assert.Equal(Enumerable.LastOrDefault(manyElements), ImmutableArrayExtensions.LastOrDefault(manyElements));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(oneElement, null));
}
[Fact]
public void LastOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(empty));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(empty, null));
}
[Fact]
public void LastOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(emptyDefault, null));
}
[Fact]
public void Single()
{
Assert.Equal(Enumerable.Single(oneElement), ImmutableArrayExtensions.Single(oneElement));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(manyElements));
}
[Fact]
public void SingleEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(empty, null));
}
[Fact]
public void SingleEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(emptyDefault, null));
}
[Fact]
public void SingleOrDefault()
{
Assert.Equal(Enumerable.SingleOrDefault(oneElement), ImmutableArrayExtensions.SingleOrDefault(oneElement));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(manyElements));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(oneElement, null));
}
[Fact]
public void SingleOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(empty));
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(empty, null));
}
[Fact]
public void SingleOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(emptyDefault, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(emptyDefault, null));
}
[Fact]
public void ToDictionary()
{
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, (Func<int, int>)null, n => n));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, (Func<int, int>)null, n => n, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, n => n, (Func<int, string>)null));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, n => n, (Func<int, string>)null, EqualityComparer<int>.Default));
var result = ImmutableArrayExtensions.ToDictionary(manyElements, n => n.ToString(), n => (n * 2).ToString());
Assert.Equal(result.Count, manyElements.Length);
Assert.Equal("2", result["1"]);
Assert.Equal("4", result["2"]);
Assert.Equal("6", result["3"]);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n, EqualityComparer<int>.Default));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n, n => n, EqualityComparer<int>.Default));
}
[Fact]
public void ToArray()
{
Assert.Equal(0, ImmutableArrayExtensions.ToArray(empty).Length);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToArray(emptyDefault));
Assert.Equal(manyElements.ToArray(), ImmutableArrayExtensions.ToArray(manyElements));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net
{
/// <summary>
/// <para>Acts as countdown timer, used to measure elapsed time over a sync operation.</para>
/// </summary>
internal static class TimerThread
{
/// <summary>
/// <para>Represents a queue of timers, which all have the same duration.</para>
/// </summary>
internal abstract class Queue
{
private readonly int _durationMilliseconds;
internal Queue(int durationMilliseconds)
{
_durationMilliseconds = durationMilliseconds;
}
/// <summary>
/// <para>The duration in milliseconds of timers in this queue.</para>
/// </summary>
internal int Duration => _durationMilliseconds;
/// <summary>
/// <para>Creates and returns a handle to a new polled timer.</para>
/// </summary>
internal Timer CreateTimer() => CreateTimer(null, null);
/// <summary>
/// <para>Creates and returns a handle to a new timer with attached context.</para>
/// </summary>
internal abstract Timer CreateTimer(Callback callback, object context);
}
/// <summary>
/// <para>Represents a timer and provides a mechanism to cancel.</para>
/// </summary>
internal abstract class Timer : IDisposable
{
private readonly int _startTimeMilliseconds;
private readonly int _durationMilliseconds;
internal Timer(int durationMilliseconds)
{
_durationMilliseconds = durationMilliseconds;
_startTimeMilliseconds = Environment.TickCount;
}
/// <summary>
/// <para>The duration in milliseconds of timer.</para>
/// </summary>
internal int Duration => _durationMilliseconds;
/// <summary>
/// <para>The time (relative to Environment.TickCount) when the timer started.</para>
/// </summary>
internal int StartTime => _startTimeMilliseconds;
/// <summary>
/// <para>The time (relative to Environment.TickCount) when the timer will expire.</para>
/// </summary>
internal int Expiration => unchecked(_startTimeMilliseconds + _durationMilliseconds);
/// <summary>
/// <para>The amount of time left on the timer. 0 means it has fired. 1 means it has expired but
/// not yet fired. -1 means infinite. Int32.MaxValue is the ceiling - the actual value could be longer.</para>
/// </summary>
internal int TimeRemaining
{
get
{
if (HasExpired)
{
return 0;
}
if (Duration == Timeout.Infinite)
{
return Timeout.Infinite;
}
int now = Environment.TickCount;
int remaining = IsTickBetween(StartTime, Expiration, now) ?
(int)(Math.Min((uint)unchecked(Expiration - now), (uint)Int32.MaxValue)) : 0;
return remaining < 2 ? remaining + 1 : remaining;
}
}
/// <summary>
/// <para>Cancels the timer. Returns true if the timer hasn't and won't fire; false if it has or will.</para>
/// </summary>
internal abstract bool Cancel();
/// <summary>
/// <para>Whether or not the timer has expired.</para>
/// </summary>
internal abstract bool HasExpired { get; }
public void Dispose() => Cancel();
}
/// <summary>
/// <para>Prototype for the callback that is called when a timer expires.</para>
/// </summary>
internal delegate void Callback(Timer timer, int timeNoticed, object context);
private const int ThreadIdleTimeoutMilliseconds = 30 * 1000;
private const int CacheScanPerIterations = 32;
private const int TickCountResolution = 15;
private static readonly LinkedList<WeakReference> s_queues = new LinkedList<WeakReference>();
private static readonly LinkedList<WeakReference> s_newQueues = new LinkedList<WeakReference>();
private static int s_threadState = (int)TimerThreadState.Idle; // Really a TimerThreadState, but need an int for Interlocked.
private static readonly AutoResetEvent s_threadReadyEvent = new AutoResetEvent(false);
private static readonly ManualResetEvent s_threadShutdownEvent = new ManualResetEvent(false);
private static readonly WaitHandle[] s_threadEvents = { s_threadShutdownEvent, s_threadReadyEvent };
private static int s_cacheScanIteration;
private static readonly Hashtable s_queuesCache = new Hashtable();
/// <summary>
/// <para>The possible states of the timer thread.</para>
/// </summary>
private enum TimerThreadState
{
Idle,
Running,
Stopped
}
/// <summary>
/// <para>Queue factory. Always synchronized.</para>
/// </summary>
internal static Queue GetOrCreateQueue(int durationMilliseconds)
{
if (durationMilliseconds == Timeout.Infinite)
{
return new InfiniteTimerQueue();
}
if (durationMilliseconds < 0)
{
throw new ArgumentOutOfRangeException(nameof(durationMilliseconds));
}
TimerQueue queue;
object key = durationMilliseconds; // Box once.
WeakReference weakQueue = (WeakReference)s_queuesCache[key];
if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null)
{
lock (s_newQueues)
{
weakQueue = (WeakReference)s_queuesCache[key];
if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null)
{
queue = new TimerQueue(durationMilliseconds);
weakQueue = new WeakReference(queue);
s_newQueues.AddLast(weakQueue);
s_queuesCache[key] = weakQueue;
// Take advantage of this lock to periodically scan the table for garbage.
if (++s_cacheScanIteration % CacheScanPerIterations == 0)
{
var garbage = new List<object>();
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = s_queuesCache.GetEnumerator();
while (e.MoveNext())
{
DictionaryEntry pair = e.Entry;
if (((WeakReference)pair.Value).Target == null)
{
garbage.Add(pair.Key);
}
}
for (int i = 0; i < garbage.Count; i++)
{
s_queuesCache.Remove(garbage[i]);
}
}
}
}
}
return queue;
}
/// <summary>
/// <para>Represents a queue of timers of fixed duration.</para>
/// </summary>
private class TimerQueue : Queue
{
// This is a GCHandle that holds onto the TimerQueue when active timers are in it.
// The TimerThread only holds WeakReferences to it so that it can be collected when the user lets go of it.
// But we don't want the user to HAVE to keep a reference to it when timers are active in it.
// It gets created when the first timer gets added, and cleaned up when the TimerThread notices it's empty.
// The TimerThread will always notice it's empty eventually, since the TimerThread will always wake up and
// try to fire the timer, even if it was cancelled and removed prematurely.
private IntPtr _thisHandle;
// This sentinel TimerNode acts as both the head and the tail, allowing nodes to go in and out of the list without updating
// any TimerQueue members. _timers.Next is the true head, and .Prev the true tail. This also serves as the list's lock.
private readonly TimerNode _timers;
/// <summary>
/// <para>Create a new TimerQueue. TimerQueues must be created while s_NewQueues is locked in
/// order to synchronize with Shutdown().</para>
/// </summary>
/// <param name="durationMilliseconds"></param>
internal TimerQueue(int durationMilliseconds) :
base(durationMilliseconds)
{
// Create the doubly-linked list with a sentinel head and tail so that this member never needs updating.
_timers = new TimerNode();
_timers.Next = _timers;
_timers.Prev = _timers;
}
/// <summary>
/// <para>Creates new timers. This method is thread-safe.</para>
/// </summary>
internal override Timer CreateTimer(Callback callback, object context)
{
TimerNode timer = new TimerNode(callback, context, Duration, _timers);
// Add this on the tail. (Actually, one before the tail - _timers is the sentinel tail.)
bool needProd = false;
lock (_timers)
{
if (!(_timers.Prev.Next == _timers))
{
NetEventSource.Fail(this, $"Tail corruption.");
}
// If this is the first timer in the list, we need to create a queue handle and prod the timer thread.
if (_timers.Next == _timers)
{
if (_thisHandle == IntPtr.Zero)
{
_thisHandle = (IntPtr)GCHandle.Alloc(this);
}
needProd = true;
}
timer.Next = _timers;
timer.Prev = _timers.Prev;
_timers.Prev.Next = timer;
_timers.Prev = timer;
}
// If, after we add the new tail, there is a chance that the tail is the next
// node to be processed, we need to wake up the timer thread.
if (needProd)
{
TimerThread.Prod();
}
return timer;
}
/// <summary>
/// <para>Called by the timer thread to fire the expired timers. Returns true if there are future timers
/// in the queue, and if so, also sets nextExpiration.</para>
/// </summary>
internal bool Fire(out int nextExpiration)
{
while (true)
{
// Check if we got to the end. If so, free the handle.
TimerNode timer = _timers.Next;
if (timer == _timers)
{
lock (_timers)
{
timer = _timers.Next;
if (timer == _timers)
{
if (_thisHandle != IntPtr.Zero)
{
((GCHandle)_thisHandle).Free();
_thisHandle = IntPtr.Zero;
}
nextExpiration = 0;
return false;
}
}
}
if (!timer.Fire())
{
nextExpiration = timer.Expiration;
return true;
}
}
}
}
/// <summary>
/// <para>A special dummy implementation for a queue of timers of infinite duration.</para>
/// </summary>
private class InfiniteTimerQueue : Queue
{
internal InfiniteTimerQueue() : base(Timeout.Infinite) { }
/// <summary>
/// <para>Always returns a dummy infinite timer.</para>
/// </summary>
internal override Timer CreateTimer(Callback callback, object context) => new InfiniteTimer();
}
/// <summary>
/// <para>Internal representation of an individual timer.</para>
/// </summary>
private class TimerNode : Timer
{
private TimerState _timerState;
private Callback _callback;
private object _context;
private object _queueLock;
private TimerNode _next;
private TimerNode _prev;
/// <summary>
/// <para>Status of the timer.</para>
/// </summary>
private enum TimerState
{
Ready,
Fired,
Cancelled,
Sentinel
}
internal TimerNode(Callback callback, object context, int durationMilliseconds, object queueLock) : base(durationMilliseconds)
{
if (callback != null)
{
_callback = callback;
_context = context;
}
_timerState = TimerState.Ready;
_queueLock = queueLock;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}");
}
// A sentinel node - both the head and tail are one, which prevent the head and tail from ever having to be updated.
internal TimerNode() : base(0)
{
_timerState = TimerState.Sentinel;
}
internal override bool HasExpired => _timerState == TimerState.Fired;
internal TimerNode Next
{
get { return _next; }
set { _next = value; }
}
internal TimerNode Prev
{
get { return _prev; }
set { _prev = value; }
}
/// <summary>
/// <para>Cancels the timer. Returns true if it hasn't and won't fire; false if it has or will, or has already been cancelled.</para>
/// </summary>
internal override bool Cancel()
{
if (_timerState == TimerState.Ready)
{
lock (_queueLock)
{
if (_timerState == TimerState.Ready)
{
// Remove it from the list. This keeps the list from getting too big when there are a lot of rapid creations
// and cancellations. This is done before setting it to Cancelled to try to prevent the Fire() loop from
// seeing it, or if it does, of having to take a lock to synchronize with the state of the list.
Next.Prev = Prev;
Prev.Next = Next;
// Just cleanup. Doesn't need to be in the lock but is easier to have here.
Next = null;
Prev = null;
_callback = null;
_context = null;
_timerState = TimerState.Cancelled;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (success)");
return true;
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (failure)");
return false;
}
/// <summary>
/// <para>Fires the timer if it is still active and has expired. Returns
/// true if it can be deleted, or false if it is still timing.</para>
/// </summary>
internal bool Fire()
{
if (_timerState == TimerState.Sentinel)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "TimerQueue tried to Fire a Sentinel.");
}
if (_timerState != TimerState.Ready)
{
return true;
}
// Must get the current tick count within this method so it is guaranteed not to be before
// StartTime, which is set in the constructor.
int nowMilliseconds = Environment.TickCount;
if (IsTickBetween(StartTime, Expiration, nowMilliseconds))
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Not firing ({StartTime} <= {nowMilliseconds} < {Expiration})");
return false;
}
bool needCallback = false;
lock (_queueLock)
{
if (_timerState == TimerState.Ready)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Firing ({StartTime} <= {nowMilliseconds} >= " + Expiration + ")");
_timerState = TimerState.Fired;
// Remove it from the list.
Next.Prev = Prev;
Prev.Next = Next;
Next = null;
Prev = null;
needCallback = _callback != null;
}
}
if (needCallback)
{
try
{
Callback callback = _callback;
object context = _context;
_callback = null;
_context = null;
callback(this, nowMilliseconds, context);
}
catch (Exception exception)
{
if (ExceptionCheck.IsFatal(exception))
throw;
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"exception in callback: {exception}");
// This thread is not allowed to go into user code, so we should never get an exception here.
// So, in debug, throw it up, killing the AppDomain. In release, we'll just ignore it.
#if DEBUG
throw;
#endif
}
}
return true;
}
}
/// <summary>
/// <para>A dummy infinite timer.</para>
/// </summary>
private class InfiniteTimer : Timer
{
internal InfiniteTimer() : base(Timeout.Infinite) { }
private int _cancelled;
internal override bool HasExpired => false;
/// <summary>
/// <para>Cancels the timer. Returns true the first time, false after that.</para>
/// </summary>
internal override bool Cancel() => Interlocked.Exchange(ref _cancelled, 1) == 0;
}
/// <summary>
/// <para>Internal mechanism used when timers are added to wake up / create the thread.</para>
/// </summary>
private static void Prod()
{
s_threadReadyEvent.Set();
TimerThreadState oldState = (TimerThreadState)Interlocked.CompareExchange(
ref s_threadState,
(int)TimerThreadState.Running,
(int)TimerThreadState.Idle);
if (oldState == TimerThreadState.Idle)
{
new Thread(new ThreadStart(ThreadProc)).Start();
}
}
/// <summary>
/// <para>Thread for the timer. Ignores all exceptions. If no activity occurs for a while,
/// the thread will shut down.</para>
/// </summary>
private static void ThreadProc()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
#if DEBUG
DebugThreadTracking.SetThreadSource(ThreadKinds.Timer);
using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
// Set this thread as a background thread. On AppDomain/Process shutdown, the thread will just be killed.
Thread.CurrentThread.IsBackground = true;
// Keep a permanent lock on s_Queues. This lets for example Shutdown() know when this thread isn't running.
lock (s_queues)
{
// If shutdown was recently called, abort here.
if (Interlocked.CompareExchange(ref s_threadState, (int)TimerThreadState.Running, (int)TimerThreadState.Running) !=
(int)TimerThreadState.Running)
{
return;
}
bool running = true;
while (running)
{
try
{
s_threadReadyEvent.Reset();
while (true)
{
// Copy all the new queues to the real queues. Since only this thread modifies the real queues, it doesn't have to lock it.
if (s_newQueues.Count > 0)
{
lock (s_newQueues)
{
for (LinkedListNode<WeakReference> node = s_newQueues.First; node != null; node = s_newQueues.First)
{
s_newQueues.Remove(node);
s_queues.AddLast(node);
}
}
}
int now = Environment.TickCount;
int nextTick = 0;
bool haveNextTick = false;
for (LinkedListNode<WeakReference> node = s_queues.First; node != null; /* node = node.Next must be done in the body */)
{
TimerQueue queue = (TimerQueue)node.Value.Target;
if (queue == null)
{
LinkedListNode<WeakReference> next = node.Next;
s_queues.Remove(node);
node = next;
continue;
}
// Fire() will always return values that should be interpreted as later than 'now' (that is, even if 'now' is
// returned, it is 0x100000000 milliseconds in the future). There's also a chance that Fire() will return a value
// intended as > 0x100000000 milliseconds from 'now'. Either case will just cause an extra scan through the timers.
int nextTickInstance;
if (queue.Fire(out nextTickInstance) && (!haveNextTick || IsTickBetween(now, nextTick, nextTickInstance)))
{
nextTick = nextTickInstance;
haveNextTick = true;
}
node = node.Next;
}
// Figure out how long to wait, taking into account how long the loop took.
// Add 15 ms to compensate for poor TickCount resolution (want to guarantee a firing).
int newNow = Environment.TickCount;
int waitDuration = haveNextTick ?
(int)(IsTickBetween(now, nextTick, newNow) ?
Math.Min(unchecked((uint)(nextTick - newNow)), (uint)(Int32.MaxValue - TickCountResolution)) + TickCountResolution :
0) :
ThreadIdleTimeoutMilliseconds;
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Waiting for {waitDuration}ms");
int waitResult = WaitHandle.WaitAny(s_threadEvents, waitDuration, false);
// 0 is s_ThreadShutdownEvent - die.
if (waitResult == 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Awoke, cause: Shutdown");
running = false;
break;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Awoke, cause {(waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod")}");
// If we timed out with nothing to do, shut down.
if (waitResult == WaitHandle.WaitTimeout && !haveNextTick)
{
Interlocked.CompareExchange(ref s_threadState, (int)TimerThreadState.Idle, (int)TimerThreadState.Running);
// There could have been one more prod between the wait and the exchange. Check, and abort if necessary.
if (s_threadReadyEvent.WaitOne(0, false))
{
if (Interlocked.CompareExchange(ref s_threadState, (int)TimerThreadState.Running, (int)TimerThreadState.Idle) ==
(int)TimerThreadState.Idle)
{
continue;
}
}
running = false;
break;
}
}
}
catch (Exception exception)
{
if (ExceptionCheck.IsFatal(exception))
throw;
if (NetEventSource.IsEnabled) NetEventSource.Error(null, exception);
// The only options are to continue processing and likely enter an error-loop,
// shut down timers for this AppDomain, or shut down the AppDomain. Go with shutting
// down the AppDomain in debug, and going into a loop in retail, but try to make the
// loop somewhat slow. Note that in retail, this can only be triggered by OutOfMemory or StackOverflow,
// or an exception thrown within TimerThread - the rest are caught in Fire().
#if !DEBUG
Thread.Sleep(1000);
#else
throw;
#endif
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Stop");
#if DEBUG
}
#endif
}
/// <summary>
/// <para>Helper for deciding whether a given TickCount is before or after a given expiration
/// tick count assuming that it can't be before a given starting TickCount.</para>
/// </summary>
private static bool IsTickBetween(int start, int end, int comparand)
{
// Assumes that if start and end are equal, they are the same time.
// Assumes that if the comparand and start are equal, no time has passed,
// and that if the comparand and end are equal, end has occurred.
return ((start <= comparand) == (end <= comparand)) != (start <= end);
}
}
}
| |
// 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.
// The BigNumber class implements methods for formatting and parsing
// big numeric values. To format and parse numeric values, applications should
// use the Format and Parse methods provided by the numeric
// classes (BigInteger). Those
// Format and Parse methods share a common implementation
// provided by this class, and are thus documented in detail here.
//
// Formatting
//
// The Format methods provided by the numeric classes are all of the
// form
//
// public static String Format(XXX value, String format);
// public static String Format(XXX value, String format, NumberFormatInfo info);
//
// where XXX is the name of the particular numeric class. The methods convert
// the numeric value to a string using the format string given by the
// format parameter. If the format parameter is null or
// an empty string, the number is formatted as if the string "G" (general
// format) was specified. The info parameter specifies the
// NumberFormatInfo instance to use when formatting the number. If the
// info parameter is null or omitted, the numeric formatting information
// is obtained from the current culture. The NumberFormatInfo supplies
// such information as the characters to use for decimal and thousand
// separators, and the spelling and placement of currency symbols in monetary
// values.
//
// Format strings fall into two categories: Standard format strings and
// user-defined format strings. A format string consisting of a single
// alphabetic character (A-Z or a-z), optionally followed by a sequence of
// digits (0-9), is a standard format string. All other format strings are
// used-defined format strings.
//
// A standard format string takes the form Axx, where A is an
// alphabetic character called the format specifier and xx is a
// sequence of digits called the precision specifier. The format
// specifier controls the type of formatting applied to the number and the
// precision specifier controls the number of significant digits or decimal
// places of the formatting operation. The following table describes the
// supported standard formats.
//
// C c - Currency format. The number is
// converted to a string that represents a currency amount. The conversion is
// controlled by the currency format information of the NumberFormatInfo
// used to format the number. The precision specifier indicates the desired
// number of decimal places. If the precision specifier is omitted, the default
// currency precision given by the NumberFormatInfo is used.
//
// D d - Decimal format. This format is
// supported for integral types only. The number is converted to a string of
// decimal digits, prefixed by a minus sign if the number is negative. The
// precision specifier indicates the minimum number of digits desired in the
// resulting string. If required, the number will be left-padded with zeros to
// produce the number of digits given by the precision specifier.
//
// E e Engineering (scientific) format.
// The number is converted to a string of the form
// "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative, and one digit always precedes the decimal point. The
// precision specifier indicates the desired number of digits after the decimal
// point. If the precision specifier is omitted, a default of 6 digits after
// the decimal point is used. The format specifier indicates whether to prefix
// the exponent with an 'E' or an 'e'. The exponent is always consists of a
// plus or minus sign and three digits.
//
// F f Fixed point format. The number is
// converted to a string of the form "-ddd.ddd....", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. The precision specifier indicates the desired number of
// decimal places. If the precision specifier is omitted, the default numeric
// precision given by the NumberFormatInfo is used.
//
// G g - General format. The number is
// converted to the shortest possible decimal representation using fixed point
// or scientific format. The precision specifier determines the number of
// significant digits in the resulting string. If the precision specifier is
// omitted, the number of significant digits is determined by the type of the
// number being converted (10 for int, 19 for long, 7 for
// float, 15 for double, 19 for Currency, and 29 for
// Decimal). Trailing zeros after the decimal point are removed, and the
// resulting string contains a decimal point only if required. The resulting
// string uses fixed point format if the exponent of the number is less than
// the number of significant digits and greater than or equal to -4. Otherwise,
// the resulting string uses scientific format, and the case of the format
// specifier controls whether the exponent is prefixed with an 'E' or an
// 'e'.
//
// N n Number format. The number is
// converted to a string of the form "-d,ddd,ddd.ddd....", where
// each 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. Thousand separators are inserted between each group of
// three digits to the left of the decimal point. The precision specifier
// indicates the desired number of decimal places. If the precision specifier
// is omitted, the default numeric precision given by the
// NumberFormatInfo is used.
//
// X x - Hexadecimal format. This format is
// supported for integral types only. The number is converted to a string of
// hexadecimal digits. The format specifier indicates whether to use upper or
// lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF',
// and 'x' for 'abcdef'). The precision specifier indicates the minimum number
// of digits desired in the resulting string. If required, the number will be
// left-padded with zeros to produce the number of digits given by the
// precision specifier.
//
// Some examples of standard format strings and their results are shown in the
// table below. (The examples all assume a default NumberFormatInfo.)
//
// Value Format Result
// 12345.6789 C $12,345.68
// -12345.6789 C ($12,345.68)
// 12345 D 12345
// 12345 D8 00012345
// 12345.6789 E 1.234568E+004
// 12345.6789 E10 1.2345678900E+004
// 12345.6789 e4 1.2346e+004
// 12345.6789 F 12345.68
// 12345.6789 F0 12346
// 12345.6789 F6 12345.678900
// 12345.6789 G 12345.6789
// 12345.6789 G7 12345.68
// 123456789 G7 1.234568E8
// 12345.6789 N 12,345.68
// 123456789 N4 123,456,789.0000
// 0x2c45e x 2c45e
// 0x2c45e X 2C45E
// 0x2c45e X8 0002C45E
//
// Format strings that do not start with an alphabetic character, or that start
// with an alphabetic character followed by a non-digit, are called
// user-defined format strings. The following table describes the formatting
// characters that are supported in user defined format strings.
//
//
// 0 - Digit placeholder. If the value being
// formatted has a digit in the position where the '0' appears in the format
// string, then that digit is copied to the output string. Otherwise, a '0' is
// stored in that position in the output string. The position of the leftmost
// '0' before the decimal point and the rightmost '0' after the decimal point
// determines the range of digits that are always present in the output
// string.
//
// # - Digit placeholder. If the value being
// formatted has a digit in the position where the '#' appears in the format
// string, then that digit is copied to the output string. Otherwise, nothing
// is stored in that position in the output string.
//
// . - Decimal point. The first '.' character
// in the format string determines the location of the decimal separator in the
// formatted value; any additional '.' characters are ignored. The actual
// character used as a the decimal separator in the output string is given by
// the NumberFormatInfo used to format the number.
//
// , - Thousand separator and number scaling.
// The ',' character serves two purposes. First, if the format string contains
// a ',' character between two digit placeholders (0 or #) and to the left of
// the decimal point if one is present, then the output will have thousand
// separators inserted between each group of three digits to the left of the
// decimal separator. The actual character used as a the decimal separator in
// the output string is given by the NumberFormatInfo used to format the
// number. Second, if the format string contains one or more ',' characters
// immediately to the left of the decimal point, or after the last digit
// placeholder if there is no decimal point, then the number will be divided by
// 1000 times the number of ',' characters before it is formatted. For example,
// the format string '0,,' will represent 100 million as just 100. Use of the
// ',' character to indicate scaling does not also cause the formatted number
// to have thousand separators. Thus, to scale a number by 1 million and insert
// thousand separators you would use the format string '#,##0,,'.
//
// % - Percentage placeholder. The presence of
// a '%' character in the format string causes the number to be multiplied by
// 100 before it is formatted. The '%' character itself is inserted in the
// output string where it appears in the format string.
//
// E+ E- e+ e- - Scientific notation.
// If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format
// string and are immediately followed by at least one '0' character, then the
// number is formatted using scientific notation with an 'E' or 'e' inserted
// between the number and the exponent. The number of '0' characters following
// the scientific notation indicator determines the minimum number of digits to
// output for the exponent. The 'E+' and 'e+' formats indicate that a sign
// character (plus or minus) should always precede the exponent. The 'E-' and
// 'e-' formats indicate that a sign character should only precede negative
// exponents.
//
// \ - Literal character. A backslash character
// causes the next character in the format string to be copied to the output
// string as-is. The backslash itself isn't copied, so to place a backslash
// character in the output string, use two backslashes (\\) in the format
// string.
//
// 'ABC' "ABC" - Literal string. Characters
// enclosed in single or double quotation marks are copied to the output string
// as-is and do not affect formatting.
//
// ; - Section separator. The ';' character is
// used to separate sections for positive, negative, and zero numbers in the
// format string.
//
// Other - All other characters are copied to
// the output string in the position they appear.
//
// For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or
// 'e-'), the number is rounded to as many decimal places as there are digit
// placeholders to the right of the decimal point. If the format string does
// not contain a decimal point, the number is rounded to the nearest
// integer. If the number has more digits than there are digit placeholders to
// the left of the decimal point, the extra digits are copied to the output
// string immediately before the first digit placeholder.
//
// For scientific formats, the number is rounded to as many significant digits
// as there are digit placeholders in the format string.
//
// To allow for different formatting of positive, negative, and zero values, a
// user-defined format string may contain up to three sections separated by
// semicolons. The results of having one, two, or three sections in the format
// string are described in the table below.
//
// Sections:
//
// One - The format string applies to all values.
//
// Two - The first section applies to positive values
// and zeros, and the second section applies to negative values. If the number
// to be formatted is negative, but becomes zero after rounding according to
// the format in the second section, then the resulting zero is formatted
// according to the first section.
//
// Three - The first section applies to positive
// values, the second section applies to negative values, and the third section
// applies to zeros. The second section may be left empty (by having no
// characters between the semicolons), in which case the first section applies
// to all non-zero values. If the number to be formatted is non-zero, but
// becomes zero after rounding according to the format in the first or second
// section, then the resulting zero is formatted according to the third
// section.
//
// For both standard and user-defined formatting operations on values of type
// float and double, if the value being formatted is a NaN (Not
// a Number) or a positive or negative infinity, then regardless of the format
// string, the resulting string is given by the NaNSymbol,
// PositiveInfinitySymbol, or NegativeInfinitySymbol property of
// the NumberFormatInfo used to format the number.
//
// Parsing
//
// The Parse methods provided by the numeric classes are all of the form
//
// public static XXX Parse(String s);
// public static XXX Parse(String s, int style);
// public static XXX Parse(String s, int style, NumberFormatInfo info);
//
// where XXX is the name of the particular numeric class. The methods convert a
// string to a numeric value. The optional style parameter specifies the
// permitted style of the numeric string. It must be a combination of bit flags
// from the NumberStyles enumeration. The optional info parameter
// specifies the NumberFormatInfo instance to use when parsing the
// string. If the info parameter is null or omitted, the numeric
// formatting information is obtained from the current culture.
//
// Numeric strings produced by the Format methods using the Currency,
// Decimal, Engineering, Fixed point, General, or Number standard formats
// (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable
// by the Parse methods if the NumberStyles.Any style is
// specified. Note, however, that the Parse methods do not accept
// NaNs or Infinities.
//
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using Conditional = System.Diagnostics.ConditionalAttribute;
namespace System.Numerics
{
internal static class BigNumber
{
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
private struct BigNumberBuffer
{
public StringBuilder digits;
public int precision;
public int scale;
public bool sign; // negative sign exists
public static BigNumberBuffer Create()
{
BigNumberBuffer number = new BigNumberBuffer();
number.digits = new StringBuilder();
return number;
}
}
internal static bool TryValidateParseStyleInteger(NumberStyles style, out ArgumentException e)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
e = new ArgumentException(SR.Format(SR.Argument_InvalidNumberStyles, "style"));
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
e = new ArgumentException(SR.Argument_InvalidHexStyle);
return false;
}
}
e = null;
return true;
}
[SecuritySafeCritical]
internal static Boolean TryParseBigInteger(String value, NumberStyles style, NumberFormatInfo info, out BigInteger result)
{
unsafe
{
result = BigInteger.Zero;
ArgumentException e;
if (!TryValidateParseStyleInteger(style, out e))
throw e; // TryParse still throws ArgumentException on invalid NumberStyles
BigNumberBuffer bignumber = BigNumberBuffer.Create();
if (!FormatProvider.TryStringToBigInteger(value, style, info, bignumber.digits, out bignumber.precision, out bignumber.scale, out bignumber.sign))
return false;
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{
if (!HexNumberToBigInteger(ref bignumber, ref result))
{
return false;
}
}
else
{
if (!NumberToBigInteger(ref bignumber, ref result))
{
return false;
}
}
return true;
}
}
internal static BigInteger ParseBigInteger(String value, NumberStyles style, NumberFormatInfo info)
{
if (value == null)
throw new ArgumentNullException("value");
ArgumentException e;
if (!TryValidateParseStyleInteger(style, out e))
throw e;
BigInteger result = BigInteger.Zero;
if (!TryParseBigInteger(value, style, info, out result))
{
throw new FormatException(SR.Overflow_ParseBigInteger);
}
return result;
}
private unsafe static Boolean HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value)
{
if (number.digits == null || number.digits.Length == 0)
return false;
int len = number.digits.Length - 1; // ignore trailing '\0'
byte[] bits = new byte[(len / 2) + (len % 2)];
bool shift = false;
bool isNegative = false;
int bitIndex = 0;
// parse the string into a little-endian two's complement byte array
// string value : O F E B 7 \0
// string index (i) : 0 1 2 3 4 5 <--
// byte[] (bitIndex): 2 1 1 0 0 <--
//
for (int i = len - 1; i > -1; i--)
{
char c = number.digits[i];
byte b;
if (c >= '0' && c <= '9')
{
b = (byte)(c - '0');
}
else if (c >= 'A' && c <= 'F')
{
b = (byte)((c - 'A') + 10);
}
else
{
Debug.Assert(c >= 'a' && c <= 'f');
b = (byte)((c - 'a') + 10);
}
if (i == 0 && (b & 0x08) == 0x08)
isNegative = true;
if (shift)
{
bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4));
bitIndex++;
}
else
{
bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b);
}
shift = !shift;
}
value = new BigInteger(bits);
return true;
}
private unsafe static Boolean NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value)
{
Int32 i = number.scale;
Int32 cur = 0;
BigInteger ten = 10;
value = 0;
while (--i >= 0)
{
value *= ten;
if (number.digits[cur] != '\0')
{
value += (Int32)(number.digits[cur++] - '0');
}
}
while (number.digits[cur] != '\0')
{
if (number.digits[cur++] != '0') return false; // disallow non-zero trailing decimal places
}
if (number.sign)
{
value = -value;
}
return true;
}
// this function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier
internal static char ParseFormatSpecifier(String format, out Int32 digits)
{
digits = -1;
if (String.IsNullOrEmpty(format))
{
return 'R';
}
int i = 0;
char ch = format[i];
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
i++;
int n = -1;
if (i < format.Length && format[i] >= '0' && format[i] <= '9')
{
n = format[i++] - '0';
while (i < format.Length && format[i] >= '0' && format[i] <= '9')
{
n = n * 10 + (format[i++] - '0');
if (n >= 10)
break;
}
}
if (i >= format.Length || format[i] == '\0')
{
digits = n;
return ch;
}
}
return (char)0; // custom format
}
private static String FormatBigIntegerToHexString(BigInteger value, char format, int digits, NumberFormatInfo info)
{
StringBuilder sb = new StringBuilder();
byte[] bits = value.ToByteArray();
String fmt = null;
int cur = bits.Length - 1;
if (cur > -1)
{
// [FF..F8] drop the high F as the two's complement negative number remains clear
// [F7..08] retain the high bits as the two's complement number is wrong without it
// [07..00] drop the high 0 as the two's complement positive number remains clear
bool clearHighF = false;
byte head = bits[cur];
if (head > 0xF7)
{
head -= 0xF0;
clearHighF = true;
}
if (head < 0x08 || clearHighF)
{
// {0xF8-0xFF} print as {8-F}
// {0x00-0x07} print as {0-7}
fmt = String.Format(CultureInfo.InvariantCulture, "{0}1", format);
sb.Append(head.ToString(fmt, info));
cur--;
}
}
if (cur > -1)
{
fmt = String.Format(CultureInfo.InvariantCulture, "{0}2", format);
while (cur > -1)
{
sb.Append(bits[cur--].ToString(fmt, info));
}
}
if (digits > 0 && digits > sb.Length)
{
// insert leading zeros. User specified "X5" so we create "0ABCD" instead of "ABCD"
sb.Insert(0, (value._sign >= 0 ? ("0") : (format == 'x' ? "f" : "F")), digits - sb.Length);
}
return sb.ToString();
}
[SecuritySafeCritical]
internal static String FormatBigInteger(BigInteger value, String format, NumberFormatInfo info)
{
int digits = 0;
char fmt = ParseFormatSpecifier(format, out digits);
if (fmt == 'x' || fmt == 'X')
return FormatBigIntegerToHexString(value, fmt, digits, info);
bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R');
if (value._bits == null)
{
if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R')
{
if (digits > 0)
format = String.Format(CultureInfo.InvariantCulture, "D{0}", digits.ToString(CultureInfo.InvariantCulture));
else
format = "D";
}
return value._sign.ToString(format, info);
}
// First convert to base 10^9.
const uint kuBase = 1000000000; // 10^9
const int kcchBase = 9;
int cuSrc = value._bits.Length;
int cuMax;
try
{
cuMax = checked(cuSrc * 10 / 9 + 2);
}
catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }
uint[] rguDst = new uint[cuMax];
int cuDst = 0;
for (int iuSrc = cuSrc; --iuSrc >= 0;)
{
uint uCarry = value._bits[iuSrc];
for (int iuDst = 0; iuDst < cuDst; iuDst++)
{
Debug.Assert(rguDst[iuDst] < kuBase);
ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry);
rguDst[iuDst] = (uint)(uuRes % kuBase);
uCarry = (uint)(uuRes / kuBase);
}
if (uCarry != 0)
{
rguDst[cuDst++] = uCarry % kuBase;
uCarry /= kuBase;
if (uCarry != 0)
rguDst[cuDst++] = uCarry;
}
}
int cchMax;
try
{
// Each uint contributes at most 9 digits to the decimal representation.
cchMax = checked(cuDst * kcchBase);
}
catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }
if (decimalFmt)
{
if (digits > 0 && digits > cchMax)
cchMax = digits;
if (value._sign < 0)
{
try
{
// Leave an extra slot for a minus sign.
cchMax = checked(cchMax + info.NegativeSign.Length);
}
catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }
}
}
int rgchBufSize;
try
{
// We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs
// to be null terminated. Let's ensure that we can allocate a buffer of that size.
rgchBufSize = checked(cchMax + 1);
}
catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }
char[] rgch = new char[rgchBufSize];
int ichDst = cchMax;
for (int iuDst = 0; iuDst < cuDst - 1; iuDst++)
{
uint uDig = rguDst[iuDst];
Debug.Assert(uDig < kuBase);
for (int cch = kcchBase; --cch >= 0;)
{
rgch[--ichDst] = (char)('0' + uDig % 10);
uDig /= 10;
}
}
for (uint uDig = rguDst[cuDst - 1]; uDig != 0;)
{
rgch[--ichDst] = (char)('0' + uDig % 10);
uDig /= 10;
}
if (!decimalFmt)
{
// sign = true for negative and false for 0 and positive values
bool sign = (value._sign < 0);
// the cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form
int precision = 29;
int scale = cchMax - ichDst;
return FormatProvider.FormatBigInteger(precision, scale, sign, format, info, rgch, ichDst);
}
// Format Round-trip decimal
// This format is supported for integral types only. The number is converted to a string of
// decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision
// specifier indicates the minimum number of digits desired in the resulting string. If required,
// the number is padded with zeros to its left to produce the number of digits given by the
// precision specifier.
int numDigitsPrinted = cchMax - ichDst;
while (digits > 0 && digits > numDigitsPrinted)
{
// pad leading zeros
rgch[--ichDst] = '0';
digits--;
}
if (value._sign < 0)
{
String negativeSign = info.NegativeSign;
for (int i = info.NegativeSign.Length - 1; i > -1; i--)
rgch[--ichDst] = info.NegativeSign[i];
}
return new String(rgch, ichDst, cchMax - ichDst);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Tests
{
public static class ArraySegmentTests
{
[Fact]
public static void Ctor_Empty()
{
var segment = new ArraySegment<int>();
Assert.Null(segment.Array);
Assert.Equal(0, segment.Offset);
Assert.Equal(0, segment.Count);
}
[Theory]
[InlineData(new int[] { 7, 8, 9, 10, 11 })]
[InlineData(new int[0])]
public static void Ctor_Array(int[] array)
{
var segment = new ArraySegment<int>(array);
Assert.Same(array, segment.Array);
Assert.Equal(0, segment.Offset);
Assert.Equal(array.Length, segment.Count);
}
[Fact]
public static void Ctor_Array_NullArray_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("array", () => new ArraySegment<int>(null)); // Array is null
}
[Theory]
[InlineData(new int[] { 7, 8, 9, 10, 11 }, 2, 3)]
[InlineData(new int[] { 7, 8, 9, 10, 11 }, 0, 5)]
[InlineData(new int[0], 0, 0)]
public static void Ctor_Array_Int_Int(int[] array, int offset, int count)
{
var segment = new ArraySegment<int>(array, offset, count);
Assert.Same(array, segment.Array);
Assert.Equal(offset, segment.Offset);
Assert.Equal(count, segment.Count);
}
[Fact]
public static void Ctor_Array_Int_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("array", () => new ArraySegment<int>(null, 0, 0)); // Array is null
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new ArraySegment<int>(new int[10], -1, 0)); // Offset < 0
Assert.Throws<ArgumentOutOfRangeException>("count", () => new ArraySegment<int>(new int[10], 0, -1)); // Count < 0
Assert.Throws<ArgumentException>(null, () => new ArraySegment<int>(new int[10], 10, 1)); // Offset + count > array.Length
Assert.Throws<ArgumentException>(null, () => new ArraySegment<int>(new int[10], 9, 2)); // Offset + count > array.Length
}
public static IEnumerable<object[]> Equals_TestData()
{
var intArray1 = new int[] { 7, 8, 9, 10, 11, 12 };
var intArray2 = new int[] { 7, 8, 9, 10, 11, 12 };
yield return new object[] { new ArraySegment<int>(intArray1), new ArraySegment<int>(intArray1), true };
yield return new object[] { new ArraySegment<int>(intArray1), new ArraySegment<int>(intArray1, 0, intArray1.Length), true };
yield return new object[] { new ArraySegment<int>(intArray1, 2, 3), new ArraySegment<int>(intArray1, 2, 3), true };
yield return new object[] { new ArraySegment<int>(intArray1, 3, 3), new ArraySegment<int>(intArray1, 2, 3), false };
yield return new object[] { new ArraySegment<int>(intArray1, 2, 4), new ArraySegment<int>(intArray1, 2, 3), false };
yield return new object[] { new ArraySegment<int>(intArray1, 2, 4), new ArraySegment<int>(intArray2, 2, 3), false };
yield return new object[] { new ArraySegment<int>(intArray1), intArray1, false };
yield return new object[] { new ArraySegment<int>(intArray1), null, false };
yield return new object[] { new ArraySegment<int>(intArray1, 2, 4), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals(ArraySegment<int> segment1, object obj, bool expected)
{
if (obj is ArraySegment<int>)
{
ArraySegment<int> segment2 = (ArraySegment<int>)obj;
Assert.Equal(expected, segment1.Equals(segment2));
Assert.Equal(expected, segment1 == segment2);
Assert.Equal(!expected, segment1 != segment2);
Assert.Equal(expected, segment1.GetHashCode().Equals(segment2.GetHashCode()));
}
Assert.Equal(expected, segment1.Equals(obj));
}
[Fact]
public static void IList_GetSetItem()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
var segment = new ArraySegment<int>(intArray, 2, 3);
IList<int> iList = segment;
Assert.Equal(segment.Count, iList.Count);
for (int i = 0; i < iList.Count; i++)
{
Assert.Equal(intArray[i + segment.Offset], iList[i]);
iList[i] = 99;
Assert.Equal(99, iList[i]);
Assert.Equal(99, intArray[i + segment.Offset]);
}
}
[Fact]
public static void IList_GetSetItem_Invalid()
{
IList<int> iList = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => iList[0]); // Array is null
Assert.Throws<InvalidOperationException>(() => iList[0] = 0); // Array is null
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
iList = new ArraySegment<int>(intArray, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>("index", () => iList[-1]); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => iList[iList.Count]); // Index >= list.Count
Assert.Throws<ArgumentOutOfRangeException>("index", () => iList[-1] = 0); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => iList[iList.Count] = 0); // Index >= list.Count
}
[Fact]
public static void IReadOnlyList_GetItem()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
var seg = new ArraySegment<int>(intArray, 2, 3);
IReadOnlyList<int> iList = seg;
for (int i = 0; i < iList.Count; i++)
{
Assert.Equal(intArray[i + seg.Offset], iList[i]);
}
}
[Fact]
public static void IReadOnlyList_GetItem_Invalid()
{
IReadOnlyList<int> iList = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => iList[0]); // Array is null
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
iList = new ArraySegment<int>(intArray, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>("index", () => iList[-1]); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => iList[iList.Count]); // List >= seg.Count
}
[Fact]
public static void IList_IndexOf()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
var segment = new ArraySegment<int>(intArray, 2, 3);
IList<int> iList = segment;
for (int i = segment.Offset; i < segment.Count; i++)
{
Assert.Equal(i - segment.Offset, iList.IndexOf(intArray[i]));
}
Assert.Equal(-1, iList.IndexOf(9999)); // No such value
Assert.Equal(-1, iList.IndexOf(7)); // No such value in range
}
[Fact]
public static void IList_IndexOf_NullArray_ThrowsInvalidOperationException()
{
IList<int> iList = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => iList.IndexOf(0)); // Array is null
}
[Fact]
public static void IList_ModifyingCollection_ThrowsNotSupportedException()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
var segment = new ArraySegment<int>(intArray, 2, 3);
IList<int> iList = segment;
Assert.True(iList.IsReadOnly);
Assert.Throws<NotSupportedException>(() => iList.Add(2));
Assert.Throws<NotSupportedException>(() => iList.Insert(0, 0));
Assert.Throws<NotSupportedException>(() => iList.Clear());
Assert.Throws<NotSupportedException>(() => iList.Remove(2));
Assert.Throws<NotSupportedException>(() => iList.RemoveAt(2));
}
[Fact]
public static void IList_Contains()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
var segment = new ArraySegment<int>(intArray, 2, 3);
IList<int> iList = segment;
for (int i = segment.Offset; i < segment.Count; i++)
{
Assert.True(iList.Contains(intArray[i]));
}
Assert.False(iList.Contains(999)); // No such value
Assert.False(iList.Contains(7)); // No such value in range
}
[Fact]
public static void IList_Contains_NullArray_ThrowsInvalidOperationException()
{
IList<int> iList = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => iList.Contains(0)); // Array is null
}
[Fact]
public static void IList_GetEnumerator()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
IList<int> iList = new ArraySegment<int>(intArray, 2, 3);
IEnumerator<int> enumerator = iList.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(intArray[counter + 2], enumerator.Current);
counter++;
}
Assert.Equal(iList.Count, counter);
enumerator.Reset();
}
}
[Fact]
public static void IList_GetEnumerator_Invalid()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
IList<int> iList = new ArraySegment<int>(intArray, 2, 3);
IEnumerator<int> enumerator = iList.GetEnumerator();
// Enumerator should throw when accessing Current before starting enumeration
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
while (enumerator.MoveNext()) ;
// Enumerator should throw when accessing Current after finishing enumeration
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Enumerator should throw when accessing Current after being reset
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
iList = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => iList.GetEnumerator()); // Underlying array is null
}
[Fact]
public static void IEnumerable_GetEnumerator()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
var segment = new ArraySegment<int>(intArray, 2, 3);
IEnumerable iList = segment;
IEnumerator enumerator = iList.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(intArray[counter + 2], enumerator.Current);
counter++;
}
Assert.Equal(segment.Count, counter);
enumerator.Reset();
}
}
[Fact]
public static void IEnumerable_GetEnumerator_Invalid()
{
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
IEnumerable enumerable = new ArraySegment<int>(intArray, 2, 3);
IEnumerator enumerator = enumerable.GetEnumerator();
// Enumerator should throw when accessing Current before starting enumeration
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
while (enumerator.MoveNext()) ;
// Enumerator should throw when accessing Current after finishing enumeration
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Enumerator should throw when accessing Current after being reset
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerable = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => enumerable.GetEnumerator()); // Underlying array is null
}
[Fact]
public static void IList_CopyTo()
{
var stringArray = new string[] { "0", "1", "2", "3", "4" };
IList<string> stringSegment = new ArraySegment<string>(stringArray, 1, 3);
stringSegment.CopyTo(stringArray, 2);
Assert.Equal(new string[] { "0", "1", "1", "2", "3" }, stringArray);
stringArray = new string[] { "0", "1", "2", "3", "4" };
stringSegment = new ArraySegment<string>(stringArray, 1, 3);
stringSegment.CopyTo(stringArray, 0);
Assert.Equal(new string[] { "1", "2", "3", "3", "4" }, stringArray);
var intArray = new int[] { 0, 1, 2, 3, 4 };
IList<int> intSegment = new ArraySegment<int>(intArray, 1, 3);
intSegment.CopyTo(intArray, 2);
Assert.Equal(new int[] { 0, 1, 1, 2, 3 }, intArray);
intArray = new int[] { 0, 1, 2, 3, 4 };
intSegment = new ArraySegment<int>(intArray, 1, 3);
intSegment.CopyTo(intArray, 0);
Assert.Equal(new int[] { 1, 2, 3, 3, 4 }, intArray);
}
[Fact]
public static void IList_CopyTo_Invalid()
{
IList<int> iList = new ArraySegment<int>();
Assert.Throws<InvalidOperationException>(() => iList.CopyTo(new int[7], 0)); // Array is null
var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
iList = new ArraySegment<int>(intArray, 2, 3);
Assert.Throws<ArgumentNullException>("dest", () => iList.CopyTo(null, 0)); // Destination array is null
Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => iList.CopyTo(new int[7], -1)); // Index < 0
Assert.Throws<ArgumentException>("", () => iList.CopyTo(new int[7], 8)); // Index > destinationArray.Length
}
}
}
| |
/* ====================================================================
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 is1 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.Record
{
using System;
using NPOI.HSSF.Record;
using NUnit.Framework;
using NPOI.HSSF.Record.Cont;
using System.Text;
/**
* Tests that records size calculates correctly.
*
* @author Jason Height (jheight at apache.org)
*/
[TestFixture]
public class TestUnicodeString
{
private static int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE;
/** a 4 character string requiring 16 bit encoding */
private static String STR_16_BIT = "A\u591A\u8A00\u8A9E";
public TestUnicodeString()
{
}
[Test]
public void TestSmallStringSize()
{
//Test a basic string
UnicodeString s = MakeUnicodeString("Test");
ConfirmSize(7, s);
//Test a small string that is uncompressed
s = MakeUnicodeString(STR_16_BIT);
s.OptionFlags = ((byte)0x01);
ConfirmSize(11, s);
//Test a compressed small string that has rich text formatting
s.String = "Test";
s.OptionFlags = ((byte)0x8);
UnicodeString.FormatRun r = new UnicodeString.FormatRun((short)0, (short)1);
s.AddFormatRun(r);
UnicodeString.FormatRun r2 = new UnicodeString.FormatRun((short)2, (short)2);
s.AddFormatRun(r2);
ConfirmSize(17, s);
//Test a uncompressed small string that has rich text formatting
s.String = STR_16_BIT;
s.OptionFlags = ((byte)0x9);
ConfirmSize(21, s);
//Test a compressed small string that has rich text and extended text
s.String = "Test";
s.OptionFlags = ((byte)0xC);
ConfirmSize(17, s);
// Extended phonetics data
// Minimum size is 14
// Also adds 4 bytes to hold the length
s.ExtendedRst=(
new UnicodeString.ExtRst()
);
ConfirmSize(35, s);
//Test a uncompressed small string that has rich text and extended text
s.String = STR_16_BIT;
s.OptionFlags = ((byte)0xD);
ConfirmSize(39, s);
}
[Test]
public void TestPerfectStringSize()
{
//Test a basic string
UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1);
ConfirmSize(MAX_DATA_SIZE, s);
//Test an uncompressed string
//Note that we can only ever Get to a maximim size of 8227 since an uncompressed
//string is1 writing double bytes.
s = MakeUnicodeString((MAX_DATA_SIZE - 2 - 1) / 2,true);
s.OptionFlags = (byte)0x1;
ConfirmSize(MAX_DATA_SIZE - 1, s);
}
[Test]
public void TestPerfectRichStringSize()
{
//Test a rich text string
UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1 - 8 - 2);
s.AddFormatRun(new UnicodeString.FormatRun((short)1, (short)0));
s.AddFormatRun(new UnicodeString.FormatRun((short)2, (short)1));
s.OptionFlags=((byte)0x8);
ConfirmSize(MAX_DATA_SIZE, s);
//Test an uncompressed rich text string
//Note that we can only ever Get to a maximim size of 8227 since an uncompressed
//string is1 writing double bytes.
s = MakeUnicodeString((MAX_DATA_SIZE - 2 - 1 - 8 - 2) / 2,true);
s.AddFormatRun(new UnicodeString.FormatRun((short)1, (short)0));
s.AddFormatRun(new UnicodeString.FormatRun((short)2, (short)1));
s.OptionFlags = ((byte)0x9);
ConfirmSize(MAX_DATA_SIZE - 1, s);
}
[Test]
public void TestContinuedStringSize()
{
UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1 + 20);
ConfirmSize(MAX_DATA_SIZE + 4 + 1 + 20, s);
}
/** Tests that a string size calculation that fits neatly in two records, the second being a continue*/
[Test]
public void TestPerfectContinuedStringSize()
{
//Test a basic string
int strSize = RecordInputStream.MAX_RECORD_DATA_SIZE * 2;
//String overhead
strSize -= 3;
//Continue Record overhead
strSize -= 4;
//Continue Record additional byte overhead
strSize -= 1;
UnicodeString s = MakeUnicodeString(strSize);
ConfirmSize(MAX_DATA_SIZE * 2, s);
}
private static void ConfirmSize(int expectedSize, UnicodeString s)
{
ConfirmSize(expectedSize, s, 0);
}
/**
* Note - a value of zero for <c>amountUsedInCurrentRecord</c> would only ever occur just
* after a {@link ContinueRecord} had been started. In the initial {@link SSTRecord} this
* value starts at 8 (for the first {@link UnicodeString} written). In general, it can be
* any value between 0 and {@link #MAX_DATA_SIZE}
*/
private static void ConfirmSize(int expectedSize, UnicodeString s, int amountUsedInCurrentRecord)
{
ContinuableRecordOutput out1 = ContinuableRecordOutput.CreateForCountingOnly();
out1.WriteContinue();
for (int i = amountUsedInCurrentRecord; i > 0; i--)
{
out1.WriteByte(0);
}
int size0 = out1.TotalSize;
s.Serialize(out1);
int size1 = out1.TotalSize;
int actualSize = size1 - size0;
Assert.AreEqual(expectedSize, actualSize);
}
private static UnicodeString MakeUnicodeString(String s)
{
UnicodeString st = new UnicodeString(s);
st.OptionFlags = ((byte)0);
return st;
}
private static UnicodeString MakeUnicodeString(int numChars)
{
StringBuilder b = new StringBuilder(numChars);
for (int i = 0; i < numChars; i++)
{
b.Append(i % 10);
}
return MakeUnicodeString(b.ToString());
}
/**
* @param is16Bit if <c>true</c> the created string will have characters > 0x00FF
* @return a string of the specified number of characters
*/
private static UnicodeString MakeUnicodeString(int numChars, bool is16Bit)
{
StringBuilder b = new StringBuilder(numChars);
int charBase = is16Bit ? 0x8A00 : 'A';
for (int i = 0; i < numChars; i++)
{
char ch = (char)((i % 16) + charBase);
b.Append(ch);
}
return MakeUnicodeString(b.ToString());
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Gallio.Common.Collections;
using Gallio.Common.Policies;
using Gallio.Runtime.Preferences;
using MbUnit.Framework;
namespace Gallio.Tests.Runtime.Preferences
{
[TestsOn(typeof(FilePreferenceSet))]
public class FilePreferenceSetTest
{
public class TopLevelOperations
{
[Test]
public void Constructor_WhenFileIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => new FilePreferenceSet(null));
}
[Test]
public void Constructor_WhenFileIsValid_InitializesPreferenceSetFile()
{
var file = new FileInfo(@"C:\Foo\Prefs.gallioprefs");
var preferenceSet = new FilePreferenceSet(file);
Assert.AreEqual(file, preferenceSet.PreferenceSetFile);
}
[Test]
public void Read_WhenActionIsNull_Throws()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
Assert.Throws<ArgumentNullException>(() => preferenceSet.Read(null));
}
[Test]
public void Read_WhenFuncIsNull_Throws()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
Assert.Throws<ArgumentNullException>(() => preferenceSet.Read<object>(null));
}
[Test]
public void Write_WhenActionIsNull_Throws()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
Assert.Throws<ArgumentNullException>(() => preferenceSet.Write(null));
}
[Test]
public void Write_WhenFuncIsNull_Throws()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
Assert.Throws<ArgumentNullException>(() => preferenceSet.Write<object>(null));
}
[Test]
public void Read_WithFunc_ReturnsFuncResult()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
int result = preferenceSet.Read(reader => 42);
Assert.AreEqual(42, result);
}
[Test]
public void Write_WithFunc_ReturnsFuncResult()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
int result = preferenceSet.Write(writer => 42);
Assert.AreEqual(42, result);
}
}
public class ReaderOperations
{
[Test]
public void GetSetting_WhenFileDoesNotExist_ReturnsNull()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("name")));
Assert.IsNull(result);
}
[Test]
public void GetSettingWithDefaultValue_WhenFileDoesNotExist_ReturnsDefaultValue()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("name"), "defaultValue"));
Assert.AreEqual("defaultValue", result);
}
[Test]
public void HasSetting_WhenFileDoesNotExist_ReturnsFalse()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
bool result = preferenceSet.Read(reader => reader.HasSetting(new Key<string>("name")));
Assert.IsFalse(result);
}
[Test]
public void GetSetting_WhenFileExistsButNameDoesNot_ReturnsNull()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("otherName")));
Assert.IsNull(result);
}
[Test]
public void GetSettingWithDefaultValue_WhenFileExistsButNameDoesNot_ReturnsDefaultValue()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("otherName"), "defaultValue"));
Assert.AreEqual("defaultValue", result);
}
[Test]
public void HasSetting_WhenFileExistsButNameDoesNot_ReturnsFalse()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
bool result = preferenceSet.Read(reader => reader.HasSetting(new Key<string>("otherName")));
Assert.IsFalse(result);
}
[Test]
public void GetSetting_WhenNameDefined_ReturnsValue()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("name")));
Assert.AreEqual("value", result);
}
[Test]
public void GetSettingWithDefaultValue_WhenNameDefined_ReturnsDefaultValue()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("name"), "defaultValue"));
Assert.AreEqual("value", result);
}
[Test]
public void HasSetting_WhenNameDefined_ReturnsTrue()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
bool result = preferenceSet.Read(reader => reader.HasSetting(new Key<string>("name")));
Assert.IsTrue(result);
}
}
public class WriterOperations
{
[Test]
public void SetSetting_WhenNameAlreadyExistsAndValueIsNonNull_ReplacesIt()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "newValue"));
string result = preferenceSet.Read(reader => reader.GetSetting(new Key<string>("name")));
Assert.AreEqual("newValue", result);
}
[Test]
public void SetSetting_WhenNameAlreadyExistsAndValueIsNull_RemovesIt()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), null));
bool result = preferenceSet.Read(reader => reader.HasSetting(new Key<string>("name")));
Assert.IsFalse(result);
}
[Test]
public void RemoveSetting_WhenNameDoesNotExist_DoesNothing()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.RemoveSetting(new Key<string>("name")));
bool result = preferenceSet.Read(reader => reader.HasSetting(new Key<string>("name")));
Assert.IsFalse(result);
}
[Test]
public void RemoveSetting_WhenNameExists_RemovesIt()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
preferenceSet.Write(writer => writer.RemoveSetting(new Key<string>("name")));
bool result = preferenceSet.Read(reader => reader.HasSetting(new Key<string>("name")));
Assert.IsFalse(result);
}
[Test]
public void SetSetting_WhenDataTypeIsInt_ConvertsItForRoundTrip()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<int>("name"), 42));
int result = preferenceSet.Read(reader => reader.GetSetting(new Key<int>("name")));
Assert.AreEqual(42, result);
}
[Test]
public void SetSetting_WhenDataTypeIsEnum_ConvertsItForRoundTrip()
{
var preferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
preferenceSet.Write(writer => writer.SetSetting(new Key<EnumType>("name"), EnumType.No));
EnumType result = preferenceSet.Read(reader => reader.GetSetting(new Key<EnumType>("name")));
Assert.AreEqual(EnumType.No, result);
}
private enum EnumType
{
Yes, No
}
}
public class Concurrency
{
[Test]
public void ShouldMigrateSettingsAcrossInstancesWhenFileModifiedExternally()
{
var firstPreferenceSet = CreateFilePreferenceSetWithNonExistantTempFile();
var secondPreferenceSet = new FilePreferenceSet(firstPreferenceSet.PreferenceSetFile);
firstPreferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "value"));
Assert.AreEqual("value", secondPreferenceSet.Read(reader => reader.GetSetting(new Key<string>("name"))),
"Setting written to first set should be reflected in second set.");
secondPreferenceSet.Write(writer => writer.SetSetting(new Key<string>("name"), "newValue"));
Assert.AreEqual("newValue", firstPreferenceSet.Read(reader => reader.GetSetting(new Key<string>("name"))),
"Setting written to second set should be reflected in first set.");
}
}
private static FilePreferenceSet CreateFilePreferenceSetWithNonExistantTempFile()
{
DirectoryInfo tempDir = SpecialPathPolicy.For<FilePreferenceSetTest>().GetTempDirectory();
FileInfo tempFile = new FileInfo(Path.Combine(tempDir.FullName, "temp.gallioprefs"));
if (tempFile.Exists)
tempFile.Delete();
return new FilePreferenceSet(tempFile);
}
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
namespace Boo.Lang.Compiler.Steps
{
using System.Diagnostics;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
public class ProcessInheritedAbstractMembers : AbstractVisitorCompilerStep
{
private Boo.Lang.List _newAbstractClasses;
private Boo.Lang.Hash _classDefinitionList;
private int depth = 0;
public ProcessInheritedAbstractMembers()
{
}
override public void Run()
{
_newAbstractClasses = new List();
_classDefinitionList = new Hash();
Visit(CompileUnit.Modules);
_classDefinitionList.Clear();
ProcessNewAbstractClasses();
}
override public void Dispose()
{
_newAbstractClasses = null;
base.Dispose();
}
override public void OnProperty(Property node)
{
if (node.IsAbstract)
{
if (null == node.Type)
{
node.Type = CodeBuilder.CreateTypeReference(TypeSystemServices.ObjectType);
}
}
Visit(node.ExplicitInfo);
}
override public void OnMethod(Method node)
{
if (node.IsAbstract)
{
if (null == node.ReturnType)
{
node.ReturnType = CodeBuilder.CreateTypeReference(TypeSystemServices.VoidType);
}
}
Visit(node.ExplicitInfo);
}
override public void OnExplicitMemberInfo(ExplicitMemberInfo node)
{
TypeMember member = (TypeMember)node.ParentNode;
CheckExplicitMemberValidity((IExplicitMember)member);
member.Visibility = TypeMemberModifiers.Private;
}
void CheckExplicitMemberValidity(IExplicitMember node)
{
IMember explicitMember = (IMember)GetEntity((Node)node);
if (explicitMember.DeclaringType.IsClass)
{
IType targetInterface = GetType(node.ExplicitInfo.InterfaceType);
if (!targetInterface.IsInterface)
{
Error(CompilerErrorFactory.InvalidInterfaceForInterfaceMember((Node)node, node.ExplicitInfo.InterfaceType.Name));
}
if (!explicitMember.DeclaringType.IsSubclassOf(targetInterface))
{
Error(CompilerErrorFactory.InterfaceImplForInvalidInterface((Node)node, targetInterface.Name, ((TypeMember)node).Name));
}
}
else
{
// TODO: Only class ITM's can do explicit interface methods
}
}
override public void LeaveInterfaceDefinition(InterfaceDefinition node)
{
MarkVisited(node);
}
override public void LeaveClassDefinition(ClassDefinition node)
{
MarkVisited(node);
if(!_classDefinitionList.Contains(node.Name))
{
_classDefinitionList.Add(node.Name, node);
}
foreach (TypeReference baseTypeRef in node.BaseTypes)
{
IType baseType = GetType(baseTypeRef);
EnsureRelatedNodeWasVisited(node, baseType);
if (baseType.IsInterface)
{
ResolveInterfaceMembers(node, baseTypeRef, baseType);
}
else
{
if (IsAbstract(baseType))
{
ResolveAbstractMembers(node, baseTypeRef, baseType);
}
}
}
}
/// <summary>
/// This function checks for inheriting implementations from EXTERNAL classes only.
/// </summary>
bool CheckInheritsInterfaceImplementation(ClassDefinition node, IEntity entity)
{
foreach( TypeReference baseTypeRef in node.BaseTypes)
{
IType type = GetType(baseTypeRef);
if( type.IsClass && !type.IsInterface)
{
//TODO: figure out why this freakish incidence happens:
//entity.Name == "CopyTo"
//vs
//entity.Name == "System.ICollection.CopyTo" ... ... ...
//Technically correct, but completely useless.
IEntity inheritedImpl = null;
foreach(IEntity oddjob in type.GetMembers())
{
string[] temp = oddjob.FullName.Split('.');
string actualName = temp[temp.Length - 1];
if( actualName == entity.Name)
{
if (null != inheritedImpl)
{
//Events and their corresponding Delegate Fields can have the same name
//In such cases, we want the Event...
if (inheritedImpl is ExternalEvent && oddjob is ExternalField &&
((ExternalField)oddjob).Type.IsSubclassOf(TypeSystemServices.MulticastDelegateType))
{
continue;
}
}
inheritedImpl = oddjob;
}
}
//inheritedImpl = NameResolutionService.ResolveMember(type, entity.Name, entity.EntityType);
if( null != inheritedImpl)
{
if(inheritedImpl == entity)
{
return false; //Evaluating yourself is a very bad habit.
}
switch( entity.EntityType)
{
case EntityType.Method:
return CheckInheritedMethodImpl(inheritedImpl as IMethod, entity as IMethod);
case EntityType.Event:
return CheckInheritedEventImpl(inheritedImpl as IEvent, entity as IEvent);
case EntityType.Property:
return CheckInheritedPropertyImpl(inheritedImpl as IProperty, entity as IProperty);
}
}
}
}
return false;
}
bool CheckInheritedMethodImpl(IMethod impl, IMethod baseMethod)
{
if (TypeSystemServices.CheckOverrideSignature(impl, baseMethod))
{
IType baseReturnType = TypeSystemServices.GetOverriddenSignature(baseMethod, impl).ReturnType;
if (impl.ReturnType == baseReturnType)
{
return true;
}
//TODO: Oh snap! No reusable error messages for this!
//Errors(CompilerErrorFactory.ConflictWithInheritedMember());
}
return false;
}
bool CheckInheritedEventImpl(IEvent impl, IEvent target)
{
return impl.Type == target.Type;
}
bool CheckInheritedPropertyImpl(IProperty impl, IProperty target)
{
if(impl.Type == target.Type)
{
if(TypeSystemServices.CheckOverrideSignature(impl.GetParameters(), target.GetParameters()))
{
if(HasGetter(target))
{
if(!HasGetter(impl))
{
return false;
}
}
if(HasSetter(target))
{
if(!HasSetter(impl))
{
return false;
}
}
/* Unnecessary?
if(impl.IsPublic != target.IsPublic ||
impl.IsProtected != target.IsProtected ||
impl.IsPrivate != target.IsPrivate)
{
return false;
}*/
return true;
}
}
return false;
}
private static bool HasGetter(IProperty property)
{
return property.GetGetMethod() != null;
}
private static bool HasSetter(IProperty property)
{
return property.GetSetMethod() != null;
}
private bool IsAbstract(IType type)
{
if (type.IsAbstract)
{
return true;
}
AbstractInternalType internalType = type as AbstractInternalType;
if (null != internalType)
{
return _newAbstractClasses.Contains(internalType.TypeDefinition);
}
return false;
}
void ResolveAbstractProperty(ClassDefinition node,
TypeReference baseTypeRef,
IProperty baseProperty)
{
foreach (Property p in GetAbstractPropertyImplementationCandidates(node, baseProperty))
{
if (!TypeSystemServices.CheckOverrideSignature(GetEntity(p).GetParameters(), baseProperty.GetParameters()))
{
continue;
}
ProcessPropertyAccessor(p, p.Getter, baseProperty.GetGetMethod());
ProcessPropertyAccessor(p, p.Setter, baseProperty.GetSetMethod());
if (null == p.Type)
{
p.Type = CodeBuilder.CreateTypeReference(baseProperty.Type);
}
else
{
if (baseProperty.Type != p.Type.Entity)
Error(CompilerErrorFactory.ConflictWithInheritedMember(p, p.FullName, baseProperty.FullName));
}
return;
}
foreach(SimpleTypeReference parent in node.BaseTypes)
{
if(_classDefinitionList.Contains(parent.Name))
{
depth++;
ResolveAbstractProperty(_classDefinitionList[parent.Name] as ClassDefinition, baseTypeRef, baseProperty);
depth--;
}
}
if(CheckInheritsInterfaceImplementation(node, baseProperty))
return;
if(depth == 0)
{
node.Members.Add(CreateAbstractProperty(baseTypeRef, baseProperty));
AbstractMemberNotImplemented(node, baseTypeRef, baseProperty);
}
}
private static void ProcessPropertyAccessor(Property p, Method accessor, IMethod method)
{
if (null != accessor)
{
accessor.Modifiers |= TypeMemberModifiers.Virtual;
if (null != p.ExplicitInfo)
{
accessor.ExplicitInfo = p.ExplicitInfo.CloneNode();
accessor.ExplicitInfo.Entity = method;
accessor.Visibility = TypeMemberModifiers.Private;
}
}
}
Property CreateAbstractProperty(TypeReference reference, IProperty property)
{
Debug.Assert(0 == property.GetParameters().Length);
Property p = CodeBuilder.CreateProperty(property.Name, property.Type);
p.Modifiers |= TypeMemberModifiers.Abstract;
IMethod getter = property.GetGetMethod();
if (getter != null)
{
p.Getter = CodeBuilder.CreateAbstractMethod(reference.LexicalInfo, getter);
}
IMethod setter = property.GetSetMethod();
if (setter != null)
{
p.Setter = CodeBuilder.CreateAbstractMethod(reference.LexicalInfo, setter);
}
return p;
}
void ResolveAbstractEvent(ClassDefinition node,
TypeReference baseTypeRef,
IEvent entity)
{
// FIXME: this will produce an internal compiler error if the class implements
// a non-event member by the same name
TypeMember member = node.Members[entity.Name];
if (null != member)
{
Event ev = (Event)member;
Method add = ev.Add;
if (add != null)
{
add.Modifiers |= TypeMemberModifiers.Final | TypeMemberModifiers.Virtual;
}
Method remove = ev.Remove;
if (remove != null)
{
remove.Modifiers |= TypeMemberModifiers.Final | TypeMemberModifiers.Virtual;
}
Method raise = ev.Remove;
if (raise != null)
{
raise.Modifiers |= TypeMemberModifiers.Final | TypeMemberModifiers.Virtual;
}
_context.TraceInfo("{0}: Event {1} implements {2}", ev.LexicalInfo, ev, entity);
return;
}
if(CheckInheritsInterfaceImplementation(node, entity))
{
return;
}
foreach(SimpleTypeReference parent in node.BaseTypes)
{
if(_classDefinitionList.Contains(parent.Name))
{
depth++;
ResolveAbstractEvent(_classDefinitionList[parent.Name] as ClassDefinition, baseTypeRef, entity);
depth--;
}
}
if(depth == 0)
{
node.Members.Add(CodeBuilder.CreateAbstractEvent(baseTypeRef.LexicalInfo, entity));
AbstractMemberNotImplemented(node, baseTypeRef, entity);
}
}
void ResolveAbstractMethod(ClassDefinition node,
TypeReference baseTypeRef,
IMethod baseMethod)
{
if (baseMethod.IsSpecialName)
return;
foreach (Method method in GetAbstractMethodImplementationCandidates(node, baseMethod))
{
IMethod methodEntity = GetEntity(method);
if (!TypeSystemServices.CheckOverrideSignature(methodEntity, baseMethod))
{
continue;
}
CallableSignature baseSignature = TypeSystemServices.GetOverriddenSignature(baseMethod, methodEntity);
if (IsUnknown(method.ReturnType))
{
method.ReturnType = CodeBuilder.CreateTypeReference(baseSignature.ReturnType);
}
else if (baseSignature.ReturnType != method.ReturnType.Entity)
{
Error(CompilerErrorFactory.ConflictWithInheritedMember(method, method.FullName, baseMethod.FullName));
}
if (null != method.ExplicitInfo)
method.ExplicitInfo.Entity = baseMethod;
if (!method.IsOverride && !method.IsVirtual)
method.Modifiers |= TypeMemberModifiers.Virtual;
_context.TraceInfo("{0}: Method {1} implements {2}", method.LexicalInfo, method, baseMethod);
return;
}
// FIXME: this will fail with InvalidCastException on a base type that's a GenericTypeReference!
foreach(SimpleTypeReference parent in node.BaseTypes)
{
if(_classDefinitionList.Contains(parent.Name))
{
depth++;
ResolveAbstractMethod(_classDefinitionList[parent.Name] as ClassDefinition, baseTypeRef, baseMethod);
depth--;
}
}
if(CheckInheritsInterfaceImplementation(node, baseMethod))
return;
if(depth == 0)
{
if (!AbstractMemberNotImplemented(node, baseTypeRef, baseMethod))
{
//BEHAVIOR < 0.7.7: no stub, mark class as abstract
node.Members.Add(CodeBuilder.CreateAbstractMethod(baseTypeRef.LexicalInfo, baseMethod));
}
}
}
private IEnumerable<Method> GetAbstractMethodImplementationCandidates(TypeDefinition node, IMethod baseMethod)
{
return GetAbstractMemberImplementationCandidates<Method, IMethod>(node, baseMethod);
}
private IEnumerable<Property> GetAbstractPropertyImplementationCandidates(TypeDefinition node, IProperty baseProperty)
{
return GetAbstractMemberImplementationCandidates<Property, IProperty>(node, baseProperty);
}
private IEnumerable<TMember> GetAbstractMemberImplementationCandidates<TMember, TEntity>(
TypeDefinition node, TEntity baseEntity)
where TEntity : IEntityWithParameters, IMember
where TMember : TypeMember, IExplicitMember
{
List<TMember> candidates = new List<TMember>();
foreach (TypeMember m in node.Members)
{
TMember member = m as TMember;
if (member != null &&
member.Name == baseEntity.Name &&
IsCorrectExplicitMemberImplOrNoExplicitMemberAtAll(member, baseEntity))
{
candidates.Add(member);
}
}
// BOO-1031: Move explicitly implemented candidates to top of list so that
// they're used for resolution before non-explicit ones, if possible.
// HACK: using IComparer<T> instead of Comparison<T> to workaround
// mono bug #399214.
candidates.Sort(new ExplicitMembersFirstComparer<TMember>());
return candidates;
}
private class ExplicitMembersFirstComparer<T> : IComparer<T>
where T : IExplicitMember
{
public int Compare(T lhs, T rhs)
{
if (lhs.ExplicitInfo != null && rhs.ExplicitInfo == null) return -1;
if (lhs.ExplicitInfo == null && rhs.ExplicitInfo != null) return 1;
return 0;
}
}
private bool IsCorrectExplicitMemberImplOrNoExplicitMemberAtAll(TypeMember member, IMember entity)
{
ExplicitMemberInfo info = ((IExplicitMember)member).ExplicitInfo;
return info == null
|| entity.DeclaringType == GetType(info.InterfaceType);
}
private static bool IsUnknown(TypeReference typeRef)
{
return Unknown.Default == typeRef.Entity;
}
//returns true if a stub has been created, false otherwise.
//TODO: add entity argument to the method to not need return type?
bool AbstractMemberNotImplemented(ClassDefinition node, TypeReference baseTypeRef, IMember member)
{
if (IsValueType(node))
{
Error(CompilerErrorFactory.ValueTypeCantHaveAbstractMember(baseTypeRef, node.FullName, GetAbstractMemberSignature(member)));
return false;
}
if (!node.IsAbstract)
{
//BEHAVIOR >= 0.7.7: (see BOO-789 for details)
//create a stub for this not implemented member
//it will raise a NotImplementedException if called at runtime
TypeMember m = CodeBuilder.CreateStub(member);
CompilerWarning warning = null;
if (null != m)
{
warning = CompilerWarningFactory.AbstractMemberNotImplementedStubCreated(baseTypeRef,
node.FullName, GetAbstractMemberSignature(member));
node.Members.Add(m);
}
else
{
warning = CompilerWarningFactory.AbstractMemberNotImplemented(baseTypeRef,
node.FullName, GetAbstractMemberSignature(member));
_newAbstractClasses.AddUnique(node);
}
Warnings.Add(warning);
return (null != m);
}
return false;
}
private static bool IsValueType(ClassDefinition node)
{
return ((IType)node.Entity).IsValueType;
}
private string GetAbstractMemberSignature(IMember member)
{
IMethod method = member as IMethod;
return method != null
? TypeSystemServices.GetSignature(method)
: member.FullName;
}
void ResolveInterfaceMembers(ClassDefinition node,
TypeReference baseTypeRef,
IType baseType)
{
foreach (IType entity in baseType.GetInterfaces())
{
ResolveInterfaceMembers(node, baseTypeRef, entity);
}
foreach (IMember entity in baseType.GetMembers())
{
ResolveAbstractMember(node, baseTypeRef, entity);
}
}
void ResolveAbstractMembers(ClassDefinition node,
TypeReference baseTypeRef,
IType baseType)
{
foreach (IEntity member in baseType.GetMembers())
{
switch (member.EntityType)
{
case EntityType.Method:
{
IMethod method = (IMethod)member;
if (method.IsAbstract)
{
ResolveAbstractMethod(node, baseTypeRef, method);
}
break;
}
case EntityType.Property:
{
IProperty property = (IProperty)member;
if (IsAbstractAccessor(property.GetGetMethod()) ||
IsAbstractAccessor(property.GetSetMethod()))
{
ResolveAbstractProperty(node, baseTypeRef, property);
}
break;
}
case EntityType.Event:
{
IEvent ev = (IEvent)member;
if (ev.IsAbstract)
{
ResolveAbstractEvent(node, baseTypeRef, ev);
}
break;
}
}
}
}
private static bool IsAbstractAccessor(IMethod accessor)
{
if (null != accessor)
{
return accessor.IsAbstract;
}
return false;
}
void ResolveAbstractMember(ClassDefinition node,
TypeReference baseTypeRef,
IMember member)
{
switch (member.EntityType)
{
case EntityType.Method:
{
ResolveAbstractMethod(node, baseTypeRef, (IMethod)member);
break;
}
case EntityType.Property:
{
ResolveAbstractProperty(node, baseTypeRef, (IProperty)member);
break;
}
case EntityType.Event:
{
ResolveAbstractEvent(node, baseTypeRef, (IEvent)member);
break;
}
default:
{
NotImplemented(baseTypeRef, "abstract member: " + member);
break;
}
}
}
void ProcessNewAbstractClasses()
{
foreach (ClassDefinition node in _newAbstractClasses)
{
node.Modifiers |= TypeMemberModifiers.Abstract;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
namespace fyiReporting.RDL
{
///<summary>
/// A collection of rows.
///</summary>
internal class Rows : System.Collections.Generic.IComparer<Row>, IDisposable
{
List<Row> _Data; // array of Row object;
List<RowsSortExpression> _SortBy; // array of expressions used to sort the data
GroupEntry[] _CurrentGroups; // group
Report _Rpt;
internal Rows(Report rpt)
{
_Rpt = rpt;
_SortBy = null;
_CurrentGroups = null;
}
// Constructor that takes existing Rows; a start, end and bitArray with the rows wanted
internal Rows(Report rpt, Rows r, int start, int end, BitArray ba)
{
_Rpt = rpt;
_SortBy = null;
_CurrentGroups = null;
if (end - start < 0) // null set?
{
_Data = new List<Row>(1);
_Data.TrimExcess();
return;
}
_Data = new List<Row>(end - start + 1);
for (int iRow = start; iRow <= end; iRow++)
{
if (ba == null || ba.Get(iRow))
{
Row or = r.Data[iRow];
Row nr = new Row(this, or);
nr.RowNumber = or.RowNumber;
_Data.Add(nr);
}
}
_Data.TrimExcess();
}
// Constructor that takes existing Rows
internal Rows(Report rpt, Rows r)
{
_Rpt = rpt;
_SortBy = null;
_CurrentGroups = null;
if (r.Data == null || r.Data.Count <= 0) // null set?
{
_Data = new List<Row>(1);
_Data.TrimExcess();
return;
}
_Data = new List<Row>(r.Data.Count);
for (int iRow = 0; iRow < r.Data.Count; iRow++)
{
Row or = r.Data[iRow];
Row nr = new Row(this, or);
nr.RowNumber = or.RowNumber;
_Data.Add(nr);
}
_Data.TrimExcess();
}
// Constructor that creates exactly one row and one column
static internal Rows CreateOneRow(Report rpt)
{
Rows or = new Rows(rpt);
or._Data = new List<Row>(1);
Row nr = new Row(or, 1);
nr.RowNumber = 0;
or._Data.Add(nr);
or._Data.TrimExcess();
return or;
}
internal Rows(Report rpt, TableGroups tg, Grouping g, Sorting s)
{
_Rpt = rpt;
_SortBy = new List<RowsSortExpression>();
// Pull all the sort expression together
if (tg != null)
{
foreach(TableGroup t in tg.Items)
{
foreach(GroupExpression ge in t.Grouping.GroupExpressions.Items)
{
_SortBy.Add(new RowsSortExpression(ge.Expression));
}
// TODO what to do with the sort expressions!!!!
}
}
if (g != null)
{
if (g.ParentGroup != null)
_SortBy.Add(new RowsSortExpression(g.ParentGroup));
else if (g.GroupExpressions != null)
{
foreach (GroupExpression ge in g.GroupExpressions.Items)
{
_SortBy.Add(new RowsSortExpression(ge.Expression));
}
}
}
if (s != null)
{
foreach (SortBy sb in s.Items)
{
_SortBy.Add(new RowsSortExpression(sb.SortExpression, sb.Direction == SortDirectionEnum.Ascending));
}
}
if (_SortBy.Count > 0)
{
_SortBy.TrimExcess();
}
else
{
_SortBy = null;
}
}
internal Report Report
{
get {return this._Rpt;}
}
internal void Sort()
{
// sort the data array by the data.
_Data.Sort(this);
}
internal List<Row> Data
{
get { return _Data; }
set
{
_Data = value; // Assign the new value
foreach(Row r in _Data) // Updata all rows
{
r.R = this;
}
}
}
internal List<RowsSortExpression> SortBy
{
get { return _SortBy; }
set { _SortBy = value; }
}
internal GroupEntry[] CurrentGroups
{
get { return _CurrentGroups; }
set { _CurrentGroups = value; }
}
#region IComparer Members
public int Compare(Row r1, Row r2)
{
if (r1 == r2) // why does the sort routine do this??
return 0;
object o1=null,o2=null;
TypeCode tc = TypeCode.Object;
int rc;
try
{
foreach (RowsSortExpression se in _SortBy)
{
o1 = se.expr.Evaluate(this._Rpt, r1);
o2 = se.expr.Evaluate(this._Rpt, r2);
tc = se.expr.GetTypeCode();
rc = Filter.ApplyCompare(tc, o1, o2);
if (rc != 0)
return se.bAscending? rc: -rc;
}
}
catch (Exception e) // this really shouldn't happen
{
_Rpt.rl.LogError(8,
string.Format("Sort rows exception\r\nArguments: {0} {1}\r\nTypecode: {2}\r\n{3}\r\n{4}",
o1, o2, tc.ToString(), e.Message, e.StackTrace));
}
return r1.RowNumber - r2.RowNumber; // in case of tie use original row number
}
#endregion
public void Dispose()
{
_Data.Clear();
}
}
class RowsSortExpression
{
internal Expression expr;
internal bool bAscending;
internal RowsSortExpression(Expression e, bool asc)
{
expr = e;
bAscending = asc;
}
internal RowsSortExpression(Expression e)
{
expr = e;
bAscending = true;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
/// Represents all of the outstanding progress activities received by the host, and includes methods to update that state
/// upon receipt of new ProgressRecords, and to render that state into an array of strings such that ProgressPane can
/// display it.
///
/// The set of activities that we're tracking is logically a binary tree, with siblings in one branch and children in
/// another. For ease of implementation, this tree is represented as lists of lists. We use ArrayList as out list type,
/// although List1 (generic List) would also have worked. I suspect that ArrayList is faster because there are fewer links
/// to twiddle, though I have not measured that.
///
/// This class uses lots of nearly identical helper functions to recursively traverse the tree. If I weren't so pressed
/// for time, I would see if generic methods could be used to collapse the number of traversers.
/// </summary>
internal
class PendingProgress
{
#region Updating Code
/// <summary>
/// Update the data structures that represent the outstanding progress records reported so far.
/// </summary>
/// <param name="sourceId">
/// Identifier of the source of the event. This is used as part of the "key" for matching newly received records with
/// records that have already been received. For a record to match (meaning that they refer to the same activity), both
/// the source and activity identifiers need to match.
/// </param>
/// <param name="record">
/// The ProgressRecord received that will either update the status of an activity which we are already tracking, or
/// represent a new activity that we need to track.
/// </param>
internal
void
Update(long sourceId, ProgressRecord record)
{
Dbg.Assert(record != null, "record should not be null");
do
{
if (record.ParentActivityId == record.ActivityId)
{
// ignore malformed records.
break;
}
ArrayList listWhereFound = null;
int indexWhereFound = -1;
ProgressNode foundNode =
FindNodeById(sourceId, record.ActivityId, out listWhereFound, out indexWhereFound);
if (foundNode != null)
{
Dbg.Assert(listWhereFound != null, "node found, but list not identified");
Dbg.Assert(indexWhereFound >= 0, "node found, but index not returned");
if (record.RecordType == ProgressRecordType.Completed)
{
RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound);
break;
}
if (record.ParentActivityId == foundNode.ParentActivityId)
{
// record is an update to an existing activity. Copy the record data into the found node, and
// reset the age of the node.
foundNode.Activity = record.Activity;
foundNode.StatusDescription = record.StatusDescription;
foundNode.CurrentOperation = record.CurrentOperation;
foundNode.PercentComplete = Math.Min(record.PercentComplete, 100);
foundNode.SecondsRemaining = record.SecondsRemaining;
foundNode.Age = 0;
break;
}
else
{
// The record's parent Id mismatches with that of the found node's. We interpret
// this to mean that the activity represented by the record (and the found node) is
// being "re-parented" elsewhere. So we remove the found node and treat the record
// as a new activity.
RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound);
}
}
// At this point, the record's activity is not in the tree. So we need to add it.
if (record.RecordType == ProgressRecordType.Completed)
{
// We don't track completion records that don't correspond to activities we're not
// already tracking.
break;
}
ProgressNode newNode = new ProgressNode(sourceId, record);
// If we're adding a node, and we have no more space, then we need to pick a node to evict.
while (_nodeCount >= maxNodeCount)
{
EvictNode();
}
if (newNode.ParentActivityId >= 0)
{
ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId);
if (parentNode != null)
{
if (parentNode.Children == null)
{
parentNode.Children = new ArrayList();
}
AddNode(parentNode.Children, newNode);
break;
}
// The parent node is not in the tree. Make the new node's parent the root,
// and add it to the tree. If the parent ever shows up, then the next time
// we receive a record for this activity, the parent id's won't match, and the
// activity will be properly re-parented.
newNode.ParentActivityId = -1;
}
AddNode(_topLevelNodes, newNode);
} while (false);
// At this point the tree is up-to-date. Make a pass to age all of the nodes
AgeNodesAndResetStyle();
}
private
void
EvictNode()
{
ArrayList listWhereFound = null;
int indexWhereFound = -1;
ProgressNode oldestNode = FindOldestLeafmostNode(out listWhereFound, out indexWhereFound);
if (oldestNode == null)
{
// Well that's a surprise. There's got to be at least one node there that's older than 0.
Dbg.Assert(false, "Must be an old node in the tree somewhere");
// We'll just pick the root node, then.
RemoveNode(_topLevelNodes, 0);
}
else
{
RemoveNode(listWhereFound, indexWhereFound);
}
}
/// <summary>
/// Removes a node from the tree.
/// </summary>
/// <param name="nodes">
/// List in the tree from which the node is to be removed.
/// </param>
/// <param name="indexToRemove">
/// Index into the list of the node to be removed.
/// </param>
private
void
RemoveNode(ArrayList nodes, int indexToRemove)
{
#if DEBUG || ASSERTIONS_TRACE
ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove];
Dbg.Assert(nodes != null, "can't remove nodes from a null list");
Dbg.Assert(indexToRemove < nodes.Count, "index is not in list");
Dbg.Assert(nodes[indexToRemove] != null, "no node at specified index");
Dbg.Assert(nodeToRemove.Children == null || nodeToRemove.Children.Count == 0, "can't remove a node with children");
#endif
nodes.RemoveAt(indexToRemove);
--_nodeCount;
#if DEBUG || ASSERTIONS_ON
Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree");
#endif
}
private
void
RemoveNodeAndPromoteChildren(ArrayList nodes, int indexToRemove)
{
ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove];
Dbg.Assert(nodes != null, "can't remove nodes from a null list");
Dbg.Assert(indexToRemove < nodes.Count, "index is not in list");
Dbg.Assert(nodeToRemove != null, "no node at specified index");
if (nodeToRemove == null)
{
return;
}
if (nodeToRemove.Children != null)
{
// promote the children.
for (int i = 0; i < nodeToRemove.Children.Count; ++i)
{
// unparent the children. If the children are ever updated again, they will be reparented.
((ProgressNode)nodeToRemove.Children[i]).ParentActivityId = -1;
}
// add the children as siblings
nodes.RemoveAt(indexToRemove);
--_nodeCount;
nodes.InsertRange(indexToRemove, nodeToRemove.Children);
#if DEBUG || ASSERTIONS_TRACE
Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree");
#endif
}
else
{
// nothing to promote
RemoveNode(nodes, indexToRemove);
return;
}
}
/// <summary>
/// Adds a node to the tree, first removing the oldest node if the tree is too large.
/// </summary>
/// <param name="nodes">
/// List in the tree where the node is to be added.
/// </param>
/// <param name="nodeToAdd">
/// Node to be added.
/// </param>
private
void
AddNode(ArrayList nodes, ProgressNode nodeToAdd)
{
nodes.Add(nodeToAdd);
++_nodeCount;
#if DEBUG || ASSERTIONS_TRACE
Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree");
Dbg.Assert(_nodeCount <= maxNodeCount, "Too many nodes in tree!");
#endif
}
private sealed class FindOldestNodeVisitor : NodeVisitor
{
internal override
bool
Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound)
{
if (node.Age >= _oldestSoFar)
{
_oldestSoFar = node.Age;
FoundNode = node;
this.ListWhereFound = listWhereFound;
this.IndexWhereFound = indexWhereFound;
}
return true;
}
internal
ProgressNode
FoundNode;
internal
ArrayList
ListWhereFound;
internal
int
IndexWhereFound = -1;
private int _oldestSoFar;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"CA1822:Mark members as static",
Justification = "Accesses instance members in preprocessor branch.")]
private
ProgressNode
FindOldestLeafmostNodeHelper(ArrayList treeToSearch, out ArrayList listWhereFound, out int indexWhereFound)
{
listWhereFound = null;
indexWhereFound = -1;
FindOldestNodeVisitor v = new FindOldestNodeVisitor();
NodeVisitor.VisitNodes(treeToSearch, v);
listWhereFound = v.ListWhereFound;
indexWhereFound = v.IndexWhereFound;
#if DEBUG || ASSERTIONS_TRACE
if (v.FoundNode == null)
{
Dbg.Assert(listWhereFound == null, "list should be null when no node found");
Dbg.Assert(indexWhereFound == -1, "index should indicate no node found");
Dbg.Assert(_topLevelNodes.Count == 0, "if there is no oldest node, then the tree must be empty");
Dbg.Assert(_nodeCount == 0, "if there is no oldest node, then the tree must be empty");
}
#endif
return v.FoundNode;
}
private
ProgressNode
FindOldestLeafmostNode(out ArrayList listWhereFound, out int indexWhereFound)
{
listWhereFound = null;
indexWhereFound = -1;
ProgressNode result = null;
ArrayList treeToSearch = _topLevelNodes;
while (true)
{
result = FindOldestLeafmostNodeHelper(treeToSearch, out listWhereFound, out indexWhereFound);
if (result == null || result.Children == null || result.Children.Count == 0)
{
break;
}
// search the subtree for the oldest child
treeToSearch = result.Children;
}
return result;
}
/// <summary>
/// Convenience overload.
/// </summary>
private
ProgressNode
FindNodeById(long sourceId, int activityId)
{
ArrayList listWhereFound = null;
int indexWhereFound = -1;
return
FindNodeById(sourceId, activityId, out listWhereFound, out indexWhereFound);
}
private sealed class FindByIdNodeVisitor : NodeVisitor
{
internal
FindByIdNodeVisitor(long sourceIdToFind, int activityIdToFind)
{
_sourceIdToFind = sourceIdToFind;
_idToFind = activityIdToFind;
}
internal override
bool
Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound)
{
if (node.ActivityId == _idToFind && node.SourceId == _sourceIdToFind)
{
this.FoundNode = node;
this.ListWhereFound = listWhereFound;
this.IndexWhereFound = indexWhereFound;
return false;
}
return true;
}
internal
ProgressNode
FoundNode;
internal
ArrayList
ListWhereFound;
internal
int
IndexWhereFound = -1;
private readonly int _idToFind = -1;
private readonly long _sourceIdToFind;
}
/// <summary>
/// Finds a node with a given ActivityId in provided set of nodes. Recursively walks the set of nodes and their children.
/// </summary>
/// <param name="sourceId">
/// Identifier of the source of the record.
/// </param>
/// <param name="activityId">
/// ActivityId to search for.
/// </param>
/// <param name="listWhereFound">
/// Receives reference to the List where the found node was located, or null if no suitable node was found.
/// </param>
/// <param name="indexWhereFound">
/// Receives the index into listWhereFound that indicating where in the list the node was located, or -1 if
/// no suitable node was found.
/// </param>
/// <returns>
/// The found node, or null if no suitable node was located.
/// </returns>
private
ProgressNode
FindNodeById(long sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound)
{
listWhereFound = null;
indexWhereFound = -1;
FindByIdNodeVisitor v = new FindByIdNodeVisitor(sourceId, activityId);
NodeVisitor.VisitNodes(_topLevelNodes, v);
listWhereFound = v.ListWhereFound;
indexWhereFound = v.IndexWhereFound;
#if DEBUG || ASSERTIONS_TRACE
if (v.FoundNode == null)
{
Dbg.Assert(listWhereFound == null, "list should be null when no node found");
Dbg.Assert(indexWhereFound == -1, "index should indicate no node found");
}
#endif
return v.FoundNode;
}
/// <summary>
/// Finds the oldest node with a given rendering style that is at least as old as a given age.
/// </summary>
/// <param name="nodes">
/// List of nodes to search. Child lists of each node in this list will also be searched.
/// </param>
/// <param name="oldestSoFar"></param>
/// The minimum age of the node to be located. To find the oldest node, pass 0.
/// <param name="style">
/// The rendering style of the node to be located.
/// </param>
/// <returns>
/// The found node, or null if no suitable node was located.
/// </returns>
private
ProgressNode
FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style)
{
if (nodes == null)
{
return null;
}
ProgressNode found = null;
for (int i = 0; i < nodes.Count; ++i)
{
ProgressNode node = (ProgressNode)nodes[i];
Dbg.Assert(node != null, "nodes should not contain null elements");
if (node.Age >= oldestSoFar && node.Style == style)
{
found = node;
oldestSoFar = found.Age;
}
if (node.Children != null)
{
ProgressNode child = FindOldestNodeOfGivenStyle(node.Children, oldestSoFar, style);
if (child != null)
{
// In this universe, parents can be younger than their children. We found a child older than us.
found = child;
oldestSoFar = found.Age;
}
}
}
#if DEBUG || ASSERTIONS_TRACE
if (found != null)
{
Dbg.Assert(found.Style == style, "unexpected style");
Dbg.Assert(found.Age >= oldestSoFar, "unexpected age");
}
#endif
return found;
}
private sealed class AgeAndResetStyleVisitor : NodeVisitor
{
internal override
bool
Visit(ProgressNode node, ArrayList unused, int unusedToo)
{
node.Age = Math.Min(node.Age + 1, Int32.MaxValue - 1);
node.Style = ProgressNode.IsMinimalProgressRenderingEnabled()
? ProgressNode.RenderStyle.Ansi
: node.Style = ProgressNode.RenderStyle.FullPlus;
return true;
}
}
/// <summary>
/// Increments the age of each of the nodes in the given list, and all their children. Also sets the rendering
/// style of each node to "full."
///
/// All nodes are aged every time a new ProgressRecord is received.
/// </summary>
private
void
AgeNodesAndResetStyle()
{
AgeAndResetStyleVisitor arsv = new AgeAndResetStyleVisitor();
NodeVisitor.VisitNodes(_topLevelNodes, arsv);
}
#endregion // Updating Code
#region Rendering Code
/// <summary>
/// Generates an array of strings representing as much of the outstanding progress activities as possible within the given
/// space. As more outstanding activities are collected, nodes are "compressed" (i.e. rendered in an increasing terse
/// fashion) in order to display as many as possible. Ultimately, some nodes may be compressed to the point of
/// invisibility. The oldest nodes are compressed first.
/// </summary>
/// <param name="maxWidth">
/// The maximum width (in BufferCells) that the rendering may consume.
/// </param>
/// <param name="maxHeight">
/// The maximum height (in BufferCells) that the rendering may consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
/// <returns>
/// An array of strings containing the textual representation of the outstanding progress activities.
/// </returns>
internal
string[]
Render(int maxWidth, int maxHeight, PSHostRawUserInterface rawUI)
{
Dbg.Assert(_topLevelNodes != null, "Shouldn't need to render progress if no data exists");
Dbg.Assert(maxWidth > 0, "maxWidth is too small");
Dbg.Assert(maxHeight >= 3, "maxHeight is too small");
if (_topLevelNodes == null || _topLevelNodes.Count <= 0)
{
// we have nothing to render.
return null;
}
int invisible = 0;
if (TallyHeight(rawUI, maxHeight, maxWidth) > maxHeight)
{
// This will smash down nodes until the tree will fit into the alloted number of lines. If in the
// process some nodes were made invisible, we will add a line to the display to say so.
invisible = CompressToFit(rawUI, maxHeight, maxWidth);
}
ArrayList result = new ArrayList();
if (ProgressNode.IsMinimalProgressRenderingEnabled())
{
RenderHelper(result, _topLevelNodes, indentation: 0, maxWidth, rawUI);
return (string[])result.ToArray(typeof(string));
}
string border = StringUtil.Padding(maxWidth);
result.Add(border);
RenderHelper(result, _topLevelNodes, 0, maxWidth, rawUI);
if (invisible == 1)
{
result.Add(
" "
+ StringUtil.Format(
ProgressNodeStrings.InvisibleNodesMessageSingular,
invisible));
}
else if (invisible > 1)
{
result.Add(
" "
+ StringUtil.Format(
ProgressNodeStrings.InvisibleNodesMessagePlural,
invisible));
}
result.Add(border);
return (string[])result.ToArray(typeof(string));
}
/// <summary>
/// Helper function for Render(). Recursively renders nodes.
/// </summary>
/// <param name="strings">
/// The rendered strings so far. Additional rendering will be appended.
/// </param>
/// <param name="nodes">
/// The nodes to be rendered. All child nodes will also be rendered.
/// </param>
/// <param name="indentation">
/// The current indentation level (in BufferCells).
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering can consume, horizontally.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
private
void
RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
Dbg.Assert(strings != null, "strings should not be null");
Dbg.Assert(nodes != null, "nodes should not be null");
if (nodes == null)
{
return;
}
foreach (ProgressNode node in nodes)
{
int lines = strings.Count;
node.Render(strings, indentation, maxWidth, rawUI);
if (node.Children != null)
{
// indent only if the rendering of node actually added lines to the strings.
int indentationIncrement = (strings.Count > lines) ? 2 : 0;
RenderHelper(strings, node.Children, indentation + indentationIncrement, maxWidth, rawUI);
}
}
}
private sealed class HeightTallyer : NodeVisitor
{
internal HeightTallyer(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
{
_rawUi = rawUi;
_maxHeight = maxHeight;
_maxWidth = maxWidth;
}
internal override
bool
Visit(ProgressNode node, ArrayList unused, int unusedToo)
{
Tally += node.LinesRequiredMethod(_rawUi, _maxWidth);
// We don't need to walk all the nodes, once it's larger than the max height, we should stop
if (Tally > _maxHeight)
{
return false;
}
return true;
}
private readonly PSHostRawUserInterface _rawUi;
private readonly int _maxHeight;
private readonly int _maxWidth;
internal int Tally;
}
/// <summary>
/// Tallies up the number of BufferCells vertically that will be required to show all the ProgressNodes in the given
/// list, and all of their children.
/// </summary>
/// <param name="maxHeight">
/// The maximum height (in BufferCells) that the rendering may consume.
/// </param>
/// <param name="rawUi">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
/// <returns>
/// The vertical height (in BufferCells) that will be required to show all of the nodes in the given list.
/// </returns>
/// <param name="maxWidth">
/// </param>
private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
{
HeightTallyer ht = new HeightTallyer(rawUi, maxHeight, maxWidth);
NodeVisitor.VisitNodes(_topLevelNodes, ht);
return ht.Tally;
}
#if DEBUG || ASSERTIONS_TRACE
/// <summary>
/// Debugging code. Verifies that all of the nodes in the given list have the given style.
/// </summary>
/// <param name="nodes"></param>
/// <param name="style"></param>
/// <returns></returns>
private
bool
AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style)
{
if (nodes == null)
{
return false;
}
for (int i = 0; i < nodes.Count; ++i)
{
ProgressNode node = (ProgressNode)nodes[i];
Dbg.Assert(node != null, "nodes should not contain null elements");
if (node.Style != style)
{
return false;
}
if (node.Children != null)
{
if (!AllNodesHaveGivenStyle(node.Children, style))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Debugging code. NodeVisitor that counts up the number of nodes in the tree.
/// </summary>
private
class
CountingNodeVisitor : NodeVisitor
{
internal override
bool
Visit(ProgressNode unused, ArrayList unusedToo, int unusedThree)
{
++Count;
return true;
}
internal
int
Count;
}
/// <summary>
/// Debugging code. Counts the number of nodes in the tree of nodes.
/// </summary>
/// <returns>
/// The number of nodes in the tree.
/// </returns>
private
int
CountNodes()
{
CountingNodeVisitor cnv = new CountingNodeVisitor();
NodeVisitor.VisitNodes(_topLevelNodes, cnv);
return cnv.Count;
}
#endif
/// <summary>
/// Helper function to CompressToFit. Considers compressing nodes from one level to another.
/// </summary>
/// <param name="rawUi">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
/// <param name="maxHeight">
/// The maximum height (in BufferCells) that the rendering may consume.
/// </param>
/// <param name="maxWidth">
/// The maximum width (in BufferCells) that the rendering may consume.
/// </param>
/// <param name="nodesCompressed">
/// Receives the number of nodes that were compressed. If the result of the method is false, then this will be the total
/// number of nodes being tracked (i.e. all of them will have been compressed).
/// </param>
/// <param name="priorStyle">
/// The rendering style (e.g. "compression level") that the nodes are expected to currently have.
/// </param>
/// <param name="newStyle">
/// The new rendering style that a node will have when it is compressed. If the result of the method is false, then all
/// nodes will have this rendering style.
/// </param>
/// <returns>
/// true to indicate that the nodes are compressed to the point that their rendering will fit within the constraint, or
/// false to indicate that all of the nodes are compressed to a given level, but that the rendering still can't fit
/// within the constraint.
/// </returns>
private
bool
CompressToFitHelper(
PSHostRawUserInterface rawUi,
int maxHeight,
int maxWidth,
out int nodesCompressed,
ProgressNode.RenderStyle priorStyle,
ProgressNode.RenderStyle newStyle)
{
nodesCompressed = 0;
while (true)
{
ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, oldestSoFar: 0, priorStyle);
if (node == null)
{
// We've compressed every node of the prior style already.
break;
}
node.Style = newStyle;
++nodesCompressed;
if (TallyHeight(rawUi, maxHeight, maxWidth) <= maxHeight)
{
return true;
}
}
// If we get all the way to here, then we've compressed all the nodes and we still don't fit.
return false;
}
/// <summary>
/// "Compresses" the nodes representing the outstanding progress activities until their rendering will fit within a
/// "given height, or until they are compressed to a given level. The oldest nodes are compressed first.
///
/// This is a 4-stage process -- from least compressed to "invisible". At each stage we find the oldest nodes in the
/// tree and change their rendering style to a more compact style. As soon as the rendering of the nodes will fit within
/// the maxHeight, we stop. The result is that the most recent nodes will be the least compressed, the idea being that
/// the rendering should show the most recently updated activities with the most complete rendering for them possible.
/// </summary>
/// <param name="rawUi">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
/// <param name="maxHeight">
/// The maximum height (in BufferCells) that the rendering may consume.
/// </param>
/// <param name="maxWidth">
/// The maximum width (in BufferCells) that the rendering may consume.
/// </param>
/// <returns>
/// The number of nodes that were made invisible during the compression.
///
///</returns>
private
int
CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth)
{
Dbg.Assert(_topLevelNodes != null, "Shouldn't need to compress if no data exists");
int nodesCompressed = 0;
// This algorithm potentially makes many, many passes over the tree. It might be possible to optimize
// that some, but I'm not trying to be too clever just yet.
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.FullPlus,
ProgressNode.RenderStyle.Full))
{
return 0;
}
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.Full,
ProgressNode.RenderStyle.Compact))
{
return 0;
}
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.Compact,
ProgressNode.RenderStyle.Minimal))
{
return 0;
}
if (
CompressToFitHelper(
rawUi,
maxHeight,
maxWidth,
out nodesCompressed,
ProgressNode.RenderStyle.Minimal,
ProgressNode.RenderStyle.Invisible))
{
// The nodes that we compressed here are now invisible.
return nodesCompressed;
}
Dbg.Assert(false, "with all nodes invisible, we should never reach this point.");
return 0;
}
#endregion // Rendering Code
#region Utility Code
private abstract
class NodeVisitor
{
/// <summary>
/// Called for each node in the tree.
/// </summary>
/// <param name="node">
/// The node being visited.
/// </param>
/// <param name="listWhereFound">
/// The list in which the node resides.
/// </param>
/// <param name="indexWhereFound">
/// The index into listWhereFound of the node.
/// </param>
/// <returns>
/// true to continue visiting nodes, false if not.
/// </returns>
internal abstract
bool
Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound);
internal static
void
VisitNodes(ArrayList nodes, NodeVisitor v)
{
if (nodes == null)
{
return;
}
for (int i = 0; i < nodes.Count; ++i)
{
ProgressNode node = (ProgressNode)nodes[i];
Dbg.Assert(node != null, "nodes should not contain null elements");
if (!v.Visit(node, nodes, i))
{
return;
}
if (node.Children != null)
{
VisitNodes(node.Children, v);
}
}
}
}
#endregion
private readonly ArrayList _topLevelNodes = new ArrayList();
private int _nodeCount;
private const int maxNodeCount = 128;
}
} // namespace
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Moq.Tests
{
public class SequenceExtensionsFixture
{
[Fact]
public void PerformSequence()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.Do())
.Returns(2)
.Returns(3)
.Returns(() => 4)
.Throws<InvalidOperationException>();
Assert.Equal(2, mock.Object.Do());
Assert.Equal(3, mock.Object.Do());
Assert.Equal(4, mock.Object.Do());
Assert.Throws<InvalidOperationException>(() => mock.Object.Do());
}
[Fact]
public void PerformSequenceAsync()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.DoAsync())
.ReturnsAsync(2)
.ReturnsAsync(3)
.ThrowsAsync(new InvalidOperationException());
Assert.Equal(2, mock.Object.DoAsync().Result);
Assert.Equal(3, mock.Object.DoAsync().Result);
try
{
var x = mock.Object.DoAsync().Result;
}
catch (AggregateException ex)
{
Assert.IsType<InvalidOperationException>(ex.GetBaseException());
}
}
[Fact]
public async Task PerformSequenceAsync_ReturnsAsync_for_Task_with_value_function()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.DoAsync())
.ReturnsAsync(() => 1)
.ReturnsAsync(() => 2);
Assert.Equal(1, await mock.Object.DoAsync());
Assert.Equal(2, await mock.Object.DoAsync());
}
[Fact]
public async Task PerformSequenceAsync_ReturnsAsync_for_ValueTask_with_value_function()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.DoValueAsync())
.ReturnsAsync(() => 1)
.ReturnsAsync(() => 2);
Assert.Equal(1, await mock.Object.DoValueAsync());
Assert.Equal(2, await mock.Object.DoValueAsync());
}
[Fact]
public void PerformSequenceOnProperty()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.Value)
.Returns("foo")
.Returns("bar")
.Throws<InvalidOperationException>();
string temp;
Assert.Equal("foo", mock.Object.Value);
Assert.Equal("bar", mock.Object.Value);
Assert.Throws<InvalidOperationException>(() => temp = mock.Object.Value);
}
[Fact]
public void PerformSequenceWithThrowsFirst()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.Do())
.Throws<Exception>()
.Returns(1);
Assert.Throws<Exception>(() => mock.Object.Do());
Assert.Equal(1, mock.Object.Do());
}
[Fact]
public void PerformSequenceWithCallBase()
{
var mock = new Mock<Foo>();
mock.SetupSequence(x => x.Do())
.Returns("Good")
.CallBase()
.Throws<InvalidOperationException>();
Assert.Equal("Good", mock.Object.Do());
Assert.Equal("Ok", mock.Object.Do());
Assert.Throws<InvalidOperationException>(() => mock.Object.Do());
}
[Fact]
public void Setting_up_a_sequence_overrides_any_preexisting_setup()
{
const string valueFromPreviousSetup = "value from previous setup";
// Arrange: set up a sequence as the second setup and consume it
var mock = new Mock<IFoo>();
mock.Setup(m => m.Value).Returns(valueFromPreviousSetup);
mock.SetupSequence(m => m.Value).Returns("1");
var _ = mock.Object.Value;
// Act: ask sequence for value when it is exhausted
var actual = mock.Object.Value;
// Assert: should have got the default value, not the one configured by the overridden setup
Assert.Equal(default(string), actual);
Assert.NotEqual(valueFromPreviousSetup, actual);
}
[Fact]
public void When_sequence_exhausted_and_there_was_no_previous_setup_return_value_is_default()
{
// Arrange: set up a sequence as the only setup and consume it
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.Value)
.Returns("1");
var _ = mock.Object.Value;
// Act: ask sequence for value when it is exhausted
string actual = mock.Object.Value;
// Assert: should have got the default value
Assert.Equal(default(string), actual);
}
[Fact]
public void When_sequence_overexhausted_and_new_responses_are_configured_those_are_used_on_next_invocation()
{
// Arrange: set up a sequence and overexhaust it, then set up more responses
var mock = new Mock<IFoo>();
var sequenceSetup = mock.SetupSequence(m => m.Value).Returns("1"); // configure 1st response
var _ = mock.Object.Value; // 1st invocation
_ = mock.Object.Value; // 2nd invocation
sequenceSetup.Returns("2"); // configure 2nd response
sequenceSetup.Returns("3"); // configure 3nd response
// Act: 3rd invocation. will we get back the 2nd configured response, or the 3rd (since we're on the 3rd invocation)?
string actual = mock.Object.Value;
// Assert: no configured response should be skipped, therefore we should get the 2nd one
Assert.Equal("2", actual);
}
[Fact]
public void Verify_can_verify_invocation_count_for_sequences()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.Do());
mock.Object.Do();
mock.Object.Do();
mock.Verify(m => m.Do(), Times.Exactly(2));
}
[Fact]
public void Func_are_invoked_deferred()
{
var mock = new Mock<IFoo>();
var i = 0;
mock.SetupSequence(m => m.Do())
.Returns(() => i);
i++;
Assert.Equal(i, mock.Object.Do());
}
[Fact]
public async Task Func_are_invoked_deferred_for_Task()
{
var mock = new Mock<IFoo>();
var i = 0;
mock.SetupSequence(m => m.DoAsync())
.ReturnsAsync(() => i);
i++;
Assert.Equal(i, await mock.Object.DoAsync());
}
[Fact]
public async Task Func_are_invoked_deferred_for_ValueTask()
{
var mock = new Mock<IFoo>();
var i = 0;
mock.SetupSequence(m => m.DoValueAsync())
.ReturnsAsync(() => i);
i++;
Assert.Equal(i, await mock.Object.DoValueAsync());
}
[Fact]
public void Func_can_be_treated_as_return_value()
{
var mock = new Mock<IFoo>();
Func<int> func = () => 1;
mock.SetupSequence(m => m.GetFunc())
.Returns(func);
Assert.Equal(func, mock.Object.GetFunc());
}
[Fact]
public void Keep_Func_as_return_value_when_setup_method_returns_implicitly_casted_type()
{
var mock = new Mock<IFoo>();
Func<object> funcObj = () => 1;
Func<Delegate> funcDel = () => new Action(() => { });
Func<MulticastDelegate> funcMulticastDel = () => new Action(() => { });
mock.SetupSequence(m => m.GetObj()).Returns(funcObj);
mock.SetupSequence(m => m.GetDel()).Returns(funcDel);
mock.SetupSequence(m => m.GetMulticastDel()).Returns(funcMulticastDel);
Assert.Equal(funcObj, mock.Object.GetObj());
Assert.Equal(funcDel, mock.Object.GetDel());
Assert.Equal(funcMulticastDel, mock.Object.GetMulticastDel());
}
public interface IFoo
{
string Value { get; set; }
int Do();
Task<int> DoAsync();
ValueTask<int> DoValueAsync();
Func<int> GetFunc();
object GetObj();
Delegate GetDel();
MulticastDelegate GetMulticastDel();
}
public class Foo
{
public virtual string Do()
{
return "Ok";
}
public virtual Task<string> DoAsync()
{
var tcs = new TaskCompletionSource<string>();
tcs.SetResult("Ok");
return tcs.Task;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Configuration;
using NUnit.Framework;
using DataPageEvictionMode = Apache.Ignite.Core.Configuration.DataPageEvictionMode;
/// <summary>
/// Tests disk persistence.
/// </summary>
public class PersistenceTest
{
/** Temp dir for WAL. */
private readonly string _tempDir = PathUtils.GetTempDirectoryName();
/// <summary>
/// Sets up the test.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.ClearWorkDir();
}
/// <summary>
/// Tears down the test.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
if (Directory.Exists(_tempDir))
{
Directory.Delete(_tempDir, true);
}
TestUtils.ClearWorkDir();
}
/// <summary>
/// Tests that cache data survives node restart.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestCacheDataSurvivesNodeRestart(
[Values(true, false)] bool withCacheStore,
[Values(true, false)] bool withCustomAffinity)
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = new DataStorageConfiguration
{
StoragePath = Path.Combine(_tempDir, "Store"),
WalPath = Path.Combine(_tempDir, "WalStore"),
WalArchivePath = Path.Combine(_tempDir, "WalArchive"),
MetricsEnabled = true,
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
PageEvictionMode = DataPageEvictionMode.Disabled,
Name = DataStorageConfiguration.DefaultDataRegionName,
PersistenceEnabled = true
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "volatileRegion",
PersistenceEnabled = false
}
}
}
};
const string cacheName = "persistentCache";
const string volatileCacheName = "volatileCache";
// Start Ignite, put data, stop.
using (var ignite = Ignition.Start(cfg))
{
ignite.GetCluster().SetActive(true);
// Create cache with default region (persistence enabled), add data.
var cache = ignite.CreateCache<int, int>(new CacheConfiguration
{
Name = cacheName,
CacheStoreFactory = withCacheStore ? new CustomStoreFactory() : null,
AffinityFunction = withCustomAffinity ? new CustomAffinityFunction() : null
});
cache[1] = 1;
// Check some metrics.
CheckDataStorageMetrics(ignite);
// Create cache with non-persistent region.
var volatileCache = ignite.CreateCache<int, int>(new CacheConfiguration
{
Name = volatileCacheName,
DataRegionName = "volatileRegion"
});
volatileCache[2] = 2;
}
// Verify directories.
Assert.IsTrue(Directory.Exists(cfg.DataStorageConfiguration.StoragePath));
Assert.IsTrue(Directory.Exists(cfg.DataStorageConfiguration.WalPath));
Assert.IsTrue(Directory.Exists(cfg.DataStorageConfiguration.WalArchivePath));
// Start Ignite, verify data survival.
using (var ignite = Ignition.Start(cfg))
{
ignite.GetCluster().SetActive(true);
// Persistent cache already exists and contains data.
var cache = ignite.GetCache<int, int>(cacheName);
Assert.AreEqual(1, cache[1]);
// Non-persistent cache does not exist.
var ex = Assert.Throws<ArgumentException>(() => ignite.GetCache<int, int>(volatileCacheName));
Assert.AreEqual("Cache doesn't exist: volatileCache", ex.Message);
}
// Delete store directory.
Directory.Delete(_tempDir, true);
// Start Ignite, verify data loss.
using (var ignite = Ignition.Start(cfg))
{
ignite.GetCluster().SetActive(true);
Assert.IsFalse(ignite.GetCacheNames().Contains(cacheName));
}
}
/// <summary>
/// Checks that data storage metrics reflect some write operations.
/// </summary>
private static void CheckDataStorageMetrics(IIgnite ignite)
{
var metrics = ignite.GetDataStorageMetrics();
Assert.Greater(metrics.WalLoggingRate, 0);
}
/// <summary>
/// Tests the grid activation with persistence (inactive by default).
/// </summary>
[Test]
public void TestGridActivationWithPersistence()
{
var cfg = GetPersistentConfiguration();
// Default config, inactive by default (IsActiveOnStart is ignored when persistence is enabled).
using (var ignite = Ignition.Start(cfg))
{
CheckIsActive(ignite, false);
ignite.GetCluster().SetActive(true);
CheckIsActive(ignite, true);
ignite.GetCluster().SetActive(false);
CheckIsActive(ignite, false);
}
}
/// <summary>
/// Tests the grid activation without persistence (active by default).
/// </summary>
[Test]
public void TestGridActivationNoPersistence()
{
var cfg = TestUtils.GetTestConfiguration();
Assert.IsTrue(cfg.IsActiveOnStart);
using (var ignite = Ignition.Start(cfg))
{
CheckIsActive(ignite, true);
ignite.GetCluster().SetActive(false);
CheckIsActive(ignite, false);
ignite.GetCluster().SetActive(true);
CheckIsActive(ignite, true);
}
cfg.IsActiveOnStart = false;
using (var ignite = Ignition.Start(cfg))
{
CheckIsActive(ignite, false);
ignite.GetCluster().SetActive(true);
CheckIsActive(ignite, true);
ignite.GetCluster().SetActive(false);
CheckIsActive(ignite, false);
}
}
/// <summary>
/// Tests the baseline topology.
/// </summary>
[Test]
[Ignore("SetBaselineAutoAdjustEnabledFlag is not supported in 8.7, and IGNITE_BASELINE_AUTO_ADJUST_ENABLED " +
"can't be set reliably with environment variables.'")]
public void TestBaselineTopology()
{
using (EnvVar.Set("IGNITE_BASELINE_AUTO_ADJUST_ENABLED", "false"))
{
var cfg1 = new IgniteConfiguration(GetPersistentConfiguration())
{
ConsistentId = "node1"
};
var cfg2 = new IgniteConfiguration(GetPersistentConfiguration())
{
ConsistentId = "node2",
IgniteInstanceName = "2"
};
using (var ignite = Ignition.Start(cfg1))
{
// Start and stop to bump topology version.
Ignition.Start(cfg2);
Ignition.Stop(cfg2.IgniteInstanceName, true);
var cluster = ignite.GetCluster();
Assert.AreEqual(3, cluster.TopologyVersion);
// Can not set baseline while inactive.
var ex = Assert.Throws<IgniteException>(() => cluster.SetBaselineTopology(2));
Assert.AreEqual("Changing BaselineTopology on inactive cluster is not allowed.", ex.Message);
cluster.SetActive(true);
// Can not set baseline with offline node.
ex = Assert.Throws<IgniteException>(() => cluster.SetBaselineTopology(2));
Assert.AreEqual("Check arguments. Node with consistent ID [node2] not found in server nodes.",
ex.Message);
cluster.SetBaselineTopology(1);
Assert.AreEqual("node1", cluster.GetBaselineTopology().Single().ConsistentId);
// Set with node.
cluster.SetBaselineTopology(cluster.GetBaselineTopology());
var res = cluster.GetBaselineTopology();
CollectionAssert.AreEquivalent(new[] {"node1"}, res.Select(x => x.ConsistentId));
cluster.SetBaselineTopology(cluster.GetTopology(1));
Assert.AreEqual("node1", cluster.GetBaselineTopology().Single().ConsistentId);
// Can not set baseline with offline node.
ex = Assert.Throws<IgniteException>(() => cluster.SetBaselineTopology(cluster.GetTopology(2)));
Assert.AreEqual("Check arguments. Node with consistent ID [node2] not found in server nodes.",
ex.Message);
}
// Check auto activation on cluster restart.
using (var ignite = Ignition.Start(cfg1))
using (Ignition.Start(cfg2))
{
var cluster = ignite.GetCluster();
Assert.IsTrue(cluster.IsActive());
var res = cluster.GetBaselineTopology();
CollectionAssert.AreEquivalent(new[] {"node1"}, res.Select(x => x.ConsistentId));
}
}
}
/// <summary>
/// Tests the wal disable/enable functionality.
/// </summary>
[Test]
public void TestWalDisableEnable()
{
using (var ignite = Ignition.Start(GetPersistentConfiguration()))
{
var cluster = ignite.GetCluster();
cluster.SetActive(true);
var cache = ignite.CreateCache<int, int>("foo");
Assert.IsTrue(cluster.IsWalEnabled(cache.Name));
cache[1] = 1;
cluster.DisableWal(cache.Name);
Assert.IsFalse(cluster.IsWalEnabled(cache.Name));
cache[2] = 2;
cluster.EnableWal(cache.Name);
Assert.IsTrue(cluster.IsWalEnabled(cache.Name));
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
// Check exceptions.
var ex = Assert.Throws<IgniteException>(() => cluster.IsWalEnabled("bar"));
Assert.AreEqual("Cache not found: bar", ex.Message);
ex = Assert.Throws<IgniteException>(() => cluster.DisableWal("bar"));
Assert.AreEqual("Cache doesn't exist: bar", ex.Message);
ex = Assert.Throws<IgniteException>(() => cluster.EnableWal("bar"));
Assert.AreEqual("Cache doesn't exist: bar", ex.Message);
}
}
/// <summary>
/// Test the configuration of IsBaselineAutoAdjustEnabled flag
/// </summary>
[Test]
public void TestBaselineTopologyAutoAdjustEnabledDisabled()
{
using (var ignite = Ignition.Start(GetPersistentConfiguration()))
{
ICluster cluster = ignite.GetCluster();
cluster.SetActive(true);
bool isEnabled = cluster.IsBaselineAutoAdjustEnabled();
cluster.SetBaselineAutoAdjustEnabledFlag(!isEnabled);
Assert.AreNotEqual(isEnabled, cluster.IsBaselineAutoAdjustEnabled());
}
}
/// <summary>
/// Test the configuration of BaselineAutoAdjustTimeout property
/// </summary>
[Test]
public void TestBaselineTopologyAutoAdjustTimeoutWriteRead()
{
const long newTimeout = 333000;
using (var ignite = Ignition.Start(GetPersistentConfiguration()))
{
ICluster cluster = ignite.GetCluster();
cluster.SetActive(true);
cluster.SetBaselineAutoAdjustTimeout(newTimeout);
Assert.AreEqual(newTimeout, cluster.GetBaselineAutoAdjustTimeout());
}
}
/// <summary>
/// Checks active state.
/// </summary>
private static void CheckIsActive(IIgnite ignite, bool isActive)
{
Assert.AreEqual(isActive, ignite.GetCluster().IsActive());
if (isActive)
{
var cache = ignite.GetOrCreateCache<int, int>("default");
cache[1] = 1;
Assert.AreEqual(1, cache[1]);
}
else
{
var ex = Assert.Throws<IgniteException>(() => ignite.GetOrCreateCache<int, int>("default"));
Assert.AreEqual("Can not perform the operation because the cluster is inactive.",
ex.Message.Substring(0, 62));
}
}
/// <summary>
/// Gets the persistent configuration.
/// </summary>
private static IgniteConfiguration GetPersistentConfiguration()
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = new DataStorageConfiguration
{
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
PersistenceEnabled = true,
Name = "foo"
}
}
};
}
private class CustomStoreFactory : IFactory<ICacheStore>
{
public ICacheStore CreateInstance()
{
return new CustomStore();
}
}
private class CustomStore : CacheStoreAdapter<object, object>
{
public override object Load(object key)
{
return null;
}
public override void Write(object key, object val)
{
// No-op.
}
public override void Delete(object key)
{
// No-op.
}
}
private class CustomAffinityFunction : RendezvousAffinityFunction
{
public override int Partitions
{
get { return 10; }
set { throw new NotSupportedException(); }
}
}
}
}
| |
//-----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IdentityModel.Configuration;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Security;
using Attributes = System.IdentityModel.Tokens.JwtConfigurationStrings.Attributes;
using AttributeValues = System.IdentityModel.Tokens.JwtConfigurationStrings.AttributeValues;
using CertMode = System.ServiceModel.Security.X509CertificateValidationMode;
using Elements = System.IdentityModel.Tokens.JwtConfigurationStrings.Elements;
namespace System.IdentityModel.Test
{
public class ExpectedJwtSecurityTokenRequirement
{
public ExpectedJwtSecurityTokenRequirement
(
uint? tokenSize = null, TimeSpan? clock = null, uint? life = null, X509CertificateValidator cert = null, string name = JwtConstants.ReservedClaims.Subject, string role = null, X509RevocationMode? revMode = null, X509CertificateValidationMode? certMode = null, StoreLocation? storeLoc = null, ExpectedException expectedException = null,
string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement,
string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "",
string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment,
string elementClose = closeRequirement
)
{
MaxTokenSizeInBytes = tokenSize;
NameClaimType = name;
RoleClaimType = role;
CertValidator = cert;
MaxClockSkew = clock;
DefaultTokenLifetimeInMinutes = life;
CertRevocationMode = revMode;
CertValidationMode = certMode;
CertStoreLocation = storeLoc;
ExpectedException = expectedException;
string[] sParams =
{
handler,
requirement,
CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ),
attributeEx1,
CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ),
attributeEx2,
CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.JWT.Test" ),
attributeEx3,
CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ),
attributeEx4,
elementEx1,
MaxClockSkew == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, MaxClockSkew.Value.TotalMinutes.ToString() ),
elementEx2,
MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ),
elementEx3,
DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ),
elementEx4,
NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ),
elementEx5,
RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ),
elementEx6,
elementClose,
};
Config = string.Format( ElementTemplate, sParams );
}
public bool AsExpected( JwtSecurityTokenRequirement requirement )
{
bool asExpected = true;
JwtSecurityTokenRequirement controlRequirement = new JwtSecurityTokenRequirement();
if ( requirement == null )
{
return false;
}
Assert.IsFalse(
MaxTokenSizeInBytes != null && MaxTokenSizeInBytes.Value != requirement.MaximumTokenSizeInBytes,
string.Format(CultureInfo.InvariantCulture,
"MaximumTokenSizeInBytes (expected, config): '{0}'. '{1}'.",
MaxTokenSizeInBytes.ToString(),
requirement.MaximumTokenSizeInBytes.ToString()));
Assert.IsFalse(
MaxTokenSizeInBytes == null
&& requirement.MaximumTokenSizeInBytes != controlRequirement.MaximumTokenSizeInBytes,
string.Format(CultureInfo.InvariantCulture,
"MaximumTokenSizeInBytes should be default (default, config): '{0}'. '{1}'.",
controlRequirement.MaximumTokenSizeInBytes.ToString(),
requirement.MaximumTokenSizeInBytes.ToString()));
Assert.IsFalse(
MaxClockSkew != null && MaxClockSkew.Value != requirement.MaxClockSkew,
string.Format(CultureInfo.InvariantCulture,
"MaxClockSkew (expected, config): '{0}'. '{1}'.",
MaxClockSkew.ToString(),
requirement.MaxClockSkew.ToString() ) );
Assert.IsFalse(
MaxClockSkew == null && requirement.MaxClockSkew != controlRequirement.MaxClockSkew,
string.Format(CultureInfo.InvariantCulture,
"MaxClockSkew should be default (default, config): '{0}'. '{1}'.",
controlRequirement.MaxClockSkew.ToString(),
requirement.MaxClockSkew.ToString() ) );
Assert.IsFalse(
DefaultTokenLifetimeInMinutes != null
&& DefaultTokenLifetimeInMinutes.Value != requirement.DefaultTokenLifetimeInMinutes,
string.Format(CultureInfo.InvariantCulture,
"DefaultTokenLifetimeInMinutes (expected, config): '{0}'. '{1}'.",
DefaultTokenLifetimeInMinutes.ToString(),
requirement.DefaultTokenLifetimeInMinutes.ToString() ) );
Assert.IsFalse(
DefaultTokenLifetimeInMinutes == null
&& requirement.DefaultTokenLifetimeInMinutes != controlRequirement.DefaultTokenLifetimeInMinutes,
string.Format(CultureInfo.InvariantCulture,
"DefaultTokenLifetimeInMinutes should be default (default, config): '{0}'. '{1}'.",
controlRequirement.DefaultTokenLifetimeInMinutes.ToString(),
requirement.DefaultTokenLifetimeInMinutes.ToString() ) );
// make sure nameclaim and roleclaim are same, or null together.
Assert.IsFalse( NameClaimType == null && requirement.NameClaimType != null , "NameClaimType == null && requirement.NameClaimType != null" );
Assert.IsFalse( NameClaimType != null && requirement.NameClaimType == null , "NameClaimType != null && requirement.NameClaimType == null" );
if ( ( NameClaimType != null && requirement.NameClaimType != null )
&& ( NameClaimType != requirement.NameClaimType ) )
{
Assert.Fail(string.Format(CultureInfo.InvariantCulture, "NameClaimType (expected, config): '{0}'. '{1}'.", NameClaimType, requirement.NameClaimType));
asExpected = false;
}
Assert.IsFalse( RoleClaimType == null && requirement.RoleClaimType != null , "RoleClaimType == null && requirement.RoleClaimType != null" );
Assert.IsFalse( RoleClaimType != null && requirement.RoleClaimType == null , "RoleClaimType != null && requirement.RoleClaimType == null" );
if ( ( RoleClaimType != null && requirement.RoleClaimType != null )
&& ( RoleClaimType != requirement.RoleClaimType ) )
{
Assert.Fail(string.Format(CultureInfo.InvariantCulture, "RoleClaimType (expected, config): '{0}'. '{1}'.", RoleClaimType, requirement.RoleClaimType));
asExpected = false;
}
// != null => this variation sets a custom validator.
if ( CertValidator != null )
{
if ( requirement.CertificateValidator == null )
{
return false;
}
Assert.IsFalse( CertValidator.GetType() != requirement.CertificateValidator.GetType() , string.Format( "CertificateValidator.GetType() != requirement.CertificateValidator.GetType(). (expected, config): '{0}'. '{1}'.", CertValidator.GetType(), requirement.CertificateValidator.GetType() ) );
}
else
{
if ( CertValidationMode.HasValue || CertRevocationMode.HasValue || CertStoreLocation.HasValue )
{
Assert.IsFalse( requirement.CertificateValidator == null , string.Format( "X509CertificateValidationMode.HasValue || X09RevocationMode.HasValue || StoreLocation.HasValue is true, there should be a validator" ) );
// get and check _certificateValidationMode
Type type = requirement.CertificateValidator.GetType();
FieldInfo fi = type.GetField( "validator", BindingFlags.NonPublic | BindingFlags.Instance );
X509CertificateValidator validator = (X509CertificateValidator)fi.GetValue( requirement.CertificateValidator );
// make sure we created the right validator
if ( CertValidationMode == CertMode.ChainTrust && ( validator.GetType() != X509CertificateValidator.ChainTrust.GetType() )
|| CertValidationMode == CertMode.PeerTrust && ( validator.GetType() != X509CertificateValidator.PeerTrust.GetType() )
|| CertValidationMode == CertMode.PeerOrChainTrust && ( validator.GetType() != X509CertificateValidator.PeerOrChainTrust.GetType() )
|| CertValidationMode == CertMode.None && ( validator.GetType() != X509CertificateValidator.None.GetType() ) )
{
Assert.Fail(string.Format(CultureInfo.InvariantCulture, "X509CertificateValidator type. expected: '{0}', actual: '{1}'", CertValidationMode.HasValue ? CertValidationMode.Value.ToString() : "null", validator.GetType().ToString()));
asExpected = false;
}
// if these 'Modes' HasValue, then it should be matched, otherwise expect default.
fi = type.GetField( "certificateValidationMode", BindingFlags.NonPublic | BindingFlags.Instance );
CertMode certMode = (CertMode)fi.GetValue( requirement.CertificateValidator );
if ( CertValidationMode.HasValue )
{
Assert.IsFalse(CertValidationMode.Value != certMode, string.Format(CultureInfo.InvariantCulture, "X509CertificateValidationMode. expected: '{0}', actual: '{1}'", CertValidationMode.Value.ToString(), certMode.ToString()));
// if mode includes chain building, revocation mode Policy s/b null.
if (CertValidationMode.Value == X509CertificateValidationMode.ChainTrust
|| CertValidationMode.Value == X509CertificateValidationMode.PeerOrChainTrust)
{
// check inner policy
if (CertRevocationMode.HasValue)
{
fi = type.GetField("chainPolicy", BindingFlags.NonPublic | BindingFlags.Instance);
X509ChainPolicy chainPolicy =
(X509ChainPolicy)fi.GetValue(requirement.CertificateValidator);
Assert.IsFalse(
chainPolicy.RevocationMode != CertRevocationMode.Value,
string.Format(
CultureInfo.InvariantCulture,
"chainPolicy.RevocationMode. . expected: '{0}', actual: '{1}'",
CertRevocationMode.Value.ToString(),
chainPolicy.RevocationMode.ToString()));
}
}
}
}
}
return asExpected;
}
public uint? MaxTokenSizeInBytes { get; set; }
public TimeSpan? MaxClockSkew { get; set; }
public string NameClaimType { get; set; }
public string RoleClaimType { get; set; }
public X509CertificateValidator CertValidator { get; set; }
public uint? DefaultTokenLifetimeInMinutes { get; set; }
public X509RevocationMode? CertRevocationMode { get; set; }
public X509CertificateValidationMode? CertValidationMode { get; set; }
public StoreLocation? CertStoreLocation { get; set; }
public ExpectedException ExpectedException { get; set; }
public string Config { get; set; }
public const string ElementTemplate = @"<add type='{0}'><{1} {2} {3} {4} {5} {6} {7} {8} {9} >{10}{11}{12}{13}{14}{15}{16}{17}{18}{19}{20}{21}</add>";
public const string JwtSecurityTokenHandlerType = "System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt";
public const string AlwaysSucceedCertificateValidator = "System.IdentityModel.Test.AlwaysSucceedCertificateValidator, System.IdentityModel.Tokens.Jwt.Test";
public const string comment = @"<!-- Comment -->";
public const string closeRequirement = "</" + Elements.JwtSecurityTokenRequirement + ">";
public static string CloseElement( string element ) { return "</" + element + ">"; }
public static string ElementValue( string element, string value ) { return "<" + element + " " + Attributes.Value + "='" + value + "' />"; }
public static string Attribute( string attribute, string value ) { return attribute + "='" + value + "'"; }
public string[] StringParams( string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement,
string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "",
string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment,
string elementClose = closeRequirement )
{
return new string[]
{
handler,
requirement,
CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ),
attributeEx1,
CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ),
attributeEx2,
CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.JWT.Test" ),
attributeEx3,
CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ),
attributeEx4,
elementEx1,
MaxClockSkew == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, MaxClockSkew.Value.TotalMinutes.ToString() ),
elementEx2,
MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ),
elementEx3,
DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ),
elementEx4,
NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ),
elementEx5,
RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ),
elementEx6,
elementClose,
};
}
};
public class JwtHandlerConfigVariation
{
public ExpectedJwtSecurityTokenRequirement ExpectedJwtSecurityTokenRequirement { get; set; }
public JwtSecurityTokenHandler ExpectedSecurityTokenHandler{ get; set; }
public static List<ExpectedJwtSecurityTokenRequirement> RequirementVariations;
public static string ElementValue( string element, string value, string attributeValue = Attributes.Value, int count = 1)
{
string attributePart = string.Empty;
string postfix = string.Empty;
for ( int i = 0; i < count; i++ )
{
attributePart += attributeValue + ( i == 0 ? string.Empty : i.ToString() ) + "='" + value + "' ";
}
return "<" + element + " " + attributePart + " />";
}
//public static string ElementValue( string element, string value, string attributeValue = Attributes.Value ) { return "<" + element + " " + attributeValue + "='" + value + "' />"; }
public static string ElementValueMultipleAttributes( string element, string value, string value2 ) { return "<" + element + " " + Attributes.Value + "='" + value + " " + Attributes.Value + "='" + value2 + "' />"; }
public static string Attribute( string attribute, string value ) { return attribute + "='" + value + "'"; }
public static void BuildExpectedRequirements()
{
RequirementVariations = new List<ExpectedJwtSecurityTokenRequirement>();
// Empty Element
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: "<>", expectedException: ExpectedException.Config( id: "initialize" ) ) );
// unknown element
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( "UnknownElement", "@http://AllItemsSet/nameClaim" ), expectedException: ExpectedException.Config( id: "Jwt10611" ) ) );
// element.Localname empty
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( "", "@http://AllItemsSet/nameClaim" ), expectedException: ExpectedException.Config( id: "initialize" ) ) );
// Element attribute name is not 'value'
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.DefaultTokenLifetimeInMinutes, "6000", attributeValue: "NOTvalue" ), expectedException: ExpectedException.Config( id: "Jwt10610:" ) ) );
// Attribute name empty
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( attributeEx1: Attribute( "", AttributeValues.X509CertificateValidationModeChainTrust ), expectedException: ExpectedException.Config( id: "initialize" ) ) );
// Attribute value empty
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( attributeEx1: Attribute( Attributes.ValidationMode, "" ), expectedException: ExpectedException.Config( id: "Jwt10600" ) ) );
// Multiple Attributes
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.NameClaimType, "Bob", count: 2 ), expectedException: ExpectedException.Config( id: "Jwt10609" ) ) );
// No Attributes
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.NameClaimType, "Bob", count: 0 ), expectedException: ExpectedException.Config( id: "Jwt10607" ) ) );
// for each variation, make sure a validator is created.
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( revMode: X509RevocationMode.NoCheck, storeLoc: StoreLocation.CurrentUser, certMode: X509CertificateValidationMode.ChainTrust ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( revMode: X509RevocationMode.Offline ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( revMode: X509RevocationMode.Online ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.ChainTrust ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.Custom, expectedException: ExpectedException.Config( "Jwt10612" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.None ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.PeerOrChainTrust ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.PeerTrust ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( storeLoc: StoreLocation.CurrentUser ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( storeLoc: StoreLocation.LocalMachine ) );
// Error Conditions - lifetime
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( life: 0, expectedException: ExpectedException.Config( inner: new ArgumentOutOfRangeException(), id: "Jwt10603" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.DefaultTokenLifetimeInMinutes, "-1" ), expectedException: ExpectedException.Config( inner: new OverflowException(), id: "Jwt10603" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.DefaultTokenLifetimeInMinutes, "abc" ), expectedException: ExpectedException.Config( inner: new FormatException() ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.DefaultTokenLifetimeInMinutes, "15372286729" ), expectedException: ExpectedException.Config( inner: new OverflowException() ) ) );
// Error Conditions - tokensSize
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 0, expectedException: ExpectedException.Config( inner: new ArgumentOutOfRangeException(), id: "Jwt10603" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.MaxTokenSizeInBytes, "-1" ), expectedException: ExpectedException.Config(inner: new OverflowException(), id: "Jwt10603" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.MaxTokenSizeInBytes, "abc" ), expectedException: ExpectedException.Config( inner: new FormatException() ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( elementEx1: ElementValue( Elements.MaxTokenSizeInBytes, "4294967296" ), expectedException: ExpectedException.Config( inner: new OverflowException() ) ) );
// Duplicate Elements, we have to catch them.
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 1000, revMode: X509RevocationMode.NoCheck, elementEx1: ElementValue( Elements.MaxTokenSizeInBytes, "1024" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 1000, revMode: X509RevocationMode.NoCheck, elementEx3: ElementValue( Elements.MaxTokenSizeInBytes, "1024" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( name: @"http://AllItemsSet/nameClaim", revMode: X509RevocationMode.NoCheck, elementEx3: ElementValue( Elements.NameClaimType, "1024" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( name: @"http://AllItemsSet/nameClaim", revMode: X509RevocationMode.NoCheck, elementEx5: ElementValue( Elements.NameClaimType, "1024" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( role: @"http://AllItemsSet/roleClaim", revMode: X509RevocationMode.NoCheck, elementEx3: ElementValue( Elements.RoleClaimType, "1024" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( role: @"http://AllItemsSet/roleClaim", revMode: X509RevocationMode.NoCheck, elementEx6: ElementValue( Elements.RoleClaimType, "1024" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( clock: TimeSpan.FromMinutes( 15 ), certMode: X509CertificateValidationMode.PeerTrust, elementEx1: ElementValue( Elements.MaxClockSkewInMinutes, "5" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( clock: TimeSpan.FromMinutes( 15 ), revMode: X509RevocationMode.NoCheck, elementEx2: ElementValue( Elements.MaxClockSkewInMinutes, "5" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( life: 1000, revMode: X509RevocationMode.NoCheck, elementEx1: ElementValue( Elements.DefaultTokenLifetimeInMinutes, "60" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( life: 1000, revMode: X509RevocationMode.NoCheck, elementEx4: ElementValue( Elements.DefaultTokenLifetimeInMinutes, "60" ), expectedException: ExpectedException.Config( id: "Jwt10616" ) ) );
// Duplicate Attributes, System.Configuration will catch them.
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( revMode: X509RevocationMode.NoCheck, attributeEx1: Attribute( Attributes.RevocationMode, AttributeValues.X509RevocationModeNoCheck.ToString() ), expectedException: ExpectedException.Config( id: "initialize", inner: new ConfigurationErrorsException( Attributes.RevocationMode ) ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.PeerTrust, attributeEx2: Attribute( Attributes.ValidationMode, AttributeValues.X509CertificateValidationModeNone.ToString() ), expectedException: ExpectedException.Config( id: "initialize", inner: new ConfigurationErrorsException( Attributes.RevocationMode ) ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( storeLoc: StoreLocation.LocalMachine, attributeEx4: Attribute( Attributes.TrustedStoreLocation, StoreLocation.LocalMachine.ToString() ), expectedException: ExpectedException.Config( id: "initialize", inner: new ConfigurationErrorsException( Attributes.RevocationMode ) ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( cert: new AlwaysSucceedCertificateValidator(), attributeEx1: Attribute( Attributes.Validator, typeof( AlwaysSucceedCertificateValidator ).ToString() ), expectedException: ExpectedException.Config( "initialize" ) ) );
// certificate validator
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.Custom, cert: new AlwaysSucceedCertificateValidator() ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 1000 ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 4294967295 ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( name: @"http://AllItemsSet/nameClaim" ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( role: @"http://AllItemsSet/roleClaim" ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( cert: new AlwaysSucceedCertificateValidator(), expectedException: ExpectedException.Config( "Jwt10619" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( clock: TimeSpan.FromMinutes( 15 ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim" ) ) ;
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( cert: new AlwaysSucceedCertificateValidator(), clock: TimeSpan.FromMinutes( 15 ), expectedException: ExpectedException.Config( "Jwt10619" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 1000, name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim", clock: TimeSpan.FromMinutes( 15 ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 1000, name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim", clock: TimeSpan.FromMinutes( 15 ), cert: new AlwaysSucceedCertificateValidator(), certMode: X509CertificateValidationMode.Custom ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( tokenSize: 1000, name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim", clock: TimeSpan.FromMinutes( 15 ), cert: new AlwaysSucceedCertificateValidator(), expectedException: ExpectedException.Config( "Jwt10619" ) ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( role: @"http://AllItemsSet/roleClaim", cert: new AlwaysSucceedCertificateValidator(), clock: TimeSpan.FromMinutes( 15 ), certMode: X509CertificateValidationMode.Custom ) );
RequirementVariations.Add( new ExpectedJwtSecurityTokenRequirement( certMode: X509CertificateValidationMode.PeerTrust, cert: new AlwaysSucceedCertificateValidator(), expectedException: ExpectedException.Config( "Jwt10619" ) ) );
}
//
public static JwtHandlerConfigVariation Variation( string variation )
{
if ( RequirementVariations == null )
{
BuildExpectedRequirements();
}
return BuildVariation( Convert.ToInt32( variation ) );
}
public static JwtHandlerConfigVariation BuildVariation( Int32 variation )
{
return new JwtHandlerConfigVariation()
{
ExpectedSecurityTokenHandler = new JwtSecurityTokenHandler(),
ExpectedJwtSecurityTokenRequirement = RequirementVariations[variation],
};
}
}
[TestClass]
public class JwtSecurityTokenHandlerConfigTest : ConfigurationTest
{
static Dictionary<string, string> _testCases = new Dictionary<string, string>();
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
public JwtSecurityTokenHandlerConfigTest()
{
}
[ClassInitialize]
public static void ClassSetup( TestContext testContext )
{
}
[TestInitialize]
public void Initialize()
{
_testContextProvider = new TestContextProvider( TestContext );
}
/// <summary>
/// The test context that is set by Visual Studio and TAEF - need to keep this exact signature
/// </summary>
public TestContext TestContext { get; set; }
protected override string GetConfiguration( string variationId )
{
JwtHandlerConfigVariation variation = JwtHandlerConfigVariation.Variation( variationId );
string config = @"<system.identityModel><identityConfiguration><securityTokenHandlers>"
+ variation.ExpectedJwtSecurityTokenRequirement.Config
+ @"</securityTokenHandlers></identityConfiguration></system.identityModel>";
Console.WriteLine( string.Format( "\n===================================\nTesting variation: '{0}'\nConfig:\n{1}", variationId, config ) );
return config;
}
protected override void ValidateTestCase( string variationId )
{
JwtHandlerConfigVariation variation = JwtHandlerConfigVariation.Variation( variationId );
try
{
IdentityConfiguration identityConfig = new IdentityConfiguration( IdentityConfiguration.DefaultServiceName );
ExpectedException.ProcessNoException( variation.ExpectedJwtSecurityTokenRequirement.ExpectedException );
VerifyConfig( identityConfig, variation );
}
catch ( Exception ex )
{
ExpectedException.ProcessException( variation.ExpectedJwtSecurityTokenRequirement.ExpectedException, ex );
}
}
private void VerifyConfig( IdentityConfiguration identityconfig, JwtHandlerConfigVariation variation )
{
if ( variation.ExpectedSecurityTokenHandler != null )
{
JwtSecurityTokenHandler handler = identityconfig.SecurityTokenHandlers[typeof( JwtSecurityToken )] as JwtSecurityTokenHandler;
if ( variation.ExpectedJwtSecurityTokenRequirement != null )
{
Assert.IsFalse( !variation.ExpectedJwtSecurityTokenRequirement.AsExpected( handler.JwtSecurityTokenRequirement ) , "JwtSecurityTokenRequirement was not as expected" );
}
}
}
[TestMethod]
[TestProperty( "TestCaseID", "1E62250E-9208-4917-8677-0C82EFE6823E" )]
[Description( "JwtSecurityTokenHandler Configuration Tests" )]
public void JwtSecurityTokenHandler_ConfigTests()
{
JwtHandlerConfigVariation.BuildExpectedRequirements();
for ( int i = 0; i < JwtHandlerConfigVariation.RequirementVariations.Count; i++ )
{
RunTestCase( i.ToString() );
}
}
}
}
| |
namespace android.text
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.text.Layout_))]
public abstract partial class Layout : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Layout()
{
InitJNI();
}
protected Layout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Alignment : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Alignment()
{
InitJNI();
}
internal Alignment(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values7696;
public static global::android.text.Layout.Alignment[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.text.Layout.Alignment>(@__env.CallStaticObjectMethod(android.text.Layout.Alignment.staticClass, global::android.text.Layout.Alignment._values7696)) as android.text.Layout.Alignment[];
}
internal static global::MonoJavaBridge.MethodId _valueOf7697;
public static global::android.text.Layout.Alignment valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.Layout.Alignment.staticClass, global::android.text.Layout.Alignment._valueOf7697, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Alignment;
}
internal static global::MonoJavaBridge.FieldId _ALIGN_CENTER7698;
public static global::android.text.Layout.Alignment ALIGN_CENTER
{
get
{
return default(global::android.text.Layout.Alignment);
}
}
internal static global::MonoJavaBridge.FieldId _ALIGN_NORMAL7699;
public static global::android.text.Layout.Alignment ALIGN_NORMAL
{
get
{
return default(global::android.text.Layout.Alignment);
}
}
internal static global::MonoJavaBridge.FieldId _ALIGN_OPPOSITE7700;
public static global::android.text.Layout.Alignment ALIGN_OPPOSITE
{
get
{
return default(global::android.text.Layout.Alignment);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout.Alignment.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout$Alignment"));
global::android.text.Layout.Alignment._values7696 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.Alignment.staticClass, "values", "()[Landroid/text/Layout/Alignment;");
global::android.text.Layout.Alignment._valueOf7697 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.Alignment.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/text/Layout$Alignment;");
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class Directions : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Directions()
{
InitJNI();
}
protected Directions(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout.Directions.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout$Directions"));
}
}
internal static global::MonoJavaBridge.MethodId _getLineWidth7701;
public virtual float getLineWidth(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getLineWidth7701, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineWidth7701, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getText7702;
public virtual global::java.lang.CharSequence getText()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Layout._getText7702)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getText7702)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _draw7703;
public virtual void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Layout._draw7703, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._draw7703, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _draw7704;
public virtual void draw(android.graphics.Canvas arg0, android.graphics.Path arg1, android.graphics.Paint arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Layout._draw7704, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._draw7704, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getWidth7705;
public virtual int getWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getWidth7705);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getWidth7705);
}
internal static global::MonoJavaBridge.MethodId _getHeight7706;
public virtual int getHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getHeight7706);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getHeight7706);
}
internal static global::MonoJavaBridge.MethodId _getPaint7707;
public virtual global::android.text.TextPaint getPaint()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Layout._getPaint7707)) as android.text.TextPaint;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getPaint7707)) as android.text.TextPaint;
}
internal static global::MonoJavaBridge.MethodId _getLineCount7708;
public abstract int getLineCount();
internal static global::MonoJavaBridge.MethodId _getLineBounds7709;
public virtual int getLineBounds(int arg0, android.graphics.Rect arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineBounds7709, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineBounds7709, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getDesiredWidth7710;
public static float getDesiredWidth(java.lang.CharSequence arg0, int arg1, int arg2, android.text.TextPaint arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.text.Layout.staticClass, global::android.text.Layout._getDesiredWidth7710, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getDesiredWidth7711;
public static float getDesiredWidth(java.lang.CharSequence arg0, android.text.TextPaint arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.text.Layout.staticClass, global::android.text.Layout._getDesiredWidth7711, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getEllipsizedWidth7712;
public virtual int getEllipsizedWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getEllipsizedWidth7712);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getEllipsizedWidth7712);
}
internal static global::MonoJavaBridge.MethodId _increaseWidthTo7713;
public virtual void increaseWidthTo(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Layout._increaseWidthTo7713, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._increaseWidthTo7713, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getAlignment7714;
public virtual global::android.text.Layout.Alignment getAlignment()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Layout._getAlignment7714)) as android.text.Layout.Alignment;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getAlignment7714)) as android.text.Layout.Alignment;
}
internal static global::MonoJavaBridge.MethodId _getSpacingMultiplier7715;
public virtual float getSpacingMultiplier()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getSpacingMultiplier7715);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getSpacingMultiplier7715);
}
internal static global::MonoJavaBridge.MethodId _getSpacingAdd7716;
public virtual float getSpacingAdd()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getSpacingAdd7716);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getSpacingAdd7716);
}
internal static global::MonoJavaBridge.MethodId _getLineTop7717;
public abstract int getLineTop(int arg0);
internal static global::MonoJavaBridge.MethodId _getLineDescent7718;
public abstract int getLineDescent(int arg0);
internal static global::MonoJavaBridge.MethodId _getLineStart7719;
public abstract int getLineStart(int arg0);
internal static global::MonoJavaBridge.MethodId _getParagraphDirection7720;
public abstract int getParagraphDirection(int arg0);
internal static global::MonoJavaBridge.MethodId _getLineContainsTab7721;
public abstract bool getLineContainsTab(int arg0);
internal static global::MonoJavaBridge.MethodId _getLineDirections7722;
public abstract global::android.text.Layout.Directions getLineDirections(int arg0);
internal static global::MonoJavaBridge.MethodId _getTopPadding7723;
public abstract int getTopPadding();
internal static global::MonoJavaBridge.MethodId _getBottomPadding7724;
public abstract int getBottomPadding();
internal static global::MonoJavaBridge.MethodId _getPrimaryHorizontal7725;
public virtual float getPrimaryHorizontal(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getPrimaryHorizontal7725, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getPrimaryHorizontal7725, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSecondaryHorizontal7726;
public virtual float getSecondaryHorizontal(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getSecondaryHorizontal7726, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getSecondaryHorizontal7726, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineLeft7727;
public virtual float getLineLeft(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getLineLeft7727, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineLeft7727, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineRight7728;
public virtual float getLineRight(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getLineRight7728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineRight7728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineMax7729;
public virtual float getLineMax(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.text.Layout._getLineMax7729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineMax7729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineForVertical7730;
public virtual int getLineForVertical(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineForVertical7730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineForVertical7730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineForOffset7731;
public virtual int getLineForOffset(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineForOffset7731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineForOffset7731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOffsetForHorizontal7732;
public virtual int getOffsetForHorizontal(int arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getOffsetForHorizontal7732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getOffsetForHorizontal7732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getLineEnd7733;
public virtual int getLineEnd(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineEnd7733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineEnd7733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineVisibleEnd7734;
public virtual int getLineVisibleEnd(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineVisibleEnd7734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineVisibleEnd7734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineBottom7735;
public virtual int getLineBottom(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineBottom7735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineBottom7735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineBaseline7736;
public virtual int getLineBaseline(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineBaseline7736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineBaseline7736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineAscent7737;
public virtual int getLineAscent(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getLineAscent7737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getLineAscent7737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOffsetToLeftOf7738;
public virtual int getOffsetToLeftOf(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getOffsetToLeftOf7738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getOffsetToLeftOf7738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOffsetToRightOf7739;
public virtual int getOffsetToRightOf(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getOffsetToRightOf7739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getOffsetToRightOf7739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCursorPath7740;
public virtual void getCursorPath(int arg0, android.graphics.Path arg1, java.lang.CharSequence arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Layout._getCursorPath7740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getCursorPath7740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public void getCursorPath(int arg0, android.graphics.Path arg1, string arg2)
{
getCursorPath(arg0, arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2);
}
internal static global::MonoJavaBridge.MethodId _getSelectionPath7741;
public virtual void getSelectionPath(int arg0, int arg1, android.graphics.Path arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.Layout._getSelectionPath7741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getSelectionPath7741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _getParagraphAlignment7742;
public virtual global::android.text.Layout.Alignment getParagraphAlignment(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Layout._getParagraphAlignment7742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Alignment;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getParagraphAlignment7742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Alignment;
}
internal static global::MonoJavaBridge.MethodId _getParagraphLeft7743;
public virtual int getParagraphLeft(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getParagraphLeft7743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getParagraphLeft7743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getParagraphRight7744;
public virtual int getParagraphRight(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout._getParagraphRight7744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._getParagraphRight7744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isSpanned7745;
protected virtual bool isSpanned()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.Layout._isSpanned7745);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.Layout.staticClass, global::android.text.Layout._isSpanned7745);
}
internal static global::MonoJavaBridge.MethodId _getEllipsisStart7746;
public abstract int getEllipsisStart(int arg0);
internal static global::MonoJavaBridge.MethodId _getEllipsisCount7747;
public abstract int getEllipsisCount(int arg0);
internal static global::MonoJavaBridge.MethodId _Layout7748;
protected Layout(java.lang.CharSequence arg0, android.text.TextPaint arg1, int arg2, android.text.Layout.Alignment arg3, float arg4, float arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.Layout.staticClass, global::android.text.Layout._Layout7748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
Init(@__env, handle);
}
public static int DIR_LEFT_TO_RIGHT
{
get
{
return 1;
}
}
public static int DIR_RIGHT_TO_LEFT
{
get
{
return -1;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout"));
global::android.text.Layout._getLineWidth7701 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineWidth", "(I)F");
global::android.text.Layout._getText7702 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getText", "()Ljava/lang/CharSequence;");
global::android.text.Layout._draw7703 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "draw", "(Landroid/graphics/Canvas;)V");
global::android.text.Layout._draw7704 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "draw", "(Landroid/graphics/Canvas;Landroid/graphics/Path;Landroid/graphics/Paint;I)V");
global::android.text.Layout._getWidth7705 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getWidth", "()I");
global::android.text.Layout._getHeight7706 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getHeight", "()I");
global::android.text.Layout._getPaint7707 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getPaint", "()Landroid/text/TextPaint;");
global::android.text.Layout._getLineCount7708 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineCount", "()I");
global::android.text.Layout._getLineBounds7709 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineBounds", "(ILandroid/graphics/Rect;)I");
global::android.text.Layout._getDesiredWidth7710 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.staticClass, "getDesiredWidth", "(Ljava/lang/CharSequence;IILandroid/text/TextPaint;)F");
global::android.text.Layout._getDesiredWidth7711 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.staticClass, "getDesiredWidth", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;)F");
global::android.text.Layout._getEllipsizedWidth7712 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getEllipsizedWidth", "()I");
global::android.text.Layout._increaseWidthTo7713 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "increaseWidthTo", "(I)V");
global::android.text.Layout._getAlignment7714 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getAlignment", "()Landroid/text/Layout$Alignment;");
global::android.text.Layout._getSpacingMultiplier7715 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getSpacingMultiplier", "()F");
global::android.text.Layout._getSpacingAdd7716 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getSpacingAdd", "()F");
global::android.text.Layout._getLineTop7717 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineTop", "(I)I");
global::android.text.Layout._getLineDescent7718 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineDescent", "(I)I");
global::android.text.Layout._getLineStart7719 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineStart", "(I)I");
global::android.text.Layout._getParagraphDirection7720 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getParagraphDirection", "(I)I");
global::android.text.Layout._getLineContainsTab7721 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineContainsTab", "(I)Z");
global::android.text.Layout._getLineDirections7722 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineDirections", "(I)Landroid/text/Layout$Directions;");
global::android.text.Layout._getTopPadding7723 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getTopPadding", "()I");
global::android.text.Layout._getBottomPadding7724 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getBottomPadding", "()I");
global::android.text.Layout._getPrimaryHorizontal7725 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getPrimaryHorizontal", "(I)F");
global::android.text.Layout._getSecondaryHorizontal7726 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getSecondaryHorizontal", "(I)F");
global::android.text.Layout._getLineLeft7727 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineLeft", "(I)F");
global::android.text.Layout._getLineRight7728 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineRight", "(I)F");
global::android.text.Layout._getLineMax7729 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineMax", "(I)F");
global::android.text.Layout._getLineForVertical7730 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineForVertical", "(I)I");
global::android.text.Layout._getLineForOffset7731 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineForOffset", "(I)I");
global::android.text.Layout._getOffsetForHorizontal7732 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getOffsetForHorizontal", "(IF)I");
global::android.text.Layout._getLineEnd7733 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineEnd", "(I)I");
global::android.text.Layout._getLineVisibleEnd7734 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineVisibleEnd", "(I)I");
global::android.text.Layout._getLineBottom7735 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineBottom", "(I)I");
global::android.text.Layout._getLineBaseline7736 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineBaseline", "(I)I");
global::android.text.Layout._getLineAscent7737 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getLineAscent", "(I)I");
global::android.text.Layout._getOffsetToLeftOf7738 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getOffsetToLeftOf", "(I)I");
global::android.text.Layout._getOffsetToRightOf7739 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getOffsetToRightOf", "(I)I");
global::android.text.Layout._getCursorPath7740 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getCursorPath", "(ILandroid/graphics/Path;Ljava/lang/CharSequence;)V");
global::android.text.Layout._getSelectionPath7741 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getSelectionPath", "(IILandroid/graphics/Path;)V");
global::android.text.Layout._getParagraphAlignment7742 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getParagraphAlignment", "(I)Landroid/text/Layout$Alignment;");
global::android.text.Layout._getParagraphLeft7743 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getParagraphLeft", "(I)I");
global::android.text.Layout._getParagraphRight7744 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getParagraphRight", "(I)I");
global::android.text.Layout._isSpanned7745 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "isSpanned", "()Z");
global::android.text.Layout._getEllipsisStart7746 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getEllipsisStart", "(I)I");
global::android.text.Layout._getEllipsisCount7747 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "getEllipsisCount", "(I)I");
global::android.text.Layout._Layout7748 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "<init>", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;ILandroid/text/Layout$Alignment;FF)V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.Layout))]
public sealed partial class Layout_ : android.text.Layout
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Layout_()
{
InitJNI();
}
internal Layout_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getLineCount7749;
public override int getLineCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getLineCount7749);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getLineCount7749);
}
internal static global::MonoJavaBridge.MethodId _getLineTop7750;
public override int getLineTop(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getLineTop7750, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getLineTop7750, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineDescent7751;
public override int getLineDescent(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getLineDescent7751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getLineDescent7751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineStart7752;
public override int getLineStart(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getLineStart7752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getLineStart7752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getParagraphDirection7753;
public override int getParagraphDirection(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getParagraphDirection7753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getParagraphDirection7753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineContainsTab7754;
public override bool getLineContainsTab(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.Layout_._getLineContainsTab7754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getLineContainsTab7754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLineDirections7755;
public override global::android.text.Layout.Directions getLineDirections(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.Layout_._getLineDirections7755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Directions;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getLineDirections7755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Directions;
}
internal static global::MonoJavaBridge.MethodId _getTopPadding7756;
public override int getTopPadding()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getTopPadding7756);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getTopPadding7756);
}
internal static global::MonoJavaBridge.MethodId _getBottomPadding7757;
public override int getBottomPadding()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getBottomPadding7757);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getBottomPadding7757);
}
internal static global::MonoJavaBridge.MethodId _getEllipsisStart7758;
public override int getEllipsisStart(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getEllipsisStart7758, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getEllipsisStart7758, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getEllipsisCount7759;
public override int getEllipsisCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.text.Layout_._getEllipsisCount7759, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.Layout_.staticClass, global::android.text.Layout_._getEllipsisCount7759, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout"));
global::android.text.Layout_._getLineCount7749 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getLineCount", "()I");
global::android.text.Layout_._getLineTop7750 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getLineTop", "(I)I");
global::android.text.Layout_._getLineDescent7751 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getLineDescent", "(I)I");
global::android.text.Layout_._getLineStart7752 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getLineStart", "(I)I");
global::android.text.Layout_._getParagraphDirection7753 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getParagraphDirection", "(I)I");
global::android.text.Layout_._getLineContainsTab7754 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getLineContainsTab", "(I)Z");
global::android.text.Layout_._getLineDirections7755 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getLineDirections", "(I)Landroid/text/Layout$Directions;");
global::android.text.Layout_._getTopPadding7756 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getTopPadding", "()I");
global::android.text.Layout_._getBottomPadding7757 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getBottomPadding", "()I");
global::android.text.Layout_._getEllipsisStart7758 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getEllipsisStart", "(I)I");
global::android.text.Layout_._getEllipsisCount7759 = @__env.GetMethodIDNoThrow(global::android.text.Layout_.staticClass, "getEllipsisCount", "(I)I");
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.ServiceModel.Channels.Message.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.ServiceModel.Channels
{
abstract public partial class Message : IDisposable
{
#region Methods and constructors
public void Close()
{
}
public MessageBuffer CreateBufferedCopy(int maxBufferSize)
{
Contract.Requires(0 <= maxBufferSize);
Contract.Ensures(Contract.Result<MessageBuffer>() != null);
return default(MessageBuffer);
}
public static Message CreateMessage(System.Xml.XmlDictionaryReader envelopeReader, int maxSizeOfHeaders, MessageVersion version)
{
Contract.Requires(envelopeReader != null);
Contract.Requires(version != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(System.Xml.XmlReader envelopeReader, int maxSizeOfHeaders, MessageVersion version)
{
Contract.Requires(envelopeReader != null);
Contract.Requires(version != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, System.ServiceModel.FaultCode faultCode, string reason, string action)
{
Contract.Requires(version != null);
Contract.Requires(faultCode != null);
Contract.Requires(reason != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, MessageFault fault, string action)
{
Contract.Requires(version != null);
Contract.Requires(fault != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, System.ServiceModel.FaultCode faultCode, string reason, Object detail, string action)
{
Contract.Requires(version != null);
Contract.Requires(faultCode != null);
Contract.Requires(reason != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, string action)
{
Contract.Requires(version != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, string action, Object body, System.Runtime.Serialization.XmlObjectSerializer serializer)
{
Contract.Requires(version != null);
Contract.Requires(body != null);
Contract.Requires(serializer != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, string action, Object body)
{
Contract.Requires(version != null);
Contract.Requires(body != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, string action, System.Xml.XmlReader body)
{
Contract.Requires(version != null);
Contract.Requires(body != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, string action, BodyWriter body)
{
Contract.Requires(version != null);
Contract.Requires(body != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public static Message CreateMessage(MessageVersion version, string action, System.Xml.XmlDictionaryReader body)
{
Contract.Requires(version != null);
Contract.Requires(body != null);
Contract.Ensures(Contract.Result<System.ServiceModel.Channels.Message>() != null);
return default(Message);
}
public T GetBody<T>()
{
Contract.Ensures(Contract.Result<T>() != null);
return default(T);
}
public T GetBody<T>(System.Runtime.Serialization.XmlObjectSerializer serializer)
{
Contract.Ensures(Contract.Result<T>() != null);
return default(T);
}
public string GetBodyAttribute(string localName, string ns)
{
Contract.Requires(localName != null);
Contract.Requires(ns != null);
return default(string);
}
public System.Xml.XmlDictionaryReader GetReaderAtBodyContents()
{
return default(System.Xml.XmlDictionaryReader);
}
protected Message()
{
}
protected virtual new void OnBodyToString(System.Xml.XmlDictionaryWriter writer)
{
Contract.Requires(writer != null);
}
protected virtual new void OnClose()
{
}
protected virtual new MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
Contract.Requires(0 <= maxBufferSize);
return default(MessageBuffer);
}
protected virtual new string OnGetBodyAttribute(string localName, string ns)
{
return default(string);
}
protected virtual new System.Xml.XmlDictionaryReader OnGetReaderAtBodyContents()
{
return default(System.Xml.XmlDictionaryReader);
}
protected abstract void OnWriteBodyContents(System.Xml.XmlDictionaryWriter writer);
protected virtual new void OnWriteMessage(System.Xml.XmlDictionaryWriter writer)
{
}
protected virtual new void OnWriteStartBody(System.Xml.XmlDictionaryWriter writer)
{
Contract.Requires(writer != null);
}
protected virtual new void OnWriteStartEnvelope(System.Xml.XmlDictionaryWriter writer)
{
}
protected virtual new void OnWriteStartHeaders(System.Xml.XmlDictionaryWriter writer)
{
}
void System.IDisposable.Dispose()
{
}
public void WriteBody(System.Xml.XmlWriter writer)
{
}
public void WriteBody(System.Xml.XmlDictionaryWriter writer)
{
Contract.Requires(writer != null);
}
public void WriteBodyContents(System.Xml.XmlDictionaryWriter writer)
{
}
public void WriteMessage(System.Xml.XmlWriter writer)
{
}
public void WriteMessage(System.Xml.XmlDictionaryWriter writer)
{
}
public void WriteStartBody(System.Xml.XmlDictionaryWriter writer)
{
}
public void WriteStartBody(System.Xml.XmlWriter writer)
{
}
public void WriteStartEnvelope(System.Xml.XmlDictionaryWriter writer)
{
}
#endregion
#region Properties and indexers
public abstract MessageHeaders Headers
{
get;
}
protected bool IsDisposed
{
get
{
return default(bool);
}
}
public virtual new bool IsEmpty
{
get
{
return default(bool);
}
}
public virtual new bool IsFault
{
get
{
return default(bool);
}
}
public abstract MessageProperties Properties
{
get;
}
public MessageState State
{
get
{
return default(MessageState);
}
}
public abstract MessageVersion Version
{
get;
}
#endregion
}
#region Message contract binding
[ContractClass(typeof(MessageContract))]
public partial class Message {
}
[ContractClassFor(typeof(Message))]
abstract class MessageContract : Message {
protected override void OnWriteBodyContents(Xml.XmlDictionaryWriter writer) {
throw new NotImplementedException();
}
public override MessageHeaders Headers {
get {
Contract.Ensures(Contract.Result<MessageHeaders>() != null);
throw new NotImplementedException(); }
}
public override MessageProperties Properties {
get {
Contract.Ensures(Contract.Result<MessageProperties>() != null);
throw new NotImplementedException();
}
}
public override MessageVersion Version {
get {
Contract.Ensures(Contract.Result<MessageVersion>() != null);
throw new NotImplementedException(); }
}
}
#endregion
}
| |
/*
* CSharpCodeCompiler.cs - Implementation of the
* System.CodeDom.Compiler.CSharpCodeCompiler class.
*
* Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.CodeDom.Compiler
{
#if CONFIG_CODEDOM
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Text;
using System.Diagnostics;
internal class CSharpCodeCompiler : CodeCompiler
{
// List of reserved words in C#.
private static readonly String[] reservedWords = {
"abstract", "__arglist", "as", "base", "bool",
"break", "__builtin", "byte", "case", "catch",
"char", "checked", "class", "const", "continue",
"decimal", "default", "delegate", "do", "double",
"else", "enum", "event", "explicit", "extern",
"false", "finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit", "in", "int",
"interface", "internal", "is", "lock", "long",
"__long_double", "__makeref", "__module", "namespace",
"new", "null", "object", "operator", "out", "override",
"params", "private", "protected", "public", "readonly",
"ref", "__reftype", "__refvalue", "return", "sbyte",
"sealed", "short", "sizeof", "stackalloc", "static",
"string", "struct", "switch", "this", "throw", "true",
"try", "typeof", "uint", "ulong", "unchecked", "unsafe",
"ushort", "using", "virtual", "void", "volatile", "while"
};
// Internal state.
private bool outputForInit;
// Constructor.
public CSharpCodeCompiler() : base()
{
outputForInit = false;
}
// Get the name of the compiler.
protected override String CompilerName
{
get
{
// Use the Portable.NET C# compiler.
String cscc = Environment.GetEnvironmentVariable("CSCC");
if(cscc != null)
{
return cscc;
}
else
{
return "cscc";
}
}
}
// Get the file extension to use for source files.
protected override String FileExtension
{
get
{
return ".cs";
}
}
// Add an argument to an argument array.
private static void AddArgument(ref String[] args, String arg)
{
String[] newArgs = new String [args.Length + 1];
Array.Copy(args, newArgs, args.Length);
newArgs[args.Length] = arg;
args = newArgs;
}
// Build a list of arguments from an option string. The arguments
// are assumed to use the "csc" syntax, which we will convert into
// the "cscc" syntax within "CmdArgsFromParameters".
private static String[] ArgsFromOptions(String options)
{
return ProcessStartInfo.ArgumentsToArgV(options);
}
// Determine if a string looks like a "csc" option.
private static bool IsOption(String opt, String name)
{
return (String.Compare(opt, name, true,
CultureInfo.InvariantCulture) == 0);
}
// Add a list of "csc" defines to a "cscc" command-line.
private static void AddDefines(ref String[] args, String defines)
{
if(defines != String.Empty)
{
String[] defs = defines.Split(',', ';');
foreach(String def in defs)
{
AddArgument(ref args, "-D" + def);
}
}
}
// Convert compiler parameters into compiler arguments (common code).
internal static String CmdArgsFromParameters
(CompilerParameters options, String language)
{
String[] args = new String [0];
int posn, posn2;
AddArgument(ref args, "-x");
AddArgument(ref args, language);
if(options.OutputAssembly != null)
{
AddArgument(ref args, "-o");
AddArgument(ref args, options.OutputAssembly);
}
if(options.IncludeDebugInformation)
{
AddArgument(ref args, "-g");
}
if(!(options.GenerateExecutable))
{
AddArgument(ref args, "-shared");
}
if(options.TreatWarningsAsErrors)
{
AddArgument(ref args, "-Werror");
}
if(options.WarningLevel >= 0)
{
AddArgument(ref args, "-Wall");
}
if(options.MainClass != null)
{
AddArgument(ref args, "-e");
AddArgument(ref args, options.MainClass);
}
foreach(String _refAssem in options.ReferencedAssemblies)
{
// Strip ".dll" from the end of the assembly name.
String refAssem = _refAssem;
if(refAssem.Length > 4 &&
String.Compare(refAssem, refAssem.Length - 4,
".dll", 0, 4, true,
CultureInfo.InvariantCulture) == 0)
{
refAssem = refAssem.Substring(0, refAssem.Length - 4);
}
// Split the assembly into its path and base name.
posn = refAssem.LastIndexOf('/');
posn2 = refAssem.LastIndexOf('\\');
if(posn2 > posn)
{
posn = posn2;
}
if(posn != -1)
{
// Add "-L" and "-l" options to the command-line.
AddArgument(ref args,
"-L" + refAssem.Substring(0, posn));
AddArgument(ref args,
"-l" + refAssem.Substring(posn + 1));
}
else
{
// Add just a "-l" option to the command-line.
AddArgument(ref args, "-l" + refAssem);
}
}
if(options.Win32Resource != null)
{
AddArgument(ref args,
"-fresources=" + options.Win32Resource);
}
if(options.CompilerOptions != null)
{
String[] cscArgs = ArgsFromOptions(options.CompilerOptions);
foreach(String opt in cscArgs)
{
if(IsOption(opt, "/optimize") ||
IsOption(opt, "/optimize+") ||
IsOption(opt, "/o") ||
IsOption(opt, "/o+"))
{
AddArgument(ref args, "-O2");
}
else if(IsOption(opt, "/checked") ||
IsOption(opt, "/checked+"))
{
AddArgument(ref args, "-fchecked");
}
else if(IsOption(opt, "/checked-"))
{
AddArgument(ref args, "-funchecked");
}
else if(IsOption(opt, "/unsafe") ||
IsOption(opt, "/unsafe+"))
{
AddArgument(ref args, "-funsafe");
}
else if(IsOption(opt, "/nostdlib") ||
IsOption(opt, "/nostdlib+"))
{
AddArgument(ref args, "-fnostdlib");
}
else if(String.Compare(opt, 0, "/define:", 0, 8, true,
CultureInfo.InvariantCulture)
== 0)
{
AddDefines(ref args, opt.Substring(8));
}
else if(String.Compare(opt, 0, "/d:", 0, 3, true,
CultureInfo.InvariantCulture)
== 0)
{
AddDefines(ref args, opt.Substring(3));
}
}
}
return JoinStringArray(args, " ");
}
// Convert compiler parameters into compiler arguments.
protected override String CmdArgsFromParameters
(CompilerParameters options)
{
return CmdArgsFromParameters(options, "csharp");
}
// Process an output line from the compiler.
protected override void ProcessCompilerOutputLine
(CompilerResults results, String line)
{
CompilerError error = ProcessCompilerOutputLine(line);
if(error != null)
{
results.Errors.Add(error);
}
}
// Get the token for "null".
protected override String NullToken
{
get
{
return "null";
}
}
// Create an escaped identifier if "value" is a language keyword.
protected override String CreateEscapedIdentifier(String value)
{
if(Array.IndexOf(reservedWords, value) != -1)
{
return "@" + value;
}
else
{
return value;
}
}
// Create a valid identifier if "value" is a language keyword.
protected override String CreateValidIdentifier(String value)
{
if(Array.IndexOf(reservedWords, value) != -1)
{
return "_" + value;
}
else
{
return value;
}
}
// Normalize a type name to its keyword form.
private String NormalizeTypeName(String type)
{
switch(type)
{
case "System.Void": type = "void"; break;
case "System.Boolean": type = "bool"; break;
case "System.Char": type = "char"; break;
case "System.Byte": type = "byte"; break;
case "System.SByte": type = "sbyte"; break;
case "System.Int16": type = "short"; break;
case "System.UInt16": type = "ushort"; break;
case "System.Int32": type = "int"; break;
case "System.UInt32": type = "uint"; break;
case "System.Int64": type = "long"; break;
case "System.UInt64": type = "ulong"; break;
case "System.Single": type = "float"; break;
case "System.Double": type = "double"; break;
case "System.Decimal": type = "decimal"; break;
case "System.String": type = "string"; break;
case "System.Object": type = "object"; break;
default: break;
}
return type;
}
// Generate various expression categories.
protected override void GenerateArgumentReferenceExpression
(CodeArgumentReferenceExpression e)
{
OutputIdentifier(e.ParameterName);
}
protected override void GenerateArrayCreateExpression
(CodeArrayCreateExpression e)
{
Output.Write("new ");
if(e.Initializers.Count == 0)
{
Output.Write(NormalizeTypeName(e.CreateType.BaseType));
Output.Write("[");
if(e.SizeExpression != null)
{
GenerateExpression(e.SizeExpression);
}
else
{
Output.Write(e.Size);
}
Output.Write("]");
}
else
{
OutputType(e.CreateType);
if(e.CreateType.ArrayRank == 0)
{
Output.Write("[]");
}
Output.WriteLine(" {");
Indent += 1;
OutputExpressionList(e.Initializers, true);
Indent -= 1;
Output.Write("}");
}
}
protected override void GenerateArrayIndexerExpression
(CodeArrayIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write("[");
OutputExpressionList(e.Indices);
Output.Write("]");
}
protected override void GenerateBaseReferenceExpression
(CodeBaseReferenceExpression e)
{
Output.Write("base");
}
protected override void GenerateCastExpression
(CodeCastExpression e)
{
// Heavily bracket the cast to prevent the possibility
// of ambiguity issues within the compiler. See the
// Portable.NET "cs_grammar.y" file for a description of
// the possible conflicts that may arise without brackets.
Output.Write("((");
OutputType(e.TargetType);
Output.Write(")(");
GenerateExpression(e.Expression);
Output.Write("))");
}
protected override void GenerateDelegateCreateExpression
(CodeDelegateCreateExpression e)
{
Output.Write("new ");
OutputType(e.DelegateType);
Output.Write("(");
if(e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.MethodName);
Output.Write(")");
}
protected override void GenerateDelegateInvokeExpression
(CodeDelegateInvokeExpression e)
{
if(e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
}
Output.Write("(");
OutputExpressionList(e.Parameters);
Output.Write(")");
}
protected override void GenerateEventReferenceExpression
(CodeEventReferenceExpression e)
{
if(e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.EventName);
}
protected override void GenerateFieldReferenceExpression
(CodeFieldReferenceExpression e)
{
if(e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.FieldName);
}
protected override void GenerateIndexerExpression
(CodeIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write("[");
OutputExpressionList(e.Indices);
Output.Write("]");
}
protected override void GenerateMethodInvokeExpression
(CodeMethodInvokeExpression e)
{
GenerateMethodReferenceExpression(e.Method);
Output.Write("(");
OutputExpressionList(e.Parameters);
Output.Write(")");
}
protected override void GenerateMethodReferenceExpression
(CodeMethodReferenceExpression e)
{
if(e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.MethodName);
}
protected override void GenerateObjectCreateExpression
(CodeObjectCreateExpression e)
{
Output.Write("new ");
OutputType(e.CreateType);
Output.Write("(");
OutputExpressionList(e.Parameters);
Output.Write(")");
}
protected override void GeneratePropertyReferenceExpression
(CodePropertyReferenceExpression e)
{
if(e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.PropertyName);
}
protected override void GeneratePropertySetValueReferenceExpression
(CodePropertySetValueReferenceExpression e)
{
Output.Write("value");
}
protected override void GenerateSnippetExpression
(CodeSnippetExpression e)
{
Output.Write(e.Value);
}
protected override void GenerateThisReferenceExpression
(CodeThisReferenceExpression e)
{
Output.Write("this");
}
protected override void GenerateVariableReferenceExpression
(CodeVariableReferenceExpression e)
{
OutputIdentifier(e.VariableName);
}
// Start a new indented block.
private void StartBlock()
{
if(Options.BracingStyle == "C")
{
Output.WriteLine();
Output.WriteLine("{");
}
else
{
Output.WriteLine(" {");
}
Indent += 1;
}
// End an indented block.
private void EndBlock()
{
Indent -= 1;
Output.WriteLine("}");
}
// Generate various statement categories.
protected override void GenerateAssignStatement
(CodeAssignStatement e)
{
GenerateExpression(e.Left);
Output.Write(" = ");
GenerateExpression(e.Right);
if(!outputForInit)
{
Output.WriteLine(";");
}
}
protected override void GenerateAttachEventStatement
(CodeAttachEventStatement e)
{
GenerateExpression(e.Event);
Output.Write(" += ");
GenerateExpression(e.Listener);
Output.WriteLine(";");
}
protected override void GenerateConditionStatement
(CodeConditionStatement e)
{
Output.Write("if (");
GenerateExpression(e.Condition);
Output.Write(")");
StartBlock();
GenerateStatements(e.TrueStatements);
EndBlock();
CodeStatementCollection stmts = e.FalseStatements;
if(stmts.Count > 0 || Options.ElseOnClosing)
{
Output.Write("else");
StartBlock();
GenerateStatements(stmts);
EndBlock();
}
}
protected override void GenerateExpressionStatement
(CodeExpressionStatement e)
{
GenerateExpression(e.Expression);
if(!outputForInit)
{
Output.WriteLine(";");
}
}
protected override void GenerateGotoStatement
(CodeGotoStatement e)
{
Output.Write("goto ");
Output.Write(e.Label);
Output.WriteLine(";");
}
protected override void GenerateIterationStatement
(CodeIterationStatement e)
{
if(e.InitStatement == null &&
e.TestExpression != null &&
e.IncrementStatement == null)
{
// Special case - output a "while" statement.
Output.Write("while (");
GenerateExpression(e.TestExpression);
Output.Write(")");
StartBlock();
GenerateStatements(e.Statements);
EndBlock();
}
else
{
// Output a "for" statement.
Output.Write("for (");
outputForInit = true;
if(e.InitStatement != null)
{
GenerateStatement(e.InitStatement);
}
Output.Write("; ");
if(e.TestExpression != null)
{
GenerateExpression(e.TestExpression);
}
Output.Write("; ");
if(e.IncrementStatement != null)
{
GenerateStatement(e.IncrementStatement);
}
outputForInit = false;
Output.Write(")");
StartBlock();
GenerateStatements(e.Statements);
EndBlock();
}
}
protected override void GenerateLabeledStatement
(CodeLabeledStatement e)
{
Indent -= 1;
Output.Write(e.Label);
Output.WriteLine(":");
Indent += 1;
GenerateStatement(e.Statement);
}
protected override void GenerateMethodReturnStatement
(CodeMethodReturnStatement e)
{
if(e.Expression != null)
{
Output.Write("return ");
GenerateExpression(e.Expression);
Output.WriteLine(";");
}
else
{
Output.WriteLine("return;");
}
}
protected override void GenerateRemoveEventStatement
(CodeRemoveEventStatement e)
{
GenerateExpression(e.Event);
Output.Write(" -= ");
GenerateExpression(e.Listener);
Output.WriteLine(";");
}
protected override void GenerateThrowExceptionStatement
(CodeThrowExceptionStatement e)
{
if(e.ToThrow != null)
{
Output.Write("throw ");
GenerateExpression(e.ToThrow);
Output.WriteLine(";");
}
else
{
Output.WriteLine("throw;");
}
}
protected override void GenerateTryCatchFinallyStatement
(CodeTryCatchFinallyStatement e)
{
Output.Write("try");
StartBlock();
GenerateStatements(e.TryStatements);
EndBlock();
CodeCatchClauseCollection clauses = e.CatchClauses;
if(clauses.Count > 0)
{
foreach(CodeCatchClause clause in clauses)
{
if(clause.CatchExceptionType != null)
{
Output.Write("catch (");
OutputType(clause.CatchExceptionType);
if(clause.LocalName != null)
{
Output.Write(" ");
OutputIdentifier(clause.LocalName);
}
Output.Write(")");
}
else
{
Output.Write("catch");
}
StartBlock();
GenerateStatements(clause.Statements);
EndBlock();
}
}
CodeStatementCollection fin = e.FinallyStatements;
if(fin.Count > 0)
{
Output.Write("finally");
StartBlock();
GenerateStatements(fin);
EndBlock();
}
}
protected override void GenerateVariableDeclarationStatement
(CodeVariableDeclarationStatement e)
{
OutputTypeNamePair(e.Type, e.Name);
if(e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
if(!outputForInit)
{
Output.WriteLine(";");
}
}
// Generate various declaration categories.
protected override void GenerateAttributeDeclarationsStart
(CodeAttributeDeclarationCollection attributes)
{
Output.Write("[");
}
protected override void GenerateAttributeDeclarationsEnd
(CodeAttributeDeclarationCollection attributes)
{
Output.Write("]");
}
protected override void GenerateConstructor
(CodeConstructor e, CodeTypeDeclaration c)
{
// Bail out if not a class or struct.
if(!IsCurrentClass && !IsCurrentStruct)
{
return;
}
// Output the attributes and constructor signature.
OutputAttributeDeclarations(e.CustomAttributes);
OutputMemberAccessModifier(e.Attributes);
OutputIdentifier(CurrentTypeName);
Output.Write("(");
OutputParameters(e.Parameters);
Output.Write(")");
// Output the ": base" or ": this" expressions.
if(e.BaseConstructorArgs.Count > 0)
{
Output.WriteLine(" : ");
Indent += 2;
Output.Write("base(");
OutputExpressionList(e.BaseConstructorArgs);
Output.Write(")");
Indent -= 2;
}
if(e.ChainedConstructorArgs.Count > 0)
{
Output.WriteLine(" : ");
Indent += 2;
Output.Write("base(");
OutputExpressionList(e.ChainedConstructorArgs);
Output.Write(")");
Indent -= 2;
}
// Output the body of the constructor.
StartBlock();
GenerateStatements(e.Statements);
EndBlock();
}
protected override void GenerateEntryPointMethod
(CodeEntryPointMethod e, CodeTypeDeclaration c)
{
Output.Write("public static void Main()");
StartBlock();
GenerateStatements(e.Statements);
EndBlock();
}
protected override void GenerateEvent
(CodeMemberEvent e, CodeTypeDeclaration c)
{
// Bail out if not a class, struct, or interface.
if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface)
{
return;
}
// Output the event definition.
OutputAttributeDeclarations(e.CustomAttributes);
if(e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
Output.Write("event ");
OutputTypeNamePair(e.Type, e.Name);
}
else
{
Output.Write("event ");
OutputTypeNamePair
(e.Type, e.PrivateImplementationType + "." + e.Name);
}
Output.WriteLine(";");
}
protected override void GenerateField(CodeMemberField e)
{
// Bail out if not a class, struct, or enum.
if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentEnum)
{
return;
}
// Generate information about the field.
if(!IsCurrentEnum)
{
OutputAttributeDeclarations(e.CustomAttributes);
OutputMemberAccessModifier(e.Attributes);
OutputFieldScopeModifier(e.Attributes);
OutputTypeNamePair(e.Type, e.Name);
if(e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine(";");
}
else
{
OutputAttributeDeclarations(e.CustomAttributes);
OutputIdentifier(e.Name);
if(e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine(",");
}
}
protected override void GenerateMethod
(CodeMemberMethod e, CodeTypeDeclaration c)
{
// Bail out if not a class, struct, or interface.
if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface)
{
return;
}
// Output the attributes and method signature.
OutputAttributeDeclarations(e.CustomAttributes);
if(e.ReturnTypeCustomAttributes.Count > 0)
{
OutputAttributeDeclarations
("return: ", e.ReturnTypeCustomAttributes);
}
if(!IsCurrentInterface)
{
if(e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
}
else if((e.Attributes & MemberAttributes.VTableMask)
== MemberAttributes.New)
{
Output.Write("new ");
}
if(e.ReturnType != null)
{
OutputType(e.ReturnType);
}
else
{
Output.Write("void");
}
Output.Write(" ");
if(e.PrivateImplementationType != null && !IsCurrentInterface)
{
Output.Write(e.PrivateImplementationType.BaseType);
Output.Write(".");
}
OutputIdentifier(e.Name);
Output.Write("(");
OutputParameters(e.Parameters);
Output.Write(")");
// Output the body of the method.
if(IsCurrentInterface ||
(e.Attributes & MemberAttributes.ScopeMask) ==
MemberAttributes.Abstract)
{
Output.WriteLine(";");
}
else
{
StartBlock();
GenerateStatements(e.Statements);
EndBlock();
}
}
protected override void GenerateProperty
(CodeMemberProperty e, CodeTypeDeclaration c)
{
// Bail out if not a class, struct, or interface.
if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentInterface)
{
return;
}
// Output the attributes and property signature.
OutputAttributeDeclarations(e.CustomAttributes);
if(!IsCurrentInterface)
{
if(e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
}
else if((e.Attributes & MemberAttributes.VTableMask)
== MemberAttributes.New)
{
Output.Write("new ");
}
OutputType(e.Type);
Output.Write(" ");
if(e.PrivateImplementationType != null && !IsCurrentInterface)
{
Output.Write(e.PrivateImplementationType.BaseType);
Output.Write(".");
}
if(e.Parameters.Count == 0)
{
OutputIdentifier(e.Name);
}
else
{
Output.Write("this[");
OutputParameters(e.Parameters);
Output.Write("]");
}
// Output the body of the property.
StartBlock();
if(e.HasGet)
{
if(IsCurrentInterface ||
(e.Attributes & MemberAttributes.ScopeMask)
== MemberAttributes.Abstract)
{
Output.WriteLine("get;");
}
else
{
Output.Write("get");
StartBlock();
GenerateStatements(e.GetStatements);
EndBlock();
}
}
if(e.HasSet)
{
if(IsCurrentInterface ||
(e.Attributes & MemberAttributes.ScopeMask)
== MemberAttributes.Abstract)
{
Output.WriteLine("set;");
}
else
{
Output.Write("set");
StartBlock();
GenerateStatements(e.SetStatements);
EndBlock();
}
}
EndBlock();
}
protected override void GenerateNamespaceStart(CodeNamespace e)
{
String name = e.Name;
if(name != null && name.Length != 0)
{
Output.Write("namespace ");
OutputIdentifier(name);
StartBlock();
}
}
protected override void GenerateNamespaceEnd(CodeNamespace e)
{
String name = e.Name;
if(name != null && name.Length != 0)
{
EndBlock();
}
}
protected override void GenerateNamespaceImport(CodeNamespaceImport e)
{
Output.Write("using ");
OutputIdentifier(e.Namespace);
Output.WriteLine(";");
}
protected override void GenerateSnippetMember
(CodeSnippetTypeMember e)
{
Output.Write(e.Text);
}
protected override void GenerateTypeConstructor
(CodeTypeConstructor e)
{
Output.Write("static ");
OutputIdentifier(CurrentTypeName);
Output.Write("()");
StartBlock();
GenerateStatements(e.Statements);
EndBlock();
}
protected override void GenerateTypeStart(CodeTypeDeclaration e)
{
OutputAttributeDeclarations(e.CustomAttributes);
if(!IsCurrentDelegate)
{
OutputTypeAttributes
(e.TypeAttributes, IsCurrentStruct, IsCurrentEnum);
OutputIdentifier(e.Name);
String sep = " : ";
foreach(CodeTypeReference type in e.BaseTypes)
{
Output.Write(sep);
OutputType(type);
sep = ",";
}
StartBlock();
}
else
{
switch(e.TypeAttributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.NestedPrivate:
Output.Write("private "); break;
case TypeAttributes.Public:
case TypeAttributes.NestedPublic:
Output.Write("public "); break;
}
Output.Write("delegate ");
CodeTypeDelegate d = (CodeTypeDelegate)e;
if(d.ReturnType != null)
{
OutputType(d.ReturnType);
}
else
{
Output.Write("void");
}
Output.Write(" ");
OutputIdentifier(d.Name);
Output.Write("(");
OutputParameters(d.Parameters);
Output.WriteLine(");");
}
}
protected override void GenerateTypeEnd(CodeTypeDeclaration e)
{
if(!IsCurrentDelegate)
{
EndBlock();
}
}
// Generate various misc categories.
protected override void GenerateComment(CodeComment e)
{
String text = e.Text;
String commentSeq = (e.DocComment ? "/// " : "// ");
if(text == null)
{
return;
}
int posn = 0;
int end, next;
while(posn < text.Length)
{
end = posn;
next = end;
while(end < text.Length)
{
if(text[end] == '\r')
{
if((end + 1) < text.Length &&
text[end + 1] == '\n')
{
next = end + 1;
}
break;
}
else if(text[end] == '\n' ||
text[end] == '\u2028' ||
text[end] == '\u2029')
{
break;
}
++end;
next = end;
}
Output.Write(commentSeq);
Output.WriteLine(text.Substring(posn, end - posn));
posn = next + 1;
}
}
protected override void GenerateLinePragmaStart(CodeLinePragma e)
{
Output.WriteLine();
Output.WriteLine("#line {0} \"{1}\"",
e.LineNumber, e.FileName);
}
protected override void GenerateLinePragmaEnd(CodeLinePragma e)
{
Output.WriteLine();
Output.WriteLine("#line default");
}
protected override String GetTypeOutput(CodeTypeReference value)
{
String baseType;
if(value.ArrayElementType != null)
{
baseType = GetTypeOutput(value.ArrayElementType);
}
else
{
baseType = value.BaseType;
}
baseType = NormalizeTypeName(baseType);
int rank = value.ArrayRank;
if(rank > 0)
{
baseType += "[";
while(rank > 1)
{
baseType += ",";
--rank;
}
baseType += "]";
}
return baseType;
}
// Determine if "value" is a valid identifier.
protected override bool IsValidIdentifier(String value)
{
if(value == null || value.Length == 0)
{
return false;
}
else if(Array.IndexOf(reservedWords, value) != -1)
{
return false;
}
else
{
return IsValidLanguageIndependentIdentifier(value);
}
}
// Output an identifier.
protected override void OutputIdentifier(String ident)
{
Output.Write(CreateEscapedIdentifier(ident));
}
// Output a type.
protected override void OutputType(CodeTypeReference typeRef)
{
Output.Write(GetTypeOutput(typeRef));
}
// Hex characters for use in "QuoteSnippetString".
private const String hexchars = "0123456789abcdef";
// Quote a snippet string.
protected override String QuoteSnippetString(String value)
{
StringBuilder builder = new StringBuilder(value.Length + 16);
builder.Append('"');
int length = 0;
foreach(char ch in value)
{
if(ch == '\0')
{
builder.Append("\\0");
length += 2;
}
else if(ch == '\r')
{
builder.Append("\\r");
length += 2;
}
else if(ch == '\n')
{
builder.Append("\\n");
length += 2;
}
else if(ch == '\t')
{
builder.Append("\\t");
length += 2;
}
else if(ch == '\\' || ch == '"')
{
builder.Append('\\');
builder.Append(ch);
length += 2;
}
else if(ch < 0x0020 || ch > 0x007E)
{
builder.Append('\\');
builder.Append('u');
builder.Append(hexchars[(ch >> 12) & 0x0F]);
builder.Append(hexchars[(ch >> 8) & 0x0F]);
builder.Append(hexchars[(ch >> 4) & 0x0F]);
builder.Append(hexchars[ch & 0x0F]);
length += 6;
}
else
{
builder.Append(ch);
++length;
}
if(length >= 60)
{
builder.Append("\" +" + Output.NewLine + "\"");
length = 0;
}
}
builder.Append('"');
return builder.ToString();
}
// Determine if this code generator supports a particular
// set of generator options.
protected override bool Supports(GeneratorSupport supports)
{
return ((supports & (GeneratorSupport)0x001FFFFF) == supports);
}
}; // class CSharpCodeCompiler
#endif // CONFIG_CODEDOM
}; // namespace System.CodeDom.Compiler
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ResourcesServer.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Store;
using Microsoft.WindowsAzure.Management.Store.Models;
namespace Microsoft.WindowsAzure.Management.Store
{
/// <summary>
/// Provides REST operations for working with Store add-ins from the
/// Windows Azure store service.
/// </summary>
internal partial class AddOnOperations : IServiceOperations<StoreManagementClient>, IAddOnOperations
{
/// <summary>
/// Initializes a new instance of the AddOnOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AddOnOperations(StoreManagementClient client)
{
this._client = client;
}
private StoreManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Store.StoreManagementClient.
/// </summary>
public StoreManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The add on name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginCreatingAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (addOnName == null)
{
throw new ArgumentNullException("addOnName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Plan == null)
{
throw new ArgumentNullException("parameters.Plan");
}
if (parameters.Type == null)
{
throw new ArgumentNullException("parameters.Type");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("addOnName", addOnName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/CloudServices/";
url = url + Uri.EscapeDataString(cloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(parameters.Type);
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/";
url = url + Uri.EscapeDataString(addOnName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.Type;
resourceElement.Add(typeElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.Plan;
resourceElement.Add(planElement);
if (parameters.PromotionCode != null)
{
XElement promotionCodeElement = new XElement(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure"));
promotionCodeElement.Value = parameters.PromotionCode;
resourceElement.Add(promotionCodeElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Store entries
/// that re provisioned for a subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// Required. The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// Required. The name of this resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginDeletingAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
if (resourceProviderType == null)
{
throw new ArgumentNullException("resourceProviderType");
}
if (resourceProviderName == null)
{
throw new ArgumentNullException("resourceProviderName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("resourceProviderType", resourceProviderType);
tracingParameters.Add("resourceProviderName", resourceProviderName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/CloudServices/";
url = url + Uri.EscapeDataString(cloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(resourceProviderType);
url = url + "/";
url = url + Uri.EscapeDataString(resourceProviderName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The add on name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> CreateAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken)
{
StoreManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("addOnName", addOnName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.AddOns.BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Storeentries
/// that are provisioned for a subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// Required. The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// Required. The name of this resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> DeleteAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken)
{
StoreManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("resourceProviderType", resourceProviderType);
tracingParameters.Add("resourceProviderName", resourceProviderName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.AddOns.BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Update Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service to which this store item
/// will be assigned.
/// </param>
/// <param name='resourceName'>
/// Required. The name of this resource.
/// </param>
/// <param name='addOnName'>
/// Required. The addon name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters used to specify how the Create procedure will
/// function.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> UpdateAsync(string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (addOnName == null)
{
throw new ArgumentNullException("addOnName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Plan == null)
{
throw new ArgumentNullException("parameters.Plan");
}
if (parameters.Type == null)
{
throw new ArgumentNullException("parameters.Type");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("addOnName", addOnName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/CloudServices/";
url = url + Uri.EscapeDataString(cloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(parameters.Type);
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/";
url = url + Uri.EscapeDataString(addOnName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", "*");
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.Type;
resourceElement.Add(typeElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.Plan;
resourceElement.Add(planElement);
if (parameters.PromotionCode != null)
{
XElement promotionCodeElement = new XElement(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure"));
promotionCodeElement.Value = parameters.PromotionCode;
resourceElement.Add(promotionCodeElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NQuery.Tests
{
[TestClass]
public sealed class IdentifierTests : AutomatedTestFixtureBase
{
[TestMethod]
public void FromSourceParenthesized()
{
Identifier identifier;
identifier = Identifier.FromSource("[Test]");
Assert.AreEqual("Test", identifier.Text);
Assert.AreEqual("[Test]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.FromSource("[Test 123 test]");
Assert.AreEqual("Test 123 test", identifier.Text);
Assert.AreEqual("[Test 123 test]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.FromSource("[Test\t123\ntest]");
Assert.AreEqual("Test\t123\ntest", identifier.Text);
Assert.AreEqual("[Test\t123\ntest]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
}
[TestMethod]
public void FormSourceQuoted()
{
Identifier identifier;
identifier = Identifier.FromSource("\"Test\"");
Assert.AreEqual("Test", identifier.Text);
Assert.AreEqual("\"Test\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.FromSource("\"Test 123 test\"");
Assert.AreEqual("Test 123 test", identifier.Text);
Assert.AreEqual("\"Test 123 test\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.FromSource("\"Test\t123\ntest\"");
Assert.AreEqual("Test\t123\ntest", identifier.Text);
Assert.AreEqual("\"Test\t123\ntest\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
}
[TestMethod]
public void FromSourceParenthesizedAndEscaped()
{
Identifier identifier;
identifier = Identifier.FromSource("[Test]]]");
Assert.AreEqual("Test]", identifier.Text);
Assert.AreEqual("[Test]]]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.FromSource("[Test]]xx]");
Assert.AreEqual("Test]xx", identifier.Text);
Assert.AreEqual("[Test]]xx]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
}
[TestMethod]
public void FormSourceQuotedAndEscaped()
{
Identifier identifier;
identifier = Identifier.FromSource("\"Test\"\"\"");
Assert.AreEqual("Test\"", identifier.Text);
Assert.AreEqual("\"Test\"\"\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.FromSource("\"Test\"\"xx\"");
Assert.AreEqual("Test\"xx", identifier.Text);
Assert.AreEqual("\"Test\"\"xx\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
}
[TestMethod]
public void SimpleIsNotParenthesized()
{
Identifier identifier;
identifier = Identifier.CreateNonVerbatim("Identifier");
Assert.AreEqual("Identifier", identifier.Text);
Assert.AreEqual("Identifier", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.CreateNonVerbatim("_Identifier");
Assert.AreEqual("_Identifier", identifier.Text);
Assert.AreEqual("_Identifier", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.CreateNonVerbatim("This_is_a_valid_identifier");
Assert.AreEqual("This_is_a_valid_identifier", identifier.Text);
Assert.AreEqual("This_is_a_valid_identifier", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.CreateNonVerbatim("Identifier1");
Assert.AreEqual("Identifier1", identifier.Text);
Assert.AreEqual("Identifier1", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.CreateNonVerbatim("My$Dollars");
Assert.AreEqual("My$Dollars", identifier.Text);
Assert.AreEqual("My$Dollars", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.CreateNonVerbatim("This_is_a_valid$_identifier_42_$");
Assert.AreEqual("This_is_a_valid$_identifier_42_$", identifier.Text);
Assert.AreEqual("This_is_a_valid$_identifier_42_$", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
}
[TestMethod]
public void SimpleRemainsQuoted()
{
Identifier identifier;
identifier = Identifier.CreateVerbatim("Identifier");
Assert.AreEqual("Identifier", identifier.Text);
Assert.AreEqual("\"Identifier\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.CreateVerbatim("_Identifier");
Assert.AreEqual("_Identifier", identifier.Text);
Assert.AreEqual("\"_Identifier\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.CreateVerbatim("This_is_a_valid_identifier");
Assert.AreEqual("This_is_a_valid_identifier", identifier.Text);
Assert.AreEqual("\"This_is_a_valid_identifier\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.CreateVerbatim("Identifier1");
Assert.AreEqual("Identifier1", identifier.Text);
Assert.AreEqual("\"Identifier1\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.CreateVerbatim("My$Dollars");
Assert.AreEqual("My$Dollars", identifier.Text);
Assert.AreEqual("\"My$Dollars\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.CreateVerbatim("This_is_a_valid$_identifier_42_$");
Assert.AreEqual("This_is_a_valid$_identifier_42_$", identifier.Text);
Assert.AreEqual("\"This_is_a_valid$_identifier_42_$\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
}
[TestMethod]
public void KeywordsAreParenthesized()
{
Identifier identifier;
identifier = Identifier.CreateNonVerbatim("SELECT");
Assert.AreEqual("SELECT", identifier.Text);
Assert.AreEqual("[SELECT]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
identifier = Identifier.CreateNonVerbatim("Top");
Assert.AreEqual("Top", identifier.Text);
Assert.AreEqual("[Top]", identifier.ToSource());
Assert.IsTrue(identifier.Parenthesized);
Assert.IsFalse(identifier.Verbatim);
}
[TestMethod]
public void KeywordsRemainsQuoted()
{
Identifier identifier;
identifier = Identifier.CreateVerbatim("SELECT");
Assert.AreEqual("SELECT", identifier.Text);
Assert.AreEqual("\"SELECT\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
identifier = Identifier.CreateVerbatim("Top");
Assert.AreEqual("Top", identifier.Text);
Assert.AreEqual("\"Top\"", identifier.ToSource());
Assert.IsFalse(identifier.Parenthesized);
Assert.IsTrue(identifier.Verbatim);
}
[TestMethod]
public void MatchingWorks()
{
Identifier a1 = Identifier.CreateVerbatim("Name");
Identifier a2 = Identifier.CreateVerbatim("NAME");
Identifier b1 = Identifier.CreateNonVerbatim("Name");
Identifier b2 = Identifier.CreateNonVerbatim("NAME");
// Every identifier matches itself
Assert.IsTrue(a1.Matches(a1));
Assert.IsTrue(a2.Matches(a2));
Assert.IsTrue(b1.Matches(b1));
Assert.IsTrue(b2.Matches(b2));
// Verbatim idenfiers are compared case sensitive
Assert.IsFalse(a1.Matches(a2));
Assert.IsFalse(a2.Matches(a1));
// Non verbatim identifiers are compared case insensitive
Assert.IsTrue(b1.Matches(b2));
Assert.IsTrue(b2.Matches(b1));
// A verbatim identifier compared with a non-verbatim identifier will never produce a match
Assert.IsFalse(a1.Matches(b1));
Assert.IsFalse(a2.Matches(b2));
// A non-verbatim identifier and a verbatim identifier are compared case insensitive
Assert.IsTrue(b1.Matches(a1));
Assert.IsTrue(b1.Matches(a2));
Assert.IsTrue(b2.Matches(a1));
Assert.IsTrue(b2.Matches(a2));
}
[TestMethod]
public void EqualityWorks()
{
Identifier a1 = Identifier.CreateVerbatim("Name");
Identifier a2 = Identifier.CreateVerbatim("NAME");
Identifier b1 = Identifier.CreateNonVerbatim("Name");
Identifier b2 = Identifier.CreateNonVerbatim("NAME");
// Every identifier equals itself
#pragma warning disable 1718 // Comparison made to same variable; did you mean to compare something else?
Assert.IsTrue(a1 == a1);
Assert.IsTrue(a2 == a2);
Assert.IsTrue(b1 == b1);
Assert.IsTrue(b2 == b2);
#pragma warning restore 1718
// Equality is done case sensitive. Thefore both the verbatim and non-verbatim version
// should not be equal to each other.
Assert.IsFalse(a1 == a2);
Assert.IsFalse(a1 == b1);
Assert.IsFalse(a1 == b2);
Assert.IsFalse(a2 == a1);
Assert.IsFalse(a1 == b1);
Assert.IsFalse(a1 == b2);
Assert.IsFalse(b1 == a1);
Assert.IsFalse(b1 == a2);
Assert.IsFalse(b1 == b2);
Assert.IsFalse(b2 == a1);
Assert.IsFalse(b2 == a2);
Assert.IsFalse(b2 == b1);
}
[TestMethod]
public void LexerAcceptsAllTypesOfIdentifiers()
{
RunTestOfCallingMethod();
}
}
}
| |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.Logging
{
using System;
using NLog;
/// <summary>
/// A logger that wraps to NLog. See http://stackoverflow.com/questions/7412156/how-to-retain-callsite-information-when-wrapping-nlog
/// </summary>
public class NLogLogWriter :
LogWriter
{
readonly Logger _log;
/// <summary>
/// Create a new NLog logger instance.
/// </summary>
/// <param name="log"> </param>
/// <param name="name"> Name of type to log as. </param>
public NLogLogWriter(Logger log, string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
_log = log;
}
public bool IsDebugEnabled
{
get { return _log.IsDebugEnabled; }
}
public bool IsInfoEnabled
{
get { return _log.IsInfoEnabled; }
}
public bool IsWarnEnabled
{
get { return _log.IsWarnEnabled; }
}
public bool IsErrorEnabled
{
get { return _log.IsErrorEnabled; }
}
public bool IsFatalEnabled
{
get { return _log.IsFatalEnabled; }
}
public void Log(LoggingLevel level, object obj)
{
_log.Log(GetNLogLevel(level), obj);
}
public void Log(LoggingLevel level, object obj, Exception exception)
{
if (obj != null)
_log.Log(GetNLogLevel(level), exception, obj.ToString());
else
_log.Log(GetNLogLevel(level), exception);
}
public void Log(LoggingLevel level, LogWriterOutputProvider messageProvider)
{
_log.Log(GetNLogLevel(level), ToGenerator(messageProvider));
}
public void LogFormat(LoggingLevel level, IFormatProvider formatProvider, string format,
params object[] args)
{
_log.Log(GetNLogLevel(level), formatProvider, format, args);
}
public void LogFormat(LoggingLevel level, string format, params object[] args)
{
_log.Log(GetNLogLevel(level), format, args);
}
public void Debug(object obj)
{
_log.Log(LogLevel.Debug, obj);
}
public void Debug(object obj, Exception exception)
{
if (obj != null)
_log.Log(LogLevel.Debug, exception, obj.ToString());
else
_log.Log(LogLevel.Debug, exception);
}
public void Debug(LogWriterOutputProvider messageProvider)
{
_log.Debug(ToGenerator(messageProvider));
}
public void Info(object obj)
{
_log.Log(LogLevel.Info, obj);
}
public void Info(object obj, Exception exception)
{
if (obj != null)
_log.Log(LogLevel.Info, exception, obj.ToString());
else
_log.Log(LogLevel.Info, exception);
}
public void Info(LogWriterOutputProvider messageProvider)
{
_log.Info(ToGenerator(messageProvider));
}
public void Warn(object obj)
{
_log.Log(LogLevel.Warn, obj);
}
public void Warn(object obj, Exception exception)
{
if (obj != null)
_log.Log(LogLevel.Warn, exception, obj.ToString());
else
_log.Log(LogLevel.Warn, exception);
}
public void Warn(LogWriterOutputProvider messageProvider)
{
_log.Warn(ToGenerator(messageProvider));
}
public void Error(object obj)
{
_log.Log(LogLevel.Error, obj);
}
public void Error(object obj, Exception exception)
{
if (obj != null)
_log.Log(LogLevel.Error, exception, obj.ToString());
else
_log.Log(LogLevel.Error, exception);
}
public void Error(LogWriterOutputProvider messageProvider)
{
_log.Error(ToGenerator(messageProvider));
}
public void Fatal(object obj)
{
_log.Log(LogLevel.Fatal, obj);
}
public void Fatal(object obj, Exception exception)
{
if (obj != null)
_log.Log(LogLevel.Fatal, exception, obj.ToString());
else
_log.Log(LogLevel.Fatal, exception);
}
public void Fatal(LogWriterOutputProvider messageProvider)
{
_log.Fatal(ToGenerator(messageProvider));
}
public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Debug, formatProvider, format, args);
}
public void DebugFormat(string format, params object[] args)
{
_log.Log(LogLevel.Debug, format, args);
}
public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Info, formatProvider, format, args);
}
public void InfoFormat(string format, params object[] args)
{
_log.Log(LogLevel.Info, format, args);
}
public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Warn, formatProvider, format, args);
}
public void WarnFormat(string format, params object[] args)
{
_log.Log(LogLevel.Warn, format, args);
}
public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Error, formatProvider, format, args);
}
public void ErrorFormat(string format, params object[] args)
{
_log.Log(LogLevel.Error, format, args);
}
public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Fatal, formatProvider, format, args);
}
public void FatalFormat(string format, params object[] args)
{
_log.Log(LogLevel.Fatal, format, args);
}
static LogLevel GetNLogLevel(LoggingLevel level)
{
if (level == LoggingLevel.Fatal)
return LogLevel.Fatal;
if (level == LoggingLevel.Error)
return LogLevel.Error;
if (level == LoggingLevel.Warn)
return LogLevel.Warn;
if (level == LoggingLevel.Info)
return LogLevel.Info;
if (level == LoggingLevel.Debug)
return LogLevel.Debug;
if (level == LoggingLevel.All)
return LogLevel.Trace;
return LogLevel.Off;
}
static LogMessageGenerator ToGenerator(LogWriterOutputProvider provider)
{
return () =>
{
object obj = provider?.Invoke();
return obj?.ToString() ?? "";
};
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [TextureLoader.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using DevIL;
using Image = System.Drawing.Image;
namespace open3mod
{
/// <summary>
/// Responsible for loading a texture from a given folder and file name.
/// Employs some heuristics to find lost textures. One use only.
/// </summary>
public class TextureLoader
{
public enum LoadResult
{
Good,
FileNotFound,
UnknownFileFormat
}
protected LoadResult _result;
protected Image _image;
protected string _actualLocation;
protected TextureLoader()
{
_result = LoadResult.UnknownFileFormat;
}
public TextureLoader(string name, string basedir)
{
try
{
using (var stream = ObtainStream(name, basedir, out _actualLocation))
{
Debug.Assert(stream != null);
SetFromStream(stream);
}
}
catch(Exception)
{
_result = LoadResult.FileNotFound;
}
}
protected void SetFromStream(Stream stream)
{
// try loading using standard .net first
try
{
// We need to copy the stream over to a new, in-memory bitmap to
// avoid keeping the input stream open.
// See http://support.microsoft.com/kb/814675/en-us
using(var img = Image.FromStream(stream))
{
_image = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
using (var gfx = Graphics.FromImage(_image))
{
gfx.DrawImage(img, 0, 0, img.Width, img.Height);
}
_result = LoadResult.Good;
}
}
catch (Exception)
{
// if this fails, load using DevIL
using (var imp = new DevIL.ImageImporter())
{
try
{
using(var devilImage = imp.LoadImageFromStream(stream))
{
devilImage.Bind();
var info = DevIL.Unmanaged.IL.GetImageInfo();
var bitmap = new Bitmap(info.Width, info.Height, PixelFormat.Format32bppArgb);
var rect = new Rectangle(0, 0, info.Width, info.Height);
var data = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, info.Width, info.Height, 1, DataFormat.BGRA, DataType.UnsignedByte, data.Scan0);
bitmap.UnlockBits(data);
_image = bitmap;
_result = LoadResult.Good;
}
}
catch (Exception)
{
// TODO any other viable fall back image loaders?
_result = LoadResult.UnknownFileFormat;
}
}
}
}
/// <summary>
/// Try to obtain a read stream to a given file, looking at some alternative
/// locations if direct access fails. In case of failure, this method
/// throws IOException.
/// </summary>
/// <param name="name"></param>
/// <param name="basedir"></param>
/// <param name="actualLocation"></param>
/// <returns>A valid stream</returns>
public static Stream ObtainStream(string name, string basedir, out string actualLocation)
{
Debug.Assert(name != null);
Debug.Assert(basedir != null);
Stream s = null;
string path = null;
try
{
path = Path.Combine(basedir, name);
s = new FileStream(path, FileMode.Open, FileAccess.Read);
}
catch (IOException)
{
var fileName = Path.GetFileName(name);
if (fileName == null)
{
throw;
}
try
{
path = Path.Combine(basedir, fileName);
s = new FileStream(path, FileMode.Open, FileAccess.Read);
}
catch (IOException)
{
try
{
path = name;
s = new FileStream(name, FileMode.Open, FileAccess.Read);
}
catch (IOException)
{
if (CoreSettings.CoreSettings.Default.AdditionalTextureFolders != null)
{
foreach (var folder in CoreSettings.CoreSettings.Default.AdditionalTextureFolders)
{
try
{
path = Path.Combine(folder, fileName);
s = new FileStream(path, FileMode.Open, FileAccess.Read);
break;
}
catch (IOException)
{
continue;
}
}
}
if (s == null)
{
throw new IOException();
}
}
}
}
Debug.Assert(s != null);
Debug.Assert(path != null);
actualLocation = path;
return s;
}
public Image Image
{
get { return _image; }
}
public LoadResult Result
{
get { return _result; }
}
public string ActualLocation
{
get { return _actualLocation; }
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */
| |
#region HEADER
/* This file was derived from libmspack
* (C) 2003-2004 Stuart Caie.
* (C) 2011 Ali Scissons.
*
* The LZX method was created by Jonathan Forbes and Tomi Poutanen, adapted
* by Microsoft Corporation.
*
* This source file is Dual licensed; meaning the end-user of this source file
* may redistribute/modify it under the LGPL 2.1 or MS-PL licenses.
*/
#region LGPL License
/* GNU LESSER GENERAL PUBLIC LICENSE version 2.1
* LzxDecoder is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*/
#endregion
#region MS-PL License
/*
* MICROSOFT PUBLIC LICENSE
* This source code is subject to the terms of the Microsoft Public License (Ms-PL).
*
* Redistribution and use in source and binary forms, with or without modification,
* is permitted provided that redistributions of the source code retain the above
* copyright notices and this file header.
*
* Additional copyright notices should be appended to the list above.
*
* For details, see <http://www.opensource.org/licenses/ms-pl.html>.
*/
#endregion
/*
* This derived work is recognized by Stuart Caie and is authorized to adapt
* any changes made to lzxd.c in his libmspack library and will still retain
* this dual licensing scheme. Big thanks to Stuart Caie!
*
* DETAILS
* This file is a pure C# port of the lzxd.c file from libmspack, with minor
* changes towards the decompression of XNB files. The original decompression
* software of LZX encoded data was written by Suart Caie in his
* libmspack/cabextract projects, which can be located at
* http://http://www.cabextract.org.uk/
*/
#endregion
using System;
using System.Diagnostics;
namespace Microsoft.Xna.Framework.Content
{
using System.IO;
class LzxDecoder
{
public static uint[] position_base = null;
public static byte[] extra_bits = null;
private LzxState m_state;
public LzxDecoder (int window)
{
uint wndsize = (uint)(1 << window);
int posn_slots;
// setup proper exception
if(window < 15 || window > 21) throw new UnsupportedWindowSizeRange();
// let's initialise our state
m_state = new LzxState();
m_state.actual_size = 0;
m_state.window = new byte[wndsize];
for(int i = 0; i < wndsize; i++) m_state.window[i] = 0xDC;
m_state.actual_size = wndsize;
m_state.window_size = wndsize;
m_state.window_posn = 0;
/* initialize static tables */
if(extra_bits == null)
{
extra_bits = new byte[52];
for(int i = 0, j = 0; i <= 50; i += 2)
{
extra_bits[i] = extra_bits[i+1] = (byte)j;
if ((i != 0) && (j < 17)) j++;
}
}
if(position_base == null)
{
position_base = new uint[51];
for(int i = 0, j = 0; i <= 50; i++)
{
position_base[i] = (uint)j;
j += 1 << extra_bits[i];
}
}
/* calculate required position slots */
if(window == 20) posn_slots = 42;
else if(window == 21) posn_slots = 50;
else posn_slots = window << 1;
m_state.R0 = m_state.R1 = m_state.R2 = 1;
m_state.main_elements = (ushort)(LzxConstants.NUM_CHARS + (posn_slots << 3));
m_state.header_read = 0;
m_state.frames_read = 0;
m_state.block_remaining = 0;
m_state.block_type = LzxConstants.BLOCKTYPE.INVALID;
m_state.intel_curpos = 0;
m_state.intel_started = 0;
// yo dawg i herd u liek arrays so we put arrays in ur arrays so u can array while u array
m_state.PRETREE_table = new ushort[(1 << LzxConstants.PRETREE_TABLEBITS) + (LzxConstants.PRETREE_MAXSYMBOLS << 1)];
m_state.PRETREE_len = new byte[LzxConstants.PRETREE_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY];
m_state.MAINTREE_table = new ushort[(1 << LzxConstants.MAINTREE_TABLEBITS) + (LzxConstants.MAINTREE_MAXSYMBOLS << 1)];
m_state.MAINTREE_len = new byte[LzxConstants.MAINTREE_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY];
m_state.LENGTH_table = new ushort[(1 << LzxConstants.LENGTH_TABLEBITS) + (LzxConstants.LENGTH_MAXSYMBOLS << 1)];
m_state.LENGTH_len = new byte[LzxConstants.LENGTH_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY];
m_state.ALIGNED_table = new ushort[(1 << LzxConstants.ALIGNED_TABLEBITS) + (LzxConstants.ALIGNED_MAXSYMBOLS << 1)];
m_state.ALIGNED_len = new byte[LzxConstants.ALIGNED_MAXSYMBOLS + LzxConstants.LENTABLE_SAFETY];
/* initialise tables to 0 (because deltas will be applied to them) */
for(int i = 0; i < LzxConstants.MAINTREE_MAXSYMBOLS; i++) m_state.MAINTREE_len[i] = 0;
for(int i = 0; i < LzxConstants.LENGTH_MAXSYMBOLS; i++) m_state.LENGTH_len[i] = 0;
}
public int Decompress(Stream inData, int inLen, Stream outData, int outLen)
{
BitBuffer bitbuf = new BitBuffer(inData);
long startpos = inData.Position;
long endpos = inData.Position + inLen;
byte[] window = m_state.window;
uint window_posn = m_state.window_posn;
uint window_size = m_state.window_size;
uint R0 = m_state.R0;
uint R1 = m_state.R1;
uint R2 = m_state.R2;
uint i, j;
int togo = outLen, this_run, main_element, match_length, match_offset, length_footer, extra, verbatim_bits;
int rundest, runsrc, copy_length, aligned_bits;
bitbuf.InitBitStream();
/* read header if necessary */
if(m_state.header_read == 0)
{
uint intel = bitbuf.ReadBits(1);
if(intel != 0)
{
// read the filesize
i = bitbuf.ReadBits(16); j = bitbuf.ReadBits(16);
m_state.intel_filesize = (int)((i << 16) | j);
}
m_state.header_read = 1;
}
/* main decoding loop */
while(togo > 0)
{
/* last block finished, new block expected */
if(m_state.block_remaining == 0)
{
// TODO may screw something up here
if(m_state.block_type == LzxConstants.BLOCKTYPE.UNCOMPRESSED) {
if((m_state.block_length & 1) == 1) inData.ReadByte(); /* realign bitstream to word */
bitbuf.InitBitStream();
}
m_state.block_type = (LzxConstants.BLOCKTYPE)bitbuf.ReadBits(3);;
i = bitbuf.ReadBits(16);
j = bitbuf.ReadBits(8);
m_state.block_remaining = m_state.block_length = (uint)((i << 8) | j);
switch(m_state.block_type)
{
case LzxConstants.BLOCKTYPE.ALIGNED:
for(i = 0, j = 0; i < 8; i++) { j = bitbuf.ReadBits(3); m_state.ALIGNED_len[i] = (byte)j; }
MakeDecodeTable(LzxConstants.ALIGNED_MAXSYMBOLS, LzxConstants.ALIGNED_TABLEBITS,
m_state.ALIGNED_len, m_state.ALIGNED_table);
/* rest of aligned header is same as verbatim */
goto case LzxConstants.BLOCKTYPE.VERBATIM;
case LzxConstants.BLOCKTYPE.VERBATIM:
ReadLengths(m_state.MAINTREE_len, 0, 256, bitbuf);
ReadLengths(m_state.MAINTREE_len, 256, m_state.main_elements, bitbuf);
MakeDecodeTable(LzxConstants.MAINTREE_MAXSYMBOLS, LzxConstants.MAINTREE_TABLEBITS,
m_state.MAINTREE_len, m_state.MAINTREE_table);
if(m_state.MAINTREE_len[0xE8] != 0) m_state.intel_started = 1;
ReadLengths(m_state.LENGTH_len, 0, LzxConstants.NUM_SECONDARY_LENGTHS, bitbuf);
MakeDecodeTable(LzxConstants.LENGTH_MAXSYMBOLS, LzxConstants.LENGTH_TABLEBITS,
m_state.LENGTH_len, m_state.LENGTH_table);
break;
case LzxConstants.BLOCKTYPE.UNCOMPRESSED:
m_state.intel_started = 1; /* because we can't assume otherwise */
bitbuf.EnsureBits(16); /* get up to 16 pad bits into the buffer */
if(bitbuf.GetBitsLeft() > 16) inData.Seek(-2, SeekOrigin.Current); /* and align the bitstream! */
byte hi, mh, ml, lo;
lo = (byte)inData.ReadByte(); ml = (byte)inData.ReadByte(); mh = (byte)inData.ReadByte(); hi = (byte)inData.ReadByte();
R0 = (uint)(lo | ml << 8 | mh << 16 | hi << 24);
lo = (byte)inData.ReadByte(); ml = (byte)inData.ReadByte(); mh = (byte)inData.ReadByte(); hi = (byte)inData.ReadByte();
R1 = (uint)(lo | ml << 8 | mh << 16 | hi << 24);
lo = (byte)inData.ReadByte(); ml = (byte)inData.ReadByte(); mh = (byte)inData.ReadByte(); hi = (byte)inData.ReadByte();
R2 = (uint)(lo | ml << 8 | mh << 16 | hi << 24);
break;
default:
return -1; // TODO throw proper exception
}
}
/* buffer exhaustion check */
if(inData.Position > (startpos + inLen))
{
/* it's possible to have a file where the next run is less than
* 16 bits in size. In this case, the READ_HUFFSYM() macro used
* in building the tables will exhaust the buffer, so we should
* allow for this, but not allow those accidentally read bits to
* be used (so we check that there are at least 16 bits
* remaining - in this boundary case they aren't really part of
* the compressed data)
*/
//Debug.WriteLine("WTF");
if(inData.Position > (startpos+inLen+2) || bitbuf.GetBitsLeft() < 16) return -1; //TODO throw proper exception
}
while((this_run = (int)m_state.block_remaining) > 0 && togo > 0)
{
if(this_run > togo) this_run = togo;
togo -= this_run;
m_state.block_remaining -= (uint)this_run;
/* apply 2^x-1 mask */
window_posn &= window_size - 1;
/* runs can't straddle the window wraparound */
if((window_posn + this_run) > window_size)
return -1; //TODO throw proper exception
switch(m_state.block_type)
{
case LzxConstants.BLOCKTYPE.VERBATIM:
while(this_run > 0)
{
main_element = (int)ReadHuffSym(m_state.MAINTREE_table, m_state.MAINTREE_len,
LzxConstants.MAINTREE_MAXSYMBOLS, LzxConstants.MAINTREE_TABLEBITS,
bitbuf);
if(main_element < LzxConstants.NUM_CHARS)
{
/* literal: 0 to NUM_CHARS-1 */
window[window_posn++] = (byte)main_element;
this_run--;
}
else
{
/* match: NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
main_element -= LzxConstants.NUM_CHARS;
match_length = main_element & LzxConstants.NUM_PRIMARY_LENGTHS;
if(match_length == LzxConstants.NUM_PRIMARY_LENGTHS)
{
length_footer = (int)ReadHuffSym(m_state.LENGTH_table, m_state.LENGTH_len,
LzxConstants.LENGTH_MAXSYMBOLS, LzxConstants.LENGTH_TABLEBITS,
bitbuf);
match_length += length_footer;
}
match_length += LzxConstants.MIN_MATCH;
match_offset = main_element >> 3;
if(match_offset > 2)
{
/* not repeated offset */
if(match_offset != 3)
{
extra = extra_bits[match_offset];
verbatim_bits = (int)bitbuf.ReadBits((byte)extra);
match_offset = (int)position_base[match_offset] - 2 + verbatim_bits;
}
else
{
match_offset = 1;
}
/* update repeated offset LRU queue */
R2 = R1; R1 = R0; R0 = (uint)match_offset;
}
else if(match_offset == 0)
{
match_offset = (int)R0;
}
else if(match_offset == 1)
{
match_offset = (int)R1;
R1 = R0; R0 = (uint)match_offset;
}
else /* match_offset == 2 */
{
match_offset = (int)R2;
R2 = R0; R0 = (uint)match_offset;
}
rundest = (int)window_posn;
this_run -= match_length;
/* copy any wrapped around source data */
if(window_posn >= match_offset)
{
/* no wrap */
runsrc = rundest - match_offset;
}
else
{
runsrc = rundest + ((int)window_size - match_offset);
copy_length = match_offset - (int)window_posn;
if(copy_length < match_length)
{
match_length -= copy_length;
window_posn += (uint)copy_length;
while(copy_length-- > 0) window[rundest++] = window[runsrc++];
runsrc = 0;
}
}
window_posn += (uint)match_length;
/* copy match data - no worries about destination wraps */
while(match_length-- > 0) window[rundest++] = window[runsrc++];
}
}
break;
case LzxConstants.BLOCKTYPE.ALIGNED:
while(this_run > 0)
{
main_element = (int)ReadHuffSym(m_state.MAINTREE_table, m_state.MAINTREE_len,
LzxConstants.MAINTREE_MAXSYMBOLS, LzxConstants.MAINTREE_TABLEBITS,
bitbuf);
if(main_element < LzxConstants.NUM_CHARS)
{
/* literal 0 to NUM_CHARS-1 */
window[window_posn++] = (byte)main_element;
this_run--;
}
else
{
/* match: NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
main_element -= LzxConstants.NUM_CHARS;
match_length = main_element & LzxConstants.NUM_PRIMARY_LENGTHS;
if(match_length == LzxConstants.NUM_PRIMARY_LENGTHS)
{
length_footer = (int)ReadHuffSym(m_state.LENGTH_table, m_state.LENGTH_len,
LzxConstants.LENGTH_MAXSYMBOLS, LzxConstants.LENGTH_TABLEBITS,
bitbuf);
match_length += length_footer;
}
match_length += LzxConstants.MIN_MATCH;
match_offset = main_element >> 3;
if(match_offset > 2)
{
/* not repeated offset */
extra = extra_bits[match_offset];
match_offset = (int)position_base[match_offset] - 2;
if(extra > 3)
{
/* verbatim and aligned bits */
extra -= 3;
verbatim_bits = (int)bitbuf.ReadBits((byte)extra);
match_offset += (verbatim_bits << 3);
aligned_bits = (int)ReadHuffSym(m_state.ALIGNED_table, m_state.ALIGNED_len,
LzxConstants.ALIGNED_MAXSYMBOLS, LzxConstants.ALIGNED_TABLEBITS,
bitbuf);
match_offset += aligned_bits;
}
else if(extra == 3)
{
/* aligned bits only */
aligned_bits = (int)ReadHuffSym(m_state.ALIGNED_table, m_state.ALIGNED_len,
LzxConstants.ALIGNED_MAXSYMBOLS, LzxConstants.ALIGNED_TABLEBITS,
bitbuf);
match_offset += aligned_bits;
}
else if (extra > 0) /* extra==1, extra==2 */
{
/* verbatim bits only */
verbatim_bits = (int)bitbuf.ReadBits((byte)extra);
match_offset += verbatim_bits;
}
else /* extra == 0 */
{
/* ??? */
match_offset = 1;
}
/* update repeated offset LRU queue */
R2 = R1; R1 = R0; R0 = (uint)match_offset;
}
else if( match_offset == 0)
{
match_offset = (int)R0;
}
else if(match_offset == 1)
{
match_offset = (int)R1;
R1 = R0; R0 = (uint)match_offset;
}
else /* match_offset == 2 */
{
match_offset = (int)R2;
R2 = R0; R0 = (uint)match_offset;
}
rundest = (int)window_posn;
this_run -= match_length;
/* copy any wrapped around source data */
if(window_posn >= match_offset)
{
/* no wrap */
runsrc = rundest - match_offset;
}
else
{
runsrc = rundest + ((int)window_size - match_offset);
copy_length = match_offset - (int)window_posn;
if(copy_length < match_length)
{
match_length -= copy_length;
window_posn += (uint)copy_length;
while(copy_length-- > 0) window[rundest++] = window[runsrc++];
runsrc = 0;
}
}
window_posn += (uint)match_length;
/* copy match data - no worries about destination wraps */
while(match_length-- > 0) window[rundest++] = window[runsrc++];
}
}
break;
case LzxConstants.BLOCKTYPE.UNCOMPRESSED:
if((inData.Position + this_run) > endpos) return -1; //TODO throw proper exception
byte[] temp_buffer = new byte[this_run];
inData.Read(temp_buffer, 0, this_run);
temp_buffer.CopyTo(window, (int)window_posn);
window_posn += (uint)this_run;
break;
default:
return -1; //TODO throw proper exception
}
}
}
if(togo != 0) return -1; //TODO throw proper exception
int start_window_pos = (int)window_posn;
if(start_window_pos == 0) start_window_pos = (int)window_size;
start_window_pos -= outLen;
outData.Write(window, start_window_pos, outLen);
m_state.window_posn = window_posn;
m_state.R0 = R0;
m_state.R1 = R1;
m_state.R2 = R2;
// TODO finish intel E8 decoding
/* intel E8 decoding */
if((m_state.frames_read++ < 32768) && m_state.intel_filesize != 0)
{
if(outLen <= 6 || m_state.intel_started == 0)
{
m_state.intel_curpos += outLen;
}
else
{
int dataend = outLen - 10;
uint curpos = (uint)m_state.intel_curpos;
uint filesize = (uint)m_state.intel_filesize;
//uint abs_off, rel_off;
m_state.intel_curpos = (int)curpos + outLen;
while(outData.Position < dataend)
{
if(outData.ReadByte() != 0xE8) { curpos++; continue; }
//abs_off =
}
}
return -1;
}
return 0;
}
// READ_LENGTHS(table, first, last)
// if(lzx_read_lens(LENTABLE(table), first, last, bitsleft))
// return ERROR (ILLEGAL_DATA)
//
// TODO make returns throw exceptions
private int MakeDecodeTable(uint nsyms, uint nbits, byte[] length, ushort[] table)
{
ushort sym;
uint leaf;
byte bit_num = 1;
uint fill;
uint pos = 0; /* the current position in the decode table */
uint table_mask = (uint)(1 << (int)nbits);
uint bit_mask = table_mask >> 1; /* don't do 0 length codes */
uint next_symbol = bit_mask; /* base of allocation for long codes */
/* fill entries for codes short enough for a direct mapping */
while (bit_num <= nbits )
{
for(sym = 0; sym < nsyms; sym++)
{
if(length[sym] == bit_num)
{
leaf = pos;
if((pos += bit_mask) > table_mask) return 1; /* table overrun */
/* fill all possible lookups of this symbol with the symbol itself */
fill = bit_mask;
while(fill-- > 0) table[leaf++] = sym;
}
}
bit_mask >>= 1;
bit_num++;
}
/* if there are any codes longer than nbits */
if(pos != table_mask)
{
/* clear the remainder of the table */
for(sym = (ushort)pos; sym < table_mask; sym++) table[sym] = 0;
/* give ourselves room for codes to grow by up to 16 more bits */
pos <<= 16;
table_mask <<= 16;
bit_mask = 1 << 15;
while(bit_num <= 16)
{
for(sym = 0; sym < nsyms; sym++)
{
if(length[sym] == bit_num)
{
leaf = pos >> 16;
for(fill = 0; fill < bit_num - nbits; fill++)
{
/* if this path hasn't been taken yet, 'allocate' two entries */
if(table[leaf] == 0)
{
table[(next_symbol << 1)] = 0;
table[(next_symbol << 1) + 1] = 0;
table[leaf] = (ushort)(next_symbol++);
}
/* follow the path and select either left or right for next bit */
leaf = (uint)(table[leaf] << 1);
if(((pos >> (int)(15-fill)) & 1) == 1) leaf++;
}
table[leaf] = sym;
if((pos += bit_mask) > table_mask) return 1;
}
}
bit_mask >>= 1;
bit_num++;
}
}
/* full talbe? */
if(pos == table_mask) return 0;
/* either erroneous table, or all elements are 0 - let's find out. */
for(sym = 0; sym < nsyms; sym++) if(length[sym] != 0) return 1;
return 0;
}
// TODO throw exceptions instead of returns
private void ReadLengths(byte[] lens, uint first, uint last, BitBuffer bitbuf)
{
uint x, y;
int z;
// hufftbl pointer here?
for(x = 0; x < 20; x++)
{
y = bitbuf.ReadBits(4);
m_state.PRETREE_len[x] = (byte)y;
}
MakeDecodeTable(LzxConstants.PRETREE_MAXSYMBOLS, LzxConstants.PRETREE_TABLEBITS,
m_state.PRETREE_len, m_state.PRETREE_table);
for(x = first; x < last;)
{
z = (int)ReadHuffSym(m_state.PRETREE_table, m_state.PRETREE_len,
LzxConstants.PRETREE_MAXSYMBOLS, LzxConstants.PRETREE_TABLEBITS, bitbuf);
if(z == 17)
{
y = bitbuf.ReadBits(4); y += 4;
while(y-- != 0) lens[x++] = 0;
}
else if(z == 18)
{
y = bitbuf.ReadBits(5); y += 20;
while(y-- != 0) lens[x++] = 0;
}
else if(z == 19)
{
y = bitbuf.ReadBits(1); y += 4;
z = (int)ReadHuffSym(m_state.PRETREE_table, m_state.PRETREE_len,
LzxConstants.PRETREE_MAXSYMBOLS, LzxConstants.PRETREE_TABLEBITS, bitbuf);
z = lens[x] - z; if(z < 0) z += 17;
while(y-- != 0) lens[x++] = (byte)z;
}
else
{
z = lens[x] - z; if(z < 0) z += 17;
lens[x++] = (byte)z;
}
}
}
private uint ReadHuffSym(ushort[] table, byte[] lengths, uint nsyms, uint nbits, BitBuffer bitbuf)
{
uint i, j;
bitbuf.EnsureBits(16);
if((i = table[bitbuf.PeekBits((byte)nbits)]) >= nsyms)
{
j = (uint)(1 << (int)((sizeof(uint)*8) - nbits));
do
{
j >>= 1; i <<= 1; i |= (bitbuf.GetBuffer() & j) != 0 ? (uint)1 : 0;
if(j == 0) return 0; // TODO throw proper exception
} while((i = table[i]) >= nsyms);
}
j = lengths[i];
bitbuf.RemoveBits((byte)j);
return i;
}
#region Our BitBuffer Class
private class BitBuffer
{
uint buffer;
byte bitsleft;
Stream byteStream;
public BitBuffer(Stream stream)
{
byteStream = stream;
InitBitStream();
}
public void InitBitStream()
{
buffer = 0;
bitsleft = 0;
}
public void EnsureBits(byte bits)
{
while(bitsleft < bits) {
int lo = (byte)byteStream.ReadByte();
int hi = (byte)byteStream.ReadByte();
int amount2shift = sizeof(uint)*8 - 16 - bitsleft;
buffer |= (uint)(((hi << 8) | lo) << (sizeof(uint)*8 - 16 - bitsleft));
bitsleft += 16;
}
}
public uint PeekBits(byte bits)
{
return (buffer >> ((sizeof(uint)*8) - bits));
}
public void RemoveBits(byte bits)
{
buffer <<= bits;
bitsleft -= bits;
}
public uint ReadBits(byte bits)
{
uint ret = 0;
if(bits > 0)
{
EnsureBits(bits);
ret = PeekBits(bits);
RemoveBits(bits);
}
return ret;
}
public uint GetBuffer()
{
return buffer;
}
public byte GetBitsLeft()
{
return bitsleft;
}
}
#endregion
struct LzxState {
public uint R0, R1, R2; /* for the LRU offset system */
public ushort main_elements; /* number of main tree elements */
public int header_read; /* have we started decoding at all yet? */
public LzxConstants.BLOCKTYPE block_type; /* type of this block */
public uint block_length; /* uncompressed length of this block */
public uint block_remaining; /* uncompressed bytes still left to decode */
public uint frames_read; /* the number of CFDATA blocks processed */
public int intel_filesize; /* magic header value used for transform */
public int intel_curpos; /* current offset in transform space */
public int intel_started; /* have we seen any translateable data yet? */
public ushort[] PRETREE_table;
public byte[] PRETREE_len;
public ushort[] MAINTREE_table;
public byte[] MAINTREE_len;
public ushort[] LENGTH_table;
public byte[] LENGTH_len;
public ushort[] ALIGNED_table;
public byte[] ALIGNED_len;
// NEEDED MEMBERS
// CAB actualsize
// CAB window
// CAB window_size
// CAB window_posn
public uint actual_size;
public byte[] window;
public uint window_size;
public uint window_posn;
}
}
/* CONSTANTS */
struct LzxConstants {
public const ushort MIN_MATCH = 2;
public const ushort MAX_MATCH = 257;
public const ushort NUM_CHARS = 256;
public enum BLOCKTYPE {
INVALID = 0,
VERBATIM = 1,
ALIGNED = 2,
UNCOMPRESSED = 3
}
public const ushort PRETREE_NUM_ELEMENTS = 20;
public const ushort ALIGNED_NUM_ELEMENTS = 8;
public const ushort NUM_PRIMARY_LENGTHS = 7;
public const ushort NUM_SECONDARY_LENGTHS = 249;
public const ushort PRETREE_MAXSYMBOLS = PRETREE_NUM_ELEMENTS;
public const ushort PRETREE_TABLEBITS = 6;
public const ushort MAINTREE_MAXSYMBOLS = NUM_CHARS + 50*8;
public const ushort MAINTREE_TABLEBITS = 12;
public const ushort LENGTH_MAXSYMBOLS = NUM_SECONDARY_LENGTHS + 1;
public const ushort LENGTH_TABLEBITS = 12;
public const ushort ALIGNED_MAXSYMBOLS = ALIGNED_NUM_ELEMENTS;
public const ushort ALIGNED_TABLEBITS = 7;
public const ushort LENTABLE_SAFETY = 64;
}
/* EXCEPTIONS */
class UnsupportedWindowSizeRange : Exception
{
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using Timestamper.Properties;
namespace Timestamper
{
/// <summary>
/// A feature class extension for timestamping features with creation dates, modification dates, and
/// the name of the user who created or last modified the feature.
/// </summary>
[Guid("31b0b791-3606-4c58-b4d9-940c157dca4c")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("Timestamper.TimestampClassExtension")]
[ComVisible(true)]
public class TimestampClassExtension : IClassExtension, IObjectClassExtension, IFeatureClassExtension,
IObjectClassEvents, IObjectClassInfo
{
#region Member Variables
/// <summary>
/// Provides a reference to the extension's class.
/// </summary>
private IClassHelper classHelper = null;
/// <summary>
/// The extension properties.
/// </summary>
private IPropertySet extensionProperties = null;
/// <summary>
/// The name of the "created" date field.
/// </summary>
private String createdFieldName = Resources.DefaultCreatedField;
/// <summary>
/// The position of the "created" date field.
/// </summary>
private int createdFieldIndex = -1;
/// <summary>
/// The name of the "modified" date field.
/// </summary>
private String modifiedFieldName = Resources.DefaultModifiedField;
/// <summary>
/// The position of the "modified" date field.
/// </summary>
private int modifiedFieldIndex = -1;
/// <summary>
/// The name of the "user" text field.
/// </summary>
private String userFieldName = Resources.DefaultUserField;
/// <summary>
/// The position of the "user" text field.
/// </summary>
private int userFieldIndex = -1;
/// <summary>
/// The length of the "user" text field.
/// </summary>
private int userFieldLength = 0;
/// <summary>
/// The name of the current user.
/// </summary>
private String userName = String.Empty;
#endregion
#region IClassExtension Methods
/// <summary>
/// Initializes the extension.
/// </summary>
/// <param name="classHelper">Provides a reference to the extension's class.</param>
/// <param name="extensionProperties">A set of properties unique to the extension.</param>
public void Init(IClassHelper classHelper, IPropertySet extensionProperties)
{
// Store the class helper as a member variable.
this.classHelper = classHelper;
IClass baseClass = classHelper.Class;
// Get the names of the created and modified fields, if they exist.
if (extensionProperties != null)
{
this.extensionProperties = extensionProperties;
object createdObject = extensionProperties.GetProperty(Resources.CreatedFieldKey);
object modifiedObject = extensionProperties.GetProperty(Resources.ModifiedFieldKey);
object userObject = extensionProperties.GetProperty(Resources.UserFieldKey);
// Make sure the properties exist and are strings.
if (createdObject != null && createdObject is String)
{
createdFieldName = Convert.ToString(createdObject);
}
if (modifiedObject != null && modifiedObject is String)
{
modifiedFieldName = Convert.ToString(modifiedObject);
}
if (userObject != null && userObject is String)
{
userFieldName = Convert.ToString(userObject);
}
}
else
{
// First time the extension has been run. Initialize with default values.
InitNewExtension();
}
// Set the positions of the fields.
SetFieldIndexes();
// Set the current user name.
userName = GetCurrentUser();
}
/// <summary>
/// Informs the extension that the class is being disposed of.
/// </summary>
public void Shutdown()
{
classHelper = null;
}
#endregion
#region IObjectClassEvents Methods
/// <summary>
/// Fired when an object's attributes or geometry is updated.
/// </summary>
/// <param name="obj">The updated object.</param>
public void OnChange(IObject obj)
{
// Set the modified field's value to the current date and time.
if (modifiedFieldIndex != -1)
{
obj.set_Value(modifiedFieldIndex, DateTime.Now);
// Set the user field's value to the current user.
if (userFieldIndex != -1)
{
obj.set_Value(userFieldIndex, userName);
}
}
}
/// <summary>
/// Fired when a new object is created.
/// </summary>
/// <param name="obj">The new object.</param>
public void OnCreate(IObject obj)
{
// Set the created field's value to the current date and time.
if (createdFieldIndex != -1)
{
obj.set_Value(createdFieldIndex, DateTime.Now);
}
// Set the user field's value to the current user.
if (userFieldIndex != -1)
{
obj.set_Value(userFieldIndex, userName);
}
}
/// <summary>
/// Fired when an object is deleted.
/// </summary>
/// <param name="obj">The deleted object.</param>
public void OnDelete(IObject obj)
{}
#endregion
#region IObjectClassInfo Methods
/// <summary>
/// Indicates if updates to objects can bypass the Store method and OnChange notifications for efficiency.
/// </summary>
/// <returns>False; this extension requires Store to be called.</returns>
public Boolean CanBypassStoreMethod()
{
return false;
}
#endregion
#region Public Members
/// <summary>
/// Changes the member variables and extension properties to store the provided field names
/// as the created, modified and user fields (positions are also refreshed). Empty strings
/// indicate the values should not be saved in a field.
/// </summary>
/// <param name="createdField">The name of the "created" field.</param>
/// <param name="modifiedField">The name of the "modified" field.</param>
/// <param name="userField">The name of the "user" field.</param>
public void SetTimestampFields(String createdField, String modifiedField, String userField)
{
IClass baseClass = classHelper.Class;
ISchemaLock schemaLock = (ISchemaLock)baseClass;
try
{
// Get an exclusive lock. We want to do this prior to making any changes
// to ensure the member variables and extension properties remain synchronized.
schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
// Set the name member variables.
createdFieldName = createdField;
modifiedFieldName = modifiedField;
userFieldName = userField;
// Set the positions of the fields.
SetFieldIndexes();
// Modify the extension properties.
extensionProperties.SetProperty(Resources.CreatedFieldKey, createdFieldName);
extensionProperties.SetProperty(Resources.ModifiedFieldKey, modifiedFieldName);
extensionProperties.SetProperty(Resources.UserFieldKey, userFieldName);
// Change the properties.
IClassSchemaEdit2 classSchemaEdit = (IClassSchemaEdit2)baseClass;
classSchemaEdit.AlterClassExtensionProperties(extensionProperties);
}
catch (COMException comExc)
{
throw new Exception(Resources.FailedToSavePropertiesMsg, comExc);
}
finally
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
}
/// <summary>
/// The field storing the creation date of features.
/// </summary>
public String CreatedField
{
get
{
return createdFieldName;
}
}
/// <summary>
/// The field storing the modification date of features.
/// </summary>
public String ModifiedField
{
get
{
return modifiedFieldName;
}
}
/// <summary>
/// The field storing the user who created or last modified the feature.
/// </summary>
public String UserField
{
get
{
return userFieldName;
}
}
#endregion
#region Private Methods
/// <summary>
/// This method should be called the first time the extension is initialized, when the
/// extension properties are null. This will create a new set of properties with the default
/// field names.
/// </summary>
private void InitNewExtension()
{
// First time the extension has been run, initialize the extension properties.
extensionProperties = new PropertySetClass();
extensionProperties.SetProperty(Resources.CreatedFieldKey, createdFieldName);
extensionProperties.SetProperty(Resources.ModifiedFieldKey, modifiedFieldName);
extensionProperties.SetProperty(Resources.UserFieldKey, userFieldName);
// Store the properties.
IClass baseClass = classHelper.Class;
IClassSchemaEdit2 classSchemaEdit = (IClassSchemaEdit2)baseClass;
classSchemaEdit.AlterClassExtensionProperties(extensionProperties);
}
/// <summary>
/// Gets the name of the extension's user. For local geodatabases, this is the username as known
/// by the operating system (in a domain\username format). For remote geodatabases, the
/// IDatabaseConnectionInfo interface is utilized.
/// </summary>
/// <returns>The name of the current user.</returns>
private String GetCurrentUser()
{
// Get the base class' workspace.
IClass baseClass = classHelper.Class;
IDataset dataset = (IDataset)baseClass;
IWorkspace workspace = dataset.Workspace;
// If supported, use the IDatabaseConnectionInfo interface to get the username.
IDatabaseConnectionInfo databaseConnectionInfo = workspace as IDatabaseConnectionInfo;
if (databaseConnectionInfo != null)
{
String connectedUser = databaseConnectionInfo.ConnectedUser;
// If the user name is longer than the user field allows, shorten it.
if (connectedUser.Length > userFieldLength)
{
connectedUser = connectedUser.Substring(0, userFieldLength);
}
return connectedUser;
}
// Get the current Windows user.
String userDomain = Environment.UserDomainName;
String userName = Environment.UserName;
String qualifiedUserName = String.Format(@"{0}\{1}", userDomain, userName);
// If the user name is longer than the user field allows, shorten it.
if (qualifiedUserName.Length > userFieldLength)
{
qualifiedUserName = qualifiedUserName.Substring(0, userFieldLength);
}
return qualifiedUserName;
}
/// <summary>
/// Finds the positions of the created, modified and user fields, and verifies that
/// the specified field has the correct data type.
/// </summary>
private void SetFieldIndexes()
{
// Get the base class from the class helper.
IClass baseClass = classHelper.Class;
// Find the indexes of the fields.
createdFieldIndex = baseClass.FindField(createdFieldName);
modifiedFieldIndex = baseClass.FindField(modifiedFieldName);
userFieldIndex = baseClass.FindField(userFieldName);
// Verify that the field data types are correct.
IFields fields = baseClass.Fields;
if (createdFieldIndex != -1)
{
IField createdField = fields.get_Field(createdFieldIndex);
// If the "created" field is not a date field, do not use it.
if (createdField.Type != esriFieldType.esriFieldTypeDate)
{
createdFieldIndex = -1;
}
}
if (modifiedFieldIndex != -1)
{
IField modifiedField = fields.get_Field(modifiedFieldIndex);
// If the "modified" field is not a date field, do not use it.
if (modifiedField.Type != esriFieldType.esriFieldTypeDate)
{
modifiedFieldIndex = -1;
}
}
if (userFieldIndex != -1)
{
IField userField = fields.get_Field(userFieldIndex);
// If the "user" field is not a text field, do not use it.
if (userField.Type != esriFieldType.esriFieldTypeString)
{
userFieldIndex = -1;
}
else
{
// Get the length of the text field.
userFieldLength = userField.Length;
}
}
}
#endregion
#region COM Registration Function(s)
/// <summary>
/// Registers the class extension in the appropriate component category.
/// </summary>
/// <param name="registerType">The class description's type.</param>
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GeoObjectClassExtensions.Register(regKey);
}
/// <summary>
/// Removes the class extension from the appropriate component category.
/// </summary>
/// <param name="registerType">The class description's type.</param>
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GeoObjectClassExtensions.Unregister(regKey);
}
#endregion
}
}
| |
namespace CSharpCLI {
using System;
using System.Reflection;
internal class TableDescriptor {
internal FieldInfo[] columns;
internal int nColumns;
internal Connection.CLIType[] types;
internal Type cls;
internal ConstructorInfo constructor;
internal bool autoincrement;
static Type[] constructorProfile = new Type[0];
static object[] constructorParameters = new object[0];
internal TableDescriptor(Type tableClass) {
int i, n;
Type c;
for (c = tableClass, n = 0; c != null; c = c.BaseType) {
FieldInfo[] classFields = c.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
for (i = 0; i < classFields.Length; i++) {
FieldInfo f = classFields[i];
if (!f.IsStatic && !f.IsNotSerialized) {
n += 1;
}
}
}
columns = new FieldInfo[n];
types = new Connection.CLIType[n];
nColumns = n;
cls = tableClass;
constructor = tableClass.GetConstructor(constructorProfile);
for (c = tableClass, n = 0; c != null; c = c.BaseType) {
FieldInfo[] classFields = c.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
for (i = 0; i < classFields.Length; i++) {
FieldInfo f = classFields[i];
if (!f.IsStatic && !f.IsNotSerialized) {
columns[n] = f;
Type type = f.FieldType;
Connection.CLIType cliType;
if (type == typeof(byte)) {
cliType = Connection.CLIType.cli_int1;
} else if (type == typeof(short)) {
cliType = Connection.CLIType.cli_int2;
} else if (type == typeof(int)) {
if (f.GetCustomAttributes(typeof(AutoincrementAttribute), false).Length > 0) {
cliType = Connection.CLIType.cli_autoincrement;
autoincrement = true;
}
else {
cliType = Connection.CLIType.cli_int4;
}
} else if (type == typeof(bool)) {
cliType = Connection.CLIType.cli_bool;
} else if (type == typeof(long)) {
cliType = Connection.CLIType.cli_int8;
} else if (type == typeof(float)) {
cliType = Connection.CLIType.cli_real4;
} else if (type == typeof(double)) {
cliType = Connection.CLIType.cli_real8;
} else if (type == typeof(Reference)) {
cliType = Connection.CLIType.cli_oid;
} else if (type == typeof(Rectangle)) {
cliType = Connection.CLIType.cli_rectangle;
} else if (type == typeof(string)) {
cliType = Connection.CLIType.cli_asciiz;
} else if (type == typeof(DateTime)) {
cliType = Connection.CLIType.cli_datetime;
} else if (type.IsArray) {
type = type.GetElementType();
if (type == typeof(byte)) {
cliType = Connection.CLIType.cli_array_of_int1;
} else if (type == typeof(short)) {
cliType = Connection.CLIType.cli_array_of_int2;
} else if (type == typeof(int)) {
cliType = Connection.CLIType.cli_array_of_int4;
} else if (type == typeof(bool)) {
cliType = Connection.CLIType.cli_array_of_bool;
} else if (type == typeof(long)) {
cliType = Connection.CLIType.cli_array_of_int8;
} else if (type == typeof(float)) {
cliType = Connection.CLIType.cli_array_of_real4;
} else if (type == typeof(double)) {
cliType = Connection.CLIType.cli_array_of_real8;
} else if (type == typeof(Reference)) {
cliType = Connection.CLIType.cli_array_of_oid;
} else if (type == typeof(string)) {
cliType = Connection.CLIType.cli_array_of_string;
} else {
throw new CliError("Unsupported array type " + type.Name);
}
} else {
throw new CliError("Unsupported field type " + type.Name);
}
types[n++] = cliType;
}
}
}
}
internal void writeColumnDefs(ComBuffer buf) {
for (int i = 0, n = nColumns; i < n; i++) {
buf.putByte((int)types[i]);
buf.putAsciiz(columns[i].Name);
}
}
internal void writeColumnValues(ComBuffer buf, Object obj) {
int i, j, n, len;
for (i = 0, n = nColumns; i < n; i++)
{
switch (types[i])
{
case Connection.CLIType.cli_int1:
buf.putByte((byte)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_int2:
buf.putShort((short)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_int4:
buf.putInt((int)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_int8:
buf.putLong((long)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_real4:
buf.putFloat((float)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_real8:
buf.putDouble((double)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_bool:
buf.putByte((bool)columns[i].GetValue(obj) ? 1 : 0);
break;
case Connection.CLIType.cli_oid:
Reference r = (Reference)columns[i].GetValue(obj);
buf.putInt(r != null ? r.oid : 0);
break;
case Connection.CLIType.cli_rectangle:
Rectangle rect = (Rectangle)columns[i].GetValue(obj);
if (rect == null)
{
rect = new Rectangle();
}
buf.putRectangle(rect);
break;
case Connection.CLIType.cli_asciiz:
buf.putString((string)columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_datetime:
buf.putInt((int)(((DateTime)columns[i].GetValue(obj)).Ticks / 1000000));
break;
case Connection.CLIType.cli_array_of_int1:
buf.putByteArray((byte[])columns[i].GetValue(obj));
break;
case Connection.CLIType.cli_array_of_int2:
{
short[] arr = (short[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putShort(arr[j]);
}
break;
}
case Connection.CLIType.cli_array_of_int4:
{
int[] arr = (int[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putInt(arr[j]);
}
break;
}
case Connection.CLIType.cli_array_of_int8:
{
long[] arr = (long[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putLong(arr[j]);
}
break;
}
case Connection.CLIType.cli_array_of_real4:
{
float[] arr = (float[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putFloat(arr[j]);
}
break;
}
case Connection.CLIType.cli_array_of_real8:
{
double[] arr = (double[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putDouble(arr[j]);
}
break;
}
case Connection.CLIType.cli_array_of_bool:
{
bool[] arr = (bool[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putByte(arr[j] ? 1 : 0);
}
break;
}
case Connection.CLIType.cli_array_of_oid:
{
Reference[] arr = (Reference[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putInt(arr[j] != null ? arr[j].oid : 0);
}
break;
}
case Connection.CLIType.cli_array_of_string:
{
string[] arr = (string[])columns[i].GetValue(obj);
len = arr == null ? 0 : arr.Length;
buf.putInt(len);
for (j = 0; j < len; j++)
{
buf.putAsciiz(arr[j]);
}
break;
}
case Connection.CLIType.cli_autoincrement:
break;
default:
throw new CliError("Unsupported type " + types[i]);
}
}
}
internal object readObject(ComBuffer buf)
{
Object obj = constructor.Invoke(constructorParameters);
int i, j, n, len;
for (i = 0, n = nColumns; i < n; i++)
{
Connection.CLIType type = (Connection.CLIType)buf.getByte();
if (type != types[i])
{
throw new CliError("Unexpected type of column: " + type
+ " instead of " + types[i]);
}
switch (types[i])
{
case Connection.CLIType.cli_int1:
columns[i].SetValue(obj, buf.getByte());
break;
case Connection.CLIType.cli_int2:
columns[i].SetValue(obj, buf.getShort());
break;
case Connection.CLIType.cli_int4:
case Connection.CLIType.cli_autoincrement:
columns[i].SetValue(obj, buf.getInt());
break;
case Connection.CLIType.cli_int8:
columns[i].SetValue(obj, buf.getLong());
break;
case Connection.CLIType.cli_real4:
columns[i].SetValue(obj, buf.getFloat());
break;
case Connection.CLIType.cli_real8:
columns[i].SetValue(obj, buf.getDouble());
break;
case Connection.CLIType.cli_bool:
columns[i].SetValue(obj, buf.getByte() != 0);
break;
case Connection.CLIType.cli_oid:
{
int oid = buf.getInt();
columns[i].SetValue(obj, (oid != 0) ? new Reference(oid) : null);
break;
}
case Connection.CLIType.cli_rectangle:
columns[i].SetValue(obj, buf.getRectangle());
break;
case Connection.CLIType.cli_asciiz:
columns[i].SetValue(obj, buf.getString());
break;
case Connection.CLIType.cli_datetime:
columns[i].SetValue(obj, new DateTime(((long)buf.getInt() & 0xFFFFFFFFL)*1000000));
break;
case Connection.CLIType.cli_array_of_int1:
{
len = buf.getInt();
byte[] arr = new byte[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getByte();
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_int2:
{
len = buf.getInt();
short[] arr = new short[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getShort();
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_int4:
{
len = buf.getInt();
int[] arr = new int[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getInt();
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_int8:
{
len = buf.getInt();
long[] arr = new long[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getLong();
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_real4:
{
len = buf.getInt();
float[] arr = new float[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getFloat();
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_real8:
{
len = buf.getInt();
double[] arr = new double[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getDouble();
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_bool:
{
len = buf.getInt();
bool[] arr = new bool[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getByte() != 0;
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_oid:
{
len = buf.getInt();
Reference[] arr = new Reference[len];
for (j = 0; j < len; j++)
{
int oid = buf.getInt();
arr[j] = oid != 0 ? new Reference(oid) : null;
}
columns[i].SetValue(obj, arr);
break;
}
case Connection.CLIType.cli_array_of_string:
{
len = buf.getInt();
string[] arr = new string[len];
for (j = 0; j < len; j++)
{
arr[j] = buf.getAsciiz();
}
columns[i].SetValue(obj, arr);
break;
}
default:
throw new CliError("Unsupported type " + types[i]);
}
}
return obj;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Artem.Data.Access {
/// <summary>
///
/// </summary>
internal static class ObjectHelper {
#region Static Fields ///////////////////////////////////////////////////////////
//private static readonly Type _TypeOf_DatabaseCommandAttribute = typeof(DatabaseCommandAttribute);
private static readonly Type _TypeOf_Field = typeof(DbFieldAttribute);
#endregion
#region Static Methods ///////////////////////////////////////////////////////////
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="command"></param>
/// <returns></returns>
public static DbCommandAttribute FindCommand(Type type, string command) {
DbCommandAttribute commandAttribute = null;
foreach (Attribute attribute in TypeDescriptor.GetAttributes(type)) {
commandAttribute = attribute as DbCommandAttribute;
if (commandAttribute != null && commandAttribute.CommandName == command)
return commandAttribute;
}
throw CommandNotExists(command, type);
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static PropertyDescriptor FindPrimaryProperty(Type type) {
if (IsDataObjectSource(type)) {
DataObjectFieldAttribute attribute = null;
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type)) {
attribute = (DataObjectFieldAttribute)
property.Attributes[typeof(DataObjectFieldAttribute)];
if (attribute != null && attribute.PrimaryKey) return property;
}
throw PrimaryNotExists(type);
}
throw IsNotDataObject(type);
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="fieldName"></param>
/// <returns></returns>
public static PropertyDescriptor FindPropertyByField(Type type, string fieldName) {
DbFieldAttribute attribute = null;
fieldName = fieldName.ToLower();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type)) {
attribute = (DbFieldAttribute)property.Attributes[_TypeOf_Field];
if (attribute != null && attribute.FieldName.ToLower() == fieldName) return property;
}
throw FieldNotExists(fieldName, type);
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static PropertyDescriptor FindPropertyByParameter(Type type, string parameterName) {
DbFieldAttribute attribute = null;
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type)) {
attribute = (DbFieldAttribute)property.Attributes[_TypeOf_Field];
if(attribute != null && attribute.ParameterName == parameterName) return property;
}
throw ParameterNotExists(parameterName, type);
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IList<string> GetAllFields(Type type) {
DbFieldAttribute attribute = null;
List<string> list = new List<string>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type)) {
attribute = property.Attributes[_TypeOf_Field] as DbFieldAttribute;
if (attribute != null) list.Add(attribute.FieldName);
}
return list;
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IList<string> GetAllParameters(Type type) {
DbFieldAttribute attribute = null;
List<string> list = new List<string>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type)) {
attribute = property.Attributes[_TypeOf_Field] as DbFieldAttribute;
if (attribute != null) list.Add(attribute.ParameterName);
}
return list;
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static string GetFieldName(Type type, string propertyName) {
PropertyDescriptor property = TypeDescriptor.GetProperties(type)[propertyName];
if (property != null) {
return GetFieldName(property);
}
throw PropertyNotExists(propertyName, type);
}
/// <summary>
///
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public static string GetFieldName(PropertyDescriptor property) {
DbFieldAttribute attribute =
property.Attributes[_TypeOf_Field] as DbFieldAttribute;
if (attribute != null) {
return attribute.FieldName;
}
throw FieldNotExists(string.Format("for property: {0}", property.Name), property.GetType());
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="fieldName"></param>
/// <returns></returns>
public static Type GetFieldType(Type type, string fieldName) {
PropertyDescriptor property =
ObjectHelper.FindPropertyByField(type, fieldName);
if(property != null) {
return property.PropertyType;
}
throw FieldNotExists(fieldName, type);
}
/// <summary>
///
/// </summary>
/// <param name="dataObject"></param>
/// <param name="fieldName"></param>
/// <returns></returns>
public static object GetFieldValue(object dataObject, string fieldName) {
PropertyDescriptor property =
ObjectHelper.FindPropertyByField(dataObject.GetType(), fieldName);
if (property != null) {
return property.GetValue(dataObject);
}
throw FieldNotExists(fieldName, dataObject.GetType());
}
/// <summary>
///
/// </summary>
/// <param name="dataObject"></param>
/// <param name="fieldName"></param>
/// <param name="value"></param>
public static void SetFieldValue(object dataObject, string fieldName, object value) {
PropertyDescriptor property =
ObjectHelper.FindPropertyByField(dataObject.GetType(), fieldName);
if (property != null) {
property.SetValue(dataObject, DbDataConvert.ToAny(value, property.PropertyType));
}
else {
throw FieldNotExists(fieldName, dataObject.GetType());
}
}
/// <summary>
///
/// </summary>
/// <param name="dataObject"></param>
/// <param name="value"></param>
public static void SetPrimaryFieldValue(object dataObject, object value) {
PropertyDescriptor property =
ObjectHelper.FindPrimaryProperty(dataObject.GetType());
if (property != null) {
property.SetValue(dataObject, DbDataConvert.ToAny(value, property.PropertyType));
}
else {
throw PrimaryNotExists(dataObject.GetType());
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static string GetParameterName(Type type, string propertyName) {
PropertyDescriptor property = TypeDescriptor.GetProperties(type)[propertyName];
if (property != null) {
return GetParameterName(property);
}
throw PropertyNotExists(propertyName, type);
}
/// <summary>
///
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public static string GetParameterName(PropertyDescriptor property) {
DbFieldAttribute attribute =
property.Attributes[_TypeOf_Field] as DbFieldAttribute;
if (attribute != null) {
return attribute.ParameterName;
}
throw ParameterNotExists(string.Format("for property: {0}", property.Name), property.GetType());
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static Type GetParameterType(Type type, string parameterName) {
PropertyDescriptor property =
ObjectHelper.FindPropertyByParameter(type, parameterName);
if(property != null) {
return property.PropertyType;
}
throw ParameterNotExists(parameterName, type);
}
/// <summary>
///
/// </summary>
/// <param name="dataObject"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static object GetParameterValue(object dataObject, string parameterName) {
PropertyDescriptor property =
ObjectHelper.FindPropertyByParameter(dataObject.GetType(), parameterName);
if (property != null) {
return property.GetValue(dataObject);
}
throw ParameterNotExists(parameterName, dataObject.GetType());
}
/// <summary>
///
/// </summary>
/// <param name="dataObject"></param>
/// <param name="parameterName"></param>
/// <param name="value"></param>
public static void SetParameterValue(object dataObject, string parameterName, object value) {
PropertyDescriptor property =
ObjectHelper.FindPropertyByParameter(dataObject.GetType(), parameterName);
if (property != null) {
property.SetValue(dataObject, DbDataConvert.ToAny(value, property.PropertyType));
}
else {
throw ParameterNotExists(parameterName, dataObject.GetType());
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsDataObjectSource(Type type) {
return TypeDescriptor.GetAttributes(type)[typeof(DataObjectAttribute)] != null;
}
#region Exception helpers
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static Exception IsNotDataObject(Type type) {
return new Exception(string.Format(
@"Type {0} is not a DataObject type! Ensure {0} is marked with
System.ComponentModel.DataObjectAttribute and has a primary property
marked with System.ComponentModel.DataObjectFieldAttribute", type));
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static Exception PrimaryNotExists(Type type) {
return new Exception(string.Format(
@"Type {0} does not have a primary field! Ensure {0} is marked with
System.ComponentModel.DataObjectAttribute and has a primary property
marked with System.ComponentModel.DataObjectFieldAttribute", type));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
private static Exception CommandNotExists(string name, Type type) {
return new Exception(
string.Format(@"Command '{0}' does not exists in Type '{1}'!
Ensure you are using a correct command name or you have marked
such a command with DatabaseCommandAttribute.", name, type));
}
/// <summary>
///
/// </summary>
private static Exception PropertyNotExists(string name, Type type) {
return new Exception(
string.Format(@"Property '{0}' does not exists in Type '{1}'!
Ensure you are using a correct property name.", name, type));
}
/// <summary>
///
/// </summary>
private static Exception FieldNotExists(string name, Type type) {
return new Exception(
string.Format(@"Field '{0}' does not exists in Type '{1}'!
Ensure you are using a correct field name or you have marked
such a field with DatabaseFieldAttribute.", name, type));
}
/// <summary>
///
/// </summary>
private static Exception ParameterNotExists(string name, Type type) {
return new Exception(
string.Format(@"Parameter '{0}' does not exists in Type '{1}'!
Ensure you are using a correct parameter name or you have marked
such a parameter with DatabaseFieldAttribute.", name, type));
}
#endregion
#endregion
}
}
| |
/*++
Copyright (c) Microsoft Corporation
Module Name:
RequestCachePolicy.cs
Abstract:
The class implements caching policy paradigms that is used by all webrequest cache-aware clients
Author:
Alexei Vopilov 21-Dec-2002
Revision History:
4 Dec 2003 - Reworked as per design review.
30 Jul 2004 - Updated to accomodate FTP caching feature
--*/
namespace System.Net.Cache {
using System.Globalization;
// The enum describes cache settings applicable for any webrequest
public enum RequestCacheLevel
{
// Default cache behavior determined by the protocol class
Default = 0,
// Bypass the cache completely
BypassCache = 1,
// Only serve requests from cache, an exception is thrown if not found
CacheOnly = 2,
// Serve from the cache, but will [....] up with the server if not found
CacheIfAvailable = 3,
// Attempt to revalidate cache with the server, reload if unable to
Revalidate = 4,
// Reload the data from the origin server
Reload = 5,
// Bypass the cache and removing existing entries in the cache
NoCacheNoStore = 6
}
//
// Common request cache policy used for caching of Http, FTP, etc.
//
public class RequestCachePolicy
{
private RequestCacheLevel m_Level;
//
// Public stuff
//
public RequestCachePolicy(): this (RequestCacheLevel.Default)
{
}
public RequestCachePolicy(RequestCacheLevel level)
{
if (level < RequestCacheLevel.Default || level > RequestCacheLevel.NoCacheNoStore)
throw new ArgumentOutOfRangeException("level");
m_Level = level;
}
//
public RequestCacheLevel Level
{
get {
return m_Level;
}
}
//
public override string ToString()
{
return "Level:" + m_Level.ToString();
}
//
// Internal stuff
//
//
#if TRAVE
/*
// Consider removing.
internal static string ToString(RequestCachePolicy Policy)
{
if (Policy == null) {
return "null";
}
return Policy.ToString();
}
*/
#endif
}
// The enum describes cache settings for http
public enum HttpRequestCacheLevel
{
// Default cache behavior, server fresh response fomr cache, otherwise attempt
// to revalidate with the server or reload
Default = 0,
// Bypass the cache completely
BypassCache = 1,
// Only serve requests from cache, an exception is thrown if not found
CacheOnly = 2,
// Serve from the cache, but will [....] up with the server if not found
CacheIfAvailable = 3,
// Validate cached data with the server even if it looks fresh
Revalidate = 4,
// Reload the data from the origin server
Reload = 5,
// Bypass the cache and removing existing entries in the cache
NoCacheNoStore = 6,
// Serve from cache, or the next cache along the path
CacheOrNextCacheOnly= 7,
// Reload the data either from the origin server or from an uplevel cache
//This is equvalent to Cache-Control:MaxAge=0 HTTP semantic
Refresh = 8,
}
//
// CacheAgeControl is used to specify preferences with respect of cached item age and freshness.
//
public enum HttpCacheAgeControl {
// Invalid value. Indicates the enum is not initialized
None = 0x0,
// Cached item must be at least fresh for specified period since now
MinFresh = 0x1,
// Cached item must be fresh and it's age must not exceed specified period
MaxAge = 0x2,
// Cached item may be not fresh but it's expiration must not exceed specified period
MaxStale = 0x4,
// Cached item must fresh for some period in future and it's age must be less than specified
MaxAgeAndMinFresh = 0x3, // MaxAge|MinFresh,
// Cached item may be found as stale for some period but it's age must be less than specified
MaxAgeAndMaxStale = 0x6, // MaxAge|MaxStale,
}
//
// HTTP cache policy that expresses RFC2616 HTTP caching semantic
//
public class HttpRequestCachePolicy: RequestCachePolicy {
internal static readonly HttpRequestCachePolicy BypassCache = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);
//Private members
private HttpRequestCacheLevel m_Level = HttpRequestCacheLevel.Default;
private DateTime m_LastSyncDateUtc = DateTime.MinValue;
private TimeSpan m_MaxAge = TimeSpan.MaxValue;
private TimeSpan m_MinFresh = TimeSpan.MinValue;
private TimeSpan m_MaxStale = TimeSpan.MinValue;
//
// Public stuff
//
public HttpRequestCachePolicy():this(HttpRequestCacheLevel.Default)
{
}
//
public HttpRequestCachePolicy(HttpRequestCacheLevel level): base(MapLevel(level))
{
m_Level = level;
}
//
// Creates an automatic cache policy that is bound to a simples age control
//
public HttpRequestCachePolicy(HttpCacheAgeControl cacheAgeControl, TimeSpan ageOrFreshOrStale):this(HttpRequestCacheLevel.Default)
{
switch(cacheAgeControl) {
case HttpCacheAgeControl.MinFresh:
m_MinFresh = ageOrFreshOrStale;
break;
case HttpCacheAgeControl.MaxAge:
m_MaxAge = ageOrFreshOrStale;
break;
case HttpCacheAgeControl.MaxStale:
m_MaxStale = ageOrFreshOrStale;
break;
default:
throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "HttpCacheAgeControl"), "cacheAgeControl");
}
}
//
// Creates an automatic cache policy that is bound to a complex age control
//
public HttpRequestCachePolicy(HttpCacheAgeControl cacheAgeControl, TimeSpan maxAge, TimeSpan freshOrStale):this(HttpRequestCacheLevel.Default)
{
switch(cacheAgeControl) {
case HttpCacheAgeControl.MinFresh:
m_MinFresh = freshOrStale;
break;
case HttpCacheAgeControl.MaxAge:
m_MaxAge = maxAge;
break;
case HttpCacheAgeControl.MaxStale:
m_MaxStale = freshOrStale;
break;
case HttpCacheAgeControl.MaxAgeAndMinFresh:
m_MaxAge = maxAge;
m_MinFresh = freshOrStale;
break;
case HttpCacheAgeControl.MaxAgeAndMaxStale:
m_MaxAge = maxAge;
m_MaxStale = freshOrStale;
break;
default:
throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "HttpCacheAgeControl"), "cacheAgeControl");
}
}
//
// Creates an automatic cache policy with the Date Synchronization requirement
//
public HttpRequestCachePolicy(DateTime cacheSyncDate):this(HttpRequestCacheLevel.Default)
{
m_LastSyncDateUtc = cacheSyncDate.ToUniversalTime();
}
//
//
//
public HttpRequestCachePolicy(HttpCacheAgeControl cacheAgeControl, TimeSpan maxAge, TimeSpan freshOrStale, DateTime cacheSyncDate)
:this(cacheAgeControl, maxAge, freshOrStale)
{
m_LastSyncDateUtc = cacheSyncDate.ToUniversalTime();
}
//
// Properties
//
public new HttpRequestCacheLevel Level
{
get {
return m_Level;
}
}
//
// Requires revalidation of items stored before lastSyncDate
//
public DateTime CacheSyncDate {
get {
if (m_LastSyncDateUtc == DateTime.MinValue || m_LastSyncDateUtc == DateTime.MaxValue) {
return m_LastSyncDateUtc;
}
return m_LastSyncDateUtc.ToLocalTime();}
}
//
internal DateTime InternalCacheSyncDateUtc {
get {return m_LastSyncDateUtc;}
}
//
// Specifies age policy according to HTTP 1.1 RFC caching semantic
//
public TimeSpan MaxAge {
get {return m_MaxAge;}
}
//
// Specifies age policy according to HTTP 1.1 RFC caching semantic
//
public TimeSpan MinFresh {
get {return m_MinFresh;}
}
//
// Specifies age policy according to HTTP 1.1 RFC caching semantic
//
public TimeSpan MaxStale {
get {return m_MaxStale;}
}
//
//
//
public override string ToString()
{
return "Level:" + m_Level.ToString() +
(m_MaxAge == TimeSpan.MaxValue? string.Empty: " MaxAge:" + m_MaxAge.ToString()) +
(m_MinFresh == TimeSpan.MinValue? string.Empty: " MinFresh:" + m_MinFresh.ToString()) +
(m_MaxStale == TimeSpan.MinValue? string.Empty: " MaxStale:" + m_MaxStale.ToString()) +
(CacheSyncDate==DateTime.MinValue? string.Empty: " CacheSyncDate:" + CacheSyncDate.ToString(CultureInfo.CurrentCulture));
}
//
//
//
private static RequestCacheLevel MapLevel(HttpRequestCacheLevel level)
{
if (level <= HttpRequestCacheLevel.NoCacheNoStore)
return (RequestCacheLevel) level;
if (level == HttpRequestCacheLevel.CacheOrNextCacheOnly)
return RequestCacheLevel.CacheOnly;
if (level == HttpRequestCacheLevel.Refresh)
return RequestCacheLevel.Reload;
throw new ArgumentOutOfRangeException("level");
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Abstract;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace Contoso.Abstract
{
/// <summary>
/// ITraceSourceServiceLog
/// </summary>
public interface ITraceSourceServiceLog : IServiceLog
{
/// <summary>
/// Gets the log.
/// </summary>
TraceSource Log { get; }
}
/// <summary>
/// TraceSourceServiceLog
/// </summary>
public class TraceSourceServiceLog : ITraceSourceServiceLog, ServiceLogManager.ISetupRegistration
{
private static readonly Dictionary<string, TraceSource> _logs = new Dictionary<string, TraceSource>();
static TraceSourceServiceLog() { ServiceLogManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="TraceSourceServiceLog"/> class.
/// </summary>
/// <param name="name">The name.</param>
public TraceSourceServiceLog(string name)
: this(name, SourceLevels.Off) { }
/// <summary>
/// Initializes a new instance of the <see cref="TraceSourceServiceLog"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultLevel">The default level.</param>
public TraceSourceServiceLog(string name, SourceLevels defaultLevel)
{
Name = name;
Log = GetAndCache(name, defaultLevel);
}
Action<IServiceLocator, string> ServiceLogManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLogManager.RegisterInstance<ITraceSourceServiceLog>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
// get
/// <summary>
/// Gets the name.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public IServiceLog Get(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
return new TraceSourceServiceLog(name);
}
/// <summary>
/// Gets the specified name.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public IServiceLog Get(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return new TraceSourceServiceLog(type.Name);
}
// log
/// <summary>
/// Writes the specified level.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
public void Write(ServiceLog.LogLevel level, Exception ex, string s)
{
if (Log == null)
throw new NullReferenceException("Log");
if (ex == null)
Log.TraceEvent(ToTraceEventType(level), 0, s);
else
Log.TraceData(ToTraceEventType(level), 0, new object[] { s, ex });
}
#region Domain-specific
/// <summary>
/// Gets the log.
/// </summary>
public TraceSource Log { get; private set; }
#endregion
private static TraceEventType ToTraceEventType(ServiceLog.LogLevel level)
{
switch (level)
{
case ServiceLog.LogLevel.Fatal:
return TraceEventType.Critical;
case ServiceLog.LogLevel.Error:
return TraceEventType.Error;
case ServiceLog.LogLevel.Warning:
return TraceEventType.Warning;
case ServiceLog.LogLevel.Information:
return TraceEventType.Information;
case ServiceLog.LogLevel.Debug:
return TraceEventType.Verbose;
default:
return TraceEventType.Verbose;
}
}
private static TraceSource GetAndCache(string name, SourceLevels defaultLevel)
{
TraceSource log;
if (_logs.TryGetValue(name, out log))
return log;
lock (_logs)
{
if (_logs.TryGetValue(name, out log))
return log;
log = new TraceSource(name);
if (!HasDefaultSource(log))
{
var source = new TraceSource("Default", defaultLevel);
for (var shortName = ShortenName(name); !string.IsNullOrEmpty(shortName); shortName = ShortenName(shortName))
{
var source2 = new TraceSource(shortName, defaultLevel);
if (!HasDefaultSource(source2))
{
source = source2;
break;
}
}
log.Switch = source.Switch;
var listeners = log.Listeners;
listeners.Clear();
foreach (TraceListener listener in source.Listeners)
listeners.Add(listener);
}
_logs.Add(name, log);
}
return log;
}
private static string ShortenName(string name)
{
int length = name.LastIndexOf('.');
return (length != -1 ? name.Substring(0, length) : null);
}
private static bool HasDefaultSource(TraceSource source)
{
return (source.Listeners.Count == 1 && source.Listeners[0] is DefaultTraceListener && source.Listeners[0].Name == "Default");
}
}
}
| |
// The MotionDriver is an advanced motion control system making it much easier to make accurately
// controlled drones. Motion drivers work both in space and in natural gravity (in the latter case,
// gravity is automatically taken into account).
//
// To use the MotionDriver, you make an instance for your script (and provide it with the ship controller
// it should be using - it doesn't even have to be a remote control block).
//
// The MotionDriver will also need a MotionController to control its behaviour. You can change the controller
// at any moment, or set it to null to disable the MotionDriver.
// Interface for motion controllers. Motion controllers define where, how fast and in which orientation the
// MotionDriver should set the given ship. (in fact, it determines the position it should be after delta seconds).
//
// Implementation highly depends on the purpose. Sample implementations are provided in the motioncontroller directory.
public interface MotionController
{
MotionDriver.MotionTarget Tick(MotionDriver.MotionState state, double delta);
void OnArrived(MotionDriver.MotionState state);
void OnArrivedPosition(MotionDriver.MotionState state);
void OnArrivedOrientation(MotionDriver.MotionState state);
string Serialize();
}
// Used to deserialize motioncontrollers
public delegate MotionController MotionControllerDeserializer(string serialized);
public class MotionDriver
{
// Defines the current state of the controlled ship. It is passed to the motion controller to help it
// calculate the target position, velocity and orientation.
public class MotionState
{
public readonly double Time;
public readonly Vector3D Position;
public readonly Quaternion Orientation;
public readonly double BaseMass;
public readonly double TotalMass;
public readonly Matrix WorldMatrix;
public readonly Matrix WorldMatrixInverse;
public readonly Vector3D VelocityLocal;
public readonly Vector3D VelocityWorld;
public readonly Vector3D AngularVelocityWorldYPR;
public readonly Quaternion AngularVelocityWorld;
public readonly Vector3D AngularVelocityLocalYPR;
public readonly Quaternion AngularVelocityLocal;
public readonly Vector3D GravityWorld;
public readonly Vector3D GravityLocal;
public readonly double PowerPosX; // right
public readonly double PowerNegX; // left
public readonly double PowerPosY; // up
public readonly double PowerNegY; // down
public readonly double PowerPosZ; // backward
public readonly double PowerNegZ; // forward
public MotionState(MotionDriver driver)
{
Time = driver.time;
Position = driver.shipController.GetPosition();
Orientation = Quaternion.CreateFromRotationMatrix(driver.shipController.CubeGrid.WorldMatrix.GetOrientation());
BaseMass = driver.baseMass;
TotalMass = driver.totalMass;
WorldMatrix = driver.shipController.CubeGrid.WorldMatrix;
WorldMatrixInverse = MatrixD.Invert(WorldMatrix);
PowerPosX = driver.powerPosX;
PowerPosY = driver.powerPosY;
PowerPosZ = driver.powerPosZ;
PowerNegX = driver.powerNegX;
PowerNegY = driver.powerNegY;
PowerNegZ = driver.powerNegZ;
var velocities = driver.shipController.GetShipVelocities();
VelocityWorld = velocities.LinearVelocity;
VelocityLocal = Vector3D.TransformNormal(VelocityWorld, WorldMatrixInverse);
AngularVelocityWorldYPR = velocities.AngularVelocity;
Quaternion.CreateFromYawPitchRoll((float)-AngularVelocityWorldYPR.Y, (float)AngularVelocityWorldYPR.X, (float)-AngularVelocityWorldYPR.Z, out AngularVelocityWorld);
AngularVelocityLocalYPR = Vector3D.TransformNormal(AngularVelocityLocalYPR, WorldMatrixInverse);
Quaternion.CreateFromYawPitchRoll((float)-AngularVelocityLocalYPR.Y, (float)AngularVelocityLocalYPR.X, (float)-AngularVelocityLocalYPR.Z, out AngularVelocityLocal);
// TODO: double-check gravity compensation
GravityWorld = driver.shipController.GetNaturalGravity();
GravityLocal = Vector3D.TransformNormal(GravityWorld, WorldMatrixInverse);
}
}
// Motion targets define where the ship should go. They are constructed by the motion controller tick function.
public struct MotionTarget
{
public static MotionTarget ToPosition(Vector3D position)
{
return new MotionTarget(position, null, null);
}
public static MotionTarget LinearLocal(IMyTerminalBlock relativeTo, Vector3D position, Vector3D velocity)
{
return new MotionTarget(position, Vector3D.TransformNormal(velocity, relativeTo.WorldMatrix), null);
}
public static MotionTarget LinearWorld(Vector3D position, Vector3D velocity)
{
return new MotionTarget(position, velocity, null);
}
public static MotionTarget Orientation(IMyTerminalBlock relativeTo, Quaternion orientation)
{
Quaternion blockOrientation;
relativeTo.Orientation.GetQuaternion(out blockOrientation);
return new MotionTarget(null, null, Quaternion.Inverse(blockOrientation) * orientation);
}
public Vector3D? Position;
public Vector3D Speed;
public Quaternion? Rotation;
public MotionTarget(string serialized)
{
string[] items = serialized.Split(':');
Position = items[0].Length == 0 ? null : (Vector3D?)Serializer.ParseVector(items[0]);
Speed = items[1].Length == 0 ? Vector3D.Zero : Serializer.ParseVector(items[1]);
Rotation = items[2].Length == 0 ? null : (Quaternion?)Serializer.ParseQuaternion(items[2]);
}
public MotionTarget(Vector3D? position, Vector3D? speed, Quaternion? rotation)
{
Position = position;
Speed = speed ?? Vector3D.Zero;
Rotation = rotation;
}
public void SetOrientation(IMyTerminalBlock relativeTo, Quaternion orientation)
{
Quaternion blockOrientation;
relativeTo.Orientation.GetQuaternion(out blockOrientation);
Rotation = Quaternion.Inverse(blockOrientation) * orientation;
}
public string Serialize()
{
StringBuilder result = new StringBuilder();
if (Position.HasValue)
result.Append(Serializer.SerializeVector(Position.Value));
result.Append(":");
if (Speed != Vector3D.Zero)
result.Append(Serializer.SerializeVector(Speed));
result.Append(":");
if (Rotation.HasValue)
result.Append(Serializer.SerializeQuaternion(Rotation.Value));
return result.ToString();
}
}
// tweakable variables
public double positionPrecision = 0.04; // square of tolerated position difference
public double velocityPrecision = 0.1; // square of tolerated velocity difference
public double angularPrecision = 0.001;
// !! tweak this according to your ship properties
// - without proper tweaking your ship will rotate either slowly or overshoot its target rotation
public Vector3D rotationDampening = new Vector3D(0.5, 0.5, 0.5);
// you could tweak this too, determines how fast it should rotate
// low values will decrease rotation speed, but too high values will destabilize the rotation
public Vector3D angularCorrectionFactor = new Vector3D(10, 10, 10);
private void InitThrusterPowers()
{
// If modded thrusters are used, add their subblock IDs here
register("SmallBlockSmallThrust", 12000, 0, 1, 1.0, 0.3);
register("SmallBlockLargeThrust", 144000, 0, 1, 1.0, 0.3);
register("LargeBlockSmallThrust", 288000, 0, 1, 1.0, 0.3);
register("LargeBlockLargeThrust", 3600000, 0, 1, 1.0, 0.3);
register("SmallBlockLargeHydrogenThrust", 400000, 0, 1, 1, 1);
register("SmallBlockSmallHydrogenThrust", 82000, 0, 1, 1, 1);
register("LargeBlockLargeHydrogenThrust", 6000000, 0, 1, 1, 1);
register("LargeBlockSmallHydrogenThrust", 900000, 0, 1, 1, 1);
register("SmallBlockLargeAtmosphericThrust", 408000, 0.3, 1.0, 0, 1, true);
register("SmallBlockSmallAtmosphericThrust", 80000, 0.3, 1.0, 0, 1, true);
register("LargeBlockLargeAtmosphericThrust", 5400000, 0.3, 1.0, 0, 1, true);
register("LargeBlockSmallAtmosphericThrust", 420000, 0.3, 1.0, 0, 1, true);
// Armored thrusters
register("SmallBlockArmorThrust", 12000, 0, 1, 1, .3);
register("SmallBlockArmorSlopedThrust", 12000, 0, 1, 1, .3);
register("SBLArmorThrust", 144000, 0, 1, 1, .3);
register("SBLArmorThrustSloped", 144000, 0, 1, 1, .3);
register("LargeBlockArmorThrust", 288000, 0, 1, 1, .3);
register("LargeBlockArmorSlopedThrust", 288000, 0, 1, 1, .3);
register("LBLArmorThrust", 3600000, 0, 1, 1, .3);
register("LBLArmorThrustSloped", 3600000, 0, 1, 1, .3);
}
private const double TICK_TIME = 1.0 / 60.0;
private const int TICKS_PER_RUN = 6;
private const double DELTA = TICK_TIME * TICKS_PER_RUN;
private const double DELTA_SQ_2 = DELTA * DELTA / 2;
private readonly Dictionary<String, ThrusterInfo> thrusterTypes = new Dictionary<String, ThrusterInfo>();
private readonly IMyShipController shipController;
private readonly Program program;
private readonly double maxSpeed;
public readonly List<IMyGyro> gyros = new List<IMyGyro>();
public readonly List<IMyThrust> thrusters = new List<IMyThrust>();
private double baseMass;
private double totalMass;
private int ticks = 0;
private double time = 0;
private MotionController controller;
private double atmosphereDensity = 1.0;
private double atmosphereAltitude = 8000;
private bool gyroOverride = false;
private bool gyroHold = false;
private bool thrustersStopped = false;
private bool enableDampeners = false;
private double powerPosX = 0; // right
private double powerNegX = 0; // left
private double powerPosY = 0; // up
private double powerNegY = 0; // down
private double powerPosZ = 0; // backward
private double powerNegZ = 0; // forward
public string MotionDebug = "";
public MotionState LastState = null;
public string MotionStateDebug = "";
/// <summary>
/// Initializes a motion controller. Only blocks on the grid of the given ship controller will be taken into account.
/// </summary>
/// <param name="shipController">Ship controller to be used to determine ship.</param>
/// <param name="terminalSystem">Terminal system of this ship</param>
/// <param name="dampening">Rotation dampening factor. Increase this value if the ship overshoots its target orientation when rotating (and wiggles before stabilizing). Decrease it when the ship rotates slowly.</param>
public MotionDriver(IMyShipController shipController, Program program, double maxSpeed)
{
this.shipController = shipController;
this.program = program;
this.maxSpeed = maxSpeed;
InitThrusterPowers();
}
// Used to construct a motion driver from a saved state
public MotionDriver(IMyShipController shipController, Program program, double maxSpeed, string serialized, MotionControllerDeserializer deserializer)
:this(shipController, program, maxSpeed)
{
if (serialized == null || serialized.Length == 0)
return;
string[] elements = serialized.Split(":".ToCharArray(), 2);
SetController(deserializer(elements[1]), double.Parse(elements[0]));
}
private void register(
string subId,
double force,
double minPlanetaryInfluence,
double maxPlanetaryInfluence,
double effectivenessAtMinInfluence,
double effectivenessAtMaxInfluence,
bool needsAtmosphereForInfluence = false)
{
thrusterTypes[subId] = new ThrusterInfo(
force,
minPlanetaryInfluence,
maxPlanetaryInfluence,
effectivenessAtMinInfluence,
effectivenessAtMaxInfluence,
needsAtmosphereForInfluence);
}
public MotionState GetState()
{
return new MotionState(this);
}
// Probably 1.0 & 8000 for earth
public void SetPlanetAtmosphere(double density, double altitude)
{
this.atmosphereDensity = density;
this.atmosphereAltitude = altitude;
}
public void SetController(MotionController controller, double time = 0)
{
this.time = time;
this.controller = controller;
}
public string Serialize()
{
return String.Format("{0:0.00}:{1}", time, controller.Serialize());
}
public void Tick()
{
ticks++;
if ((ticks % 60) == 1)
UpdateThrusters();
if ((ticks % 60) == 2)
UpdateMass();
if ((ticks % 60) == 3)
UpdateThrusterPower();
if ((ticks % 60) == 4)
UpdateGyros();
if ((ticks % 6) != 0)
return;
if (controller == null)
{
ClearThrustersOverride();
return;
}
var state = GetState();
var target = controller.Tick(state, DELTA);
LastState = state;
var arrivedPosition = false;
var arrived = true;
if (target.Position.HasValue || target.Speed.LengthSquared() > 0)
{
arrivedPosition = TickThrusters(state, target);
arrived &= arrivedPosition;
}
else
{
ClearThrustersOverride();
}
var arrivedOrientation = false;
if (target.Rotation.HasValue)
{
arrivedOrientation = TickGyros(state, target);
arrived &= arrivedOrientation;
}
else
{
SetGyrosOverride(false);
}
if (arrived)
controller.OnArrived(state);
if (arrivedPosition)
controller.OnArrivedPosition(state);
if (arrivedOrientation)
controller.OnArrivedOrientation(state);
time += DELTA;
}
private bool TickThrusters(MotionState state, MotionTarget target)
{
Vector3D currentVelocity = state.VelocityLocal;
Vector3D currentPosition = Vector3D.Transform(state.Position, state.WorldMatrixInverse);
Vector3D currentGravity = state.GravityLocal;
Vector3D targetSpeed = target.Speed;
Vector3D targetPosition = Vector3D.Transform(target.Position ?? (state.Position + (targetSpeed + currentVelocity) * DELTA * .66), state.WorldMatrixInverse);
Vector3D speedDifference = targetSpeed - currentVelocity;
Vector3D positionDifference = targetPosition - currentPosition;
if (speedDifference.LengthSquared() < velocityPrecision && positionDifference.LengthSquared() < positionPrecision)
{
ClearThrustersOverride();
SetDampeners(true);
return true;
}
Vector3D deceleration = GetAccelerations(speedDifference) + currentGravity;
Vector3D decelerationTimes = speedDifference / deceleration;
Vector3D positionAtFullStop = currentPosition + currentVelocity * decelerationTimes + deceleration * decelerationTimes * decelerationTimes / 2;
Vector3D maxAccelerationDelta = targetPosition - positionAtFullStop;
Vector3D shipAcceleration = GetAccelerations(maxAccelerationDelta);
Vector3D acceleration = shipAcceleration + currentGravity;
Vector3D accelerationForTick = (maxAccelerationDelta - currentVelocity * DELTA) / DELTA_SQ_2 - currentGravity;
Vector3D overrides = Vector3D.Max(-Vector3D.One, Vector3D.Min(Vector3D.One, 0.5 * accelerationForTick / shipAcceleration)) * 100;
if (maxAccelerationDelta.X < 0)
overrides.X = -overrides.X;
if (maxAccelerationDelta.Y < 0)
overrides.Y = -overrides.Y;
if (maxAccelerationDelta.Z < 0)
overrides.Z = -overrides.Z;
if (currentVelocity.LengthSquared() >= maxSpeed * maxSpeed && (overrides * currentVelocity).Min() >= -0.01)
{
ClearThrustersOverride();
return false;
}
SetDampeners(decelerationTimes.Max() < DELTA);
SetThrustersOverride(overrides);
return false;
}
private Vector3D GetAccelerations(Vector3D directions)
{
return new Vector3D(
(directions.X > 0 ? powerPosX : -powerNegX) / totalMass,
(directions.Y > 0 ? powerPosY : -powerNegY) / totalMass,
(directions.Z > 0 ? powerPosZ : -powerNegZ) / totalMass);
}
private Vector3D GetMaxAcceleration(Vector3D deltaV)
{
double powerX = deltaV.X < 0 ? powerNegX : powerPosX;
double powerY = deltaV.Y < 0 ? powerNegY : powerPosY;
double powerZ = deltaV.Z < 0 ? powerNegZ : powerPosZ;
return new Vector3D(powerX / totalMass, powerY / totalMass, powerZ / totalMass);
}
private bool TickGyros(MotionState state, MotionTarget target)
{
Quaternion targetOrientation = Quaternion.Inverse(target.Rotation.Value);
Quaternion orientation = state.Orientation;
double delta = Math.Abs(orientation.X - targetOrientation.X)
+ Math.Abs(orientation.Y - targetOrientation.Y)
+ Math.Abs(orientation.Z - targetOrientation.Z)
+ Math.Abs(orientation.W - targetOrientation.W);
SetGyrosOverride(true);
bool hold = delta < angularPrecision && state.AngularVelocityLocalYPR.LengthSquared() < angularPrecision;
SetHoldGyros(hold);
if (hold)
return true;
foreach (IMyGyro gyro in gyros)
{
Vector3D rotationAngles = calculateGyroRotation(gyro, targetOrientation);
Vector3D rotationSpeedRad = rotationAngles * angularCorrectionFactor;
Matrix gyroOrientation;
gyro.Orientation.GetMatrix(out gyroOrientation);
Vector3D relativeAngularVelocity = Vector3D.TransformNormal(state.AngularVelocityLocalYPR, gyroOrientation);
Vector3D rotationSpeedDampened = rotationSpeedRad - relativeAngularVelocity * rotationDampening;
gyro.SetValueFloat("Yaw", (float)rotationSpeedDampened.Y);
gyro.SetValueFloat("Pitch", -(float)rotationSpeedDampened.X);
gyro.SetValueFloat("Roll", (float)rotationSpeedDampened.Z);
}
return false;
}
private void UpdateThrusters()
{
thrusters.Clear();
program.GridTerminalSystem.GetBlocksOfType<IMyThrust>(thrusters, thruster => thruster.IsWorking && thruster.CubeGrid == shipController.CubeGrid);
}
private void UpdateGyros()
{
gyros.Clear();
program.GridTerminalSystem.GetBlocksOfType<IMyGyro>(gyros, gyro => gyro.IsWorking && gyro.CubeGrid == shipController.CubeGrid);
}
private void SetGyrosOverride(bool gyroOverride)
{
if (gyroOverride == this.gyroOverride)
return;
this.gyroOverride = gyroOverride;
foreach (IMyGyro gyro in gyros)
gyro.SetValueBool("Override", gyroOverride);
}
private void SetHoldGyros(bool hold)
{
if (hold == this.gyroHold)
return;
this.gyroHold = hold;
foreach (IMyGyro gyro in gyros)
{
gyro.SetValueFloat("Yaw", 0);
gyro.SetValueFloat("Pitch", 0);
gyro.SetValueFloat("Roll", 0);
}
}
private void ClearThrustersOverride()
{
if (thrustersStopped)
return;
thrustersStopped = true;
foreach (IMyThrust thruster in thrusters)
thruster.SetValueFloat("Override", 0);
}
private void SetThrustersOverride(Vector3D overrides)
{
thrustersStopped = false;
MyBlockOrientation orientation = shipController.Orientation;
foreach (IMyThrust thruster in thrusters)
{
Base6Directions.Direction direction = Base6Directions.GetFlippedDirection(thruster.Orientation.Forward);
switch (direction)
{
case Base6Directions.Direction.Right:
thruster.SetValueFloat("Override", Math.Max(0, (float)overrides.X));
break;
case Base6Directions.Direction.Left:
thruster.SetValueFloat("Override", Math.Max(0, (float)-overrides.X));
break;
case Base6Directions.Direction.Up:
thruster.SetValueFloat("Override", Math.Max(0, (float)overrides.Y));
break;
case Base6Directions.Direction.Down:
thruster.SetValueFloat("Override", Math.Max(0, (float)-overrides.Y));
break;
case Base6Directions.Direction.Backward:
thruster.SetValueFloat("Override", Math.Max(0, (float)overrides.Z));
break;
case Base6Directions.Direction.Forward:
thruster.SetValueFloat("Override", Math.Max(0, (float)-overrides.Z));
break;
}
}
}
private void UpdateThrusterPower()
{
MotionDebug = "";
powerPosX = 0;
powerNegX = 0;
powerPosY = 0;
powerNegY = 0;
powerPosZ = 0;
powerNegZ = 0;
bool inAtmosphere = false;
double airDensity = 0;
double altitude;
if (shipController.TryGetPlanetElevation(MyPlanetElevation.Sealevel, out altitude))
{
inAtmosphere = altitude < atmosphereAltitude;
if (inAtmosphere)
airDensity = getAirDensityAtPlanet(altitude);
}
foreach (IMyThrust thruster in thrusters)
{
Base6Directions.Direction direction = Base6Directions.GetFlippedDirection(thruster.Orientation.Forward);
ThrusterInfo info = thrusterTypes.GetValueOrDefault(thruster.BlockDefinition.SubtypeId);
if (info == null)
{
program.Echo("Unknown thruster type: " + thruster.BlockDefinition.SubtypeId);
continue;
}
double power = info.GetPower(inAtmosphere, airDensity);
switch (direction)
{
case Base6Directions.Direction.Right:
powerPosX += power;
break;
case Base6Directions.Direction.Left:
powerNegX += power;
break;
case Base6Directions.Direction.Up:
powerPosY += power;
break;
case Base6Directions.Direction.Down:
powerNegY += power;
break;
case Base6Directions.Direction.Backward:
powerPosZ += power;
break;
case Base6Directions.Direction.Forward:
powerNegZ += power;
break;
}
}
}
private void UpdateMass()
{
var mass = shipController.CalculateShipMass();
baseMass = mass.BaseMass;
totalMass = mass.TotalMass;
}
private Vector3D calculateGyroRotation(IMyGyro gyro, Quaternion desiredOrientation)
{
Quaternion gyroOrientation;
gyro.Orientation.GetQuaternion(out gyroOrientation);
Quaternion relativeOrientation = Quaternion.Inverse(Quaternion.CreateFromRotationMatrix(gyro.WorldMatrix)) * Quaternion.Inverse(gyroOrientation) * desiredOrientation;
return quaternionToYPR(relativeOrientation);
}
public Vector3D quaternionToYPR(Quaternion rotation)
{
MatrixD transform = MatrixD.CreateFromQuaternion(rotation);
Vector3D result = new Vector3D();
MatrixD.GetEulerAnglesXYZ(ref transform, out result);
return result;
}
private double ClampRotation(double rotation)
{
if (rotation > Math.PI)
return rotation - 2 * Math.PI;
if (rotation < -Math.PI)
return rotation + 2 * Math.PI;
return rotation;
}
private void SetDampeners(bool enable)
{
if (enable == enableDampeners)
return;
enableDampeners = enable;
shipController.SetValueBool("DampenersOverride", enable);
}
private double getAirDensityAtPlanet(double altitude)
{
double relativeAltitude = MathHelper.Clamp(1.0 - altitude / atmosphereAltitude, 0.0, 1.0);
return relativeAltitude * atmosphereDensity;
}
}
public class ThrusterInfo
{
public readonly double Force;
public readonly double MinPlanetaryInfluence;
public readonly double MaxPlanetaryInfluence;
public readonly double EffectivenessAtMinInfluence;
public readonly double EffectivenessAtMaxInfluence;
public readonly bool NeedsAtmosphereForInfluence;
public ThrusterInfo(
double force,
double minPlanetoryInfluence,
double maxPlanetaryInfluence,
double effectivenessAtMinInfluence,
double effectivenessAtMaxInfluence,
bool needsAtmosphere)
{
Force = force;
MinPlanetaryInfluence = minPlanetoryInfluence;
MaxPlanetaryInfluence = maxPlanetaryInfluence;
EffectivenessAtMinInfluence = effectivenessAtMinInfluence;
EffectivenessAtMaxInfluence = effectivenessAtMaxInfluence;
NeedsAtmosphereForInfluence = needsAtmosphere;
}
public double GetPower(bool inAtmosphere, double airDensity)
{
if (!inAtmosphere)
return NeedsAtmosphereForInfluence ? 0 : Force * EffectivenessAtMinInfluence;
if (EffectivenessAtMinInfluence == EffectivenessAtMaxInfluence)
return Force * EffectivenessAtMaxInfluence;
double influence = MathHelper.Clamp((airDensity - MinPlanetaryInfluence) / (MaxPlanetaryInfluence - MinPlanetaryInfluence), 0f, 1f);
return Force * MathHelper.Lerp(EffectivenessAtMinInfluence, EffectivenessAtMaxInfluence, influence);
}
}
public static class Serializer
{
public static string SerializeVector(Vector3D vector)
{
return String.Format("{0:0.000} {1:0.000} {2:0.000}", vector.X, vector.Y, vector.Z);
}
public static string SerializeQuaternion(Quaternion quaternion)
{
return String.Format("{0:0.000} {1:0.000} {2:0.000} {3:0.000}", quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
}
public static string SerializeMatrix(MatrixD matrix)
{
return String.Format(
"{0:0.000} {1:0.000} {2:0.000} {3:0.000} "
+ "{4:0.000} {5:0.000} {6:0.000} {7:0.000} "
+ "{8:0.000} {9:0.000} {10:0.000} {11:0.000} "
+ "{12:0.000} {13:0.000} {14:0.000} {15:0.000}",
matrix.M11, matrix.M12, matrix.M13, matrix.M14,
matrix.M21, matrix.M22, matrix.M23, matrix.M24,
matrix.M31, matrix.M32, matrix.M33, matrix.M34,
matrix.M41, matrix.M42, matrix.M43, matrix.M44);
}
public static string SerializeDetectedEntity(MyDetectedEntityInfo entity)
{
Vector3D boundingBoxMin = entity.BoundingBox.Min;
Vector3D boundingBoxMax = entity.BoundingBox.Max;
return String.Format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}:{8}:{9}",
SerializeVector(entity.BoundingBox.Min),
SerializeVector(entity.BoundingBox.Max),
entity.EntityId,
entity.HitPosition.HasValue ? SerializeVector(entity.HitPosition.Value) : "",
entity.Name.Replace(':', ' '),
SerializeMatrix(entity.Orientation),
(int) entity.Relationship,
entity.TimeStamp,
(int) entity.Type,
SerializeVector(entity.Velocity));
}
public static Vector3D ParseVector(string serialized)
{
string[] components = serialized.Split(' ');
return new Vector3D(double.Parse(components[0]), double.Parse(components[1]), double.Parse(components[2]));
}
public static Quaternion ParseQuaternion(string serialized)
{
string[] components = serialized.Split(' ');
return new Quaternion(float.Parse(components[0]), float.Parse(components[1]), float.Parse(components[2]), float.Parse(components[3]));
}
public static MatrixD ParseMatrix(string serialized)
{
string[] components = serialized.Split(' ');
return new MatrixD(
double.Parse(components[0]), double.Parse(components[1]), double.Parse(components[2]), double.Parse(components[3]),
double.Parse(components[4]), double.Parse(components[5]), double.Parse(components[6]), double.Parse(components[7]),
double.Parse(components[8]), double.Parse(components[9]), double.Parse(components[10]), double.Parse(components[11]),
double.Parse(components[12]), double.Parse(components[13]), double.Parse(components[14]), double.Parse(components[15]));
}
public static MyDetectedEntityInfo ParseDetectedEntity(string serialized)
{
string[] parts = serialized.Split(':');
Vector3D boundingBoxMin = ParseVector(parts[0]);
Vector3D boundingBoxMax = ParseVector(parts[1]);
long entityId = long.Parse(parts[2]);
Vector3D? hitPosition = parts[3].Length == 0 ? (Vector3D?)null : ParseVector(parts[3]);
string name = parts[4];
MatrixD orientation = ParseMatrix(parts[5]);
MyRelationsBetweenPlayerAndBlock relationship = (MyRelationsBetweenPlayerAndBlock) int.Parse(parts[6]);
long timestamp = long.Parse(parts[7]);
MyDetectedEntityType type = (MyDetectedEntityType) int.Parse(parts[8]);
Vector3D velocity = ParseVector(parts[9]);
return new MyDetectedEntityInfo(entityId, name, type, hitPosition, orientation, velocity, relationship, new BoundingBoxD(boundingBoxMin, boundingBoxMax), timestamp);
}
public static string StripPrefix(string value, string prefix)
{
if (!value.StartsWith(prefix))
throw new InvalidOperationException("Value doesn't start with the given prefix");
return value.Substring(prefix.Length);
}
}
| |
#region License
/*
* Logger.cs
*
* The MIT License
*
* Copyright (c) 2013-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Diagnostics;
using System.IO;
namespace WebSocketSharp
{
/// <summary>
/// Provides a set of methods and properties for logging.
/// </summary>
/// <remarks>
/// <para>
/// If you output a log with lower than the <see cref="Logger.Level"/>,
/// it cannot be outputted.
/// </para>
/// <para>
/// The default output action writes a log to the standard output stream and
/// the <see cref="Logger.File"/> if it has a valid path.
/// </para>
/// <para>
/// If you would like to use the custom output action, you should set the
/// <see cref="Logger.Output"/> to any <c>Action<LogData, string></c> delegate.
/// </para>
/// </remarks>
public class Logger
{
#region Private Fields
private volatile string _file;
private volatile LogLevel _level;
private Action<LogData, string> _output;
private object _sync;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class.
/// </summary>
/// <remarks>
/// This constructor initializes the current logging level with <see cref="LogLevel.Error"/>.
/// </remarks>
public Logger ()
: this (LogLevel.Error, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class with the specified
/// logging <paramref name="level"/>.
/// </summary>
/// <param name="level">
/// One of the <see cref="LogLevel"/> enum values.
/// </param>
public Logger (LogLevel level)
: this (level, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class with the specified
/// logging <paramref name="level"/>, path to the log <paramref name="file"/>, and
/// <paramref name="output"/> action.
/// </summary>
/// <param name="level">
/// One of the <see cref="LogLevel"/> enum values.
/// </param>
/// <param name="file">
/// A <see cref="string"/> that represents the path to the log file.
/// </param>
/// <param name="output">
/// An <c>Action<LogData, string></c> delegate that references the method(s)
/// used to output a log. A <see cref="string"/> parameter passed to this delegate
/// is <paramref name="file"/>.
/// </param>
public Logger (LogLevel level, string file, Action<LogData, string> output)
{
_level = level;
_file = file;
_output = output ?? defaultOutput;
_sync = new object ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the current path to the log file.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the current path to the log file if any.
/// </value>
public string File {
get {
return _file;
}
set {
lock (_sync) {
_file = value;
Warn (
String.Format ("The current path to the log file has been changed to {0}.", _file));
}
}
}
/// <summary>
/// Gets or sets the current logging level.
/// </summary>
/// <remarks>
/// A log with lower than the value of this property cannot be outputted.
/// </remarks>
/// <value>
/// One of the <see cref="LogLevel"/> enum values, indicates the current logging level.
/// </value>
public LogLevel Level {
get {
return _level;
}
set {
lock (_sync) {
_level = value;
Warn (String.Format ("The current logging level has been changed to {0}.", _level));
}
}
}
/// <summary>
/// Gets or sets the current output action used to output a log.
/// </summary>
/// <value>
/// <para>
/// An <c>Action<LogData, string></c> delegate that references the method(s) used to
/// output a log. A <see cref="string"/> parameter passed to this delegate is the value of
/// the <see cref="Logger.File"/>.
/// </para>
/// <para>
/// If the value to set is <see langword="null"/>, the current output action is changed to
/// the default output action.
/// </para>
/// </value>
public Action<LogData, string> Output {
get {
return _output;
}
set {
lock (_sync) {
_output = value ?? defaultOutput;
Warn ("The current output action has been changed.");
}
}
}
#endregion
#region Private Methods
private static void defaultOutput (LogData data, string path)
{
var log = data.ToString ();
Console.WriteLine (log);
if (path != null && path.Length > 0)
writeToFile (log, path);
}
private void output (string message, LogLevel level)
{
lock (_sync) {
if (_level > level)
return;
LogData data = null;
try {
data = new LogData (level, new StackFrame (2, true), message);
_output (data, _file);
}
catch (Exception ex) {
data = new LogData (LogLevel.Fatal, new StackFrame (0, true), ex.Message);
Console.WriteLine (data.ToString ());
}
}
}
private static void writeToFile (string value, string path)
{
using (var writer = new StreamWriter (path, true))
using (var syncWriter = TextWriter.Synchronized (writer))
syncWriter.WriteLine (value);
}
#endregion
#region Public Methods
/// <summary>
/// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Debug"/>.
/// </summary>
/// <remarks>
/// If the current logging level is higher than <see cref="LogLevel.Debug"/>,
/// this method doesn't output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the message to output as a log.
/// </param>
public void Debug (string message)
{
if (_level > LogLevel.Debug)
return;
output (message, LogLevel.Debug);
}
/// <summary>
/// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Error"/>.
/// </summary>
/// <remarks>
/// If the current logging level is higher than <see cref="LogLevel.Error"/>,
/// this method doesn't output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the message to output as a log.
/// </param>
public void Error (string message)
{
if (_level > LogLevel.Error)
return;
output (message, LogLevel.Error);
}
/// <summary>
/// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Fatal"/>.
/// </summary>
/// <param name="message">
/// A <see cref="string"/> that represents the message to output as a log.
/// </param>
public void Fatal (string message)
{
output (message, LogLevel.Fatal);
}
/// <summary>
/// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Info"/>.
/// </summary>
/// <remarks>
/// If the current logging level is higher than <see cref="LogLevel.Info"/>,
/// this method doesn't output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the message to output as a log.
/// </param>
public void Info (string message)
{
if (_level > LogLevel.Info)
return;
output (message, LogLevel.Info);
}
/// <summary>
/// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Trace"/>.
/// </summary>
/// <remarks>
/// If the current logging level is higher than <see cref="LogLevel.Trace"/>,
/// this method doesn't output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the message to output as a log.
/// </param>
public void Trace (string message)
{
if (_level > LogLevel.Trace)
return;
output (message, LogLevel.Trace);
}
/// <summary>
/// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Warn"/>.
/// </summary>
/// <remarks>
/// If the current logging level is higher than <see cref="LogLevel.Warn"/>,
/// this method doesn't output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the message to output as a log.
/// </param>
public void Warn (string message)
{
if (_level > LogLevel.Warn)
return;
output (message, LogLevel.Warn);
}
#endregion
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="SearchFolderParameters.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the SearchFolderParameters class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
/// <summary>
/// Represents the parameters associated with a search folder.
/// </summary>
public sealed class SearchFolderParameters : ComplexProperty
{
private SearchFolderTraversal traversal;
private FolderIdCollection rootFolderIds = new FolderIdCollection();
private SearchFilter searchFilter;
/// <summary>
/// Initializes a new instance of the <see cref="SearchFolderParameters"/> class.
/// </summary>
internal SearchFolderParameters()
: base()
{
this.rootFolderIds.OnChange += this.PropertyChanged;
}
/// <summary>
/// Property changed.
/// </summary>
/// <param name="complexProperty">The complex property.</param>
private void PropertyChanged(ComplexProperty complexProperty)
{
this.Changed();
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.BaseFolderIds:
this.RootFolderIds.InternalClear();
this.RootFolderIds.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.Restriction:
reader.Read();
this.searchFilter = SearchFilter.LoadFromXml(reader);
return true;
default:
return false;
}
}
/// <summary>
/// Reads the attributes from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal override void ReadAttributesFromXml(EwsServiceXmlReader reader)
{
this.Traversal = reader.ReadAttributeValue<SearchFolderTraversal>(XmlAttributeNames.Traversal);
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonProperty">The json property.</param>
/// <param name="service">The service.</param>
internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service)
{
foreach (string key in jsonProperty.Keys)
{
switch (key)
{
case XmlElementNames.BaseFolderIds:
this.RootFolderIds.InternalClear();
((IJsonCollectionDeserializer)this.RootFolderIds).CreateFromJsonCollection(jsonProperty.ReadAsArray(key), service);
break;
case XmlElementNames.Restriction:
JsonObject restriction = jsonProperty.ReadAsJsonObject(key);
this.searchFilter = SearchFilter.LoadSearchFilterFromJson(restriction.ReadAsJsonObject(XmlElementNames.Item), service);
break;
case XmlAttributeNames.Traversal:
this.Traversal = jsonProperty.ReadEnumValue<SearchFolderTraversal>(key);
break;
default:
break;
}
}
}
/// <summary>
/// Writes the attributes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
writer.WriteAttributeValue(XmlAttributeNames.Traversal, this.Traversal);
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
if (this.SearchFilter != null)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Restriction);
this.SearchFilter.WriteToXml(writer);
writer.WriteEndElement(); // Restriction
}
this.RootFolderIds.WriteToXml(writer, XmlElementNames.BaseFolderIds);
}
/// <summary>
/// Serializes the property to a Json value.
/// </summary>
/// <param name="service">The service.</param>
/// <returns>
/// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
/// </returns>
internal override object InternalToJson(ExchangeService service)
{
JsonObject jsonProperty = new JsonObject();
jsonProperty.Add(XmlAttributeNames.Traversal, this.Traversal);
jsonProperty.Add(XmlElementNames.BaseFolderIds, this.RootFolderIds.InternalToJson(service));
if (this.SearchFilter != null)
{
JsonObject restriction = new JsonObject();
restriction.Add(XmlElementNames.Item, this.SearchFilter.InternalToJson(service));
jsonProperty.Add(XmlElementNames.Restriction, restriction);
}
return jsonProperty;
}
/// <summary>
/// Validates this instance.
/// </summary>
internal void Validate()
{
// Search folder must have at least one root folder id.
if (this.RootFolderIds.Count == 0)
{
throw new ServiceValidationException(Strings.SearchParametersRootFolderIdsEmpty);
}
// Validate the search filter
if (this.SearchFilter != null)
{
this.SearchFilter.InternalValidate();
}
}
/// <summary>
/// Gets or sets the traversal mode for the search folder.
/// </summary>
public SearchFolderTraversal Traversal
{
get { return this.traversal; }
set { this.SetFieldValue<SearchFolderTraversal>(ref this.traversal, value); }
}
/// <summary>
/// Gets the list of root folders the search folder searches in.
/// </summary>
public FolderIdCollection RootFolderIds
{
get { return this.rootFolderIds; }
}
/// <summary>
/// Gets or sets the search filter associated with the search folder. Available search filter classes include
/// SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection.
/// </summary>
public SearchFilter SearchFilter
{
get
{
return this.searchFilter;
}
set
{
if (this.searchFilter != null)
{
this.searchFilter.OnChange -= this.PropertyChanged;
}
this.SetFieldValue<SearchFilter>(ref this.searchFilter, value);
if (this.searchFilter != null)
{
this.searchFilter.OnChange += this.PropertyChanged;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
using SteamTrade.TradeWebAPI;
namespace SteamTrade
{
public partial class Trade
{
#region Static Public data
public static Schema CurrentSchema = null;
#endregion
private const int WEB_REQUEST_MAX_RETRIES = 3;
private const int WEB_REQUEST_TIME_BETWEEN_RETRIES_MS = 600;
// list to store all trade events already processed
private readonly List<TradeEvent> eventList;
// current bot's sid
private readonly SteamID mySteamId;
private readonly Dictionary<int, TradeUserAssets> myOfferedItemsLocalCopy;
private readonly TradeSession session;
private readonly Task<Inventory> myInventoryTask;
private readonly Task<Inventory> otherInventoryTask;
private List<TradeUserAssets> myOfferedItems;
private List<TradeUserAssets> otherOfferedItems;
internal Trade(SteamID me, SteamID other, string sessionId, string token, Task<Inventory> myInventoryTask, Task<Inventory> otherInventoryTask)
{
TradeStarted = false;
OtherIsReady = false;
MeIsReady = false;
mySteamId = me;
OtherSID = other;
session = new TradeSession(sessionId, token, other);
this.eventList = new List<TradeEvent>();
myOfferedItemsLocalCopy = new Dictionary<int, TradeUserAssets>();
otherOfferedItems = new List<TradeUserAssets>();
myOfferedItems = new List<TradeUserAssets>();
this.otherInventoryTask = otherInventoryTask;
this.myInventoryTask = myInventoryTask;
}
#region Public Properties
/// <summary>Gets the other user's steam ID.</summary>
public SteamID OtherSID { get; private set; }
/// <summary>
/// Gets the bot's Steam ID.
/// </summary>
public SteamID MySteamId
{
get { return mySteamId; }
}
/// <summary>
/// Gets the inventory of the other user.
/// </summary>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets the private inventory of the other user.
/// </summary>
public ForeignInventory OtherPrivateInventory { get; private set; }
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the items the user has offered, by itemid.
/// </summary>
/// <value>
/// The other offered items.
/// </value>
public IEnumerable<TradeUserAssets> OtherOfferedItems
{
get { return otherOfferedItems; }
}
/// <summary>
/// Gets the items the bot has offered, by itemid.
/// </summary>
/// <value>
/// The bot offered items.
/// </value>
public IEnumerable<TradeUserAssets> MyOfferedItems
{
get { return myOfferedItems; }
}
/// <summary>
/// Gets a value indicating if the other user is ready to trade.
/// </summary>
public bool OtherIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if the bot is ready to trade.
/// </summary>
public bool MeIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if a trade has started.
/// </summary>
public bool TradeStarted { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner cancelled the trade.
/// </summary>
public bool OtherUserCancelled { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade completed normally. This
/// is independent of other flags.
/// </summary>
public bool HasTradeCompletedOk { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner accepted the trade.
/// </summary>
public bool OtherUserAccepted { get; private set; }
#endregion
#region Public Events
public delegate void CloseHandler();
public delegate void CompleteHandler();
public delegate void ErrorHandler(string error);
public delegate void TimeoutHandler();
public delegate void SuccessfulInit();
public delegate void UserAddItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem);
public delegate void UserRemoveItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem);
public delegate void MessageHandler(string msg);
public delegate void UserSetReadyStateHandler(bool ready);
public delegate void UserAcceptHandler();
/// <summary>
/// When the trade closes, this is called. It doesn't matter
/// whether or not it was a timeout or an error, this is called
/// to close the trade.
/// </summary>
public event CloseHandler OnClose;
/// <summary>
/// Called when the trade completes successfully.
/// </summary>
public event CompleteHandler OnSuccess;
/// <summary>
/// This is for handling errors that may occur, like inventories
/// not loading.
/// </summary>
public event ErrorHandler OnError;
/// <summary>
/// This occurs after Inventories have been loaded.
/// </summary>
public event SuccessfulInit OnAfterInit;
/// <summary>
/// This occurs when the other user adds an item to the trade.
/// </summary>
public event UserAddItemHandler OnUserAddItem;
/// <summary>
/// This occurs when the other user removes an item from the
/// trade.
/// </summary>
public event UserAddItemHandler OnUserRemoveItem;
/// <summary>
/// This occurs when the user sends a message to the bot over
/// trade.
/// </summary>
public event MessageHandler OnMessage;
/// <summary>
/// This occurs when the user sets their ready state to either
/// true or false.
/// </summary>
public event UserSetReadyStateHandler OnUserSetReady;
/// <summary>
/// This occurs when the user accepts the trade.
/// </summary>
public event UserAcceptHandler OnUserAccept;
#endregion
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
public bool CancelTrade()
{
return RetryWebRequest(session.CancelTradeWebCmd);
}
/// <summary>
/// Adds a specified TF2 item by its itemid.
/// If the item is not a TF2 item, use the AddItem(ulong itemid, int appid, long contextid) overload
/// </summary>
/// <returns><c>false</c> if the tf2 item was not found in the inventory.</returns>
public bool AddItem(ulong itemid)
{
if(MyInventory.GetItem(itemid) == null)
{
return false;
}
else
{
return AddItem(new TradeUserAssets(440, 2, itemid));
}
}
public bool AddItem(ulong itemid, int appid, long contextid)
{
return AddItem(new TradeUserAssets(appid, contextid, itemid));
}
public bool AddItem(TradeUserAssets item)
{
var slot = NextTradeSlot();
bool success = RetryWebRequest(() => session.AddItemWebCmd(item.assetid, slot, item.appid, item.contextid));
if(success)
myOfferedItemsLocalCopy[slot] = item;
return success;
}
/// <summary>
/// Adds a single item by its Defindex.
/// </summary>
/// <returns>
/// <c>true</c> if an item was found with the corresponding
/// defindex, <c>false</c> otherwise.
/// </returns>
public bool AddItemByDefindex(int defindex)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable)
{
return AddItem(item.Id);
}
}
return false;
}
/// <summary>
/// Adds an entire set of items by Defindex to each successive
/// slot in the trade.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param>
/// <returns>Number of items added.</returns>
public uint AddAllItemsByDefindex(int defindex, uint numToAdd = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
uint added = 0;
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable)
{
bool success = AddItem(item.Id);
if(success)
added++;
if(numToAdd > 0 && added >= numToAdd)
return added;
}
}
return added;
}
public bool RemoveItem(TradeUserAssets item)
{
return RemoveItem(item.assetid, item.appid, item.contextid);
}
/// <summary>
/// Removes an item by its itemid.
/// </summary>
/// <returns><c>false</c> the item was not found in the trade.</returns>
public bool RemoveItem(ulong itemid, int appid = 440, long contextid = 2)
{
int? slot = GetItemSlot(itemid);
if(!slot.HasValue)
return false;
bool success = RetryWebRequest(() => session.RemoveItemWebCmd(itemid, slot.Value, appid, contextid));
if(success)
myOfferedItemsLocalCopy.Remove(slot.Value);
return success;
}
/// <summary>
/// Removes an item with the given Defindex from the trade.
/// </summary>
/// <returns>
/// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise.
/// </returns>
public bool RemoveItemByDefindex(int defindex)
{
foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values)
{
Inventory.Item item = MyInventory.GetItem(asset.assetid);
if(item != null && item.Defindex == defindex)
{
return RemoveItem(item.Id);
}
}
return false;
}
/// <summary>
/// Removes an entire set of items by Defindex.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItemsByDefindex(int defindex, uint numToRemove = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
uint removed = 0;
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.Any(o => o.assetid == item.Id))
{
bool success = RemoveItem(item.Id);
if(success)
removed++;
if(numToRemove > 0 && removed >= numToRemove)
return removed;
}
}
return removed;
}
/// <summary>
/// Removes all offered items from the trade.
/// </summary>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItems()
{
uint numRemoved = 0;
foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values.ToList())
{
Inventory.Item item = MyInventory.GetItem(asset.assetid);
if(item != null)
{
bool wasRemoved = RemoveItem(item.Id);
if(wasRemoved)
numRemoved++;
}
}
return numRemoved;
}
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
public bool SendMessage(string msg)
{
return RetryWebRequest(() => session.SendMessageWebCmd(msg));
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
public bool SetReady(bool ready)
{
//If the bot calls SetReady(false) and the call fails, we still want meIsReady to be
//set to false. Otherwise, if the call to SetReady() was a result of a callback
//from Trade.Poll() inside of the OnTradeAccept() handler, the OnTradeAccept()
//handler might think the bot is ready, when really it's not!
if(!ready)
MeIsReady = false;
ValidateLocalTradeItems();
return RetryWebRequest(() => session.SetReadyWebCmd(ready));
}
/// <summary>
/// Accepts the trade from the user. Returns a deserialized
/// JSON object.
/// </summary>
public bool AcceptTrade()
{
ValidateLocalTradeItems();
return RetryWebRequest(session.AcceptTradeWebCmd);
}
/// <summary>
/// Calls the given function multiple times, until we get a non-null/non-false/non-zero result, or we've made at least
/// WEB_REQUEST_MAX_RETRIES attempts (with WEB_REQUEST_TIME_BETWEEN_RETRIES_MS between attempts)
/// </summary>
/// <returns>The result of the function if it succeeded, or default(T) (null/false/0) otherwise</returns>
private T RetryWebRequest<T>(Func<T> webEvent)
{
for(int i = 0; i < WEB_REQUEST_MAX_RETRIES; i++)
{
//Don't make any more requests if the trade has ended!
if(HasTradeCompletedOk || OtherUserCancelled)
return default(T);
try
{
T result = webEvent();
// if the web request returned some error.
if(!EqualityComparer<T>.Default.Equals(result, default(T)))
return result;
}
catch(Exception ex)
{
// TODO: log to SteamBot.Log but... see issue #394
// realistically we should not throw anymore
Console.WriteLine(ex);
}
if(i != WEB_REQUEST_MAX_RETRIES)
{
//This will cause the bot to stop responding while we wait between web requests. ...Is this really what we want?
Thread.Sleep(WEB_REQUEST_TIME_BETWEEN_RETRIES_MS);
}
}
return default(T);
}
/// <summary>
/// This updates the trade. This is called at an interval of a
/// default of 800ms, not including the execution time of the
/// method itself.
/// </summary>
/// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns>
public bool Poll()
{
bool otherDidSomething = false;
if(!TradeStarted)
{
TradeStarted = true;
// since there is no feedback to let us know that the trade
// is fully initialized we assume that it is when we start polling.
if(OnAfterInit != null)
OnAfterInit();
}
TradeStatus status = RetryWebRequest(session.GetStatus);
if(status == null)
return false;
switch(status.trade_status)
{
// Nothing happened. i.e. trade hasn't closed yet.
case 0:
break;
// Successful trade
case 1:
HasTradeCompletedOk = true;
return false;
// All other known values (3, 4) correspond to trades closing.
default:
FireOnErrorEvent("Trade was closed by other user. Trade status: " + status.trade_status);
OtherUserCancelled = true;
return false;
}
if (status.newversion)
{
HandleTradeVersionChange(status);
return true;
}
else if(status.version > session.Version)
{
// oh crap! we missed a version update abort so we don't get
// scammed. if we could get what steam thinks what's in the
// trade then this wouldn't be an issue. but we can only get
// that when we see newversion == true
throw new TradeException("The trade version does not match. Aborting.");
}
// Update Local Variables
if(status.them != null)
{
OtherIsReady = status.them.ready == 1;
MeIsReady = status.me.ready == 1;
OtherUserAccepted = status.them.confirmed == 1;
}
var events = status.GetAllEvents();
foreach(var tradeEvent in events)
{
if(eventList.Contains(tradeEvent))
continue;
//add event to processed list, as we are taking care of this event now
eventList.Add(tradeEvent);
bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString();
// dont process if this is something the bot did
if(isBot)
continue;
otherDidSomething = true;
switch((TradeEventType) tradeEvent.action)
{
case TradeEventType.ItemAdded:
//The ItemAdded and ItemRemoved events from Steam cannot be trusted. See https://github.com/Jessecar96/SteamBot/issues/602
//Instead, we now manually call FireOnUserAddItem/RemoveItem from HandleTradeVersionChange()
break;
case TradeEventType.ItemRemoved:
//Do nothing; see above comment
break;
case TradeEventType.UserSetReady:
OnUserSetReady(true);
break;
case TradeEventType.UserSetUnReady:
OnUserSetReady(false);
break;
case TradeEventType.UserAccept:
OnUserAccept();
break;
case TradeEventType.UserChat:
OnMessage(tradeEvent.text);
break;
default:
// Todo: add an OnWarning or similar event
FireOnErrorEvent("Unknown Event ID: " + tradeEvent.action);
break;
}
}
if(status.logpos != 0)
{
session.LogPos = status.logpos;
}
return otherDidSomething;
}
private void HandleTradeVersionChange(TradeStatus status)
{
//Figure out which items have been added/removed
IEnumerable<TradeUserAssets> otherOfferedItemsUpdated = status.them.GetAssets();
IEnumerable<TradeUserAssets> addedItems = otherOfferedItemsUpdated.Except(otherOfferedItems).ToList();
IEnumerable<TradeUserAssets> removedItems = otherOfferedItems.Except(otherOfferedItemsUpdated).ToList();
//Copy of the new items and update the version number
otherOfferedItems = status.them.GetAssets().ToList();
myOfferedItems = status.me.GetAssets().ToList();
session.Version = status.version;
//Fire the OnUserRemoveItem events
foreach (TradeUserAssets asset in removedItems)
{
FireOnUserRemoveItem(asset);
}
//Fire the OnUserAddItem events
foreach (TradeUserAssets asset in addedItems)
{
FireOnUserAddItem(asset);
}
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
private void FireOnUserAddItem(TradeUserAssets asset)
{
if(OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(asset.assetid);
if(item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if(schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, item);
}
else
{
item = new Inventory.Item
{
Id = asset.assetid,
AppId = asset.appid,
ContextId = asset.contextid
};
//Console.WriteLine("User added a non TF2 item to the trade.");
OnUserAddItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(asset);
if(schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, null);
// todo: figure out what to send in with Inventory item.....
}
}
private Schema.Item GetItemFromPrivateBp(TradeUserAssets asset)
{
if(OtherPrivateInventory == null)
{
// get the foreign inventory
var f = session.GetForiegnInventory(OtherSID, asset.contextid, asset.appid);
OtherPrivateInventory = new ForeignInventory(f);
}
ushort defindex = OtherPrivateInventory.GetDefIndex(asset.assetid);
Schema.Item schemaItem = CurrentSchema.GetItem(defindex);
return schemaItem;
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <returns></returns>
private void FireOnUserRemoveItem(TradeUserAssets asset)
{
if(OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(asset.assetid);
if(item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if(schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, item);
}
else
{
// TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema
item = new Inventory.Item
{
Id = asset.assetid,
AppId = asset.appid,
ContextId = asset.contextid
};
OnUserRemoveItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(asset);
if(schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, null);
}
}
internal void FireOnSuccessEvent()
{
var onSuccessEvent = OnSuccess;
if(onSuccessEvent != null)
onSuccessEvent();
}
internal void FireOnCloseEvent()
{
var onCloseEvent = OnClose;
if(onCloseEvent != null)
onCloseEvent();
}
internal void FireOnErrorEvent(string errorMessage)
{
var onErrorEvent = OnError;
if(onErrorEvent != null)
onErrorEvent(errorMessage);
}
private int NextTradeSlot()
{
int slot = 0;
while(myOfferedItemsLocalCopy.ContainsKey(slot))
{
slot++;
}
return slot;
}
private int? GetItemSlot(ulong itemid)
{
foreach(int slot in myOfferedItemsLocalCopy.Keys)
{
if(myOfferedItemsLocalCopy[slot].assetid == itemid)
{
return slot;
}
}
return null;
}
private void ValidateLocalTradeItems()
{
if (!myOfferedItemsLocalCopy.Values.OrderBy(o => o).SequenceEqual(MyOfferedItems.OrderBy(o => o)))
{
throw new TradeException("Error validating local copy of offered items in the trade");
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Diagnostics;
using System.Net;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security.Authentication.ExtendedProtection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.Threading;
using System.Xml;
using System.ServiceModel.Diagnostics.Application;
delegate void ServerSessionPreambleCallback(ServerSessionPreambleConnectionReader serverSessionPreambleReader);
delegate void ServerSessionPreambleDemuxCallback(ServerSessionPreambleConnectionReader serverSessionPreambleReader, ConnectionDemuxer connectionDemuxer);
interface ISessionPreambleHandler
{
void HandleServerSessionPreamble(ServerSessionPreambleConnectionReader serverSessionPreambleReader,
ConnectionDemuxer connectionDemuxer);
}
// reads everything we need in order to match a channel (i.e. up to the via)
class ServerSessionPreambleConnectionReader : InitialServerConnectionReader
{
ServerSessionDecoder decoder;
byte[] connectionBuffer;
int offset;
int size;
TransportSettingsCallback transportSettingsCallback;
ServerSessionPreambleCallback callback;
static WaitCallback readCallback;
IConnectionOrientedTransportFactorySettings settings;
Uri via;
Action<Uri> viaDelegate;
TimeoutHelper receiveTimeoutHelper;
IConnection rawConnection;
static AsyncCallback onValidate;
public ServerSessionPreambleConnectionReader(IConnection connection, Action connectionDequeuedCallback,
long streamPosition, int offset, int size, TransportSettingsCallback transportSettingsCallback,
ConnectionClosedCallback closedCallback, ServerSessionPreambleCallback callback)
: base(connection, closedCallback)
{
this.rawConnection = connection;
this.decoder = new ServerSessionDecoder(streamPosition, MaxViaSize, MaxContentTypeSize);
this.offset = offset;
this.size = size;
this.transportSettingsCallback = transportSettingsCallback;
this.callback = callback;
this.ConnectionDequeuedCallback = connectionDequeuedCallback;
}
public int BufferOffset
{
get { return offset; }
}
public int BufferSize
{
get { return size; }
}
public ServerSessionDecoder Decoder
{
get { return decoder; }
}
public IConnection RawConnection
{
get { return rawConnection; }
}
public Uri Via
{
get { return this.via; }
}
TimeSpan GetRemainingTimeout()
{
return this.receiveTimeoutHelper.RemainingTime();
}
static void ReadCallback(object state)
{
ServerSessionPreambleConnectionReader reader = (ServerSessionPreambleConnectionReader)state;
bool success = false;
try
{
reader.GetReadResult();
reader.ContinueReading();
success = true;
}
catch (CommunicationException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
catch (TimeoutException exception)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(exception.Message);
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!ExceptionHandler.HandleTransportExceptionHelper(e))
{
throw;
}
// containment -- all errors abort the reader, no additional containment action needed
}
finally
{
if (!success)
{
reader.Abort();
}
}
}
void GetReadResult()
{
offset = 0;
size = Connection.EndRead();
if (size == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
}
void ContinueReading()
{
bool success = false;
try
{
for (;;)
{
if (size == 0)
{
if (readCallback == null)
{
readCallback = new WaitCallback(ReadCallback);
}
if (Connection.BeginRead(0, connectionBuffer.Length, GetRemainingTimeout(), readCallback, this)
== AsyncCompletionResult.Queued)
{
break;
}
GetReadResult();
}
int bytesDecoded = decoder.Decode(connectionBuffer, offset, size);
if (bytesDecoded > 0)
{
offset += bytesDecoded;
size -= bytesDecoded;
}
if (decoder.CurrentState == ServerSessionDecoder.State.PreUpgradeStart)
{
if (onValidate == null)
{
onValidate = Fx.ThunkCallback(new AsyncCallback(OnValidate));
}
this.via = decoder.Via;
IAsyncResult result = this.Connection.BeginValidate(this.via, onValidate, this);
if (result.CompletedSynchronously)
{
if (!VerifyValidationResult(result))
{
// This goes through the failure path (Abort) even though it doesn't throw.
return;
}
}
break; //exit loop, set success=true;
}
}
success = true;
}
catch (CommunicationException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
catch (TimeoutException exception)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(exception.Message);
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!ExceptionHandler.HandleTransportExceptionHelper(e))
{
throw;
}
// containment -- all exceptions abort the reader, no additional containment action necessary
}
finally
{
if (!success)
{
Abort();
}
}
}
//returns true if validation was successful
bool VerifyValidationResult(IAsyncResult result)
{
return this.Connection.EndValidate(result) && this.ContinuePostValidationProcessing();
}
static void OnValidate(IAsyncResult result)
{
bool success = false;
ServerSessionPreambleConnectionReader thisPtr = (ServerSessionPreambleConnectionReader)result.AsyncState;
try
{
if (!result.CompletedSynchronously)
{
if (!thisPtr.VerifyValidationResult(result))
{
// This goes through the failure path (Abort) even though it doesn't throw.
return;
}
}
success = true;
}
catch (CommunicationException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
catch (TimeoutException exception)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(exception.Message);
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
finally
{
if (!success)
{
thisPtr.Abort();
}
}
}
//returns false if the connection should be aborted
bool ContinuePostValidationProcessing()
{
if (viaDelegate != null)
{
try
{
viaDelegate(via);
}
catch (ServiceActivationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
// return fault and close connection
SendFault(FramingEncodingString.ServiceActivationFailedFault);
return true;
}
}
this.settings = transportSettingsCallback(via);
if (settings == null)
{
EndpointNotFoundException e = new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, decoder.Via));
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
SendFault(FramingEncodingString.EndpointNotFoundFault);
return false;
}
// we have enough information to hand off to a channel. Our job is done
callback(this);
return true;
}
public void SendFault(string faultString)
{
InitialServerConnectionReader.SendFault(
Connection, faultString, this.connectionBuffer, GetRemainingTimeout(),
TransportDefaults.MaxDrainSize);
base.Close(GetRemainingTimeout());
}
public void StartReading(Action<Uri> viaDelegate, TimeSpan receiveTimeout)
{
this.viaDelegate = viaDelegate;
this.receiveTimeoutHelper = new TimeoutHelper(receiveTimeout);
this.connectionBuffer = Connection.AsyncReadBuffer;
ContinueReading();
}
public IDuplexSessionChannel CreateDuplexSessionChannel(ConnectionOrientedTransportChannelListener channelListener, EndpointAddress localAddress, bool exposeConnectionProperty, ConnectionDemuxer connectionDemuxer)
{
return new ServerFramingDuplexSessionChannel(channelListener, this, localAddress, exposeConnectionProperty, connectionDemuxer);
}
class ServerFramingDuplexSessionChannel : FramingDuplexSessionChannel
{
ConnectionOrientedTransportChannelListener channelListener;
ConnectionDemuxer connectionDemuxer;
ServerSessionConnectionReader sessionReader;
ServerSessionDecoder decoder;
IConnection rawConnection;
byte[] connectionBuffer;
int offset;
int size;
StreamUpgradeAcceptor upgradeAcceptor;
IStreamUpgradeChannelBindingProvider channelBindingProvider;
public ServerFramingDuplexSessionChannel(ConnectionOrientedTransportChannelListener channelListener, ServerSessionPreambleConnectionReader preambleReader,
EndpointAddress localAddress, bool exposeConnectionProperty, ConnectionDemuxer connectionDemuxer)
: base(channelListener, localAddress, preambleReader.Via, exposeConnectionProperty)
{
this.channelListener = channelListener;
this.connectionDemuxer = connectionDemuxer;
this.Connection = preambleReader.Connection;
this.decoder = preambleReader.Decoder;
this.connectionBuffer = preambleReader.connectionBuffer;
this.offset = preambleReader.BufferOffset;
this.size = preambleReader.BufferSize;
this.rawConnection = preambleReader.RawConnection;
StreamUpgradeProvider upgrade = channelListener.Upgrade;
if (upgrade != null)
{
this.channelBindingProvider = upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();
this.upgradeAcceptor = upgrade.CreateUpgradeAcceptor();
}
}
protected override void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout)
{
IConnection localConnection = null;
if (this.sessionReader != null)
{
lock (ThisLock)
{
localConnection = this.sessionReader.GetRawConnection();
}
}
if (localConnection != null)
{
if (abort)
{
localConnection.Abort();
}
else
{
this.connectionDemuxer.ReuseConnection(localConnection, timeout);
}
this.connectionDemuxer = null;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IChannelBindingProvider))
{
return (T)(object)this.channelBindingProvider;
}
return base.GetProperty<T>();
}
protected override void PrepareMessage(Message message)
{
channelListener.RaiseMessageReceived();
base.PrepareMessage(message);
}
// perform security handshake and ACK connection
protected override void OnOpen(TimeSpan timeout)
{
bool success = false;
try
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
// first validate our content type
ValidateContentType(ref timeoutHelper);
// next read any potential upgrades and finish consuming the preamble
for (;;)
{
if (size == 0)
{
offset = 0;
size = Connection.Read(connectionBuffer, 0, connectionBuffer.Length, timeoutHelper.RemainingTime());
if (size == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
}
for (;;)
{
DecodeBytes();
switch (decoder.CurrentState)
{
case ServerSessionDecoder.State.UpgradeRequest:
ProcessUpgradeRequest(ref timeoutHelper);
// accept upgrade
Connection.Write(ServerSessionEncoder.UpgradeResponseBytes, 0, ServerSessionEncoder.UpgradeResponseBytes.Length, true, timeoutHelper.RemainingTime());
IConnection connectionToUpgrade = this.Connection;
if (this.size > 0)
{
connectionToUpgrade = new PreReadConnection(connectionToUpgrade, this.connectionBuffer, this.offset, this.size);
}
try
{
this.Connection = InitialServerConnectionReader.UpgradeConnection(connectionToUpgrade, upgradeAcceptor, this);
if (this.channelBindingProvider != null && this.channelBindingProvider.IsChannelBindingSupportEnabled)
{
this.SetChannelBinding(this.channelBindingProvider.GetChannelBinding(this.upgradeAcceptor, ChannelBindingKind.Endpoint));
}
this.connectionBuffer = Connection.AsyncReadBuffer;
}
#pragma warning suppress 56500
catch (Exception exception)
{
if (Fx.IsFatal(exception))
throw;
// Audit Authentication Failure
WriteAuditFailure(upgradeAcceptor as StreamSecurityUpgradeAcceptor, exception);
throw;
}
break;
case ServerSessionDecoder.State.Start:
SetupSecurityIfNecessary();
// we've finished the preamble. Ack and return.
Connection.Write(ServerSessionEncoder.AckResponseBytes, 0,
ServerSessionEncoder.AckResponseBytes.Length, true, timeoutHelper.RemainingTime());
SetupSessionReader();
success = true;
return;
}
if (size == 0)
break;
}
}
}
finally
{
if (!success)
{
Connection.Abort();
}
}
}
void AcceptUpgradedConnection(IConnection upgradedConnection)
{
this.Connection = upgradedConnection;
if (this.channelBindingProvider != null && this.channelBindingProvider.IsChannelBindingSupportEnabled)
{
this.SetChannelBinding(this.channelBindingProvider.GetChannelBinding(this.upgradeAcceptor, ChannelBindingKind.Endpoint));
}
this.connectionBuffer = Connection.AsyncReadBuffer;
}
void ValidateContentType(ref TimeoutHelper timeoutHelper)
{
this.MessageEncoder = channelListener.MessageEncoderFactory.CreateSessionEncoder();
if (!this.MessageEncoder.IsContentTypeSupported(decoder.ContentType))
{
SendFault(FramingEncodingString.ContentTypeInvalidFault, ref timeoutHelper);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(
SR.ContentTypeMismatch, decoder.ContentType, this.MessageEncoder.ContentType)));
}
ICompressedMessageEncoder compressedMessageEncoder = this.MessageEncoder as ICompressedMessageEncoder;
if (compressedMessageEncoder != null && compressedMessageEncoder.CompressionEnabled)
{
compressedMessageEncoder.SetSessionContentType(this.decoder.ContentType);
}
}
void DecodeBytes()
{
int bytesDecoded = decoder.Decode(connectionBuffer, offset, size);
if (bytesDecoded > 0)
{
offset += bytesDecoded;
size -= bytesDecoded;
}
}
void ProcessUpgradeRequest(ref TimeoutHelper timeoutHelper)
{
if (this.upgradeAcceptor == null)
{
SendFault(FramingEncodingString.UpgradeInvalidFault, ref timeoutHelper);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.UpgradeRequestToNonupgradableService, decoder.Upgrade)));
}
if (!this.upgradeAcceptor.CanUpgrade(decoder.Upgrade))
{
SendFault(FramingEncodingString.UpgradeInvalidFault, ref timeoutHelper);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.UpgradeProtocolNotSupported, decoder.Upgrade)));
}
}
void SendFault(string faultString, ref TimeoutHelper timeoutHelper)
{
InitialServerConnectionReader.SendFault(Connection, faultString,
connectionBuffer, timeoutHelper.RemainingTime(), TransportDefaults.MaxDrainSize);
}
void SetupSecurityIfNecessary()
{
StreamSecurityUpgradeAcceptor securityUpgradeAcceptor = this.upgradeAcceptor as StreamSecurityUpgradeAcceptor;
if (securityUpgradeAcceptor != null)
{
this.RemoteSecurity = securityUpgradeAcceptor.GetRemoteSecurity();
if (this.RemoteSecurity == null)
{
Exception securityFailedException = new ProtocolException(
SR.GetString(SR.RemoteSecurityNotNegotiatedOnStreamUpgrade, this.Via));
WriteAuditFailure(securityUpgradeAcceptor, securityFailedException);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(securityFailedException);
}
else
{
// Audit Authentication Success
WriteAuditEvent(securityUpgradeAcceptor, AuditLevel.Success, null);
}
}
}
void SetupSessionReader()
{
this.sessionReader = new ServerSessionConnectionReader(this);
base.SetMessageSource(this.sessionReader);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OpenAsyncResult(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OpenAsyncResult.End(result);
}
#region Transport Security Auditing
void WriteAuditFailure(StreamSecurityUpgradeAcceptor securityUpgradeAcceptor, Exception exception)
{
try
{
WriteAuditEvent(securityUpgradeAcceptor, AuditLevel.Failure, exception);
}
#pragma warning suppress 56500 // covered by FxCop
catch (Exception auditException)
{
if (Fx.IsFatal(auditException))
{
throw;
}
DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
}
}
void WriteAuditEvent(StreamSecurityUpgradeAcceptor securityUpgradeAcceptor, AuditLevel auditLevel, Exception exception)
{
if ((this.channelListener.AuditBehavior.MessageAuthenticationAuditLevel & auditLevel) != auditLevel)
{
return;
}
if (securityUpgradeAcceptor == null)
{
return;
}
String primaryIdentity = String.Empty;
SecurityMessageProperty clientSecurity = securityUpgradeAcceptor.GetRemoteSecurity();
if (clientSecurity != null)
{
primaryIdentity = GetIdentityNameFromContext(clientSecurity);
}
ServiceSecurityAuditBehavior auditBehavior = this.channelListener.AuditBehavior;
if (auditLevel == AuditLevel.Success)
{
SecurityAuditHelper.WriteTransportAuthenticationSuccessEvent(auditBehavior.AuditLogLocation,
auditBehavior.SuppressAuditFailure, null, this.LocalVia, primaryIdentity);
}
else
{
SecurityAuditHelper.WriteTransportAuthenticationFailureEvent(auditBehavior.AuditLogLocation,
auditBehavior.SuppressAuditFailure, null, this.LocalVia, primaryIdentity, exception);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static string GetIdentityNameFromContext(SecurityMessageProperty clientSecurity)
{
return SecurityUtils.GetIdentityNamesFromContext(
clientSecurity.ServiceSecurityContext.AuthorizationContext);
}
#endregion
class OpenAsyncResult : AsyncResult
{
ServerFramingDuplexSessionChannel channel;
TimeoutHelper timeoutHelper;
static WaitCallback readCallback;
static WaitCallback onWriteAckResponse;
static WaitCallback onWriteUpgradeResponse;
static AsyncCallback onUpgradeConnection;
public OpenAsyncResult(ServerFramingDuplexSessionChannel channel, TimeSpan timeout,
AsyncCallback callback, object state)
: base(callback, state)
{
this.channel = channel;
this.timeoutHelper = new TimeoutHelper(timeout);
bool completeSelf = false;
bool success = false;
try
{
channel.ValidateContentType(ref this.timeoutHelper);
completeSelf = ContinueReading();
success = true;
}
finally
{
if (!success)
{
CleanupOnError();
}
}
if (completeSelf)
{
base.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<OpenAsyncResult>(result);
}
void CleanupOnError()
{
this.channel.Connection.Abort();
}
bool ContinueReading()
{
for (;;)
{
if (channel.size == 0)
{
if (readCallback == null)
{
readCallback = new WaitCallback(ReadCallback);
}
if (channel.Connection.BeginRead(0, channel.connectionBuffer.Length, timeoutHelper.RemainingTime(),
readCallback, this) == AsyncCompletionResult.Queued)
{
return false;
}
GetReadResult();
}
for (;;)
{
channel.DecodeBytes();
switch (channel.decoder.CurrentState)
{
case ServerSessionDecoder.State.UpgradeRequest:
channel.ProcessUpgradeRequest(ref this.timeoutHelper);
// accept upgrade
if (onWriteUpgradeResponse == null)
{
onWriteUpgradeResponse = Fx.ThunkCallback(new WaitCallback(OnWriteUpgradeResponse));
}
AsyncCompletionResult writeResult = channel.Connection.BeginWrite(
ServerSessionEncoder.UpgradeResponseBytes, 0, ServerSessionEncoder.UpgradeResponseBytes.Length,
true, timeoutHelper.RemainingTime(), onWriteUpgradeResponse, this);
if (writeResult == AsyncCompletionResult.Queued)
{
return false;
}
if (!HandleWriteUpgradeResponseComplete())
{
return false;
}
break;
case ServerSessionDecoder.State.Start:
channel.SetupSecurityIfNecessary();
// we've finished the preamble. Ack and return.
if (onWriteAckResponse == null)
{
onWriteAckResponse = Fx.ThunkCallback(new WaitCallback(OnWriteAckResponse));
}
AsyncCompletionResult writeAckResult =
channel.Connection.BeginWrite(ServerSessionEncoder.AckResponseBytes, 0,
ServerSessionEncoder.AckResponseBytes.Length, true, timeoutHelper.RemainingTime(),
onWriteAckResponse, this);
if (writeAckResult == AsyncCompletionResult.Queued)
{
return false;
}
return HandleWriteAckComplete();
}
if (channel.size == 0)
break;
}
}
}
void GetReadResult()
{
channel.offset = 0;
channel.size = channel.Connection.EndRead();
if (channel.size == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(channel.decoder.CreatePrematureEOFException());
}
}
bool HandleWriteUpgradeResponseComplete()
{
channel.Connection.EndWrite();
IConnection connectionToUpgrade = channel.Connection;
if (channel.size > 0)
{
connectionToUpgrade = new PreReadConnection(connectionToUpgrade, channel.connectionBuffer, channel.offset, channel.size);
}
if (onUpgradeConnection == null)
{
onUpgradeConnection = Fx.ThunkCallback(new AsyncCallback(OnUpgradeConnection));
}
try
{
IAsyncResult upgradeConnectionResult = InitialServerConnectionReader.BeginUpgradeConnection(
connectionToUpgrade, channel.upgradeAcceptor, channel, onUpgradeConnection, this);
if (!upgradeConnectionResult.CompletedSynchronously)
{
return false;
}
return HandleUpgradeConnectionComplete(upgradeConnectionResult);
}
#pragma warning suppress 56500
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
// Audit Authentication Failure
this.channel.WriteAuditFailure(channel.upgradeAcceptor as StreamSecurityUpgradeAcceptor, exception);
throw;
}
}
bool HandleUpgradeConnectionComplete(IAsyncResult result)
{
channel.AcceptUpgradedConnection(InitialServerConnectionReader.EndUpgradeConnection(result));
return true;
}
bool HandleWriteAckComplete()
{
channel.Connection.EndWrite();
channel.SetupSessionReader();
return true;
}
static void ReadCallback(object state)
{
OpenAsyncResult thisPtr = (OpenAsyncResult)state;
bool completeSelf = false;
Exception completionException = null;
try
{
thisPtr.GetReadResult();
completeSelf = thisPtr.ContinueReading();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
thisPtr.CleanupOnError();
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
static void OnWriteUpgradeResponse(object asyncState)
{
OpenAsyncResult thisPtr = (OpenAsyncResult)asyncState;
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = thisPtr.HandleWriteUpgradeResponseComplete();
if (completeSelf)
{
completeSelf = thisPtr.ContinueReading();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
completeSelf = true;
thisPtr.CleanupOnError();
// Audit Authentication Failure
thisPtr.channel.WriteAuditFailure(thisPtr.channel.upgradeAcceptor as StreamSecurityUpgradeAcceptor, e);
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
static void OnUpgradeConnection(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState;
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = thisPtr.HandleUpgradeConnectionComplete(result);
if (completeSelf)
{
completeSelf = thisPtr.ContinueReading();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
completeSelf = true;
thisPtr.CleanupOnError();
// Audit Authentication Failure
thisPtr.channel.WriteAuditFailure(thisPtr.channel.upgradeAcceptor as StreamSecurityUpgradeAcceptor, e);
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
static void OnWriteAckResponse(object asyncState)
{
OpenAsyncResult thisPtr = (OpenAsyncResult)asyncState;
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = thisPtr.HandleWriteAckComplete();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
completeSelf = true;
thisPtr.CleanupOnError();
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
}
class ServerSessionConnectionReader : SessionConnectionReader
{
ServerSessionDecoder decoder;
int maxBufferSize;
BufferManager bufferManager;
MessageEncoder messageEncoder;
string contentType;
IConnection rawConnection;
public ServerSessionConnectionReader(ServerFramingDuplexSessionChannel channel)
: base(channel.Connection, channel.rawConnection, channel.offset, channel.size, channel.RemoteSecurity)
{
this.decoder = channel.decoder;
this.contentType = this.decoder.ContentType;
this.maxBufferSize = channel.channelListener.MaxBufferSize;
this.bufferManager = channel.channelListener.BufferManager;
this.messageEncoder = channel.MessageEncoder;
this.rawConnection = channel.rawConnection;
}
protected override void EnsureDecoderAtEof()
{
if (!(decoder.CurrentState == ServerSessionDecoder.State.End || decoder.CurrentState == ServerSessionDecoder.State.EnvelopeEnd))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
}
protected override Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEof, TimeSpan timeout)
{
while (!isAtEof && size > 0)
{
int bytesRead = decoder.Decode(buffer, offset, size);
if (bytesRead > 0)
{
if (EnvelopeBuffer != null)
{
if (!object.ReferenceEquals(buffer, EnvelopeBuffer))
{
System.Buffer.BlockCopy(buffer, offset, EnvelopeBuffer, EnvelopeOffset, bytesRead);
}
EnvelopeOffset += bytesRead;
}
offset += bytesRead;
size -= bytesRead;
}
switch (decoder.CurrentState)
{
case ServerSessionDecoder.State.EnvelopeStart:
int envelopeSize = decoder.EnvelopeSize;
if (envelopeSize > maxBufferSize)
{
base.SendFault(FramingEncodingString.MaxMessageSizeExceededFault, timeout);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(maxBufferSize));
}
EnvelopeBuffer = bufferManager.TakeBuffer(envelopeSize);
EnvelopeOffset = 0;
EnvelopeSize = envelopeSize;
break;
case ServerSessionDecoder.State.EnvelopeEnd:
if (EnvelopeBuffer != null)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity(true) : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage);
}
Message message = null;
try
{
message = messageEncoder.ReadMessage(new ArraySegment<byte>(EnvelopeBuffer, 0, EnvelopeSize), bufferManager, this.contentType);
}
catch (XmlException xmlException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.MessageXmlProtocolError), xmlException));
}
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.TransferFromTransport(message);
}
EnvelopeBuffer = null;
return message;
}
}
break;
case ServerSessionDecoder.State.End:
isAtEof = true;
break;
}
}
return null;
}
protected override void PrepareMessage(Message message)
{
base.PrepareMessage(message);
IPEndPoint remoteEndPoint = this.rawConnection.RemoteIPEndPoint;
// pipes will return null
if (remoteEndPoint != null)
{
RemoteEndpointMessageProperty remoteEndpointProperty = new RemoteEndpointMessageProperty(remoteEndPoint);
message.Properties.Add(RemoteEndpointMessageProperty.Name, remoteEndpointProperty);
}
}
}
}
}
abstract class SessionConnectionReader : IMessageSource
{
bool isAtEOF;
bool usingAsyncReadBuffer;
IConnection connection;
byte[] buffer;
int offset;
int size;
byte[] envelopeBuffer;
int envelopeOffset;
int envelopeSize;
bool readIntoEnvelopeBuffer;
WaitCallback onAsyncReadComplete;
Message pendingMessage;
Exception pendingException;
WaitCallback pendingCallback;
object pendingCallbackState;
SecurityMessageProperty security;
TimeoutHelper readTimeoutHelper;
// Raw connection that we will revert to after end handshake
IConnection rawConnection;
protected SessionConnectionReader(IConnection connection, IConnection rawConnection,
int offset, int size, SecurityMessageProperty security)
{
this.offset = offset;
this.size = size;
if (size > 0)
{
this.buffer = connection.AsyncReadBuffer;
}
this.connection = connection;
this.rawConnection = rawConnection;
this.onAsyncReadComplete = new WaitCallback(OnAsyncReadComplete);
this.security = security;
}
Message DecodeMessage(TimeSpan timeout)
{
if (DiagnosticUtility.ShouldUseActivity &&
ServiceModelActivity.Current != null &&
ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction)
{
ServiceModelActivity.Current.Resume();
}
if (!readIntoEnvelopeBuffer)
{
return DecodeMessage(buffer, ref offset, ref size, ref isAtEOF, timeout);
}
else
{
// decode from the envelope buffer
int dummyOffset = this.envelopeOffset;
return DecodeMessage(envelopeBuffer, ref dummyOffset, ref size, ref isAtEOF, timeout);
}
}
protected abstract Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEof, TimeSpan timeout);
protected byte[] EnvelopeBuffer
{
get { return envelopeBuffer; }
set { envelopeBuffer = value; }
}
protected int EnvelopeOffset
{
get { return envelopeOffset; }
set { envelopeOffset = value; }
}
protected int EnvelopeSize
{
get { return envelopeSize; }
set { envelopeSize = value; }
}
public IConnection GetRawConnection()
{
IConnection result = null;
if (this.rawConnection != null)
{
result = this.rawConnection;
this.rawConnection = null;
if (size > 0)
{
PreReadConnection preReadConnection = result as PreReadConnection;
if (preReadConnection != null) // make sure we don't keep wrapping
{
preReadConnection.AddPreReadData(this.buffer, this.offset, this.size);
}
else
{
result = new PreReadConnection(result, this.buffer, this.offset, this.size);
}
}
}
return result;
}
public AsyncReceiveResult BeginReceive(TimeSpan timeout, WaitCallback callback, object state)
{
if (pendingMessage != null || pendingException != null)
{
return AsyncReceiveResult.Completed;
}
this.readTimeoutHelper = new TimeoutHelper(timeout);
for (;;)
{
if (isAtEOF)
{
return AsyncReceiveResult.Completed;
}
if (size > 0)
{
pendingMessage = DecodeMessage(readTimeoutHelper.RemainingTime());
if (pendingMessage != null)
{
PrepareMessage(pendingMessage);
return AsyncReceiveResult.Completed;
}
else if (isAtEOF) // could have read the END record under DecodeMessage
{
return AsyncReceiveResult.Completed;
}
}
if (size != 0)
{
throw Fx.AssertAndThrow("BeginReceive: DecodeMessage() should consume the outstanding buffer or return a message.");
}
if (!usingAsyncReadBuffer)
{
buffer = connection.AsyncReadBuffer;
usingAsyncReadBuffer = true;
}
pendingCallback = callback;
pendingCallbackState = state;
bool throwing = true;
AsyncCompletionResult asyncReadResult;
try
{
asyncReadResult =
connection.BeginRead(0, buffer.Length, readTimeoutHelper.RemainingTime(), onAsyncReadComplete, null);
throwing = false;
}
finally
{
if (throwing)
{
pendingCallback = null;
pendingCallbackState = null;
}
}
if (asyncReadResult == AsyncCompletionResult.Queued)
{
return AsyncReceiveResult.Pending;
}
pendingCallback = null;
pendingCallbackState = null;
int bytesRead = connection.EndRead();
HandleReadComplete(bytesRead, false);
}
}
public Message Receive(TimeSpan timeout)
{
Message message = GetPendingMessage();
if (message != null)
{
return message;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
for (;;)
{
if (isAtEOF)
{
return null;
}
if (size > 0)
{
message = DecodeMessage(timeoutHelper.RemainingTime());
if (message != null)
{
PrepareMessage(message);
return message;
}
else if (isAtEOF) // could have read the END record under DecodeMessage
{
return null;
}
}
if (size != 0)
{
throw Fx.AssertAndThrow("Receive: DecodeMessage() should consume the outstanding buffer or return a message.");
}
if (buffer == null)
{
buffer = DiagnosticUtility.Utility.AllocateByteArray(connection.AsyncReadBufferSize);
}
int bytesRead;
if (EnvelopeBuffer != null &&
(EnvelopeSize - EnvelopeOffset) >= buffer.Length)
{
bytesRead = connection.Read(EnvelopeBuffer, EnvelopeOffset, buffer.Length, timeoutHelper.RemainingTime());
HandleReadComplete(bytesRead, true);
}
else
{
bytesRead = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime());
HandleReadComplete(bytesRead, false);
}
}
}
public Message EndReceive()
{
return GetPendingMessage();
}
Message GetPendingMessage()
{
if (pendingException != null)
{
Exception exception = pendingException;
pendingException = null;
throw TraceUtility.ThrowHelperError(exception, pendingMessage);
}
if (pendingMessage != null)
{
Message message = pendingMessage;
pendingMessage = null;
return message;
}
return null;
}
public AsyncReceiveResult BeginWaitForMessage(TimeSpan timeout, WaitCallback callback, object state)
{
try
{
return BeginReceive(timeout, callback, state);
}
catch (TimeoutException e)
{
pendingException = e;
return AsyncReceiveResult.Completed;
}
}
public bool EndWaitForMessage()
{
try
{
Message message = EndReceive();
this.pendingMessage = message;
return true;
}
catch (TimeoutException e)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(e.Message);
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
return false;
}
}
public bool WaitForMessage(TimeSpan timeout)
{
try
{
Message message = Receive(timeout);
this.pendingMessage = message;
return true;
}
catch (TimeoutException e)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(e.Message);
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
return false;
}
}
protected abstract void EnsureDecoderAtEof();
void HandleReadComplete(int bytesRead, bool readIntoEnvelopeBuffer)
{
this.readIntoEnvelopeBuffer = readIntoEnvelopeBuffer;
if (bytesRead == 0)
{
EnsureDecoderAtEof();
isAtEOF = true;
}
else
{
this.offset = 0;
this.size = bytesRead;
}
}
void OnAsyncReadComplete(object state)
{
try
{
for (;;)
{
int bytesRead = connection.EndRead();
HandleReadComplete(bytesRead, false);
if (isAtEOF)
{
break;
}
Message message = DecodeMessage(this.readTimeoutHelper.RemainingTime());
if (message != null)
{
PrepareMessage(message);
this.pendingMessage = message;
break;
}
else if (isAtEOF) // could have read the END record under DecodeMessage
{
break;
}
if (size != 0)
{
throw Fx.AssertAndThrow("OnAsyncReadComplete: DecodeMessage() should consume the outstanding buffer or return a message.");
}
if (connection.BeginRead(0, buffer.Length, this.readTimeoutHelper.RemainingTime(),
onAsyncReadComplete, null) == AsyncCompletionResult.Queued)
{
return;
}
}
}
#pragma warning suppress 56500 // [....], transferring exception to caller
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
pendingException = e;
}
WaitCallback callback = pendingCallback;
object callbackState = pendingCallbackState;
pendingCallback = null;
pendingCallbackState = null;
callback(callbackState);
}
protected virtual void PrepareMessage(Message message)
{
if (security != null)
{
message.Properties.Security = (SecurityMessageProperty)security.CreateCopy();
}
}
protected void SendFault(string faultString, TimeSpan timeout)
{
byte[] drainBuffer = new byte[128];
InitialServerConnectionReader.SendFault(
connection, faultString, drainBuffer, timeout,
TransportDefaults.MaxDrainSize);
}
}
class ClientDuplexConnectionReader : SessionConnectionReader
{
ClientDuplexDecoder decoder;
int maxBufferSize;
BufferManager bufferManager;
MessageEncoder messageEncoder;
ClientFramingDuplexSessionChannel channel;
public ClientDuplexConnectionReader(ClientFramingDuplexSessionChannel channel, IConnection connection, ClientDuplexDecoder decoder,
IConnectionOrientedTransportFactorySettings settings, MessageEncoder messageEncoder)
: base(connection, null, 0, 0, null)
{
this.decoder = decoder;
this.maxBufferSize = settings.MaxBufferSize;
this.bufferManager = settings.BufferManager;
this.messageEncoder = messageEncoder;
this.channel = channel;
}
protected override void EnsureDecoderAtEof()
{
if (!(decoder.CurrentState == ClientFramingDecoderState.End
|| decoder.CurrentState == ClientFramingDecoderState.EnvelopeEnd
|| decoder.CurrentState == ClientFramingDecoderState.ReadingUpgradeRecord
|| decoder.CurrentState == ClientFramingDecoderState.UpgradeResponse))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
}
static IDisposable CreateProcessActionActivity()
{
IDisposable retval = null;
if (DiagnosticUtility.ShouldUseActivity)
{
if ((ServiceModelActivity.Current != null) &&
(ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction))
{
// Do nothing-- we are already OK
}
else if ((ServiceModelActivity.Current != null) &&
(ServiceModelActivity.Current.PreviousActivity != null) &&
(ServiceModelActivity.Current.PreviousActivity.ActivityType == ActivityType.ProcessAction))
{
retval = ServiceModelActivity.BoundOperation(ServiceModelActivity.Current.PreviousActivity);
}
else
{
ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity(true);
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage);
retval = activity;
}
}
return retval;
}
protected override Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEOF, TimeSpan timeout)
{
while (size > 0)
{
int bytesRead = decoder.Decode(buffer, offset, size);
if (bytesRead > 0)
{
if (EnvelopeBuffer != null)
{
if (!object.ReferenceEquals(buffer, EnvelopeBuffer))
System.Buffer.BlockCopy(buffer, offset, EnvelopeBuffer, EnvelopeOffset, bytesRead);
EnvelopeOffset += bytesRead;
}
offset += bytesRead;
size -= bytesRead;
}
switch (decoder.CurrentState)
{
case ClientFramingDecoderState.Fault:
channel.Session.CloseOutputSession(channel.InternalCloseTimeout);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultStringDecoder.GetFaultException(decoder.Fault, channel.RemoteAddress.Uri.ToString(), messageEncoder.ContentType));
case ClientFramingDecoderState.End:
isAtEOF = true;
return null; // we're done
case ClientFramingDecoderState.EnvelopeStart:
int envelopeSize = decoder.EnvelopeSize;
if (envelopeSize > maxBufferSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(maxBufferSize));
}
EnvelopeBuffer = bufferManager.TakeBuffer(envelopeSize);
EnvelopeOffset = 0;
EnvelopeSize = envelopeSize;
break;
case ClientFramingDecoderState.EnvelopeEnd:
if (EnvelopeBuffer != null)
{
Message message = null;
try
{
IDisposable activity = ClientDuplexConnectionReader.CreateProcessActionActivity();
using (activity)
{
message = messageEncoder.ReadMessage(new ArraySegment<byte>(EnvelopeBuffer, 0, EnvelopeSize), bufferManager);
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.TransferFromTransport(message);
}
}
}
catch (XmlException xmlException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.MessageXmlProtocolError), xmlException));
}
EnvelopeBuffer = null;
return message;
}
break;
}
}
return null;
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using J2N.Text;
using J2N.Threading;
using J2N.Threading.Atomic;
using Lucene.Net.Analysis;
using Lucene.Net.Codecs;
using Lucene.Net.Codecs.Lucene46;
using Lucene.Net.Codecs.SimpleText;
using Lucene.Net.Documents;
using Lucene.Net.Documents.Extensions;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using JCG = J2N.Collections.Generic;
using Console = Lucene.Net.Util.SystemConsole;
using Assert = Lucene.Net.TestFramework.Assert;
#if TESTFRAMEWORK_MSTEST
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#elif TESTFRAMEWORK_NUNIT
using Test = NUnit.Framework.TestAttribute;
#elif TESTFRAMEWORK_XUNIT
using Test = Lucene.Net.TestFramework.SkippableFactAttribute;
#endif
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Base class aiming at testing <see cref="Codecs.StoredFieldsFormat"/>.
/// To test a new format, all you need is to register a new <see cref="Codec"/> which
/// uses it and extend this class and override <see cref="BaseIndexFileFormatTestCase.GetCodec()"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class BaseStoredFieldsFormatTestCase : BaseIndexFileFormatTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
{
public BaseStoredFieldsFormatTestCase(BeforeAfterClass beforeAfter)
: base(beforeAfter)
{
}
#else
{
#endif
protected override void AddRandomFields(Document d)
{
int numValues = Random.Next(3);
for (int i = 0; i < numValues; ++i)
{
d.Add(new StoredField("f", TestUtil.RandomSimpleString(Random, 100)));
}
}
[Test]
public virtual void TestRandomStoredFields()
{
using (Directory dir = NewDirectory())
{
Random rand = Random;
using (RandomIndexWriter w = new RandomIndexWriter(rand, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(TestUtil.NextInt32(rand, 5, 20))))
{
//w.w.setNoCFSRatio(0.0);
int docCount = AtLeast(200);
int fieldCount = TestUtil.NextInt32(rand, 1, 5);
IList<int?> fieldIDs = new List<int?>();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.IsTokenized = false;
Field idField = NewField("id", "", customType);
for (int i = 0; i < fieldCount; i++)
{
fieldIDs.Add(i);
}
IDictionary<string, Document> docs = new Dictionary<string, Document>();
if (Verbose)
{
Console.WriteLine("TEST: build index docCount=" + docCount);
}
FieldType customType2 = new FieldType();
customType2.IsStored = true;
for (int i = 0; i < docCount; i++)
{
Document doc = new Document();
doc.Add(idField);
string id = "" + i;
idField.SetStringValue(id);
docs[id] = doc;
if (Verbose)
{
Console.WriteLine("TEST: add doc id=" + id);
}
foreach (int field in fieldIDs)
{
string s;
if (rand.Next(4) != 3)
{
s = TestUtil.RandomUnicodeString(rand, 1000);
doc.Add(NewField("f" + field, s, customType2));
}
else
{
s = null;
}
}
w.AddDocument(doc);
if (rand.Next(50) == 17)
{
// mixup binding of field name -> Number every so often
fieldIDs.Shuffle(Random);
}
if (rand.Next(5) == 3 && i > 0)
{
string delID = "" + rand.Next(i);
if (Verbose)
{
Console.WriteLine("TEST: delete doc id=" + delID);
}
w.DeleteDocuments(new Term("id", delID));
docs.Remove(delID);
}
}
if (Verbose)
{
Console.WriteLine("TEST: " + docs.Count + " docs in index; now load fields");
}
if (docs.Count > 0)
{
string[] idsList = docs.Keys.ToArray(/*new string[docs.Count]*/);
for (int x = 0; x < 2; x++)
{
using (IndexReader r = w.GetReader())
{
IndexSearcher s = NewSearcher(r);
if (Verbose)
{
Console.WriteLine("TEST: cycle x=" + x + " r=" + r);
}
int num = AtLeast(1000);
for (int iter = 0; iter < num; iter++)
{
string testID = idsList[rand.Next(idsList.Length)];
if (Verbose)
{
Console.WriteLine("TEST: test id=" + testID);
}
TopDocs hits = s.Search(new TermQuery(new Term("id", testID)), 1);
Assert.AreEqual(1, hits.TotalHits);
Document doc = r.Document(hits.ScoreDocs[0].Doc);
Document docExp = docs[testID];
for (int i = 0; i < fieldCount; i++)
{
assertEquals("doc " + testID + ", field f" + fieldCount + " is wrong", docExp.Get("f" + i), doc.Get("f" + i));
}
}
} // r.Dispose();
w.ForceMerge(1);
}
}
} // w.Dispose();
} // dir.Dispose();
}
[Test]
// LUCENE-1727: make sure doc fields are stored in order
public virtual void TestStoredFieldsOrder()
{
using (Directory d = NewDirectory())
using (IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))))
{
Document doc = new Document();
FieldType customType = new FieldType();
customType.IsStored = true;
doc.Add(NewField("zzz", "a b c", customType));
doc.Add(NewField("aaa", "a b c", customType));
doc.Add(NewField("zzz", "1 2 3", customType));
w.AddDocument(doc);
using (IndexReader r = w.GetReader())
{
Document doc2 = r.Document(0);
IEnumerator<IIndexableField> it = doc2.Fields.GetEnumerator();
Assert.IsTrue(it.MoveNext());
Field f = (Field)it.Current;
Assert.AreEqual(f.Name, "zzz");
Assert.AreEqual(f.GetStringValue(), "a b c");
Assert.IsTrue(it.MoveNext());
f = (Field)it.Current;
Assert.AreEqual(f.Name, "aaa");
Assert.AreEqual(f.GetStringValue(), "a b c");
Assert.IsTrue(it.MoveNext());
f = (Field)it.Current;
Assert.AreEqual(f.Name, "zzz");
Assert.AreEqual(f.GetStringValue(), "1 2 3");
Assert.IsFalse(it.MoveNext());
} // r.Dispose();
} // w.Dispose();, d.Dispose();
}
[Test]
// LUCENE-1219
public virtual void TestBinaryFieldOffsetLength()
{
using (Directory dir = NewDirectory())
{
var b = new byte[50];
using (IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))))
{
for (int i = 0; i < 50; i++)
{
b[i] = (byte)(i + 77);
}
Document doc = new Document();
Field f = new StoredField("binary", b, 10, 17);
var bx = f.GetBinaryValue().Bytes;
Assert.IsTrue(bx != null);
Assert.AreEqual(50, bx.Length);
Assert.AreEqual(10, f.GetBinaryValue().Offset);
Assert.AreEqual(17, f.GetBinaryValue().Length);
doc.Add(f);
w.AddDocument(doc);
} // w.Dispose();
using (IndexReader ir = DirectoryReader.Open(dir))
{
Document doc2 = ir.Document(0);
IIndexableField f2 = doc2.GetField("binary");
b = f2.GetBinaryValue().Bytes;
Assert.IsTrue(b != null);
Assert.AreEqual(17, b.Length, 17);
Assert.AreEqual((byte)87, b[0]);
} // ir.Dispose();
} // dir.Dispose();
}
[Test]
public virtual void TestNumericField()
{
using (Directory dir = NewDirectory())
{
DirectoryReader r = null;
try
{
var numDocs = AtLeast(500);
var answers = new object[numDocs];
using (var w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir))
{
NumericType[] typeAnswers = new NumericType[numDocs];
for (int id = 0; id < numDocs; id++)
{
Document doc = new Document();
Field nf;
Field sf;
object answer;
NumericType typeAnswer;
if (Random.NextBoolean())
{
// float/double
if (Random.NextBoolean())
{
float f = Random.NextSingle();
answer = Convert.ToSingle(f, CultureInfo.InvariantCulture);
nf = new SingleField("nf", f, Field.Store.NO);
sf = new StoredField("nf", f);
typeAnswer = NumericType.SINGLE;
}
else
{
double d = Random.NextDouble();
answer = Convert.ToDouble(d, CultureInfo.InvariantCulture);
nf = new DoubleField("nf", d, Field.Store.NO);
sf = new StoredField("nf", d);
typeAnswer = NumericType.DOUBLE;
}
}
else
{
// int/long
if (Random.NextBoolean())
{
int i = Random.Next();
answer = Convert.ToInt32(i, CultureInfo.InvariantCulture);
nf = new Int32Field("nf", i, Field.Store.NO);
sf = new StoredField("nf", i);
typeAnswer = NumericType.INT32;
}
else
{
long l = Random.NextInt64();
answer = Convert.ToInt64(l, CultureInfo.InvariantCulture);
nf = new Int64Field("nf", l, Field.Store.NO);
sf = new StoredField("nf", l);
typeAnswer = NumericType.INT64;
}
}
doc.Add(nf);
doc.Add(sf);
answers[id] = answer;
typeAnswers[id] = typeAnswer;
FieldType ft = new FieldType(Int32Field.TYPE_STORED);
ft.NumericPrecisionStep = int.MaxValue;
doc.Add(new Int32Field("id", id, ft));
w.AddDocument(doc);
}
r = w.GetReader();
} // w.Dispose();
Assert.AreEqual(numDocs, r.NumDocs);
foreach (AtomicReaderContext ctx in r.Leaves)
{
AtomicReader sub = ctx.AtomicReader; // LUCENENET TODO: Dispose() ?
FieldCache.Int32s ids = FieldCache.DEFAULT.GetInt32s(sub, "id", false);
for (int docID = 0; docID < sub.NumDocs; docID++)
{
Document doc = sub.Document(docID);
Field f = doc.GetField<Field>("nf");
Assert.IsTrue(f is StoredField, "got f=" + f);
#pragma warning disable 612, 618
Assert.AreEqual(answers[ids.Get(docID)], f.GetNumericValue());
#pragma warning restore 612, 618
}
}
}
finally
{
r?.Dispose();
}
} // dir.Dispose();
}
[Test]
public virtual void TestIndexedBit()
{
using (Directory dir = NewDirectory())
{
IndexReader r = null;
try
{
using (RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir))
{
Document doc = new Document();
FieldType onlyStored = new FieldType();
onlyStored.IsStored = true;
doc.Add(new Field("field", "value", onlyStored));
doc.Add(new StringField("field2", "value", Field.Store.YES));
w.AddDocument(doc);
r = w.GetReader();
} // w.Dispose();
Assert.IsFalse(r.Document(0).GetField("field").IndexableFieldType.IsIndexed);
Assert.IsTrue(r.Document(0).GetField("field2").IndexableFieldType.IsIndexed);
}
finally
{
r?.Dispose();
}
} // dir.Dispose();
}
[Test]
public virtual void TestReadSkip()
{
using (Directory dir = NewDirectory())
{
IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
{
FieldType ft = new FieldType();
ft.IsStored = true;
ft.Freeze();
string @string = TestUtil.RandomSimpleString(Random, 50);
var bytes = @string.GetBytes(Encoding.UTF8);
long l = Random.NextBoolean() ? Random.Next(42) : Random.NextInt64();
int i = Random.NextBoolean() ? Random.Next(42) : Random.Next();
float f = Random.NextSingle();
double d = Random.NextDouble();
Field[] fields = new Field[]
{
new Field("bytes", bytes, ft),
new Field("string", @string, ft),
new Int64Field("long", l, Field.Store.YES),
new Int32Field("int", i, Field.Store.YES),
new SingleField("float", f, Field.Store.YES),
new DoubleField("double", d, Field.Store.YES)
};
for (int k = 0; k < 100; ++k)
{
Document doc = new Document();
foreach (Field fld in fields)
{
doc.Add(fld);
}
iw.IndexWriter.AddDocument(doc);
}
iw.Commit();
using (DirectoryReader reader = DirectoryReader.Open(dir))
{
int docID = Random.Next(100);
foreach (Field fld in fields)
{
string fldName = fld.Name;
Document sDoc = reader.Document(docID, new JCG.HashSet<string> { fldName });
IIndexableField sField = sDoc.GetField(fldName);
if (typeof(Field) == fld.GetType())
{
Assert.AreEqual(fld.GetBinaryValue(), sField.GetBinaryValue());
Assert.AreEqual(fld.GetStringValue(), sField.GetStringValue());
}
else
{
#pragma warning disable 612, 618
Assert.AreEqual(fld.GetNumericValue(), sField.GetNumericValue());
#pragma warning restore 612, 618
}
}
} // reader.Dispose();
} // iw.Dispose();
} // dir.Dispose();
}
[Test]
public virtual void TestEmptyDocs()
{
using (Directory dir = NewDirectory())
{
IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
{
// make sure that the fact that documents might be empty is not a problem
Document emptyDoc = new Document();
int numDocs = Random.NextBoolean() ? 1 : AtLeast(1000);
for (int i = 0; i < numDocs; ++i)
{
iw.AddDocument(emptyDoc);
}
iw.Commit();
using (DirectoryReader rd = DirectoryReader.Open(dir))
{
for (int i = 0; i < numDocs; ++i)
{
Document doc = rd.Document(i);
Assert.IsNotNull(doc);
Assert.IsTrue(doc.Fields.Count <= 0);
}
} // rd.Dispose();
} // iw.Dispose();
} // dir.Dispose();
}
[Test]
public virtual void TestConcurrentReads()
{
using (Directory dir = NewDirectory())
{
IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
{
// make sure the readers are properly cloned
Document doc = new Document();
Field field = new StringField("fld", "", Field.Store.YES);
doc.Add(field);
int numDocs = AtLeast(1000);
for (int i = 0; i < numDocs; ++i)
{
field.SetStringValue("" + i);
iw.AddDocument(doc);
}
iw.Commit();
AtomicReference<Exception> ex = new AtomicReference<Exception>();
using (DirectoryReader rd = DirectoryReader.Open(dir))
{
IndexSearcher searcher = new IndexSearcher(rd);
int concurrentReads = AtLeast(5);
int readsPerThread = AtLeast(50);
IList<ThreadJob> readThreads = new List<ThreadJob>();
for (int i = 0; i < concurrentReads; ++i)
{
readThreads.Add(new ThreadAnonymousInnerClassHelper(numDocs, rd, searcher, readsPerThread, ex, i));
}
foreach (ThreadJob thread in readThreads)
{
thread.Start();
}
foreach (ThreadJob thread in readThreads)
{
thread.Join();
}
} // rd.Dispose();
if (ex.Value != null)
{
throw ex.Value;
}
} // iw.Dispose();
} // dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadJob
{
private int numDocs;
private readonly DirectoryReader rd;
private readonly IndexSearcher searcher;
private int readsPerThread;
private AtomicReference<Exception> ex;
private int i;
private readonly int[] queries;
public ThreadAnonymousInnerClassHelper(int numDocs, DirectoryReader rd, IndexSearcher searcher, int readsPerThread, AtomicReference<Exception> ex, int i)
{
this.numDocs = numDocs;
this.rd = rd;
this.searcher = searcher;
this.readsPerThread = readsPerThread;
this.ex = ex;
this.i = i;
queries = new int[this.readsPerThread];
for (int j = 0; j < queries.Length; ++j)
{
queries[j] = Random.Next(this.numDocs);
}
}
public override void Run()
{
foreach (int q in queries)
{
Query query = new TermQuery(new Term("fld", "" + q));
try
{
TopDocs topDocs = searcher.Search(query, 1);
if (topDocs.TotalHits != 1)
{
Console.WriteLine(query);
throw new InvalidOperationException("Expected 1 hit, got " + topDocs.TotalHits);
}
Document sdoc = rd.Document(topDocs.ScoreDocs[0].Doc);
if (sdoc == null || sdoc.Get("fld") == null)
{
throw new InvalidOperationException("Could not find document " + q);
}
if (!Convert.ToString(q, CultureInfo.InvariantCulture).Equals(sdoc.Get("fld"), StringComparison.Ordinal))
{
throw new InvalidOperationException("Expected " + q + ", but got " + sdoc.Get("fld"));
}
}
catch (Exception e)
{
ex.Value = e;
}
}
}
}
private static byte[] RandomByteArray(int length, int max)
{
var result = new byte[length];
for (int i = 0; i < length; ++i)
{
result[i] = (byte)Random.Next(max);
}
return result;
}
[Test]
public virtual void TestWriteReadMerge()
{
// get another codec, other than the default: so we are merging segments across different codecs
Codec otherCodec;
if ("SimpleText".Equals(Codec.Default.Name, StringComparison.Ordinal))
{
otherCodec = new Lucene46Codec();
}
else
{
otherCodec = new SimpleTextCodec();
}
using (Directory dir = NewDirectory())
{
IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
RandomIndexWriter iw = new RandomIndexWriter(Random, dir, (IndexWriterConfig)iwConf.Clone());
try
{
int docCount = AtLeast(200);
var data = new byte[docCount][][];
for (int i = 0; i < docCount; ++i)
{
int fieldCount = Rarely() ? RandomInts.RandomInt32Between(Random, 1, 500) : RandomInts.RandomInt32Between(Random, 1, 5);
data[i] = new byte[fieldCount][];
for (int j = 0; j < fieldCount; ++j)
{
int length = Rarely() ? Random.Next(1000) : Random.Next(10);
int max = Rarely() ? 256 : 2;
data[i][j] = RandomByteArray(length, max);
}
}
FieldType type = new FieldType(StringField.TYPE_STORED);
type.IsIndexed = false;
type.Freeze();
Int32Field id = new Int32Field("id", 0, Field.Store.YES);
for (int i = 0; i < data.Length; ++i)
{
Document doc = new Document();
doc.Add(id);
id.SetInt32Value(i);
for (int j = 0; j < data[i].Length; ++j)
{
Field f = new Field("bytes" + j, data[i][j], type);
doc.Add(f);
}
iw.IndexWriter.AddDocument(doc);
if (Random.NextBoolean() && (i % (data.Length / 10) == 0))
{
iw.IndexWriter.Dispose();
// test merging against a non-compressing codec
if (iwConf.Codec == otherCodec)
{
iwConf.SetCodec(Codec.Default);
}
else
{
iwConf.SetCodec(otherCodec);
}
iw = new RandomIndexWriter(Random, dir, (IndexWriterConfig)iwConf.Clone());
}
}
for (int i = 0; i < 10; ++i)
{
int min = Random.Next(data.Length);
int max = min + Random.Next(20);
iw.DeleteDocuments(NumericRangeQuery.NewInt32Range("id", min, max, true, false));
}
iw.ForceMerge(2); // force merges with deletions
iw.Commit();
using (DirectoryReader ir = DirectoryReader.Open(dir))
{
Assert.IsTrue(ir.NumDocs > 0);
int numDocs = 0;
for (int i = 0; i < ir.MaxDoc; ++i)
{
Document doc = ir.Document(i);
if (doc == null)
{
continue;
}
++numDocs;
int docId = (int)doc.GetField("id").GetInt32Value();
Assert.AreEqual(data[docId].Length + 1, doc.Fields.Count);
for (int j = 0; j < data[docId].Length; ++j)
{
var arr = data[docId][j];
BytesRef arr2Ref = doc.GetBinaryValue("bytes" + j);
var arr2 = Arrays.CopyOfRange(arr2Ref.Bytes, arr2Ref.Offset, arr2Ref.Offset + arr2Ref.Length);
Assert.AreEqual(arr, arr2);
}
}
Assert.IsTrue(ir.NumDocs <= numDocs);
} // ir.Dispose();
iw.DeleteAll();
iw.Commit();
iw.ForceMerge(1);
}
finally
{
iw.Dispose();
}
} // dir.Dispose();
}
[Test]
[Nightly]
public virtual void TestBigDocuments()
{
// "big" as "much bigger than the chunk size"
// for this test we force a FS dir
// we can't just use newFSDirectory, because this test doesn't really index anything.
// so if we get NRTCachingDir+SimpleText, we make massive stored fields and OOM (LUCENE-4484)
using (Directory dir = new MockDirectoryWrapper(Random, new MMapDirectory(CreateTempDir("testBigDocuments"))))
{
IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
{
if (dir is MockDirectoryWrapper)
{
((MockDirectoryWrapper)dir).Throttling = Throttling.NEVER;
}
Document emptyDoc = new Document(); // emptyDoc
Document bigDoc1 = new Document(); // lot of small fields
Document bigDoc2 = new Document(); // 1 very big field
Field idField = new StringField("id", "", Field.Store.NO);
emptyDoc.Add(idField);
bigDoc1.Add(idField);
bigDoc2.Add(idField);
FieldType onlyStored = new FieldType(StringField.TYPE_STORED);
onlyStored.IsIndexed = false;
Field smallField = new Field("fld", RandomByteArray(Random.Next(10), 256), onlyStored);
int numFields = RandomInts.RandomInt32Between(Random, 500000, 1000000);
for (int i = 0; i < numFields; ++i)
{
bigDoc1.Add(smallField);
}
Field bigField = new Field("fld", RandomByteArray(RandomInts.RandomInt32Between(Random, 1000000, 5000000), 2), onlyStored);
bigDoc2.Add(bigField);
int numDocs = AtLeast(5);
Document[] docs = new Document[numDocs];
for (int i = 0; i < numDocs; ++i)
{
docs[i] = RandomPicks.RandomFrom(Random, new Document[] { emptyDoc, bigDoc1, bigDoc2 });
}
for (int i = 0; i < numDocs; ++i)
{
idField.SetStringValue("" + i);
iw.AddDocument(docs[i]);
if (Random.Next(numDocs) == 0)
{
iw.Commit();
}
}
iw.Commit();
iw.ForceMerge(1); // look at what happens when big docs are merged
using (DirectoryReader rd = DirectoryReader.Open(dir))
{
IndexSearcher searcher = new IndexSearcher(rd);
for (int i = 0; i < numDocs; ++i)
{
Query query = new TermQuery(new Term("id", "" + i));
TopDocs topDocs = searcher.Search(query, 1);
Assert.AreEqual(1, topDocs.TotalHits, "" + i);
Document doc = rd.Document(topDocs.ScoreDocs[0].Doc);
Assert.IsNotNull(doc);
IIndexableField[] fieldValues = doc.GetFields("fld");
Assert.AreEqual(docs[i].GetFields("fld").Length, fieldValues.Length);
if (fieldValues.Length > 0)
{
Assert.AreEqual(docs[i].GetFields("fld")[0].GetBinaryValue(), fieldValues[0].GetBinaryValue());
}
}
} // rd.Dispose();
} // iw.Dispose();
} // dir.Dispose();
}
[Test]
public virtual void TestBulkMergeWithDeletes()
{
int numDocs = AtLeast(200);
using (Directory dir = NewDirectory())
{
RandomIndexWriter w = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NoMergePolicy.COMPOUND_FILES));
try
{
for (int i = 0; i < numDocs; ++i)
{
Document doc = new Document();
doc.Add(new StringField("id", Convert.ToString(i, CultureInfo.InvariantCulture), Field.Store.YES));
doc.Add(new StoredField("f", TestUtil.RandomSimpleString(Random)));
w.AddDocument(doc);
}
int deleteCount = TestUtil.NextInt32(Random, 5, numDocs);
for (int i = 0; i < deleteCount; ++i)
{
int id = Random.Next(numDocs);
w.DeleteDocuments(new Term("id", Convert.ToString(id, CultureInfo.InvariantCulture)));
}
w.Commit();
w.Dispose();
w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
w.ForceMerge(TestUtil.NextInt32(Random, 1, 3));
w.Commit();
}
finally
{
w.Dispose();
}
TestUtil.CheckIndex(dir);
} // dir.Dispose();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>KeywordPlan</c> resource.</summary>
public sealed partial class KeywordPlanName : gax::IResourceName, sys::IEquatable<KeywordPlanName>
{
/// <summary>The possible contents of <see cref="KeywordPlanName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
CustomerKeywordPlan = 1,
}
private static gax::PathTemplate s_customerKeywordPlan = new gax::PathTemplate("customers/{customer_id}/keywordPlans/{keyword_plan_id}");
/// <summary>Creates a <see cref="KeywordPlanName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="KeywordPlanName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KeywordPlanName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KeywordPlanName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KeywordPlanName"/> with the pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="KeywordPlanName"/> constructed from the provided ids.</returns>
public static KeywordPlanName FromCustomerKeywordPlan(string customerId, string keywordPlanId) =>
new KeywordPlanName(ResourceNameType.CustomerKeywordPlan, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </returns>
public static string Format(string customerId, string keywordPlanId) =>
FormatCustomerKeywordPlan(customerId, keywordPlanId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanName"/> with pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>.
/// </returns>
public static string FormatCustomerKeywordPlan(string customerId, string keywordPlanId) =>
s_customerKeywordPlan.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId)));
/// <summary>Parses the given resource name string into a new <see cref="KeywordPlanName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="KeywordPlanName"/> if successful.</returns>
public static KeywordPlanName Parse(string keywordPlanName) => Parse(keywordPlanName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="KeywordPlanName"/> if successful.</returns>
public static KeywordPlanName Parse(string keywordPlanName, bool allowUnparsed) =>
TryParse(keywordPlanName, allowUnparsed, out KeywordPlanName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanName, out KeywordPlanName result) =>
TryParse(keywordPlanName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanName, bool allowUnparsed, out KeywordPlanName result)
{
gax::GaxPreconditions.CheckNotNull(keywordPlanName, nameof(keywordPlanName));
gax::TemplatedResourceName resourceName;
if (s_customerKeywordPlan.TryParseName(keywordPlanName, out resourceName))
{
result = FromCustomerKeywordPlan(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(keywordPlanName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private KeywordPlanName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string keywordPlanId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
KeywordPlanId = keywordPlanId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KeywordPlanName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param>
public KeywordPlanName(string customerId, string keywordPlanId) : this(ResourceNameType.CustomerKeywordPlan, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>KeywordPlan</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string KeywordPlanId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerKeywordPlan: return s_customerKeywordPlan.Expand(CustomerId, KeywordPlanId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as KeywordPlanName);
/// <inheritdoc/>
public bool Equals(KeywordPlanName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KeywordPlanName a, KeywordPlanName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KeywordPlanName a, KeywordPlanName b) => !(a == b);
}
public partial class KeywordPlan
{
/// <summary>
/// <see cref="gagvr::KeywordPlanName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal KeywordPlanName ResourceNameAsKeywordPlanName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::KeywordPlanName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::KeywordPlanName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal KeywordPlanName KeywordPlanName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::KeywordPlanName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json
{
/// <summary>
/// Serializes and deserializes objects into and from the JSON format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
/// </summary>
public class JsonSerializer
{
#region Properties
private TypeNameHandling _typeNameHandling;
#pragma warning disable 436
private FormatterAssemblyStyle _typeNameAssemblyFormat;
private PreserveReferencesHandling _preserveReferencesHandling;
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private ObjectCreationHandling _objectCreationHandling;
private NullValueHandling _nullValueHandling;
private DefaultValueHandling _defaultValueHandling;
private ConstructorHandling _constructorHandling;
private JsonConverterCollection _converters;
private IContractResolver _contractResolver;
private IReferenceResolver _referenceResolver;
private SerializationBinder _binder;
private StreamingContext _context;
#pragma warning restore 436
/// <summary>
/// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization.
/// </summary>
public virtual event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
public virtual IReferenceResolver ReferenceResolver
{
get
{
if (_referenceResolver == null)
_referenceResolver = new DefaultReferenceResolver();
return _referenceResolver;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Reference resolver cannot be null.");
_referenceResolver = value;
}
}
#pragma warning disable 436
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
public virtual SerializationBinder Binder
{
get
{
return _binder;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Serialization binder cannot be null.");
_binder = value;
}
}
#pragma warning restore 436
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
public virtual TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling; }
set
{
if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
throw new ArgumentOutOfRangeException("value");
_typeNameHandling = value;
}
}
#pragma warning disable 436
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat; }
set
{
if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
throw new ArgumentOutOfRangeException("value");
_typeNameAssemblyFormat = value;
}
}
#pragma warning restore 436
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
public virtual PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling; }
set
{
if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
throw new ArgumentOutOfRangeException("value");
_preserveReferencesHandling = value;
}
}
/// <summary>
/// Get or set how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
public virtual ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling; }
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
throw new ArgumentOutOfRangeException("value");
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
public virtual MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled during serialization and deserialization.
/// </summary>
public virtual NullValueHandling NullValueHandling
{
get { return _nullValueHandling; }
set
{
if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_nullValueHandling = value;
}
}
/// <summary>
/// Get or set how null default are handled during serialization and deserialization.
/// </summary>
public virtual DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling; }
set
{
if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
throw new ArgumentOutOfRangeException("value");
_defaultValueHandling = value;
}
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public virtual ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling; }
set
{
if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
throw new ArgumentOutOfRangeException("value");
_objectCreationHandling = value;
}
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public virtual ConstructorHandling ConstructorHandling
{
get { return _constructorHandling; }
set
{
if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
throw new ArgumentOutOfRangeException("value");
_constructorHandling = value;
}
}
/// <summary>
/// Gets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value>
public virtual JsonConverterCollection Converters
{
get
{
if (_converters == null)
_converters = new JsonConverterCollection();
return _converters;
}
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
public virtual IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
_contractResolver = DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public virtual StreamingContext Context
{
get { return _context; }
set { _context = value; }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
/// </summary>
public JsonSerializer()
{
_referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling;
_missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling;
_nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling;
_defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling;
_objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling;
_preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling;
_constructorHandling = JsonSerializerSettings.DefaultConstructorHandling;
_typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling;
_context = JsonSerializerSettings.DefaultContext;
_binder = DefaultSerializationBinder.Instance;
}
/// <summary>
/// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
/// <returns>A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = new JsonSerializer();
if (settings != null)
{
if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
jsonSerializer.Converters.AddRange(settings.Converters);
jsonSerializer.TypeNameHandling = settings.TypeNameHandling;
jsonSerializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat;
jsonSerializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
jsonSerializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
jsonSerializer.MissingMemberHandling = settings.MissingMemberHandling;
jsonSerializer.ObjectCreationHandling = settings.ObjectCreationHandling;
jsonSerializer.NullValueHandling = settings.NullValueHandling;
jsonSerializer.DefaultValueHandling = settings.DefaultValueHandling;
jsonSerializer.ConstructorHandling = settings.ConstructorHandling;
jsonSerializer.Context = settings.Context;
if (settings.Error != null)
jsonSerializer.Error += settings.Error;
if (settings.ContractResolver != null)
jsonSerializer.ContractResolver = settings.ContractResolver;
if (settings.ReferenceResolver != null)
jsonSerializer.ReferenceResolver = settings.ReferenceResolver;
if (settings.Binder != null)
jsonSerializer.Binder = settings.Binder;
}
return jsonSerializer;
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(TextReader reader, object target)
{
Populate(new JsonTextReader(reader), target);
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(JsonReader reader, object target)
{
PopulateInternal(reader, target);
}
internal virtual void PopulateInternal(JsonReader reader, object target)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(target, "target");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
serializerReader.Populate(reader, target);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
/// <returns>The <see cref="Object"/> being deserialized.</returns>
public object Deserialize(JsonReader reader)
{
return Deserialize(reader, null);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="StringReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(TextReader reader, Type objectType)
{
return Deserialize(new JsonTextReader(reader), objectType);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
public T Deserialize<T>(JsonReader reader)
{
return (T)Deserialize(reader, typeof(T));
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(JsonReader reader, Type objectType)
{
return DeserializeInternal(reader, objectType);
}
internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
return serializerReader.Deserialize(reader, objectType);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(TextWriter textWriter, object value)
{
Serialize(new JsonTextWriter(textWriter), value);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>.
/// </summary>
/// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(JsonWriter jsonWriter, object value)
{
SerializeInternal(jsonWriter, value);
}
internal virtual void SerializeInternal(JsonWriter jsonWriter, object value)
{
ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this);
serializerWriter.Serialize(jsonWriter, value);
}
internal JsonConverter GetMatchingConverter(Type type)
{
return GetMatchingConverter(_converters, type);
}
internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
{
ValidationUtils.ArgumentNotNull(objectType, "objectType");
if (converters != null)
{
for (int i = 0; i < converters.Count; i++)
{
JsonConverter converter = converters[i];
if (converter.CanConvert(objectType))
return converter;
}
}
return null;
}
internal void OnError(ErrorEventArgs e)
{
EventHandler<ErrorEventArgs> error = Error;
if (error != null)
error(this, e);
}
}
}
#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.
//
/*=============================================================================
**
**
**
** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
=============================================================================*/
namespace System.Threading {
using System;
using System.Security.Permissions;
using System.Runtime;
using System.Runtime.Remoting;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public static class Monitor
{
/*=========================================================================
** Obtain the monitor lock of obj. Will block if another thread holds the lock
** Will not block if the current thread holds the lock,
** however the caller must ensure that the same number of Exit
** calls are made as there were Enter calls.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Enter(Object obj);
// Use a ref bool instead of out to ensure that unverifiable code must
// initialize this value to something. If we used out, the value
// could be uninitialized if we threw an exception in our prolog.
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void Enter(Object obj, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnter(obj, ref lockTaken);
Debug.Assert(lockTaken);
}
private static void ThrowLockTakenException()
{
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnter(Object obj, ref bool lockTaken);
/*=========================================================================
** Release the monitor lock. If one or more threads are waiting to acquire the
** lock, and the current thread has executed as many Exits as
** Enters, one of the threads will be unblocked and allowed to proceed.
**
** Exceptions: ArgumentNullException if object is null.
** SynchronizationLockException if the current thread does not
** own the lock.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void Exit(Object obj);
/*=========================================================================
** Similar to Enter, but will never block. That is, if the current thread can
** acquire the monitor lock without blocking, it will do so and TRUE will
** be returned. Otherwise FALSE will be returned.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
public static bool TryEnter(Object obj)
{
bool lockTaken = false;
TryEnter(obj, 0, ref lockTaken);
return lockTaken;
}
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void TryEnter(Object obj, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, 0, ref lockTaken);
}
/*=========================================================================
** Version of TryEnter that will block, but only up to a timeout period
** expressed in milliseconds. If timeout == Timeout.Infinite the method
** becomes equivalent to Enter.
**
** Exceptions: ArgumentNullException if object is null.
** ArgumentException if timeout < 0.
=========================================================================*/
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static bool TryEnter(Object obj, int millisecondsTimeout)
{
bool lockTaken = false;
TryEnter(obj, millisecondsTimeout, ref lockTaken);
return lockTaken;
}
private static int MillisecondsTimeoutFromTimeSpan(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return (int)tm;
}
public static bool TryEnter(Object obj, TimeSpan timeout)
{
return TryEnter(obj, MillisecondsTimeoutFromTimeSpan(timeout));
}
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, millisecondsTimeout, ref lockTaken);
}
public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken);
public static bool IsEntered(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
return IsEnteredNative(obj);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsEnteredNative(Object obj);
/*========================================================================
** Waits for notification from the object (via a Pulse/PulseAll).
** timeout indicates how long to wait before the method returns.
** This method acquires the monitor waithandle for the object
** If this thread holds the monitor lock for the object, it releases it.
** On exit from the method, it obtains the monitor lock back.
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
**
** Exceptions: ArgumentNullException if object is null.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, Object obj);
public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext)
{
if (obj == null)
throw (new ArgumentNullException(nameof(obj)));
return ObjWait(exitContext, millisecondsTimeout, obj);
}
public static bool Wait(Object obj, TimeSpan timeout, bool exitContext)
{
return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), exitContext);
}
public static bool Wait(Object obj, int millisecondsTimeout)
{
return Wait(obj, millisecondsTimeout, false);
}
public static bool Wait(Object obj, TimeSpan timeout)
{
return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), false);
}
public static bool Wait(Object obj)
{
return Wait(obj, Timeout.Infinite, false);
}
/*========================================================================
** Sends a notification to a single waiting object.
* Exceptions: SynchronizationLockException if this method is not called inside
* a synchronized block of code.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulse(Object obj);
public static void Pulse(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
ObjPulse(obj);
}
/*========================================================================
** Sends a notification to all waiting objects.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulseAll(Object obj);
public static void PulseAll(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
ObjPulseAll(obj);
}
}
}
| |
using System;
using System.IO;
using System.Transactions;
using System.Diagnostics;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using System.Threading;
using System.Workflow.Runtime.Hosting;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using System.Globalization;
namespace System.Workflow.Runtime.Hosting
{
#region PersistenceDBAccessor
internal sealed class PendingWorkItem
{
public enum ItemType { Instance, CompletedScope, ActivationComplete };
public ItemType Type;
public Guid InstanceId;
public Guid StateId;
public Byte[] SerializedActivity;
public int Status;
public int Blocked;
public string Info;
public bool Unlocked;
public SqlDateTime NextTimer;
}
/// <summary>
/// This class does DB accessing work in the context of one connection
/// </summary>
internal sealed class PersistenceDBAccessor : IDisposable
{
DbResourceAllocator dbResourceAllocator;
DbTransaction localTransaction;
DbConnection connection;
bool needToCloseConnection;
DbRetry dbRetry = null;
private class RetryReadException : Exception
{
}
#if DEBUG
private static Dictionary<System.Guid, string> _persistenceToDatabaseMap = new Dictionary<Guid, string>();
private static void InsertToDbMap(Guid serviceId, string dbName)
{
lock (_persistenceToDatabaseMap)
{
if (!_persistenceToDatabaseMap.ContainsKey(serviceId))
{
_persistenceToDatabaseMap[serviceId] = dbName;
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}): writing to database: {1}", serviceId.ToString(), dbName);
}
}
}
#endif
#region Constructor/Disposer
/// <summary>
/// DB access done under a transaction and uses a connection enlisted to this transaction.
/// </summary>
/// <param name="dbResourceAllocator">Helper to get database connection/command/store procedure parameters/etc</param>
/// <param name="transaction">The transaction to do this work under</param>
internal PersistenceDBAccessor(
DbResourceAllocator dbResourceAllocator,
System.Transactions.Transaction transaction,
WorkflowCommitWorkBatchService transactionService)
{
this.dbResourceAllocator = dbResourceAllocator;
this.localTransaction = DbResourceAllocator.GetLocalTransaction(
transactionService, transaction);
// Get a connection enlisted to this transaction, may or may not need to be freed depending on
// if the transaction does connection sharing
this.connection = this.dbResourceAllocator.GetEnlistedConnection(
transactionService, transaction, out needToCloseConnection);
//
// No retries for external transactions
this.dbRetry = new DbRetry(false);
}
/// <summary>
/// DB access done without a transaction in a newly opened connection
/// </summary>
/// <param name="dbResourceAllocator">Helper to get database connection/command/store procedure parameters/etc</param>
internal PersistenceDBAccessor(DbResourceAllocator dbResourceAllocator, bool enableRetries)
{
this.dbResourceAllocator = dbResourceAllocator;
this.dbRetry = new DbRetry(enableRetries);
DbConnection conn = null;
short count = 0;
while (true)
{
try
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService OpenConnection start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
conn = this.dbResourceAllocator.OpenNewConnection();
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService. OpenConnection end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
if ((null == conn) || (ConnectionState.Open != conn.State))
throw new InvalidOperationException(ExecutionStringManager.InvalidConnection);
break;
}
catch (Exception e)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService caught exception from OpenConnection: " + e.ToString());
if (dbRetry.TryDoRetry(ref count))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService retrying.");
continue;
}
throw;
}
}
connection = conn;
needToCloseConnection = true;
}
public void Dispose()
{
if (needToCloseConnection)
{
Debug.Assert(this.connection != null, "No connection to dispose");
this.connection.Dispose();
}
}
#endregion Constructor/Disposer
#region Public Methods Exposed for the Batch to call
private object DbOwnerId(Guid ownerId)
{
// Empty guid signals no lock, but the database uses null for that, so convert empty to null
if (ownerId == Guid.Empty)
return null;
return ownerId;
}
public void InsertInstanceState(PendingWorkItem item, Guid ownerId, DateTime ownedUntil)
{
/* sproc params
@uidInstanceID uniqueidentifier,
@state image,
@status int,
@artifacts image,
@queueingState image,
@unlocked int,
@blocked int,
@info ntext,
@ownerId uniqueidentifier,
@ownedUntil datetime
@nextTimer datetime
*/
DbCommand command = NewStoredProcCommand("InsertInstanceState");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@uidInstanceID", item.InstanceId));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@state", item.SerializedActivity));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@status", item.Status));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@unlocked", item.Unlocked));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@blocked", item.Blocked));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@info", item.Info));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownedUntil", ownedUntil == DateTime.MaxValue ? SqlDateTime.MaxValue : ownedUntil));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownerID", DbOwnerId(ownerId)));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@nextTimer", item.NextTimer));
DbParameter p1 = this.dbResourceAllocator.NewDbParameter();
p1.ParameterName = "@result";
p1.DbType = DbType.Int32;
p1.Value = 0;
p1.Direction = ParameterDirection.InputOutput;
command.Parameters.Add(p1);
//command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@result", DbType.Int32, ParameterDirection.Output));
DbParameter p2 = this.dbResourceAllocator.NewDbParameter();
p2.ParameterName = "@currentOwnerID";
p2.DbType = DbType.Guid;
p2.Value = Guid.Empty;
p2.Direction = ParameterDirection.InputOutput;
command.Parameters.Add(p2);
//command.Parameters.Add(new DbParameter(this.dbResourceAllocator.NewDbParameter("@currentOwnerID", DbType.Guid, ParameterDirection.InputOutput));
#if DEBUG
InsertToDbMap(ownerId, connection.Database);
#endif
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}): inserting instance: {1}, unlocking: {2} database: {3}", ownerId.ToString(), item.InstanceId.ToString(), item.Unlocked.ToString(), connection.Database);
//
// Cannot retry locally here as we don't own the tx
// Rely on external retries at the batch commit or workflow level (for tx scopes)
command.ExecuteNonQuery();
CheckOwnershipResult(command);
}
public void InsertCompletedScope(Guid instanceId, Guid scopeId, Byte[] state)
{
/* sproc params
@completedScopeID uniqueidentifier,
@state image
*/
DbCommand command = NewStoredProcCommand("InsertCompletedScope");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("instanceID", instanceId));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("completedScopeID", scopeId));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("state", state));
//
// Cannot retry locally here as we don't own the tx
// Rely on external retries at the batch commit or workflow level (for tx scopes)
command.ExecuteNonQuery();
}
public void ActivationComplete(Guid instanceId, Guid ownerId)
{
/* sproc params
@instanceID uniqueidentifier,
@ownerID uniqueidentifier,
*/
DbCommand command = NewStoredProcCommand("UnlockInstanceState");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@uidInstanceID", instanceId));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownerID", DbOwnerId(ownerId)));
#if DEBUG
InsertToDbMap(ownerId, connection.Database);
#endif
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}): unlocking instance: {1}, database: {2}", ownerId.ToString(), instanceId.ToString(), connection.Database);
command.ExecuteNonQuery();
}
public IList<Guid> RetrieveNonblockingInstanceStateIds(Guid ownerId, DateTime ownedUntil)
{
List<Guid> gs = null;
DbDataReader dr = null;
short count = 0;
while (true)
{
try
{
//
// Check and reset the connection as needed before building the command
if ((null == connection) || (ConnectionState.Open != connection.State))
ResetConnection();
DbCommand command = NewStoredProcCommand("RetrieveNonblockingInstanceStateIds");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownedUntil", ownedUntil == DateTime.MaxValue ? SqlDateTime.MaxValue : ownedUntil));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownerID", DbOwnerId(ownerId)));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@now", DateTime.UtcNow));
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveNonblockingInstanceStateIds ExecuteReader start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveNonblockingInstanceStateIds ExecuteReader end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
gs = new List<Guid>();
while (dr.Read())
{
gs.Add(dr.GetGuid(0));
}
break;
}
catch (Exception e)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService.RetrieveNonblockingInstanceStateIds caught exception from ExecuteReader: " + e.ToString());
if (dbRetry.TryDoRetry(ref count))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveNonblockingInstanceStateIds retrying.");
continue;
}
throw;
}
finally
{
if (dr != null)
dr.Close();
}
}
return gs;
}
public bool TryRetrieveANonblockingInstanceStateId(Guid ownerId, DateTime ownedUntil, out Guid instanceId)
{
short count = 0;
while (true)
{
try
{
//
// Check and reset the connection as needed before building the command
if ((null == connection) || (ConnectionState.Open != connection.State))
ResetConnection();
DbCommand command = NewStoredProcCommand("RetrieveANonblockingInstanceStateId");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownedUntil", ownedUntil == DateTime.MaxValue ? SqlDateTime.MaxValue : ownedUntil));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownerID", DbOwnerId(ownerId)));
DbParameter p2 = this.dbResourceAllocator.NewDbParameter();
p2.ParameterName = "@uidInstanceID";
p2.DbType = DbType.Guid;
p2.Value = null;
p2.Direction = ParameterDirection.InputOutput;
command.Parameters.Add(p2);
DbParameter found = this.dbResourceAllocator.NewDbParameter();
found.ParameterName = "@found";
found.DbType = DbType.Boolean;
found.Value = null;
found.Direction = ParameterDirection.Output;
command.Parameters.Add(found);
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.TryRetrieveANonblockingInstanceStateId ExecuteNonQuery start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
command.ExecuteNonQuery();
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.TryRetrieveANonblockingInstanceStateId ExecuteNonQuery end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
if ((null != found.Value) && ((bool)found.Value))
{
instanceId = (Guid)p2.Value;
return true;
}
else
{
instanceId = Guid.Empty;
return false;
}
}
catch (Exception e)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService.TryRetrieveANonblockingInstanceStateId caught exception from ExecuteNonQuery: " + e.ToString());
if (dbRetry.TryDoRetry(ref count))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.TryRetrieveANonblockingInstanceStateId retrying.");
continue;
}
throw;
}
}
}
public IList<Guid> RetrieveExpiredTimerIds(Guid ownerId, DateTime ownedUntil)
{
List<Guid> gs = null;
DbDataReader dr = null;
short count = 0;
while (true)
{
try
{
//
// Check and reset the connection as needed before building the command
if ((null == connection) || (ConnectionState.Open != connection.State))
ResetConnection();
DbCommand command = NewStoredProcCommand("RetrieveExpiredTimerIds");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownedUntil", ownedUntil == DateTime.MaxValue ? SqlDateTime.MaxValue : ownedUntil));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownerID", DbOwnerId(ownerId)));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@now", DateTime.UtcNow));
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveExpiredTimerIds ExecuteReader start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveExpiredTimerIds ExecuteReader end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
gs = new List<Guid>();
while (dr.Read())
{
gs.Add(dr.GetGuid(0));
}
break;
}
catch (Exception e)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService.RetrieveExpiredTimerIds caught exception from ExecuteReader: " + e.ToString());
if (dbRetry.TryDoRetry(ref count))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveExpiredTimerIds retrying.");
continue;
}
throw;
}
finally
{
if (dr != null)
dr.Close();
}
}
return gs;
}
public Byte[] RetrieveInstanceState(Guid instanceStateId, Guid ownerId, DateTime timeout)
{
short count = 0;
byte[] state = null;
while (true)
{
try
{
//
// Check and reset the connection as needed before building the command
if ((null == connection) || (ConnectionState.Open != connection.State))
ResetConnection();
DbCommand command = NewStoredProcCommand("RetrieveInstanceState");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@uidInstanceID", instanceStateId));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownerID", DbOwnerId(ownerId)));
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@ownedUntil", timeout == DateTime.MaxValue ? SqlDateTime.MaxValue : timeout));
DbParameter p1 = this.dbResourceAllocator.NewDbParameter();
p1.ParameterName = "@result";
p1.DbType = DbType.Int32;
p1.Value = 0;
p1.Direction = ParameterDirection.InputOutput;
command.Parameters.Add(p1);
//command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@result", DbType.Int32, ParameterDirection.Output));
DbParameter p2 = this.dbResourceAllocator.NewDbParameter();
p2.ParameterName = "@currentOwnerID";
p2.DbType = DbType.Guid;
p2.Value = Guid.Empty;
p2.Direction = ParameterDirection.InputOutput;
command.Parameters.Add(p2);
//command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@currentOwnerID", DbType.Guid, ParameterDirection.InputOutput));
#if DEBUG
InsertToDbMap(ownerId, connection.Database);
#endif
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}): retreiving instance: {1}, database: {2}", ownerId.ToString(), instanceStateId.ToString(), connection.Database);
state = RetrieveStateFromDB(command, true, instanceStateId);
break;
}
catch (Exception e)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService.RetrieveInstanceState caught exception: " + e.ToString());
if (dbRetry.TryDoRetry(ref count))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveInstanceState retrying.");
continue;
}
else if (e is RetryReadException) // ### hardcoded retry to work around sql ADM64 read bug ###
{
count++;
if (count < 10)
continue;
else
break; // give up
}
throw;
}
}
if (state == null || state.Length == 0)
{
Exception e = new InvalidOperationException(string.Format(Thread.CurrentThread.CurrentCulture, ExecutionStringManager.InstanceNotFound, instanceStateId));
e.Data["WorkflowNotFound"] = true;
throw e;
}
return state;
}
public Byte[] RetrieveCompletedScope(Guid scopeId)
{
short count = 0;
byte[] state = null;
while (true)
{
try
{
//
// Check and reset the connection as needed before building the command
if ((null == connection) || (ConnectionState.Open != connection.State))
ResetConnection();
DbCommand command = NewStoredProcCommand("RetrieveCompletedScope");
command.Parameters.Add(this.dbResourceAllocator.NewDbParameter("@completedScopeID", scopeId));
DbParameter p1 = this.dbResourceAllocator.NewDbParameter();
p1.ParameterName = "@result";
p1.DbType = DbType.Int32;
p1.Value = 0;
p1.Direction = ParameterDirection.InputOutput;
command.Parameters.Add(p1);
state = RetrieveStateFromDB(command, false, WorkflowEnvironment.WorkflowInstanceId);
break;
}
catch (Exception e)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService.RetrieveCompletedScope caught exception: " + e.ToString());
if (dbRetry.TryDoRetry(ref count))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveCompletedScope retrying.");
continue;
}
else if (e is RetryReadException) // ### hardcoded retry to work around sql ADM64 read bug ###
{
count++;
if (count < 10)
continue;
else
break; // give up
}
throw;
}
}
if (state == null || state.Length == 0)
throw new InvalidOperationException(
string.Format(Thread.CurrentThread.CurrentCulture,
ExecutionStringManager.CompletedScopeNotFound, scopeId));
return state;
}
#endregion
#region private DB accessing methods
/// <summary>
/// This should only be called for non batch commits
/// </summary>
/// <returns></returns>
private DbConnection ResetConnection()
{
if (null != localTransaction)
throw new InvalidOperationException(ExecutionStringManager.InvalidOpConnectionReset);
if (!needToCloseConnection)
throw new InvalidOperationException(ExecutionStringManager.InvalidOpConnectionNotLocal);
if ((null != connection) && (ConnectionState.Closed != connection.State))
connection.Close();
connection.Dispose();
connection = this.dbResourceAllocator.OpenNewConnection();
return connection;
}
/// <summary>
/// Returns a stored procedure type DBCommand object with current connection and transaction
/// </summary>
/// <param name="commandText"></param>
/// <returns>the command object</returns>
private DbCommand NewStoredProcCommand(string commandText)
{
DbCommand command = DbResourceAllocator.NewCommand(commandText, this.connection, this.localTransaction);
command.CommandType = CommandType.StoredProcedure;
return command;
}
private static void CheckOwnershipResult(DbCommand command)
{
DbParameter result = command.Parameters["@result"];
if (result != null && result.Value != null && (int)result.Value == -2) // -2 is an ownership conflict
{
if (command.Parameters.Contains("@currentOwnerID"))
{
Guid currentOwnerId = Guid.Empty;
if (command.Parameters["@currentOwnerID"].Value is System.Guid)
currentOwnerId = (Guid)command.Parameters["@currentOwnerID"].Value;
Guid myId = (Guid)command.Parameters["@ownerID"].Value;
Guid instId = (Guid)command.Parameters["@uidInstanceID"].Value;
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}): owership violation with {1} on instance {2}", myId.ToString(), currentOwnerId.ToString(), instId);
}
DbParameter instanceId = command.Parameters["@uidInstanceID"];
throw new WorkflowOwnershipException((Guid)instanceId.Value);
}
}
/// <summary>
/// Helper to Public methods RetrieveInstanceState and RetrieveCompletedScope.
/// Retrieves an object from the DB by calling the specified stored procedure with specified stored proc params.
/// </summary>
/// <param name="command">Contains the stored procedure setting to be used to query against the Database</param>
/// <returns>an object to be casted to an activity
/// In case of RetrieveInstanceState, only running or suspended instances are returned and
/// exception is thrown for completed/terminated/not-found instances
/// </returns>
private static Byte[] RetrieveStateFromDB(DbCommand command, bool checkOwnership, Guid instanceId)
{
DbDataReader dr = null;
byte[] result = null;
try
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveStateFromDB {0} ExecuteReader start: {1}", instanceId, DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
dr = command.ExecuteReader();
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveStateFromDB {0} ExecuteReader end: {1}", instanceId, DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
if (dr.Read())
{
result = (byte[])dr.GetValue(0);
}
else
{
DbParameter resultParam = command.Parameters["@result"];
if (resultParam == null || resultParam.Value == null)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService.RetrieveStateFromDB Failed to read results {0}", instanceId);
}
else if ((int)resultParam.Value > 0) // found results but failed to read - sql bug - retry the query
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService.RetrieveStateFromDB Failed to read results {1}, @result == {0}", (int)resultParam.Value, instanceId);
throw new RetryReadException();
}
}
}
finally
{
if (dr != null)
dr.Close();
}
if (checkOwnership)
CheckOwnershipResult(command);
return result;
}
#endregion private DB accessing methods
internal IEnumerable<SqlPersistenceWorkflowInstanceDescription> RetrieveAllInstanceDescriptions()
{
List<SqlPersistenceWorkflowInstanceDescription> retval = new List<SqlPersistenceWorkflowInstanceDescription>();
DbDataReader dr = null;
try
{
DbCommand command = NewStoredProcCommand("RetrieveAllInstanceDescriptions");
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
retval.Add(new SqlPersistenceWorkflowInstanceDescription(
dr.GetGuid(0),
(WorkflowStatus)dr.GetInt32(1),
dr.GetInt32(2) == 1 ? true : false,
dr.GetString(3),
(SqlDateTime)dr.GetDateTime(4)
));
}
}
finally
{
if (dr != null)
dr.Close();
}
return retval;
}
}
#endregion
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class SqlWorkflowPersistenceService : WorkflowPersistenceService, IPendingWork
{
#region constants
// Configure parameters for this services
private const string InstanceOwnershipTimeoutSecondsToken = "OwnershipTimeoutSeconds";
private const string UnloadOnIdleToken = "UnloadOnIdle";
private const string EnableRetriesToken = "EnableRetries";
#endregion constants
private bool _enableRetries = false;
private bool _ignoreCommonEnableRetries = false;
private DbResourceAllocator _dbResourceAllocator;
private WorkflowCommitWorkBatchService _transactionService;
private Guid _serviceInstanceId = Guid.Empty;
private TimeSpan _ownershipDelta;
private Boolean _unloadOnIdle;
const string LoadingIntervalToken = "LoadIntervalSeconds";
TimeSpan loadingInterval = new TimeSpan(0, 2, 0);
private TimeSpan maxLoadingInterval = new TimeSpan(365, 0, 0, 0, 0);
SmartTimer loadingTimer;
object timerLock = new object();
TimeSpan infinite = new TimeSpan(Timeout.Infinite);
private static int _deadlock = 1205;
// Saved from constructor input to be used in service start initialization
NameValueCollection configParameters;
string unvalidatedConnectionString;
public Guid ServiceInstanceId
{
get
{
return _serviceInstanceId;
}
}
public TimeSpan LoadingInterval
{
get { return loadingInterval; }
}
public bool EnableRetries
{
get { return _enableRetries; }
set
{
_enableRetries = value;
_ignoreCommonEnableRetries = true;
}
}
private DateTime OwnershipTimeout
{
get
{
DateTime timeout;
if (_ownershipDelta == TimeSpan.MaxValue)
timeout = DateTime.MaxValue;
else
timeout = DateTime.UtcNow + _ownershipDelta;
return timeout;
}
}
public SqlWorkflowPersistenceService(string connectionString)
{
if (String.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString", ExecutionStringManager.MissingConnectionString);
this.unvalidatedConnectionString = connectionString;
}
public SqlWorkflowPersistenceService(NameValueCollection parameters)
{
if (parameters == null)
throw new ArgumentNullException("parameters", ExecutionStringManager.MissingParameters);
_ownershipDelta = TimeSpan.MaxValue; // default is to never timeout
if (parameters != null)
{
foreach (string key in parameters.Keys)
{
if (key.Equals(DbResourceAllocator.ConnectionStringToken, StringComparison.OrdinalIgnoreCase))
{
// the resource allocator (below) will process the connection string
}
else if (key.Equals(SqlWorkflowPersistenceService.InstanceOwnershipTimeoutSecondsToken, StringComparison.OrdinalIgnoreCase))
{
int seconds = Convert.ToInt32(parameters[SqlWorkflowPersistenceService.InstanceOwnershipTimeoutSecondsToken], System.Globalization.CultureInfo.CurrentCulture);
if (seconds < 0)
throw new ArgumentOutOfRangeException(InstanceOwnershipTimeoutSecondsToken, seconds, ExecutionStringManager.InvalidOwnershipTimeoutValue);
_ownershipDelta = new TimeSpan(0, 0, seconds);
_serviceInstanceId = Guid.NewGuid();
continue;
}
else if (key.Equals(SqlWorkflowPersistenceService.UnloadOnIdleToken, StringComparison.OrdinalIgnoreCase))
{
_unloadOnIdle = bool.Parse(parameters[key]);
}
else if (key.Equals(LoadingIntervalToken, StringComparison.OrdinalIgnoreCase))
{
int interval = int.Parse(parameters[key], CultureInfo.CurrentCulture);
if (interval > 0)
this.loadingInterval = new TimeSpan(0, 0, interval);
else
this.loadingInterval = TimeSpan.Zero;
if (this.loadingInterval > maxLoadingInterval)
throw new ArgumentOutOfRangeException(LoadingIntervalToken, this.LoadingInterval, ExecutionStringManager.LoadingIntervalTooLarge);
}
else if (key.Equals(SqlWorkflowPersistenceService.EnableRetriesToken, StringComparison.OrdinalIgnoreCase))
{
//
// We have a local value for enable retries
_enableRetries = bool.Parse(parameters[key]);
_ignoreCommonEnableRetries = true;
}
else
{
throw new ArgumentException(
String.Format(Thread.CurrentThread.CurrentCulture, ExecutionStringManager.UnknownConfigurationParameter, key), "parameters");
}
}
}
this.configParameters = parameters;
}
public SqlWorkflowPersistenceService(string connectionString, bool unloadOnIdle, TimeSpan instanceOwnershipDuration, TimeSpan loadingInterval)
{
if (String.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString", ExecutionStringManager.MissingConnectionString);
if (loadingInterval > maxLoadingInterval)
throw new ArgumentOutOfRangeException("loadingInterval", loadingInterval, ExecutionStringManager.LoadingIntervalTooLarge);
if (instanceOwnershipDuration < TimeSpan.Zero)
throw new ArgumentOutOfRangeException("instanceOwnershipDuration", instanceOwnershipDuration, ExecutionStringManager.InvalidOwnershipTimeoutValue);
this._ownershipDelta = instanceOwnershipDuration;
this._unloadOnIdle = unloadOnIdle;
this.loadingInterval = loadingInterval;
this.unvalidatedConnectionString = connectionString;
_serviceInstanceId = Guid.NewGuid();
}
#region WorkflowRuntimeService
override protected internal void Start()
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({1}): Starting, LoadInternalSeconds={0}", loadingInterval.TotalSeconds, _serviceInstanceId.ToString());
_dbResourceAllocator = new DbResourceAllocator(this.Runtime, this.configParameters, this.unvalidatedConnectionString);
// Check connection string mismatch if using SharedConnectionWorkflowTransactionService
_transactionService = Runtime.GetService<WorkflowCommitWorkBatchService>();
_dbResourceAllocator.DetectSharedConnectionConflict(_transactionService);
//
// If we didn't find a local value for enable retries
// check in the common section
if ((!_ignoreCommonEnableRetries) && (null != base.Runtime))
{
NameValueConfigurationCollection commonConfigurationParameters = base.Runtime.CommonParameters;
if (commonConfigurationParameters != null)
{
// Then scan for connection string in the common configuration parameters section
foreach (string key in commonConfigurationParameters.AllKeys)
{
if (string.Compare(EnableRetriesToken, key, StringComparison.OrdinalIgnoreCase) == 0)
{
_enableRetries = bool.Parse(commonConfigurationParameters[key].Value);
break;
}
}
}
}
base.Start();
}
protected override void OnStarted()
{
if (loadingInterval > TimeSpan.Zero)
{
lock (timerLock)
{
base.OnStarted();
loadingTimer = new SmartTimer(new TimerCallback(LoadWorkflowsWithExpiredTimers), null, loadingInterval, loadingInterval);
}
}
RecoverRunningWorkflowInstances();
}
protected internal override void Stop()
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}): Stopping", _serviceInstanceId.ToString());
lock (timerLock)
{
base.Stop();
if (loadingTimer != null)
{
loadingTimer.Dispose();
loadingTimer = null;
}
}
}
#endregion WorkflowRuntimeService
private void RecoverRunningWorkflowInstances()
{
if (Guid.Empty == _serviceInstanceId)
{
//
// Only one host, get all the ids in one go
IList<Guid> instanceIds = null;
using (PersistenceDBAccessor persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, _enableRetries))
{
instanceIds = persistenceDBAccessor.RetrieveNonblockingInstanceStateIds(_serviceInstanceId, OwnershipTimeout);
}
foreach (Guid instanceId in instanceIds)
{
try
{
WorkflowInstance instance = Runtime.GetWorkflow(instanceId);
instance.Load();
}
catch (Exception e)
{
RaiseServicesExceptionNotHandledEvent(e, instanceId);
}
}
}
else
{
using (PersistenceDBAccessor persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, _enableRetries))
{
//
// Load one at a time to avoid thrashing with other hosts
Guid instanceId;
while (persistenceDBAccessor.TryRetrieveANonblockingInstanceStateId(_serviceInstanceId, OwnershipTimeout, out instanceId))
{
try
{
WorkflowInstance instance = Runtime.GetWorkflow(instanceId);
instance.Load();
}
catch (Exception e)
{
RaiseServicesExceptionNotHandledEvent(e, instanceId);
}
}
}
}
}
private void LoadWorkflowsWithExpiredTimers(object ignored)
{
lock (timerLock)
{
if (this.State == WorkflowRuntimeServiceState.Started)
{
IList<Guid> ids = null;
try
{
ids = LoadExpiredTimerIds();
}
catch (Exception e)
{
RaiseServicesExceptionNotHandledEvent(e, Guid.Empty);
}
if (ids != null)
{
foreach (Guid id in ids)
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({1}): Loading instance with expired timers {0}", id, _serviceInstanceId.ToString());
try
{
Runtime.GetWorkflow(id).Load();
}
// Ignore cases where the workflow has been stolen out from under us
catch (WorkflowOwnershipException)
{ }
catch (ObjectDisposedException)
{
throw;
}
catch (InvalidOperationException ioe)
{
if (!ioe.Data.Contains("WorkflowNotFound"))
RaiseServicesExceptionNotHandledEvent(ioe, id);
}
catch (Exception e)
{
RaiseServicesExceptionNotHandledEvent(e, id);
}
}
}
}
}
}
// uidInstanceID, status, blocked, info, nextTimer
internal protected override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock)
{
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
WorkflowStatus workflowStatus = WorkflowPersistenceService.GetWorkflowStatus(rootActivity);
bool isInstanceBlocked = WorkflowPersistenceService.GetIsBlocked(rootActivity);
string instanceInfo = WorkflowPersistenceService.GetSuspendOrTerminateInfo(rootActivity);
Guid contextGuid = (Guid)rootActivity.GetValue(Activity.ActivityContextGuidProperty);
PendingWorkItem item = new PendingWorkItem();
item.Type = PendingWorkItem.ItemType.Instance;
item.InstanceId = WorkflowEnvironment.WorkflowInstanceId;
if (workflowStatus != WorkflowStatus.Completed && workflowStatus != WorkflowStatus.Terminated)
item.SerializedActivity = WorkflowPersistenceService.GetDefaultSerializedForm(rootActivity);
else
item.SerializedActivity = new Byte[0];
item.Status = (int)workflowStatus;
item.Blocked = isInstanceBlocked ? 1 : 0;
item.Info = instanceInfo;
item.StateId = contextGuid;
item.Unlocked = unlock;
TimerEventSubscriptionCollection timers = (TimerEventSubscriptionCollection)rootActivity.GetValue(TimerEventSubscriptionCollection.TimerCollectionProperty);
Debug.Assert(timers != null, "TimerEventSubscriptionCollection should never be null, but it is");
TimerEventSubscription sub = timers.Peek();
item.NextTimer = sub == null ? SqlDateTime.MaxValue : sub.ExpiresAt;
if (item.Info == null)
item.Info = "";
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({4}):Committing instance {0}, Blocked={1}, Unlocked={2}, NextTimer={3}", contextGuid.ToString(), item.Blocked, item.Unlocked, item.NextTimer.Value.ToLocalTime(), _serviceInstanceId.ToString());
WorkflowEnvironment.WorkBatch.Add(this, item);
}
internal protected override void UnlockWorkflowInstanceState(Activity rootActivity)
{
PendingWorkItem item = new PendingWorkItem();
item.Type = PendingWorkItem.ItemType.ActivationComplete;
item.InstanceId = WorkflowEnvironment.WorkflowInstanceId;
WorkflowEnvironment.WorkBatch.Add(this, item);
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}):Unlocking instance {1}", _serviceInstanceId.ToString(), item.InstanceId.ToString());
}
internal protected override Activity LoadWorkflowInstanceState(Guid id)
{
using (PersistenceDBAccessor persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, _enableRetries))
{
WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({0}):Loading instance {1}", _serviceInstanceId.ToString(), id.ToString());
byte[] state = persistenceDBAccessor.RetrieveInstanceState(id, _serviceInstanceId, OwnershipTimeout);
return WorkflowPersistenceService.RestoreFromDefaultSerializedForm(state, null);
}
}
public IList<Guid> LoadExpiredTimerWorkflowIds()
{
if (State == WorkflowRuntimeServiceState.Started)
{
return LoadExpiredTimerIds();
}
else
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.WorkflowRuntimeNotStarted));
}
}
private IList<Guid> LoadExpiredTimerIds()
{
using (PersistenceDBAccessor persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, _enableRetries))
{
return persistenceDBAccessor.RetrieveExpiredTimerIds(_serviceInstanceId, OwnershipTimeout);
}
}
internal protected override void SaveCompletedContextActivity(Activity completedScopeActivity)
{
PendingWorkItem item = new PendingWorkItem();
item.Type = PendingWorkItem.ItemType.CompletedScope;
item.SerializedActivity = WorkflowPersistenceService.GetDefaultSerializedForm(completedScopeActivity);
item.InstanceId = WorkflowEnvironment.WorkflowInstanceId;
item.StateId = ((ActivityExecutionContextInfo)completedScopeActivity.GetValue(Activity.ActivityExecutionContextInfoProperty)).ContextGuid;
WorkflowEnvironment.WorkBatch.Add(this, item);
}
internal protected override Activity LoadCompletedContextActivity(Guid id, Activity outerActivity)
{
using (PersistenceDBAccessor persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, _enableRetries))
{
byte[] state = persistenceDBAccessor.RetrieveCompletedScope(id);
return WorkflowPersistenceService.RestoreFromDefaultSerializedForm(state, outerActivity);
}
}
internal protected override bool UnloadOnIdle(Activity activity)
{
return _unloadOnIdle;
}
public IEnumerable<SqlPersistenceWorkflowInstanceDescription> GetAllWorkflows()
{
if (State == WorkflowRuntimeServiceState.Started)
{
using (PersistenceDBAccessor persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, _enableRetries))
{
return persistenceDBAccessor.RetrieveAllInstanceDescriptions();
}
}
else
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.WorkflowRuntimeNotStarted));
}
}
#region IPendingWork methods
bool IPendingWork.MustCommit(ICollection items)
{
return true;
}
/// <summary>
/// Commmit the work items using the transaction
/// </summary>
/// <param name="transaction"></param>
/// <param name="items"></param>
void IPendingWork.Commit(System.Transactions.Transaction transaction, ICollection items)
{
PersistenceDBAccessor persistenceDBAccessor = null;
try
{
persistenceDBAccessor = new PersistenceDBAccessor(_dbResourceAllocator, transaction, _transactionService);
foreach (PendingWorkItem item in items)
{
switch (item.Type)
{
case PendingWorkItem.ItemType.Instance:
persistenceDBAccessor.InsertInstanceState(item, _serviceInstanceId, OwnershipTimeout);
break;
case PendingWorkItem.ItemType.CompletedScope:
persistenceDBAccessor.InsertCompletedScope(item.InstanceId, item.StateId, item.SerializedActivity);
break;
case PendingWorkItem.ItemType.ActivationComplete:
persistenceDBAccessor.ActivationComplete(item.InstanceId, _serviceInstanceId);
break;
default:
Debug.Assert(false, "Committing unknown pending work item type in SqlPersistenceService.Commit()");
break;
}
}
}
catch (SqlException se)
{
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService({1})Exception thrown while persisting instance: {0}", se.Message, _serviceInstanceId.ToString());
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0, "stacktrace : {0}", se.StackTrace);
if (se.Number == _deadlock)
{
PersistenceException pe = new PersistenceException(se.Message, se);
throw pe;
}
else
{
throw;
}
}
catch (Exception e)
{
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0, "SqlWorkflowPersistenceService({1}): Exception thrown while persisting instance: {0}", e.Message, _serviceInstanceId.ToString());
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0, "stacktrace : {0}", e.StackTrace);
throw e;
}
finally
{
if (persistenceDBAccessor != null)
persistenceDBAccessor.Dispose();
}
}
/// <summary>
/// Perform necesssary cleanup. Called when the scope
/// has finished processing this batch of work items
/// </summary>
/// <param name="succeeded"></param>
/// <param name="items"></param>
void IPendingWork.Complete(bool succeeded, ICollection items)
{
if (loadingTimer != null && succeeded)
{
foreach (PendingWorkItem item in items)
{
if (item.Type.Equals(PendingWorkItem.ItemType.Instance))
{
loadingTimer.Update((DateTime)item.NextTimer);
}
}
}
}
#endregion IPendingWork Methods
}
internal class SmartTimer : IDisposable
{
private object locker = new object();
private Timer timer;
private DateTime next;
private bool nextChanged;
private TimeSpan period;
private TimerCallback callback;
private TimeSpan minUpdate = new TimeSpan(0, 0, 5);
private TimeSpan infinite = new TimeSpan(Timeout.Infinite);
public SmartTimer(TimerCallback callback, object state, TimeSpan due, TimeSpan period)
{
this.period = period;
this.callback = callback;
this.next = DateTime.UtcNow + due;
this.timer = new Timer(HandleCallback, state, due, infinite);
}
public void Update(DateTime newNext)
{
if (newNext < next && (next - DateTime.UtcNow) > minUpdate)
{
lock (locker)
{
if (newNext < next && (next - DateTime.UtcNow) > minUpdate && timer != null)
{
next = newNext;
nextChanged = true;
TimeSpan when = next - DateTime.UtcNow;
if (when < TimeSpan.Zero)
when = TimeSpan.Zero;
timer.Change(when, infinite);
}
}
}
}
private void HandleCallback(object state)
{
try
{
callback(state);
}
finally
{
lock (locker)
{
if (timer != null)
{
if (!nextChanged)
next = DateTime.UtcNow + period;
else
nextChanged = false;
TimeSpan when = next - DateTime.UtcNow;
if (when < TimeSpan.Zero)
when = TimeSpan.Zero;
timer.Change(when, infinite);
}
}
}
}
public void Dispose()
{
lock (locker)
{
if (timer != null)
{
timer.Dispose();
timer = null;
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Threading;
namespace OpenSim.Region.CoreModules.World.Land
{
public class ParcelCounts
{
public int Owner = 0;
public int Group = 0;
public int Others = 0;
public int Selected = 0;
public Dictionary <UUID, int> Users = new Dictionary <UUID, int>();
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PrimCountModule")]
public class PrimCountModule : IPrimCountModule, INonSharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_Scene;
private Dictionary<UUID, PrimCounts> m_PrimCounts =
new Dictionary<UUID, PrimCounts>();
private Dictionary<UUID, UUID> m_OwnerMap =
new Dictionary<UUID, UUID>();
private Dictionary<UUID, int> m_SimwideCounts =
new Dictionary<UUID, int>();
private Dictionary<UUID, ParcelCounts> m_ParcelCounts =
new Dictionary<UUID, ParcelCounts>();
/// <value>
/// For now, a simple simwide taint to get this up. Later parcel based
/// taint to allow recounting a parcel if only ownership has changed
/// without recounting the whole sim.
///
/// We start out tainted so that the first get call resets the various prim counts.
/// </value>
private bool m_Tainted = true;
private ReaderWriterLock m_TaintLock = new ReaderWriterLock();
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
m_Scene.RegisterModuleInterface<IPrimCountModule>(this);
m_Scene.EventManager.OnObjectAddedToScene += OnParcelPrimCountAdd;
m_Scene.EventManager.OnObjectBeingRemovedFromScene +=
OnObjectBeingRemovedFromScene;
m_Scene.EventManager.OnParcelPrimCountTainted +=
OnParcelPrimCountTainted;
m_Scene.EventManager.OnLandObjectAdded += delegate(ILandObject lo) { OnParcelPrimCountTainted(); };
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "PrimCountModule"; }
}
private void OnParcelPrimCountAdd(SceneObjectGroup obj)
{
// If we're tainted already, don't bother to add. The next
// access will cause a recount anyway
if (!m_Tainted)
{
m_TaintLock.AcquireWriterLock(-1);
try
{
AddObject(obj);
}
finally
{
m_TaintLock.ReleaseWriterLock();
}
}
// else
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: Ignoring OnParcelPrimCountAdd() for {0} on {1} since count is tainted",
// obj.Name, m_Scene.RegionInfo.RegionName);
}
private void OnObjectBeingRemovedFromScene(SceneObjectGroup obj)
{
// Don't bother to update tainted counts
if (!m_Tainted)
RemoveObject(obj);
// else
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: Ignoring OnObjectBeingRemovedFromScene() for {0} on {1} since count is tainted",
// obj.Name, m_Scene.RegionInfo.RegionName);
}
private void OnParcelPrimCountTainted()
{
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: OnParcelPrimCountTainted() called on {0}", m_Scene.RegionInfo.RegionName);
m_Tainted = true;
}
public void TaintPrimCount(ILandObject land)
{
m_Tainted = true;
}
public void TaintPrimCount(int x, int y)
{
m_Tainted = true;
}
public void TaintPrimCount()
{
m_Tainted = true;
}
// NOTE: Call under Taint Lock
private void AddObject(SceneObjectGroup obj)
{
if (obj.IsAttachment)
return;
if (((obj.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0))
return;
Vector3 pos = obj.AbsolutePosition;
ILandObject landObject = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y);
// If for some reason there is no land object (perhaps the object is out of bounds) then we can't count it
if (landObject == null)
{
// m_log.WarnFormat(
// "[PRIM COUNT MODULE]: Found no land object for {0} at position ({1}, {2}) on {3}",
// obj.Name, pos.X, pos.Y, m_Scene.RegionInfo.RegionName);
return;
}
LandData landData = landObject.LandData;
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: Adding object {0} with {1} parts to prim count for parcel {2} on {3}",
// obj.Name, obj.Parts.Length, landData.Name, m_Scene.RegionInfo.RegionName);
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: Object {0} is owned by {1} over land owned by {2}",
// obj.Name, obj.OwnerID, landData.OwnerID);
ParcelCounts parcelCounts;
if (m_ParcelCounts.TryGetValue(landData.GlobalID, out parcelCounts))
{
UUID landOwner = landData.OwnerID;
int partCount = obj.Parts.Length;
m_SimwideCounts[landOwner] += partCount;
if (parcelCounts.Users.ContainsKey(obj.OwnerID))
parcelCounts.Users[obj.OwnerID] += partCount;
else
parcelCounts.Users[obj.OwnerID] = partCount;
if (obj.IsSelected)
{
parcelCounts.Selected += partCount;
}
else
{
if (landData.IsGroupOwned)
{
if (obj.OwnerID == landData.GroupID)
parcelCounts.Owner += partCount;
else if (landData.GroupID != UUID.Zero && obj.GroupID == landData.GroupID)
parcelCounts.Group += partCount;
else
parcelCounts.Others += partCount;
}
else
{
if (obj.OwnerID == landData.OwnerID)
parcelCounts.Owner += partCount;
else
parcelCounts.Others += partCount;
}
}
}
}
// NOTE: Call under Taint Lock
private void RemoveObject(SceneObjectGroup obj)
{
// m_log.DebugFormat("[PRIM COUNT MODULE]: Removing object {0} {1} from prim count", obj.Name, obj.UUID);
// Currently this is being done by tainting the count instead.
}
public IPrimCounts GetPrimCounts(UUID parcelID)
{
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetPrimCounts for parcel {0} in {1}", parcelID, m_Scene.RegionInfo.RegionName);
PrimCounts primCounts;
lock (m_PrimCounts)
{
if (m_PrimCounts.TryGetValue(parcelID, out primCounts))
return primCounts;
primCounts = new PrimCounts(parcelID, this);
m_PrimCounts[parcelID] = primCounts;
}
return primCounts;
}
/// <summary>
/// Get the number of prims on the parcel that are owned by the parcel owner.
/// </summary>
/// <param name="parcelID"></param>
/// <returns></returns>
public int GetOwnerCount(UUID parcelID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
count = counts.Owner;
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetOwnerCount for parcel {0} in {1} returning {2}",
// parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
/// <summary>
/// Get the number of prims on the parcel that have been set to the group that owns the parcel.
/// </summary>
/// <param name="parcelID"></param>
/// <returns></returns>
public int GetGroupCount(UUID parcelID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
count = counts.Group;
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetGroupCount for parcel {0} in {1} returning {2}",
// parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
/// <summary>
/// Get the number of prims on the parcel that are not owned by the parcel owner or set to the parcel group.
/// </summary>
/// <param name="parcelID"></param>
/// <returns></returns>
public int GetOthersCount(UUID parcelID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
count = counts.Others;
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetOthersCount for parcel {0} in {1} returning {2}",
// parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
/// <summary>
/// Get the number of selected prims.
/// </summary>
/// <param name="parcelID"></param>
/// <returns></returns>
public int GetSelectedCount(UUID parcelID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
count = counts.Selected;
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetSelectedCount for parcel {0} in {1} returning {2}",
// parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
/// <summary>
/// Get the total count of owner, group and others prims on the parcel.
/// FIXME: Need to do selected prims once this is reimplemented.
/// </summary>
/// <param name="parcelID"></param>
/// <returns></returns>
public int GetTotalCount(UUID parcelID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
{
count = counts.Owner;
count += counts.Group;
count += counts.Others;
count += counts.Selected;
}
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetTotalCount for parcel {0} in {1} returning {2}",
// parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
/// <summary>
/// Get the number of prims that are in the entire simulator for the owner of this parcel.
/// </summary>
/// <param name="parcelID"></param>
/// <returns></returns>
public int GetSimulatorCount(UUID parcelID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
UUID owner;
if (m_OwnerMap.TryGetValue(parcelID, out owner))
{
int val;
if (m_SimwideCounts.TryGetValue(owner, out val))
count = val;
}
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetOthersCount for parcel {0} in {1} returning {2}",
// parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
/// <summary>
/// Get the number of prims that a particular user owns on this parcel.
/// </summary>
/// <param name="parcelID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public int GetUserCount(UUID parcelID, UUID userID)
{
int count = 0;
m_TaintLock.AcquireReaderLock(-1);
try
{
if (m_Tainted)
{
LockCookie lc = m_TaintLock.UpgradeToWriterLock(-1);
try
{
Recount();
}
finally
{
m_TaintLock.DowngradeFromWriterLock(ref lc);
}
}
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
{
int val;
if (counts.Users.TryGetValue(userID, out val))
count = val;
}
}
finally
{
m_TaintLock.ReleaseReaderLock();
}
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: GetUserCount for user {0} in parcel {1} in region {2} returning {3}",
// userID, parcelID, m_Scene.RegionInfo.RegionName, count);
return count;
}
// NOTE: This method MUST be called while holding the taint lock!
private void Recount()
{
// m_log.DebugFormat("[PRIM COUNT MODULE]: Recounting prims on {0}", m_Scene.RegionInfo.RegionName);
m_OwnerMap.Clear();
m_SimwideCounts.Clear();
m_ParcelCounts.Clear();
List<ILandObject> land = m_Scene.LandChannel.AllParcels();
foreach (ILandObject l in land)
{
LandData landData = l.LandData;
m_OwnerMap[landData.GlobalID] = landData.OwnerID;
m_SimwideCounts[landData.OwnerID] = 0;
// m_log.DebugFormat(
// "[PRIM COUNT MODULE]: Initializing parcel count for {0} on {1}",
// landData.Name, m_Scene.RegionInfo.RegionName);
m_ParcelCounts[landData.GlobalID] = new ParcelCounts();
}
m_Scene.ForEachSOG(AddObject);
lock (m_PrimCounts)
{
List<UUID> primcountKeys = new List<UUID>(m_PrimCounts.Keys);
foreach (UUID k in primcountKeys)
{
if (!m_OwnerMap.ContainsKey(k))
m_PrimCounts.Remove(k);
}
}
m_Tainted = false;
}
}
public class PrimCounts : IPrimCounts
{
private PrimCountModule m_Parent;
private UUID m_ParcelID;
private UserPrimCounts m_UserPrimCounts;
public PrimCounts (UUID parcelID, PrimCountModule parent)
{
m_ParcelID = parcelID;
m_Parent = parent;
m_UserPrimCounts = new UserPrimCounts(this);
}
public int Owner
{
get
{
return m_Parent.GetOwnerCount(m_ParcelID);
}
}
public int Group
{
get
{
return m_Parent.GetGroupCount(m_ParcelID);
}
}
public int Others
{
get
{
return m_Parent.GetOthersCount(m_ParcelID);
}
}
public int Selected
{
get
{
return m_Parent.GetSelectedCount(m_ParcelID);
}
}
public int Total
{
get
{
return m_Parent.GetTotalCount(m_ParcelID);
}
}
public int Simulator
{
get
{
return m_Parent.GetSimulatorCount(m_ParcelID);
}
}
public IUserPrimCounts Users
{
get
{
return m_UserPrimCounts;
}
}
public int GetUserCount(UUID userID)
{
return m_Parent.GetUserCount(m_ParcelID, userID);
}
}
public class UserPrimCounts : IUserPrimCounts
{
private PrimCounts m_Parent;
public UserPrimCounts(PrimCounts parent)
{
m_Parent = parent;
}
public int this[UUID userID]
{
get
{
return m_Parent.GetUserCount(userID);
}
}
}
}
| |
//
// Julian.cs
//
// This class encapsulates a Julian date system where the day starts at noon.
// Some Julian dates:
// 01/01/1990 00:00 UTC - 2447892.5
// 01/01/1990 12:00 UTC - 2447893.0
// 01/01/2000 00:00 UTC - 2451544.5
// 01/01/2001 00:00 UTC - 2451910.5
//
// The Julian day begins at noon, which allows astronomers to have the
// same date in a single observing session.
//
// References:
// "Astronomical Formulae for Calculators", Jean Meeus, 4th Edition
// "Satellite Communications", Dennis Roddy, 2nd Edition, 1995.
// "Spacecraft Attitude Determination and Control", James R. Wertz, 1984
//
// Copyright (c) 2003-2012 Michael F. Henry
// Version 05/2012
//
using System;
namespace Zeptomoby.OrbitTools
{
/// <summary>
/// Encapsulates a Julian date.
/// </summary>
public class Julian
{
private const double EPOCH_JAN0_12H_1900 = 2415020.0; // Dec 31.5 1899 = Dec 31 1899 12h UTC
private const double EPOCH_JAN1_00H_1900 = 2415020.5; // Jan 1.0 1900 = Jan 1 1900 00h UTC
private const double EPOCH_JAN1_12H_1900 = 2415021.0; // Jan 1.5 1900 = Jan 1 1900 12h UTC
private const double EPOCH_JAN1_12H_2000 = 2451545.0; // Jan 1.5 2000 = Jan 1 2000 12h UTC
private double m_Date; // Julian date
private int m_Year; // Year including century
private double m_Day; // Day of year, 1.0 = Jan 1 00h
#region Construction
/// <summary>
/// Create a Julian date object from a DateTime object. The time
/// contained in the DateTime object is assumed to be UTC.
/// </summary>
/// <param name="utc">The UTC time to convert.</param>
public Julian(DateTime utc)
{
double day = utc.DayOfYear +
(utc.Hour +
((utc.Minute +
((utc.Second + (utc.Millisecond / 1000.0)) / 60.0)) / 60.0)) / 24.0;
Initialize(utc.Year, day);
}
/// <summary>
/// Create a Julian date object given a year and day-of-year.
/// </summary>
/// <param name="year">The year, including the century (i.e., 2012).</param>
/// <param name="doy">Day of year (1 means January 1, etc.).</param>
/// <remarks>
/// The fractional part of the day value is the fractional portion of
/// the day.
/// Examples:
/// day = 1.0 Jan 1 00h
/// day = 1.5 Jan 1 12h
/// day = 2.0 Jan 2 00h
/// </remarks>
public Julian(int year, double doy)
{
Initialize(year, doy);
}
#endregion
#region Properties
public double Date { get { return m_Date; } }
public double FromJan0_12h_1900() { return m_Date - EPOCH_JAN0_12H_1900; }
public double FromJan1_00h_1900() { return m_Date - EPOCH_JAN1_00H_1900; }
public double FromJan1_12h_1900() { return m_Date - EPOCH_JAN1_12H_1900; }
public double FromJan1_12h_2000() { return m_Date - EPOCH_JAN1_12H_2000; }
#endregion
/// <summary>
/// Calculates the time difference between two Julian dates.
/// </summary>
/// <param name="date">Julian date.</param>
/// <returns>
/// A TimeSpan representing the time difference between the two dates.
/// </returns>
public TimeSpan Diff(Julian date)
{
const double TICKS_PER_DAY = 8.64e11; // 1 tick = 100 nanoseconds
return new TimeSpan((long)((m_Date - date.m_Date) * TICKS_PER_DAY));
}
/// <summary>
/// Initialize the Julian date object.
/// </summary>
/// <param name="year">The year, including the century.</param>
/// <param name="doy">Day of year (1 means January 1, etc.)</param>
/// <remarks>
/// The first day of the year, Jan 1, is day 1.0. Noon on Jan 1 is
/// represented by the day value of 1.5, etc.
/// </remarks>
protected void Initialize(int year, double doy)
{
// Arbitrary years used for error checking
if (year < 1900 || year > 2100)
{
throw new ArgumentOutOfRangeException("year");
}
// The last day of a leap year is day 366
if (doy < 1.0 || doy >= 367.0)
{
throw new ArgumentOutOfRangeException("doy");
}
m_Year = year;
m_Day = doy;
// Now calculate Julian date
// Ref: "Astronomical Formulae for Calculators", Jean Meeus, pages 23-25
year--;
// Centuries are not leap years unless they divide by 400
int A = (year / 100);
int B = 2 - A + (A / 4);
double NewYears = (int)(365.25 * year) +
(int)(30.6001 * 14) +
1720994.5 + B;
m_Date = NewYears + doy;
}
/// <summary>
/// Calculate Greenwich Mean Sidereal Time for the Julian date.
/// </summary>
/// <returns>
/// The angle, in radians, measuring eastward from the Vernal Equinox to
/// the prime meridian. This angle is also referred to as "ThetaG"
/// (Theta GMST).
/// </returns>
public double ToGmst()
{
// References:
// The 1992 Astronomical Almanac, page B6.
// Explanatory Supplement to the Astronomical Almanac, page 50.
// Orbital Coordinate Systems, Part III, Dr. T.S. Kelso,
// Satellite Times, Nov/Dec 1995
double UT = (m_Date + 0.5) % 1.0;
double TU = (FromJan1_12h_2000() - UT) / 36525.0;
double GMST = 24110.54841 + TU *
(8640184.812866 + TU * (0.093104 - TU * 6.2e-06));
GMST = (GMST + Globals.SecPerDay * Globals.OmegaE * UT) % Globals.SecPerDay;
if (GMST < 0.0)
{
GMST += Globals.SecPerDay; // "wrap" negative modulo value
}
return (Globals.TwoPi * (GMST / Globals.SecPerDay));
}
/// <summary>
/// Calculate Local Mean Sidereal Time for this Julian date at the given
/// longitude.
/// </summary>
/// <param name="lon">The longitude, in radians, measured west from Greenwich.</param>
/// <returns>
/// The angle, in radians, measuring eastward from the Vernal Equinox to
/// the given longitude.
/// </returns>
public double ToLmst(double lon)
{
return (ToGmst() + lon) % Globals.TwoPi;
}
/// <summary>
/// Returns a UTC DateTime object that corresponds to this Julian date.
/// </summary>
/// <returns>A DateTime object in UTC.</returns>
public DateTime ToTime()
{
// Jan 1
DateTime dt = new DateTime(m_Year, 1, 1);
// m_Day = 1 = Jan1
dt = dt.AddDays(m_Day - 1.0);
return dt;
}
}
}
| |
using System.Globalization;
using System.Text;
namespace Meziantou.Framework.Scheduling;
public sealed class RecurrenceRuleHumanizerEnglish : RecurrenceRuleHumanizer
{
[Flags]
private enum WeekdayHumanTextOptions
{
None = 0,
AbbrDays = 1,
AbbrWeekdays = 2,
AbbrWeekendDays = 4,
Plural = 8,
}
private static string? GetWeekdayHumanText(IList<ByDay> daysOfWeek, WeekdayHumanTextOptions options)
{
if (daysOfWeek.Count == 0)
return null;
return GetWeekdayHumanText(daysOfWeek.Where(dow => !dow.Ordinal.HasValue).Select(dow => dow.DayOfWeek).ToList(), ", ", " and ", options);
}
private static void GetEndHumanText(RecurrenceRule rrule, StringBuilder sb)
{
if (rrule.Occurrences.HasValue)
{
sb.Append(" for ");
sb.Append(rrule.Occurrences.Value);
if (rrule.Occurrences.Value <= 1)
{
sb.Append(" time");
}
else
{
sb.Append(" times");
}
}
if (rrule.EndDate.HasValue)
{
sb.Append(" until ");
sb.AppendFormat(EnglishCultureInfo, "{0:MMMM d, yyyy}", rrule.EndDate.Value);
}
}
private static string GetWeekdayHumanText(IList<DayOfWeek> daysOfWeek, string separator = ", ", string lastSeparator = " and ", WeekdayHumanTextOptions options = WeekdayHumanTextOptions.None)
{
if (options.HasFlag(WeekdayHumanTextOptions.AbbrWeekdays) && IsWeekday(daysOfWeek))
{
if (options.HasFlag(WeekdayHumanTextOptions.Plural))
return "weekdays";
return "weekday";
}
if (options.HasFlag(WeekdayHumanTextOptions.AbbrDays) && IsFullWeek(daysOfWeek))
{
if (options.HasFlag(WeekdayHumanTextOptions.Plural))
return "days";
return "day";
}
if (options.HasFlag(WeekdayHumanTextOptions.AbbrWeekendDays) && IsWeekendDay(daysOfWeek))
{
if (options.HasFlag(WeekdayHumanTextOptions.Plural))
return "weekend days";
return "weekend day";
}
return ListToHumanText(EnglishCultureInfo, daysOfWeek, separator, lastSeparator);
}
private static string? GetByMonthdayHumanText(int monthday)
{
if (monthday > 0)
{
return Extensions.ToEnglishOrdinal(monthday);
}
if (monthday == -1)
{
return "last day";
}
return null;
}
private static string GetBySetPosHumanText(int setPosition)
{
return setPosition switch
{
-1 => "last",
1 => "first",
2 => "second",
3 => "third",
4 => "fourth",
_ => Extensions.ToEnglishOrdinal(setPosition),
};
}
protected override string GetText(DailyRecurrenceRule rrule!!, CultureInfo cultureInfo!!)
{
var sb = new StringBuilder();
sb.Append("every");
if (rrule.Interval == 1)
{
sb.Append(" day");
}
else if (rrule.Interval == 2)
{
sb.Append(" other day");
}
else if (rrule.Interval > 2)
{
sb.Append(' ');
sb.Append(rrule.Interval);
sb.Append(" days");
}
GetEndHumanText(rrule, sb);
return sb.ToString();
}
protected override string GetText(WeeklyRecurrenceRule rrule!!, CultureInfo cultureInfo!!)
{
var sb = new StringBuilder();
sb.Append("every");
if (rrule.Interval == 1)
{
sb.Append(" week");
}
else if (rrule.Interval == 2)
{
sb.Append(" other week");
}
else if (rrule.Interval > 2)
{
sb.Append(' ');
sb.Append(rrule.Interval);
sb.Append(" weeks");
}
if (rrule.ByWeekDays != null && rrule.ByWeekDays.Any())
{
sb.Append(" on ");
sb.Append(GetWeekdayHumanText(rrule.ByWeekDays, options: WeekdayHumanTextOptions.None));
}
GetEndHumanText(rrule, sb);
return sb.ToString();
}
protected override string GetText(MonthlyRecurrenceRule rrule!!, CultureInfo cultureInfo!!)
{
var sb = new StringBuilder();
sb.Append("every");
if (rrule.Interval == 1)
{
sb.Append(" month");
}
else if (rrule.Interval == 2)
{
sb.Append(" other month");
}
else if (rrule.Interval > 2)
{
sb.Append(' ');
sb.Append(rrule.Interval);
sb.Append(" months");
}
if (rrule.ByMonthDays != null && rrule.ByMonthDays.Any())
{
if (rrule.ByMonthDays.Any(day => day < 0))
{
sb.Append(" on the ");
}
else
{
sb.Append(" the ");
}
ListToHumanText(sb, EnglishCultureInfo, rrule.ByMonthDays.Select(GetByMonthdayHumanText).ToList(), ", ", " and ");
}
if (rrule.ByWeekDays != null && rrule.ByWeekDays.Any())
{
sb.Append(" on ");
if (rrule.BySetPositions != null && rrule.BySetPositions.Any())
{
sb.Append("the ");
sb.Append(GetBySetPosHumanText(rrule.BySetPositions[0]));
sb.Append(' ');
}
sb.Append(GetWeekdayHumanText(rrule.ByWeekDays, options: WeekdayHumanTextOptions.AbbrDays | WeekdayHumanTextOptions.AbbrWeekdays | WeekdayHumanTextOptions.AbbrWeekendDays));
}
GetEndHumanText(rrule, sb);
return sb.ToString();
}
protected override string GetText(YearlyRecurrenceRule rrule!!, CultureInfo cultureInfo!!)
{
var sb = new StringBuilder();
sb.Append("every");
if (rrule.Interval == 1)
{
sb.Append(" year");
}
else if (rrule.Interval == 2)
{
sb.Append(" other year");
}
else if (rrule.Interval > 2)
{
sb.Append(' ');
sb.Append(rrule.Interval);
sb.Append(" years");
}
if (rrule.ByMonthDays != null && rrule.ByMonthDays.Any())
{
if (rrule.ByMonthDays.Any(day => day < 0))
{
sb.Append(" on the ");
ListToHumanText(sb, EnglishCultureInfo, rrule.ByMonthDays.Select(GetByMonthdayHumanText).ToList(), ", ", " and ");
if (rrule.ByMonths != null && rrule.ByMonths.Any())
{
sb.Append(" of ");
sb.Append(rrule.ByMonths[0]);
}
}
else
{
if (rrule.ByMonths != null && rrule.ByMonths.Any())
{
sb.Append(" on ");
sb.Append(rrule.ByMonths[0]);
}
sb.Append(" the ");
ListToHumanText(sb, EnglishCultureInfo, rrule.ByMonthDays.Select(GetByMonthdayHumanText).ToList(), ", ", " and ");
}
}
if (rrule.ByWeekDays != null && rrule.ByWeekDays.Any())
{
sb.Append(" on ");
if (rrule.BySetPositions != null && rrule.BySetPositions.Any())
{
sb.Append("the ");
sb.Append(GetBySetPosHumanText(rrule.BySetPositions[0]));
sb.Append(' ');
}
sb.Append(GetWeekdayHumanText(rrule.ByWeekDays, options: WeekdayHumanTextOptions.AbbrDays | WeekdayHumanTextOptions.AbbrWeekdays | WeekdayHumanTextOptions.AbbrWeekendDays));
if (rrule.ByMonths != null && rrule.ByMonths.Any())
{
sb.Append(" of ");
sb.Append(rrule.ByMonths[0]);
}
}
GetEndHumanText(rrule, sb);
return sb.ToString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Highlight
{
/// <summary> Formats text with different color intensity depending on the score of the
/// term.
///
/// </summary>
/// <author> maharwood
/// </author>
public class GradientFormatter : Formatter
{
private float maxScore;
internal int fgRMin, fgGMin, fgBMin;
internal int fgRMax, fgGMax, fgBMax;
protected internal bool highlightForeground;
internal int bgRMin, bgGMin, bgBMin;
internal int bgRMax, bgGMax, bgBMax;
protected internal bool highlightBackground;
/// <summary> Sets the color range for the IDF scores
///
/// </summary>
/// <param name="">maxScore
/// The score (and above) displayed as maxColor (See QueryScorer.getMaxWeight
/// which can be used to callibrate scoring scale)
/// </param>
/// <param name="">minForegroundColor
/// The hex color used for representing IDF scores of zero eg
/// #FFFFFF (white) or null if no foreground color required
/// </param>
/// <param name="">maxForegroundColor
/// The largest hex color used for representing IDF scores eg
/// #000000 (black) or null if no foreground color required
/// </param>
/// <param name="">minBackgroundColor
/// The hex color used for representing IDF scores of zero eg
/// #FFFFFF (white) or null if no background color required
/// </param>
/// <param name="">maxBackgroundColor
/// The largest hex color used for representing IDF scores eg
/// #000000 (black) or null if no background color required
/// </param>
public GradientFormatter(float maxScore, System.String minForegroundColor, System.String maxForegroundColor, System.String minBackgroundColor, System.String maxBackgroundColor)
{
highlightForeground = (minForegroundColor != null) && (maxForegroundColor != null);
if (highlightForeground)
{
if (minForegroundColor.Length != 7)
{
throw new System.ArgumentException("minForegroundColor is not 7 bytes long eg a hex " + "RGB value such as #FFFFFF");
}
if (maxForegroundColor.Length != 7)
{
throw new System.ArgumentException("minForegroundColor is not 7 bytes long eg a hex " + "RGB value such as #FFFFFF");
}
fgRMin = HexToInt(minForegroundColor.Substring(1, (3) - (1)));
fgGMin = HexToInt(minForegroundColor.Substring(3, (5) - (3)));
fgBMin = HexToInt(minForegroundColor.Substring(5, (7) - (5)));
fgRMax = HexToInt(maxForegroundColor.Substring(1, (3) - (1)));
fgGMax = HexToInt(maxForegroundColor.Substring(3, (5) - (3)));
fgBMax = HexToInt(maxForegroundColor.Substring(5, (7) - (5)));
}
highlightBackground = (minBackgroundColor != null) && (maxBackgroundColor != null);
if (highlightBackground)
{
if (minBackgroundColor.Length != 7)
{
throw new System.ArgumentException("minBackgroundColor is not 7 bytes long eg a hex " + "RGB value such as #FFFFFF");
}
if (maxBackgroundColor.Length != 7)
{
throw new System.ArgumentException("minBackgroundColor is not 7 bytes long eg a hex " + "RGB value such as #FFFFFF");
}
bgRMin = HexToInt(minBackgroundColor.Substring(1, (3) - (1)));
bgGMin = HexToInt(minBackgroundColor.Substring(3, (5) - (3)));
bgBMin = HexToInt(minBackgroundColor.Substring(5, (7) - (5)));
bgRMax = HexToInt(maxBackgroundColor.Substring(1, (3) - (1)));
bgGMax = HexToInt(maxBackgroundColor.Substring(3, (5) - (3)));
bgBMax = HexToInt(maxBackgroundColor.Substring(5, (7) - (5)));
}
// this.corpusReader = corpusReader;
this.maxScore = maxScore;
// totalNumDocs = corpusReader.numDocs();
}
public virtual System.String HighlightTerm(System.String originalText, TokenGroup tokenGroup)
{
if (tokenGroup.GetTotalScore() == 0)
return originalText;
float score = tokenGroup.GetTotalScore();
if (score == 0)
{
return originalText;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<font ");
if (highlightForeground)
{
sb.Append("color=\"");
sb.Append(GetForegroundColorString(score));
sb.Append("\" ");
}
if (highlightBackground)
{
sb.Append("bgcolor=\"");
sb.Append(GetBackgroundColorString(score));
sb.Append("\" ");
}
sb.Append(">");
sb.Append(originalText);
sb.Append("</font>");
return sb.ToString();
}
protected internal virtual System.String GetForegroundColorString(float score)
{
int rVal = GetColorVal(fgRMin, fgRMax, score);
int gVal = GetColorVal(fgGMin, fgGMax, score);
int bVal = GetColorVal(fgBMin, fgBMax, score);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("#");
sb.Append(IntToHex(rVal));
sb.Append(IntToHex(gVal));
sb.Append(IntToHex(bVal));
return sb.ToString();
}
protected internal virtual System.String GetBackgroundColorString(float score)
{
int rVal = GetColorVal(bgRMin, bgRMax, score);
int gVal = GetColorVal(bgGMin, bgGMax, score);
int bVal = GetColorVal(bgBMin, bgBMax, score);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("#");
sb.Append(IntToHex(rVal));
sb.Append(IntToHex(gVal));
sb.Append(IntToHex(bVal));
return sb.ToString();
}
private int GetColorVal(int colorMin, int colorMax, float score)
{
if (colorMin == colorMax)
{
return colorMin;
}
float scale = System.Math.Abs(colorMin - colorMax);
float relScorePercent = System.Math.Min(maxScore, score) / maxScore;
float colScore = scale * relScorePercent;
return System.Math.Min(colorMin, colorMax) + (int) colScore;
}
private static char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static System.String IntToHex(int i)
{
return "" + hexDigits[(i & 0xF0) >> 4] + hexDigits[i & 0x0F];
}
/// <summary> Converts a hex string into an int. Integer.parseInt(hex, 16) assumes the
/// input is nonnegative unless there is a preceding minus sign. This method
/// reads the input as twos complement instead, so if the input is 8 bytes
/// long, it will correctly restore a negative int produced by
/// Integer.toHexString() but not neccesarily one produced by
/// Integer.toString(x,16) since that method will produce a string like '-FF'
/// for negative integer values.
///
/// </summary>
/// <param name="">hex
/// A string in capital or lower case hex, of no more then 16
/// characters.
/// </param>
/// <throws> NumberFormatException </throws>
/// <summary> if the string is more than 16 characters long, or if any
/// character is not in the set [0-9a-fA-f]
/// </summary>
public static int HexToInt(System.String hex)
{
int len = hex.Length;
if (len > 16)
throw new System.FormatException();
int l = 0;
for (int i = 0; i < len; i++)
{
l <<= 4;
int c = (int) System.Char.GetNumericValue(hex[i]);
if (c < 0)
throw new System.FormatException();
l |= c;
}
return l;
}
}
}
| |
// <copyright file="VectorAdditionClient.cs" company="Maxeler Technologies">
// Copyright 2016 Maxeler Technologies. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using com.maxeler.VectorAddition;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
/// <summary>
/// Vector addition BasicStatic example
/// </summary>
internal class VectorAdditionClient
{
/// <summary> Checks if vectorAdditionDfe and vectorAdditionCpu return the same value
/// </summary>
/// <param name = "dataOutDFE" > Data output from DFE </param>
/// <param name = "dataOutCPU" > Data output from CPU </param>
/// <param name = "size" > Size of array </param>
/// <returns> Number of elements that doesn't match </returns>
public static int Check(List<int> dataOutDFE, List<int> dataOutCPU, int size)
{
int status = 0;
for (int i = 0; i < size; i++)
{
if (dataOutDFE[i] != dataOutCPU[i])
{
Console.WriteLine("Output data @ {0} = {1} (expected {2})", i, dataOutDFE[i], dataOutCPU[i]);
status++;
}
}
return status;
}
/// <summary> Vector addition on CPU </summary>
/// <param name = "size"> Size of arrays </param>
/// <param name = "firstVector"> First vector </param>
/// <param name = "secondVector"> Second vector </param>
/// <param name = "scalar"> Scalar parameter </param>
/// <returns> Data output </returns>
public static List<int> VectorAdditionCpu(int size, List<int> firstVector, List<int> secondVector, int scalar)
{
List<int> dataOut = new List<int>();
for (int i = 0; i < size; i++)
{
dataOut.Add((firstVector[i] + secondVector[i]) + scalar);
}
return dataOut;
}
/// <summary> Vector addition on DFE </summary>
/// <param name = "size"> Size of arrays </param>
/// <param name = "firstVector"> First vector </param>
/// <param name = "secondVector"> Second vector </param>
/// <param name = "scalar"> Scalar parameter </param>
/// <returns> Data output </returns>
public static List<int> VectorAdditionDfe(int size, List<int> firstVector, List<int> secondVector, int scalar)
{
Stopwatch sw = new Stopwatch();
sw.Start();
// Make socket
var transport = new TSocket("localhost", 9090);
// Wrap in a protocol
var protocol = new TBinaryProtocol(transport);
// Create a client to use the protocol encoder
var client = new VectorAdditionService.Client(protocol);
sw.Stop();
Console.WriteLine("Creating a client:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
List<int> dataOut = new List<int>();
try
{
// Connect!
sw.Reset();
sw.Start();
transport.Open();
sw.Stop();
Console.WriteLine("Opening connection:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Allocate and send input streams to server
sw.Reset();
sw.Start();
var address_x = client.malloc_int32_t(size);
client.send_data_int32_t(address_x, firstVector);
var address_y = client.malloc_int32_t(size);
client.send_data_int32_t(address_y, secondVector);
sw.Stop();
Console.WriteLine("Sending input data:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Allocate memory for output stream on server
sw.Reset();
sw.Start();
var address_out = client.malloc_float(size);
sw.Stop();
Console.WriteLine("Allocating memory for output stream on server:\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Writing to LMem
sw.Reset();
sw.Start();
client.VectorAddition_writeLMem(0, size * 4, address_x);
sw.Stop();
Console.WriteLine("Writing to LMem:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Action default
sw.Reset();
sw.Start();
client.VectorAddition(scalar, size, address_y, address_out);
sw.Stop();
Console.WriteLine("Vector addition time:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Get output stream from server
sw.Reset();
sw.Start();
dataOut = client.receive_data_int32_t(address_out, size);
sw.Stop();
Console.WriteLine("Getting output stream:\t(size = {0} bit)\t{1}s", size * 32, sw.Elapsed.TotalMilliseconds / 1000);
// Free allocated memory for streams on server
sw.Reset();
sw.Start();
client.free(address_x);
client.free(address_y);
client.free(address_out);
sw.Stop();
Console.WriteLine("Freeing allocated memory for streams on server:\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Close
sw.Reset();
sw.Start();
transport.Close();
sw.Stop();
Console.WriteLine("Closing connection:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
}
catch (SocketException e)
{
Console.WriteLine("Could not connect to the server: {0}.", e.Message);
Environment.Exit(-1);
}
catch (Exception e)
{
Console.WriteLine("An error occured: {0}", e.Message);
Environment.Exit(-1);
}
return dataOut;
}
/// <summary> Calculates vectorAdditionDfe and vectorAdditionCpu
/// and checks if they return the same value.
/// </summary>
/// <param name = "args"> Command line arguments </param>
public static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
int status;
// Generate input data
sw.Start();
const int SIZE = 384;
List<int> firstVector = new List<int>();
List<int> secondVector = new List<int>();
const int Scalar = 3;
Random random = new Random();
for (int i = 0; i < SIZE; i++)
{
firstVector.Add(random.Next(0, 100));
secondVector.Add(random.Next(0, 100));
}
sw.Stop();
Console.WriteLine("Generating input data:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// DFE Output
sw.Reset();
sw.Start();
List<int> dataOutDFE = VectorAdditionDfe(SIZE, firstVector, secondVector, Scalar);
sw.Stop();
Console.WriteLine("DFE vector addition total time:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// CPU Output
sw.Reset();
sw.Start();
List<int> dataOutCPU = VectorAdditionCpu(SIZE, firstVector, secondVector, Scalar);
sw.Stop();
Console.WriteLine("CPU vector addition time:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Checking results
sw.Reset();
sw.Start();
status = Check(dataOutDFE, dataOutCPU, SIZE);
sw.Stop();
Console.WriteLine("Checking results:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
if (status > 0)
{
Console.WriteLine("Test failed {0} times! ", status);
Environment.Exit(-1);
}
else
{
Console.WriteLine("Test passed!");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using ModestTree;
#if !ZEN_NOT_UNITY3D
using UnityEngine;
#endif
namespace Zenject
{
internal static class TypeAnalyzer
{
static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>();
public static ZenjectTypeInfo GetInfo(Type type)
{
ZenjectTypeInfo info;
#if ZEN_MULTITHREADING
lock (_typeInfo)
#endif
{
if (!_typeInfo.TryGetValue(type, out info))
{
info = CreateTypeInfo(type);
_typeInfo.Add(type, info);
}
}
return info;
}
static ZenjectTypeInfo CreateTypeInfo(Type type)
{
var constructor = GetInjectConstructor(type);
return new ZenjectTypeInfo(
type,
GetPostInjectMethods(type),
constructor,
GetFieldInjectables(type).ToList(),
GetPropertyInjectables(type).ToList(),
GetConstructorInjectables(type, constructor).ToList());
}
static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo)
{
if (constructorInfo == null)
{
return Enumerable.Empty<InjectableInfo>();
}
return constructorInfo.GetParameters().Select(
paramInfo => CreateInjectableInfoForParam(parentType, paramInfo));
}
static InjectableInfo CreateInjectableInfoForParam(
Type parentType, ParameterInfo paramInfo)
{
var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType.Name());
var injectAttr = injectAttributes.SingleOrDefault();
string identifier = null;
bool isOptional = false;
bool localOnly = false;
if (injectAttr != null)
{
identifier = injectAttr.Identifier;
isOptional = injectAttr.IsOptional;
localOnly = injectAttr.LocalOnly;
}
bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault;
return new InjectableInfo(
isOptionalWithADefaultValue || isOptional,
identifier,
paramInfo.Name,
paramInfo.ParameterType,
parentType,
null,
isOptionalWithADefaultValue ? paramInfo.DefaultValue : null,
localOnly);
}
static List<PostInjectableInfo> GetPostInjectMethods(Type type)
{
// Note that unlike with fields and properties we use GetCustomAttributes
// This is so that we can ignore inherited attributes, which is necessary
// otherwise a base class method marked with [Inject] would cause all overridden
// derived methods to be added as well
var methods = type.GetAllMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.GetCustomAttributes(typeof(PostInjectAttribute), false).Any()).ToList();
var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList();
// Order by base classes first
// This is how constructors work so it makes more sense
var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType));
var postInjectInfos = new List<PostInjectableInfo>();
foreach (var methodInfo in values)
{
var paramsInfo = methodInfo.GetParameters();
postInjectInfos.Add(
new PostInjectableInfo(
methodInfo,
paramsInfo.Select(paramInfo =>
CreateInjectableInfoForParam(type, paramInfo)).ToList()));
}
return postInjectInfos;
}
static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type)
{
var propInfos = type.GetAllProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var propInfo in propInfos)
{
yield return CreateForMember(propInfo, type);
}
}
static IEnumerable<InjectableInfo> GetFieldInjectables(Type type)
{
var fieldInfos = type.GetAllFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var fieldInfo in fieldInfos)
{
yield return CreateForMember(fieldInfo, type);
}
}
static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType)
{
var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType.Name());
var injectAttr = injectAttributes.SingleOrDefault();
string identifier = null;
bool isOptional = false;
bool localOnly = false;
if (injectAttr != null)
{
identifier = injectAttr.Identifier;
isOptional = injectAttr.IsOptional;
localOnly = injectAttr.LocalOnly;
}
Type memberType;
Action<object, object> setter;
if (memInfo is FieldInfo)
{
var fieldInfo = (FieldInfo)memInfo;
setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value));
memberType = fieldInfo.FieldType;
}
else
{
Assert.That(memInfo is PropertyInfo);
var propInfo = (PropertyInfo)memInfo;
setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null));
memberType = propInfo.PropertyType;
}
return new InjectableInfo(
isOptional,
identifier,
memInfo.Name,
memberType,
parentType,
setter,
null,
localOnly);
}
static ConstructorInfo GetInjectConstructor(Type parentType)
{
var constructors = parentType.GetConstructors(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
#if !ZEN_NOT_UNITY3D
if (Application.platform == RuntimePlatform.WP8Player)
{
// WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy))
// So just ignore that
constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray();
}
#endif
if (constructors.IsEmpty())
{
return null;
}
if (constructors.HasMoreThan(1))
{
// This will return null if there is more than one constructor and none are marked with the [Inject] attribute
return (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault();
}
return constructors[0];
}
static bool IsWp8GeneratedConstructor(ConstructorInfo c)
{
ParameterInfo[] args = c.GetParameters();
return args.Length == 1 && args[0].ParameterType == typeof(UIntPtr) && args[0].Name == "dummy";
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileStreamBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStreamProfileStreamStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))]
public partial class LocalLBProfileStream : iControlInterface {
public LocalLBProfileStream() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void create(
string [] profile_names
) {
this.Invoke("create", new object [] {
profile_names});
}
public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
profile_names}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_profiles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void delete_all_profiles(
) {
this.Invoke("delete_all_profiles", new object [0]);
}
public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState);
}
public void Enddelete_all_profiles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void delete_profile(
string [] profile_names
) {
this.Invoke("delete_profile", new object [] {
profile_names});
}
public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_profile", new object[] {
profile_names}, callback, asyncState);
}
public void Enddelete_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStreamProfileStreamStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBProfileStreamProfileStreamStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBProfileStreamProfileStreamStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStreamProfileStreamStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_profile(
string [] profile_names
) {
object [] results = this.Invoke("get_default_profile", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_profile", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] profile_names
) {
object [] results = this.Invoke("get_description", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_source_string
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_source_string(
string [] profile_names
) {
object [] results = this.Invoke("get_source_string", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_source_string(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_source_string", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_source_string(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStreamProfileStreamStatistics get_statistics(
string [] profile_names
) {
object [] results = this.Invoke("get_statistics", new object [] {
profile_names});
return ((LocalLBProfileStreamProfileStreamStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileStreamProfileStreamStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStreamProfileStreamStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
object [] results = this.Invoke("get_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
//-----------------------------------------------------------------------
// get_target_string
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_target_string(
string [] profile_names
) {
object [] results = this.Invoke("get_target_string", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_target_string(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_target_string", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_target_string(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_base_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_base_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_base_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_base_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_base_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_system_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_system_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_system_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_system_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_system_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void reset_statistics(
string [] profile_names
) {
this.Invoke("reset_statistics", new object [] {
profile_names});
}
public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
profile_names}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void reset_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
this.Invoke("reset_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
}
public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void set_default_profile(
string [] profile_names,
string [] defaults
) {
this.Invoke("set_default_profile", new object [] {
profile_names,
defaults});
}
public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_profile", new object[] {
profile_names,
defaults}, callback, asyncState);
}
public void Endset_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void set_description(
string [] profile_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
profile_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
profile_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_source_string
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void set_source_string(
string [] profile_names,
LocalLBProfileString [] sources
) {
this.Invoke("set_source_string", new object [] {
profile_names,
sources});
}
public System.IAsyncResult Beginset_source_string(string [] profile_names,LocalLBProfileString [] sources, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_source_string", new object[] {
profile_names,
sources}, callback, asyncState);
}
public void Endset_source_string(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_target_string
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileStream",
RequestNamespace="urn:iControl:LocalLB/ProfileStream", ResponseNamespace="urn:iControl:LocalLB/ProfileStream")]
public void set_target_string(
string [] profile_names,
LocalLBProfileString [] targets
) {
this.Invoke("set_target_string", new object [] {
profile_names,
targets});
}
public System.IAsyncResult Beginset_target_string(string [] profile_names,LocalLBProfileString [] targets, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_target_string", new object[] {
profile_names,
targets}, callback, asyncState);
}
public void Endset_target_string(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileStream.ProfileStreamStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBProfileStreamProfileStreamStatisticEntry
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileStream.ProfileStreamStatistics", Namespace = "urn:iControl")]
public partial class LocalLBProfileStreamProfileStreamStatistics
{
private LocalLBProfileStreamProfileStreamStatisticEntry [] statisticsField;
public LocalLBProfileStreamProfileStreamStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
#if NET451
using System.Reflection;
#endif
namespace RdKafka.Internal
{
internal static class LibRdKafka
{
const long minVersion = 0x000901ff;
#if NET451
[DllImport("kernel32", SetLastError = true)]
private static extern IntPtr LoadLibrary(string lpFileName);
#endif
static LibRdKafka()
{
#if NET451
var is64 = IntPtr.Size == 8;
try {
var baseUri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
var baseDirectory = Path.GetDirectoryName(baseUri.LocalPath);
LoadLibrary(Path.Combine(baseDirectory, is64 ? "x64/zlib.dll" : "x86/zlib.dll"));
LoadLibrary(Path.Combine(baseDirectory, is64 ? "x64/librdkafka.dll" : "x86/librdkafka.dll"));
}
catch (Exception) { }
#endif
_version = NativeMethods.rd_kafka_version;
_version_str = NativeMethods.rd_kafka_version_str;
_get_debug_contexts = NativeMethods.rd_kafka_get_debug_contexts;
_err2str = NativeMethods.rd_kafka_err2str;
_last_error = NativeMethods.rd_kafka_last_error;
_topic_partition_list_new = NativeMethods.rd_kafka_topic_partition_list_new;
_topic_partition_list_destroy = NativeMethods.rd_kafka_topic_partition_list_destroy;
_topic_partition_list_add = NativeMethods.rd_kafka_topic_partition_list_add;
_message_destroy = NativeMethods.rd_kafka_message_destroy;
_conf_new = NativeMethods.rd_kafka_conf_new;
_conf_destroy = NativeMethods.rd_kafka_conf_destroy;
_conf_dup = NativeMethods.rd_kafka_conf_dup;
_conf_set = NativeMethods.rd_kafka_conf_set;
_conf_set_dr_msg_cb = NativeMethods.rd_kafka_conf_set_dr_msg_cb;
_conf_set_rebalance_cb = NativeMethods.rd_kafka_conf_set_rebalance_cb;
_conf_set_error_cb = NativeMethods.rd_kafka_conf_set_error_cb;
_conf_set_offset_commit_cb = NativeMethods.rd_kafka_conf_set_offset_commit_cb;
_conf_set_log_cb = NativeMethods.rd_kafka_conf_set_log_cb;
_conf_set_stats_cb = NativeMethods.rd_kafka_conf_set_stats_cb;
_conf_set_default_topic_conf = NativeMethods.rd_kafka_conf_set_default_topic_conf;
_conf_get = NativeMethods.rd_kafka_conf_get;
_topic_conf_get = NativeMethods.rd_kafka_topic_conf_get;
_conf_dump = NativeMethods.rd_kafka_conf_dump;
_topic_conf_dump = NativeMethods.rd_kafka_topic_conf_dump;
_conf_dump_free = NativeMethods.rd_kafka_conf_dump_free;
_topic_conf_new = NativeMethods.rd_kafka_topic_conf_new;
_topic_conf_dup = NativeMethods.rd_kafka_topic_conf_dup;
_topic_conf_destroy = NativeMethods.rd_kafka_topic_conf_destroy;
_topic_conf_set = NativeMethods.rd_kafka_topic_conf_set;
_topic_conf_set_partitioner_cb = NativeMethods.rd_kafka_topic_conf_set_partitioner_cb;
_topic_partition_available = NativeMethods.rd_kafka_topic_partition_available;
_new = NativeMethods.rd_kafka_new;
_destroy = NativeMethods.rd_kafka_destroy;
_name = NativeMethods.rd_kafka_name;
_memberid = NativeMethods.rd_kafka_memberid;
_topic_new = NativeMethods.rd_kafka_topic_new;
_topic_destroy = NativeMethods.rd_kafka_topic_destroy;
_topic_name = NativeMethods.rd_kafka_topic_name;
_poll = NativeMethods.rd_kafka_poll;
_query_watermark_offsets = NativeMethods.rd_kafka_query_watermark_offsets;
_get_watermark_offsets = NativeMethods.rd_kafka_get_watermark_offsets;
_mem_free = NativeMethods.rd_kafka_mem_free;
_subscribe = NativeMethods.rd_kafka_subscribe;
_unsubscribe = NativeMethods.rd_kafka_unsubscribe;
_subscription = NativeMethods.rd_kafka_subscription;
_consumer_poll = NativeMethods.rd_kafka_consumer_poll;
_consumer_close = NativeMethods.rd_kafka_consumer_close;
_assign = NativeMethods.rd_kafka_assign;
_assignment = NativeMethods.rd_kafka_assignment;
_commit = NativeMethods.rd_kafka_commit;
_committed = NativeMethods.rd_kafka_committed;
_position = NativeMethods.rd_kafka_position;
_produce = NativeMethods.rd_kafka_produce;
_metadata = NativeMethods.rd_kafka_metadata;
_metadata_destroy = NativeMethods.rd_kafka_metadata_destroy;
_list_groups = NativeMethods.rd_kafka_list_groups;
_group_list_destroy = NativeMethods.rd_kafka_group_list_destroy;
_brokers_add = NativeMethods.rd_kafka_brokers_add;
_set_log_level = NativeMethods.rd_kafka_set_log_level;
_outq_len = NativeMethods.rd_kafka_outq_len;
_wait_destroyed = NativeMethods.rd_kafka_wait_destroyed;
if ((long) version() < minVersion) {
throw new FileLoadException($"Invalid librdkafka version {(long)version():x}, expected at least {minVersion:x}");
}
}
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate void DeliveryReportCallback(
IntPtr rk,
/* const rd_kafka_message_t * */ ref rd_kafka_message rkmessage,
IntPtr opaque);
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate void CommitCallback(IntPtr rk,
ErrorCode err,
/* rd_kafka_topic_partition_list_t * */ IntPtr offsets,
IntPtr opaque);
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate void ErrorCallback(IntPtr rk,
ErrorCode err, string reason, IntPtr opaque);
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate void RebalanceCallback(IntPtr rk,
ErrorCode err,
/* rd_kafka_topic_partition_list_t * */ IntPtr partitions,
IntPtr opaque);
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate void LogCallback(IntPtr rk, int level, string fac, string buf);
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate int StatsCallback(IntPtr rk, IntPtr json, UIntPtr json_len, IntPtr opaque);
[UnmanagedFunctionPointer(callingConvention: CallingConvention.Cdecl)]
internal delegate int PartitionerCallback(
/* const rd_kafka_topic_t * */ IntPtr rkt,
IntPtr keydata,
UIntPtr keylen,
int partition_cnt,
IntPtr rkt_opaque,
IntPtr msg_opaque);
private static Func<IntPtr> _version;
internal static IntPtr version() => _version();
private static Func<IntPtr> _version_str;
internal static IntPtr version_str() => _version_str();
private static Func<IntPtr> _get_debug_contexts;
internal static IntPtr get_debug_contexts() => _get_debug_contexts();
private static Func<ErrorCode, IntPtr> _err2str;
internal static IntPtr err2str(ErrorCode err) => _err2str(err);
private static Func<IntPtr, IntPtr> _topic_partition_list_new;
internal static IntPtr topic_partition_list_new(IntPtr size)
=> _topic_partition_list_new(size);
private static Action<IntPtr> _topic_partition_list_destroy;
internal static void topic_partition_list_destroy(IntPtr rkparlist)
=> _topic_partition_list_destroy(rkparlist);
private static Func<IntPtr, string, int, IntPtr> _topic_partition_list_add;
internal static IntPtr topic_partition_list_add(IntPtr rktparlist,
string topic, int partition)
=> _topic_partition_list_add(rktparlist, topic, partition);
private static Func<ErrorCode> _last_error;
internal static ErrorCode last_error() => _last_error();
private static Action<IntPtr> _message_destroy;
internal static void message_destroy(IntPtr rkmessage) => _message_destroy(rkmessage);
private static Func<SafeConfigHandle> _conf_new;
internal static SafeConfigHandle conf_new() => _conf_new();
private static Action<IntPtr> _conf_destroy;
internal static void conf_destroy(IntPtr conf) => _conf_destroy(conf);
private static Func<IntPtr, IntPtr> _conf_dup;
internal static IntPtr conf_dup(IntPtr conf) => _conf_dup(conf);
private static Func<IntPtr, string, string, StringBuilder, UIntPtr, ConfRes> _conf_set;
internal static ConfRes conf_set(IntPtr conf, string name,
string value, StringBuilder errstr, UIntPtr errstr_size)
=> _conf_set(conf, name, value, errstr, errstr_size);
private static Action<IntPtr, DeliveryReportCallback> _conf_set_dr_msg_cb;
internal static void conf_set_dr_msg_cb(IntPtr conf, DeliveryReportCallback dr_msg_cb)
=> _conf_set_dr_msg_cb(conf, dr_msg_cb);
private static Action<IntPtr, RebalanceCallback> _conf_set_rebalance_cb;
internal static void conf_set_rebalance_cb(IntPtr conf, RebalanceCallback rebalance_cb)
=> _conf_set_rebalance_cb(conf, rebalance_cb);
private static Action<IntPtr, CommitCallback> _conf_set_offset_commit_cb;
internal static void conf_set_offset_commit_cb(IntPtr conf, CommitCallback commit_cb)
=> _conf_set_offset_commit_cb(conf, commit_cb);
private static Action<IntPtr, ErrorCallback> _conf_set_error_cb;
internal static void conf_set_error_cb(IntPtr conf, ErrorCallback error_cb)
=> _conf_set_error_cb(conf, error_cb);
private static Action<IntPtr, LogCallback> _conf_set_log_cb;
internal static void conf_set_log_cb(IntPtr conf, LogCallback log_cb)
=> _conf_set_log_cb(conf, log_cb);
private static Action<IntPtr, StatsCallback> _conf_set_stats_cb;
internal static void conf_set_stats_cb(IntPtr conf, StatsCallback stats_cb)
=> _conf_set_stats_cb(conf, stats_cb);
private static Action<IntPtr, IntPtr> _conf_set_default_topic_conf;
internal static void conf_set_default_topic_conf(IntPtr conf, IntPtr tconf)
=> _conf_set_default_topic_conf(conf, tconf);
private delegate ConfRes ConfGet(IntPtr conf, string name, StringBuilder dest,
ref UIntPtr dest_size);
private static ConfGet _conf_get;
internal static ConfRes conf_get(IntPtr conf, string name,
StringBuilder dest, ref UIntPtr dest_size)
=> _conf_get(conf, name, dest, ref dest_size);
private static ConfGet _topic_conf_get;
internal static ConfRes topic_conf_get(IntPtr conf, string name,
StringBuilder dest, ref UIntPtr dest_size)
=> _topic_conf_get(conf, name, dest, ref dest_size);
private delegate IntPtr ConfDump(IntPtr conf, out UIntPtr cntp);
private static ConfDump _conf_dump;
internal static IntPtr conf_dump(IntPtr conf, out UIntPtr cntp)
=> _conf_dump(conf, out cntp);
private static ConfDump _topic_conf_dump;
internal static IntPtr topic_conf_dump(IntPtr conf, out UIntPtr cntp)
=> _topic_conf_dump(conf, out cntp);
private static Action<IntPtr, UIntPtr> _conf_dump_free;
internal static void conf_dump_free(IntPtr arr, UIntPtr cnt)
=> _conf_dump_free(arr, cnt);
private static Func<SafeTopicConfigHandle> _topic_conf_new;
internal static SafeTopicConfigHandle topic_conf_new() => _topic_conf_new();
private static Func<IntPtr, IntPtr> _topic_conf_dup;
internal static IntPtr topic_conf_dup(IntPtr conf) => _topic_conf_dup(conf);
private static Action<IntPtr> _topic_conf_destroy;
internal static void topic_conf_destroy(IntPtr conf) => _topic_conf_destroy(conf);
private static Func<IntPtr, string, string, StringBuilder, UIntPtr, ConfRes> _topic_conf_set;
internal static ConfRes topic_conf_set(IntPtr conf, string name,
string value, StringBuilder errstr, UIntPtr errstr_size)
=> _topic_conf_set(conf, name, value, errstr, errstr_size);
private static Action<IntPtr, PartitionerCallback> _topic_conf_set_partitioner_cb;
internal static void topic_conf_set_partitioner_cb(
IntPtr topic_conf, PartitionerCallback partitioner_cb)
=> _topic_conf_set_partitioner_cb(topic_conf, partitioner_cb);
private static Func<IntPtr, int, bool> _topic_partition_available;
internal static bool topic_partition_available(IntPtr rkt, int partition)
=> _topic_partition_available(rkt, partition);
private static Func<RdKafkaType, IntPtr, StringBuilder, UIntPtr, SafeKafkaHandle> _new;
internal static SafeKafkaHandle kafka_new(RdKafkaType type, IntPtr conf,
StringBuilder errstr, UIntPtr errstr_size)
=> _new(type, conf, errstr, errstr_size);
private static Action<IntPtr> _destroy;
internal static void destroy(IntPtr rk) => _destroy(rk);
private static Func<IntPtr, IntPtr> _name;
internal static IntPtr name(IntPtr rk) => _name(rk);
private static Func<IntPtr, IntPtr> _memberid;
internal static IntPtr memberid(IntPtr rk) => _memberid(rk);
private static Func<IntPtr, string, IntPtr, SafeTopicHandle> _topic_new;
internal static SafeTopicHandle topic_new(IntPtr rk, string topic, IntPtr conf)
=> _topic_new(rk, topic, conf);
private static Action<IntPtr> _topic_destroy;
internal static void topic_destroy(IntPtr rk) => _topic_destroy(rk);
private static Func<IntPtr, IntPtr> _topic_name;
internal static IntPtr topic_name(IntPtr rkt) => _topic_name(rkt);
private static Func<IntPtr, IntPtr, IntPtr> _poll;
internal static IntPtr poll(IntPtr rk, IntPtr timeout_ms) => _poll(rk, timeout_ms);
private delegate ErrorCode QueryOffsets(IntPtr rk, string topic, int partition,
out long low, out long high, IntPtr timeout_ms);
private static QueryOffsets _query_watermark_offsets;
internal static ErrorCode query_watermark_offsets(IntPtr rk, string topic, int partition,
out long low, out long high, IntPtr timeout_ms)
=> _query_watermark_offsets(rk, topic, partition, out low, out high, timeout_ms);
private delegate ErrorCode GetOffsets(IntPtr rk, string topic, int partition,
out long low, out long high);
private static GetOffsets _get_watermark_offsets;
internal static ErrorCode get_watermark_offsets(IntPtr rk, string topic, int partition,
out long low, out long high)
=> _get_watermark_offsets(rk, topic, partition, out low, out high);
private static Action<IntPtr, IntPtr> _mem_free;
internal static void mem_free(IntPtr rk, IntPtr ptr)
=> _mem_free(rk, ptr);
private static Func<IntPtr, IntPtr, ErrorCode> _subscribe;
internal static ErrorCode subscribe(IntPtr rk, IntPtr topics) => _subscribe(rk, topics);
private static Func<IntPtr, ErrorCode> _unsubscribe;
internal static ErrorCode unsubscribe(IntPtr rk) => _unsubscribe(rk);
private delegate ErrorCode Subscription(IntPtr rk, out IntPtr topics);
private static Subscription _subscription;
internal static ErrorCode subscription(IntPtr rk, out IntPtr topics)
=> _subscription(rk, out topics);
private static Func<IntPtr, IntPtr, IntPtr> _consumer_poll;
internal static IntPtr consumer_poll(IntPtr rk, IntPtr timeout_ms)
=> _consumer_poll(rk, timeout_ms);
private static Func<IntPtr, ErrorCode> _consumer_close;
internal static ErrorCode consumer_close(IntPtr rk) => _consumer_close(rk);
private static Func<IntPtr, IntPtr, ErrorCode> _assign;
internal static ErrorCode assign(IntPtr rk, IntPtr partitions)
=> _assign(rk, partitions);
private delegate ErrorCode Assignment(IntPtr rk, out IntPtr topics);
private static Assignment _assignment;
internal static ErrorCode assignment(IntPtr rk, out IntPtr topics)
=> _assignment(rk, out topics);
private static Func<IntPtr, IntPtr, bool, ErrorCode> _commit;
internal static ErrorCode commit(IntPtr rk, IntPtr offsets, bool async)
=> _commit(rk, offsets, async);
private static Func<IntPtr, IntPtr, IntPtr, ErrorCode> _committed;
internal static ErrorCode committed(IntPtr rk, IntPtr partitions, IntPtr timeout_ms)
=> _committed(rk, partitions, timeout_ms);
private static Func<IntPtr, IntPtr, ErrorCode> _position;
internal static ErrorCode position(IntPtr rk, IntPtr partitions)
=> _position(rk, partitions);
private static Func<IntPtr, int, IntPtr, byte[], UIntPtr, byte[], UIntPtr,
IntPtr, IntPtr> _produce;
internal static IntPtr produce(
IntPtr rkt,
int partition,
IntPtr msgflags,
byte[] payload, UIntPtr len,
byte[] key, UIntPtr keylen,
IntPtr msg_opaque)
=> _produce(rkt, partition, msgflags, payload, len, key, keylen, msg_opaque);
private delegate ErrorCode Metadata(IntPtr rk, bool all_topics,
IntPtr only_rkt, out IntPtr metadatap, IntPtr timeout_ms);
private static Metadata _metadata;
internal static ErrorCode metadata(IntPtr rk, bool all_topics,
IntPtr only_rkt, out IntPtr metadatap, IntPtr timeout_ms)
=> _metadata(rk, all_topics, only_rkt, out metadatap, timeout_ms);
private static Action<IntPtr> _metadata_destroy;
internal static void metadata_destroy(IntPtr metadata)
=> _metadata_destroy(metadata);
private delegate ErrorCode ListGroups(IntPtr rk, string group,
out IntPtr grplistp, IntPtr timeout_ms);
private static ListGroups _list_groups;
internal static ErrorCode list_groups(IntPtr rk, string group,
out IntPtr grplistp, IntPtr timeout_ms)
=> _list_groups(rk, group, out grplistp, timeout_ms);
private static Action<IntPtr> _group_list_destroy;
internal static void group_list_destroy(IntPtr grplist)
=> _group_list_destroy(grplist);
private static Func<IntPtr, string, IntPtr> _brokers_add;
internal static IntPtr brokers_add(IntPtr rk, string brokerlist)
=> _brokers_add(rk, brokerlist);
private static Action<IntPtr, IntPtr> _set_log_level;
internal static void set_log_level(IntPtr rk, IntPtr level)
=> _set_log_level(rk, level);
private static Func<IntPtr, IntPtr> _outq_len;
internal static IntPtr outq_len(IntPtr rk) => _outq_len(rk);
private static Func<IntPtr, IntPtr> _wait_destroyed;
internal static IntPtr wait_destroyed(IntPtr timeout_ms)
=> _wait_destroyed(timeout_ms);
private class NativeMethods
{
private const string DllName = "librdkafka";
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_version();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_version_str();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_get_debug_contexts();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_err2str(ErrorCode err);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_last_error();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* rd_kafka_topic_partition_list_t * */ IntPtr
rd_kafka_topic_partition_list_new(IntPtr size);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_topic_partition_list_destroy(
/* rd_kafka_topic_partition_list_t * */ IntPtr rkparlist);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* rd_kafka_topic_partition_t * */ IntPtr
rd_kafka_topic_partition_list_add(
/* rd_kafka_topic_partition_list_t * */ IntPtr rktparlist,
string topic, int partition);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_message_destroy(
/* rd_kafka_message_t * */ IntPtr rkmessage);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern SafeConfigHandle rd_kafka_conf_new();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_destroy(IntPtr conf);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_conf_dup(IntPtr conf);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ConfRes rd_kafka_conf_set(
IntPtr conf,
[MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] string value,
StringBuilder errstr,
UIntPtr errstr_size);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_dr_msg_cb(
IntPtr conf,
DeliveryReportCallback dr_msg_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_rebalance_cb(
IntPtr conf, RebalanceCallback rebalance_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_offset_commit_cb(
IntPtr conf, CommitCallback commit_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_error_cb(
IntPtr conf, ErrorCallback error_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_log_cb(IntPtr conf, LogCallback log_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_stats_cb(IntPtr conf, StatsCallback stats_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_set_default_topic_conf(
IntPtr conf, IntPtr tconf);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ConfRes rd_kafka_conf_get(
IntPtr conf,
[MarshalAs(UnmanagedType.LPStr)] string name,
StringBuilder dest, ref UIntPtr dest_size);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ConfRes rd_kafka_topic_conf_get(
IntPtr conf,
[MarshalAs(UnmanagedType.LPStr)] string name,
StringBuilder dest, ref UIntPtr dest_size);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* const char ** */ IntPtr rd_kafka_conf_dump(
IntPtr conf, /* size_t * */ out UIntPtr cntp);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* const char ** */ IntPtr rd_kafka_topic_conf_dump(
IntPtr conf, out UIntPtr cntp);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_conf_dump_free(/* const char ** */ IntPtr arr, UIntPtr cnt);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern SafeTopicConfigHandle rd_kafka_topic_conf_new();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* rd_kafka_topic_conf_t * */ IntPtr rd_kafka_topic_conf_dup(
/* const rd_kafka_topic_conf_t * */ IntPtr conf);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_topic_conf_destroy(IntPtr conf);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ConfRes rd_kafka_topic_conf_set(
IntPtr conf,
[MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] string value,
StringBuilder errstr,
UIntPtr errstr_size);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_topic_conf_set_partitioner_cb(
IntPtr topic_conf, PartitionerCallback partitioner_cb);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern bool rd_kafka_topic_partition_available(
IntPtr rkt, int partition);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern SafeKafkaHandle rd_kafka_new(
RdKafkaType type, IntPtr conf,
StringBuilder errstr,
UIntPtr errstr_size);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_destroy(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* const char * */ IntPtr rd_kafka_name(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* char * */ IntPtr rd_kafka_memberid(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern SafeTopicHandle rd_kafka_topic_new(
IntPtr rk,
[MarshalAs(UnmanagedType.LPStr)] string topic,
/* rd_kafka_topic_conf_t * */ IntPtr conf);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_topic_destroy(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* const char * */ IntPtr rd_kafka_topic_name(IntPtr rkt);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_poll(IntPtr rk, IntPtr timeout_ms);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_query_watermark_offsets(IntPtr rk,
[MarshalAs(UnmanagedType.LPStr)] string topic,
int partition, out long low, out long high, IntPtr timeout_ms);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_get_watermark_offsets(IntPtr rk,
[MarshalAs(UnmanagedType.LPStr)] string topic,
int partition, out long low, out long high);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_mem_free(IntPtr rk, IntPtr ptr);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_subscribe(IntPtr rk,
/* const rd_kafka_topic_partition_list_t * */ IntPtr topics);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_unsubscribe(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_subscription(IntPtr rk,
/* rd_kafka_topic_partition_list_t ** */ out IntPtr topics);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern /* rd_kafka_message_t * */ IntPtr rd_kafka_consumer_poll(
IntPtr rk, IntPtr timeout_ms);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_consumer_close(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_assign(IntPtr rk,
/* const rd_kafka_topic_partition_list_t * */ IntPtr partitions);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_assignment(IntPtr rk,
/* rd_kafka_topic_partition_list_t ** */ out IntPtr topics);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_commit(
IntPtr rk,
/* const rd_kafka_topic_partition_list_t * */ IntPtr offsets,
bool async);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_committed(
IntPtr rk, IntPtr partitions, IntPtr timeout_ms);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_position(
IntPtr rk, IntPtr partitions);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_produce(
IntPtr rkt,
int partition,
IntPtr msgflags,
byte[] payload, UIntPtr len,
byte[] key, UIntPtr keylen,
IntPtr msg_opaque);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_metadata(
IntPtr rk, bool all_topics,
/* rd_kafka_topic_t * */ IntPtr only_rkt,
/* const struct rd_kafka_metadata ** */ out IntPtr metadatap,
IntPtr timeout_ms);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_metadata_destroy(
/* const struct rd_kafka_metadata * */ IntPtr metadata);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern ErrorCode rd_kafka_list_groups(
IntPtr rk, string group, out IntPtr grplistp,
IntPtr timeout_ms);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_group_list_destroy(
IntPtr grplist);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_brokers_add(IntPtr rk,
[MarshalAs(UnmanagedType.LPStr)] string brokerlist);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void rd_kafka_set_log_level(IntPtr rk, IntPtr level);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_outq_len(IntPtr rk);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr rd_kafka_wait_destroyed(IntPtr timeout_ms);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.