context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Umbraco.Core.Configuration;
using System;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence
{
/// <summary>
/// Used to instantiate each repository type
/// </summary>
public class RepositoryFactory
{
private readonly ILogger _logger;
private readonly ISqlSyntaxProvider _sqlSyntax;
private readonly CacheHelper _cacheHelper;
private readonly CacheHelper _noCache;
private readonly IUmbracoSettingsSection _settings;
#region Ctors
public RepositoryFactory(CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax, IUmbracoSettingsSection settings)
{
if (cacheHelper == null) throw new ArgumentNullException("cacheHelper");
if (logger == null) throw new ArgumentNullException("logger");
//if (sqlSyntax == null) throw new ArgumentNullException("sqlSyntax");
if (settings == null) throw new ArgumentNullException("settings");
_cacheHelper = cacheHelper;
//IMPORTANT: We will force the DeepCloneRuntimeCacheProvider to be used here which is a wrapper for the underlying
// runtime cache to ensure that anything that can be deep cloned in/out is done so, this also ensures that our tracks
// changes entities are reset.
if ((_cacheHelper.RuntimeCache is DeepCloneRuntimeCacheProvider) == false)
{
var origRuntimeCache = cacheHelper.RuntimeCache;
_cacheHelper.RuntimeCache = new DeepCloneRuntimeCacheProvider(origRuntimeCache);
}
//If the factory for isolated cache doesn't return DeepCloneRuntimeCacheProvider, then ensure it does
if (_cacheHelper.IsolatedRuntimeCache.CacheFactory.Method.ReturnType != typeof (DeepCloneRuntimeCacheProvider))
{
var origFactory = cacheHelper.IsolatedRuntimeCache.CacheFactory;
_cacheHelper.IsolatedRuntimeCache.CacheFactory = type =>
{
var cache = origFactory(type);
//if the result is already a DeepCloneRuntimeCacheProvider then return it, otherwise
//wrap the result with a DeepCloneRuntimeCacheProvider
return cache is DeepCloneRuntimeCacheProvider
? cache
: new DeepCloneRuntimeCacheProvider(cache);
};
}
_noCache = CacheHelper.CreateDisabledCacheHelper();
_logger = logger;
_sqlSyntax = sqlSyntax;
_settings = settings;
}
[Obsolete("Use the ctor specifying all dependencies instead")]
public RepositoryFactory()
: this(ApplicationContext.Current.ApplicationCache, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
}
[Obsolete("Use the ctor specifying all dependencies instead")]
public RepositoryFactory(CacheHelper cacheHelper)
: this(cacheHelper, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
}
[Obsolete("Use the ctor specifying all dependencies instead, NOTE: disableAllCache has zero effect")]
public RepositoryFactory(bool disableAllCache, CacheHelper cacheHelper)
: this(cacheHelper, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
if (cacheHelper == null) throw new ArgumentNullException("cacheHelper");
_cacheHelper = cacheHelper;
_noCache = CacheHelper.CreateDisabledCacheHelper();
}
[Obsolete("Use the ctor specifying all dependencies instead")]
public RepositoryFactory(bool disableAllCache)
: this(disableAllCache ? CacheHelper.CreateDisabledCacheHelper() : ApplicationContext.Current.ApplicationCache, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
}
#endregion
public virtual IExternalLoginRepository CreateExternalLoginRepository(IDatabaseUnitOfWork uow)
{
return new ExternalLoginRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IPublicAccessRepository CreatePublicAccessRepository(IDatabaseUnitOfWork uow)
{
return new PublicAccessRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual ITaskRepository CreateTaskRepository(IDatabaseUnitOfWork uow)
{
return new TaskRepository(uow,
_noCache, //never cache
_logger, _sqlSyntax);
}
public virtual IAuditRepository CreateAuditRepository(IDatabaseUnitOfWork uow)
{
return new AuditRepository(uow,
_noCache, //never cache
_logger, _sqlSyntax);
}
public virtual ITagRepository CreateTagRepository(IDatabaseUnitOfWork uow)
{
return new TagRepository(
uow,
_cacheHelper, _logger, _sqlSyntax);
}
public virtual IContentRepository CreateContentRepository(IDatabaseUnitOfWork uow)
{
return new ContentRepository(
uow,
_cacheHelper,
_logger,
_sqlSyntax,
CreateContentTypeRepository(uow),
CreateTemplateRepository(uow),
CreateTagRepository(uow),
_settings.Content)
{
EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming
};
}
public virtual IContentTypeRepository CreateContentTypeRepository(IDatabaseUnitOfWork uow)
{
return new ContentTypeRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateTemplateRepository(uow));
}
public virtual IDataTypeDefinitionRepository CreateDataTypeDefinitionRepository(IDatabaseUnitOfWork uow)
{
return new DataTypeDefinitionRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateContentTypeRepository(uow));
}
public virtual IDictionaryRepository CreateDictionaryRepository(IDatabaseUnitOfWork uow)
{
return new DictionaryRepository(
uow,
_cacheHelper,
_logger,
_sqlSyntax);
}
public virtual ILanguageRepository CreateLanguageRepository(IDatabaseUnitOfWork uow)
{
return new LanguageRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IMediaRepository CreateMediaRepository(IDatabaseUnitOfWork uow)
{
return new MediaRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateMediaTypeRepository(uow),
CreateTagRepository(uow),
_settings.Content);
}
public virtual IMediaTypeRepository CreateMediaTypeRepository(IDatabaseUnitOfWork uow)
{
return new MediaTypeRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IRelationRepository CreateRelationRepository(IDatabaseUnitOfWork uow)
{
return new RelationRepository(
uow,
_noCache,
_logger, _sqlSyntax,
CreateRelationTypeRepository(uow));
}
public virtual IRelationTypeRepository CreateRelationTypeRepository(IDatabaseUnitOfWork uow)
{
return new RelationTypeRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IScriptRepository CreateScriptRepository(IUnitOfWork uow)
{
return new ScriptRepository(uow, new PhysicalFileSystem(SystemDirectories.Scripts), _settings.Content);
}
internal virtual IPartialViewRepository CreatePartialViewRepository(IUnitOfWork uow)
{
return new PartialViewRepository(uow);
}
internal virtual IPartialViewRepository CreatePartialViewMacroRepository(IUnitOfWork uow)
{
return new PartialViewMacroRepository(uow);
}
public virtual IStylesheetRepository CreateStylesheetRepository(IUnitOfWork uow, IDatabaseUnitOfWork db)
{
return new StylesheetRepository(uow, new PhysicalFileSystem(SystemDirectories.Css));
}
public virtual ITemplateRepository CreateTemplateRepository(IDatabaseUnitOfWork uow)
{
return new TemplateRepository(uow,
_cacheHelper,
_logger, _sqlSyntax,
new PhysicalFileSystem(SystemDirectories.Masterpages),
new PhysicalFileSystem(SystemDirectories.MvcViews),
_settings.Templates);
}
public virtual IMigrationEntryRepository CreateMigrationEntryRepository(IDatabaseUnitOfWork uow)
{
return new MigrationEntryRepository(
uow,
_noCache, //never cache
_logger, _sqlSyntax);
}
public virtual IServerRegistrationRepository CreateServerRegistrationRepository(IDatabaseUnitOfWork uow)
{
return new ServerRegistrationRepository(
uow,
_cacheHelper.StaticCache,
_logger, _sqlSyntax);
}
public virtual IUserTypeRepository CreateUserTypeRepository(IDatabaseUnitOfWork uow)
{
return new UserTypeRepository(
uow,
//There's not many user types but we query on users all the time so the result needs to be cached
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IUserRepository CreateUserRepository(IDatabaseUnitOfWork uow)
{
return new UserRepository(
uow,
//Need to cache users - we look up user information more than anything in the back office!
_cacheHelper,
_logger, _sqlSyntax,
CreateUserTypeRepository(uow));
}
internal virtual IMacroRepository CreateMacroRepository(IDatabaseUnitOfWork uow)
{
return new MacroRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IMemberRepository CreateMemberRepository(IDatabaseUnitOfWork uow)
{
return new MemberRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateMemberTypeRepository(uow),
CreateMemberGroupRepository(uow),
CreateTagRepository(uow),
_settings.Content);
}
public virtual IMemberTypeRepository CreateMemberTypeRepository(IDatabaseUnitOfWork uow)
{
return new MemberTypeRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IMemberGroupRepository CreateMemberGroupRepository(IDatabaseUnitOfWork uow)
{
return new MemberGroupRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IEntityRepository CreateEntityRepository(IDatabaseUnitOfWork uow)
{
return new EntityRepository(uow);
}
public virtual IDomainRepository CreateDomainRepository(IDatabaseUnitOfWork uow)
{
return new DomainRepository(uow, _cacheHelper, _logger, _sqlSyntax);
}
public ITaskTypeRepository CreateTaskTypeRepository(IDatabaseUnitOfWork uow)
{
return new TaskTypeRepository(uow,
_noCache, //never cache
_logger, _sqlSyntax);
}
internal virtual EntityContainerRepository CreateEntityContainerRepository(IDatabaseUnitOfWork uow, Guid containerObjectType)
{
return new EntityContainerRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
containerObjectType);
}
public IRedirectUrlRepository CreateRedirectUrlRepository(IDatabaseUnitOfWork uow)
{
return new RedirectUrlRepository(
uow,
_cacheHelper,
_logger,
_sqlSyntax);
}
}
}
| |
namespace Ioke.Lang.Util {
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
public class DefaultGlobber : Ioke.Lang.Globber {
public readonly static bool DOSISH = !(Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Xbox);
public readonly static bool CASEFOLD_FILESYSTEM = DOSISH;
public const int FNM_NOESCAPE = 0x01;
public const int FNM_PATHNAME = 0x02;
public const int FNM_DOTMATCH = 0x04;
public const int FNM_CASEFOLD = 0x08;
public readonly static int FNM_SYSCASE = CASEFOLD_FILESYSTEM ? FNM_CASEFOLD : 0;
public const int FNM_NOMATCH = 1;
public const int FNM_ERROR = 2;
public readonly static string EMPTY = "";
public readonly static string SLASH = "/";
public readonly static string STAR = "*";
public readonly static string DOUBLE_STAR = "**";
private static bool IsDirSep(char c) {
return DOSISH ? (c == '\\' || c == '/') : c == '/';
}
private static int PathNext(string str, int s, int send) {
while(s < send && !IsDirSep(str[s])) {
s++;
}
return s;
}
private static int FilenameMatchHelper(string pattern, int pstart, int pend, string path, int sstart, int send, int flags) {
char test;
int s = sstart;
int pat = pstart;
bool escape = (flags & FNM_NOESCAPE) == 0;
bool pathname = (flags & FNM_PATHNAME) != 0;
bool period = (flags & FNM_DOTMATCH) == 0;
bool nocase = (flags & FNM_CASEFOLD) != 0;
while(pat<pend) {
char c = pattern[pat++];
switch(c) {
case '?':
if(s >= send || (pathname && IsDirSep(path[s])) ||
(period && path[s] == '.' && (s == 0 || (pathname && IsDirSep(path[s-1]))))) {
return FNM_NOMATCH;
}
s++;
break;
case '*':
while(pat < pend && (c = pattern[pat++]) == '*');
if(s < send && (period && path[s] == '.' && (s == 0 || (pathname && IsDirSep(path[s-1]))))) {
return FNM_NOMATCH;
}
if(pat > pend || (pat == pend && c == '*')) {
if(pathname && PathNext(path, s, send) < send) {
return FNM_NOMATCH;
} else {
return 0;
}
} else if((pathname && IsDirSep(c))) {
s = PathNext(path, s, send);
if(s < send) {
s++;
break;
}
return FNM_NOMATCH;
}
test = escape && c == '\\' && pat < pend ? pattern[pat] : c;
test = char.ToLower(test);
pat--;
while(s < send) {
if((c == '?' || c == '[' || char.ToLower(path[s]) == test) &&
FilenameMatch(pattern, pat, pend, path, s, send, flags | FNM_DOTMATCH) == 0) {
return 0;
} else if((pathname && IsDirSep(path[s]))) {
break;
}
s++;
}
return FNM_NOMATCH;
case '[':
if(s >= send || (pathname && IsDirSep(path[s]) || (period && path[s] == '.' && (s == 0 || (pathname && IsDirSep(path[s-1])))))) {
return FNM_NOMATCH;
}
pat = Range(pattern, pat, pend, path[s], flags);
if(pat == -1) {
return FNM_NOMATCH;
}
s++;
break;
case '\\':
if(escape &&
(!DOSISH ||
(pat < pend && "*?[]\\".IndexOf(pattern[pat]) != -1))) {
if(pat >= pend) {
c = '\\';
} else {
c = pattern[pat++];
}
}
goto default;
default:
if(s >= send) {
return FNM_NOMATCH;
}
if(DOSISH && (pathname && IsDirSep(c) && IsDirSep(path[s]))) {
} else {
if (nocase) {
if(char.ToLower(c) != char.ToLower(path[s])) {
return FNM_NOMATCH;
}
} else {
if(c != path[s]) {
return FNM_NOMATCH;
}
}
}
s++;
break;
}
}
return s >= send ? 0 : FNM_NOMATCH;
}
public static int FilenameMatch(String pattern, int pstart, int pend, String path, int sstart, int send, int flags) {
// This method handles '**/' patterns and delegates to
// fnmatch_helper for the main work.
bool period = (flags & FNM_DOTMATCH) == 0;
bool pathname = (flags & FNM_PATHNAME) != 0;
int pat_pos = pstart;
int str_pos = sstart;
int ptmp = -1;
int stmp = -1;
if(pathname) {
while(true) {
if (IsDoubleStarAndSlash(pattern, pat_pos)) {
do { pat_pos += 3; } while (IsDoubleStarAndSlash(pattern, pat_pos));
ptmp = pat_pos;
stmp = str_pos;
}
int patSlashIdx = NextSlashIndex(pattern, pat_pos, pend);
int strSlashIdx = NextSlashIndex(path, str_pos, send);
if(FilenameMatchHelper(pattern, pat_pos, patSlashIdx, path, str_pos, strSlashIdx, flags) == 0) {
if(patSlashIdx < pend && strSlashIdx < send) {
pat_pos = ++patSlashIdx;
str_pos = ++strSlashIdx;
continue;
}
if(patSlashIdx == pend && strSlashIdx == send) {
return 0;
}
}
/* failed : try next recursion */
if (ptmp != -1 && stmp != -1 && !(period && path[stmp] == '.')) {
stmp = NextSlashIndex(path, stmp, send);
if (stmp < send) {
pat_pos = ptmp;
stmp++;
str_pos = stmp;
continue;
}
}
return FNM_NOMATCH;
}
} else {
return FilenameMatchHelper(pattern, pstart, pend, path, sstart, send, flags);
}
}
// are we at '**/'
private static bool IsDoubleStarAndSlash(string pattern, int pos) {
if ((pattern.Length - pos) <= 2) {
return false; // not enough bytes
}
return pattern[pos] == '*'
&& pattern[pos + 1] == '*'
&& pattern[pos + 2] == '/';
}
// Look for slash, starting from 'start' position, until 'end'.
private static int NextSlashIndex(string pattern, int start, int end) {
int idx = start;
while(idx < end && idx < pattern.Length && pattern[idx] != '/') {
idx++;
}
return idx;
}
public static int Range(string _pat, int pat, int pend, char test, int flags) {
bool not;
bool ok = false;
bool nocase = (flags & FNM_CASEFOLD) != 0;
bool escape = (flags & FNM_NOESCAPE) == 0;
not = _pat[pat] == '!' || _pat[pat] == '^';
if(not) {
pat++;
}
if(nocase) {
test = char.ToLower(test);
}
while(_pat[pat] != ']') {
char cstart, cend;
if(escape && _pat[pat] == '\\') {
pat++;
}
if(pat >= pend) {
return -1;
}
cstart = cend = _pat[pat++];
if(_pat[pat] == '-' && _pat[pat+1] != ']') {
pat++;
if(escape && _pat[pat] == '\\') {
pat++;
}
if(pat >= pend) {
return -1;
}
cend = _pat[pat++];
}
if(nocase) {
if(char.ToLower(cstart) <= test
&& test <= char.ToLower(cend)) {
ok = true;
}
} else {
if(cstart <= test && test <= cend) {
ok = true;
}
}
}
return ok == not ? -1 : pat + 1;
}
public IList<string> PushGlob(string cwd, string globstring, int flags) {
var result = new List<string>();
if(globstring.Length > 0) {
PushBraces(cwd, result, new GlobPattern(globstring, flags));
}
return result;
}
private class GlobPattern {
internal readonly string path;
internal readonly int begin;
internal readonly int end;
internal int flags;
internal int index;
public GlobPattern(string path, int flags) : this(path, 0, path.Length, flags) {}
public GlobPattern(string path, int index, int end, int flags) {
this.path = path;
this.index = index;
this.begin = index;
this.end = end;
this.flags = flags;
}
public int FindClosingIndexOf(int leftTokenIndex) {
if(leftTokenIndex == -1 || leftTokenIndex > end) return -1;
char leftToken = path[leftTokenIndex];
char rightToken;
switch (leftToken) {
case '{': rightToken = '}'; break;
case '[': rightToken = ']'; break;
default: return -1;
}
int nest = 1; // leftToken made us start as nest 1
index = leftTokenIndex + 1;
while(HasNext()) {
char c = Next();
if(c == leftToken) {
nest++;
} else if(c == rightToken && --nest == 0) {
return Index;
}
}
return -1;
}
public bool HasNext() {
return index < end;
}
public void Reset() {
index = begin;
}
public int Index {
get { return index - 1; }
set { this.index = value; }
}
public int IndexOf(char c) {
while (HasNext()) if (Next() == c) return Index;
return -1;
}
public char Next() {
return path[index++];
}
}
public delegate int GlobFunc (string ptr, int p, int len, object ary);
private class GlobArgs {
internal GlobFunc func;
internal int c = -1;
internal IList<string> v;
public GlobArgs(GlobFunc func, IList<string> arg) {
this.func = func;
this.v = arg;
}
}
public static GlobFunc push_pattern = (ptr, p, len, ary) => {
((IList<string>) ary).Add(ptr.Substring(p, len));
return 0;
};
public static GlobFunc glob_caller = (ptr, p, len, ary) => {
GlobArgs args = (GlobArgs)ary;
args.c = p;
return args.func(ptr, args.c, len, args.v);
};
private static int PushBraces(string cwd, IList<string> result, GlobPattern pattern) {
pattern.Reset();
int lbrace = pattern.IndexOf('{'); // index of left-most brace
int rbrace = pattern.FindClosingIndexOf(lbrace);// index of right-most brace
// No or mismatched braces..Move along..nothing to see here
if(lbrace == -1 || rbrace == -1) return PushGlobs(cwd, result, pattern);
// Peel onion...make subpatterns out of outer layer of glob and recall with each subpattern
// Example: foo{a{c},b}bar -> fooa{c}bar, foobbar
string buf = "";
int middleRegionIndex;
int i = lbrace;
while(pattern.path[i] != '}') {
middleRegionIndex = i + 1;
for(i = middleRegionIndex; i < pattern.end && pattern.path[i] != '}' && pattern.path[i] != ','; i++) {
if (pattern.path[i] == '{') pattern.FindClosingIndexOf(i); // skip inner braces
}
buf = "";
buf += pattern.path.Substring(pattern.begin, lbrace - pattern.begin);
buf += pattern.path.Substring(middleRegionIndex, i - middleRegionIndex);
buf += pattern.path.Substring(rbrace+1, pattern.end - (rbrace+1));
int status = PushBraces(cwd, result, new GlobPattern(buf, 0, buf.Length, pattern.flags));
if(status != 0) return status;
}
return 0; // All braces pushed..
}
private static int PushGlobs(string cwd, IList<string> ary, GlobPattern pattern) {
pattern.flags |= FNM_SYSCASE;
return GlobHelper(cwd, pattern.path, pattern.begin, pattern.end, -1, pattern.flags, glob_caller, new GlobArgs(push_pattern, ary));
}
private static bool HasMagic(string pattern, int begin, int end, int flags) {
bool escape = (flags & FNM_NOESCAPE) == 0;
bool nocase = (flags & FNM_CASEFOLD) != 0;
int open = 0;
for(int i = begin; i < end; i++) {
switch(pattern[i]) {
case '?':
case '*':
return true;
case '[': /* Only accept an open brace if there is a close */
open++; /* brace to match it. Bracket expressions must be */
continue; /* complete, according to Posix.2 */
case ']':
if (open > 0) return true;
continue;
case '\\':
if (escape && i == end) return false;
break;
default:
if (FNM_SYSCASE == 0 && nocase && char.IsLetter(pattern[i])) return true;
break;
}
}
return false;
}
private static int RemoveBackslashes(StringBuilder pattern, int index, int len) {
int t = index;
for (; index < len; index++, t++) {
if (pattern[index] == '\\' && ++index == len) break;
string ss = pattern.ToString().Substring(index, 1);
pattern.Remove(t, 1);
pattern.Insert(t, ss);
}
return t;
}
private static int strchr(string pattern, int begin, int end, char ch) {
for (int i = begin; i < end; i++) {
if (pattern[i] == ch) return i;
}
return -1;
}
private static string ExtractPath(string pattern, int begin, int end) {
int len = end - begin;
if (len > 1 && pattern[end-1] == '/' && (!DOSISH || (len < 2 || pattern[end-2] != ':'))) len--;
return pattern.Substring(begin, len);
}
private static string ExtractElem(string pattern, int begin, int end) {
int elementEnd = strchr(pattern, begin, end, '/');
if (elementEnd == -1) elementEnd = end;
return ExtractPath(pattern, begin, elementEnd);
}
private static bool BASE(string _base) {
return DOSISH ?
(_base.Length > 0 && !((IsDirSep(_base[0]) && _base.Length < 2) || (_base.Length > 2 && _base[1] == ':' && IsDirSep(_base[2]) && _base.Length < 4)))
:
(_base.Length > 0 && !(IsDirSep(_base[0]) && _base.Length < 2));
}
private static string[] Files(DirectoryInfo directory) {
FileSystemInfo[] files = directory.GetFileSystemInfos();
string[] filesPlusDotFiles = new string[files.Length + 2];
filesPlusDotFiles[0] = ".";
filesPlusDotFiles[1] = "..";
for(int i=0, j=files.Length; i<j; i++)
filesPlusDotFiles[i+2] = files[i].Name;
return filesPlusDotFiles;
}
private static int GlobHelper(string cwd, string pattern, int begin, int end, int sub, int flags, GlobFunc func, GlobArgs arg) {
int p,m;
int status = 0;
StringBuilder newpath = null;
FileSystemInfo st;
p = sub != -1 ? sub : begin;
if (!HasMagic(pattern, p, end, flags)) {
if (DOSISH || (flags & FNM_NOESCAPE) == 0) {
newpath = new StringBuilder();
newpath.Append(pattern, 0, end);
if (sub != -1) {
p = (sub - begin);
end = RemoveBackslashes(newpath, p, end);
sub = p;
} else {
end = RemoveBackslashes(newpath, 0, end);
pattern = newpath.ToString();
}
}
if(pattern[begin] == '/' || (DOSISH && begin+2<end && pattern[begin+1] == ':' && IsDirSep(pattern[begin+2]))) {
string ss = pattern.Substring(begin, end-begin);
if(new FileInfo(ss).Exists || new DirectoryInfo(ss).Exists) {
status = func(pattern, begin, end, arg);
}
} else if((end - begin) > 0) { // Length check is a hack. We should not be reeiving "" as a filename ever.
string ss2 = pattern.Substring(begin, end-begin);
if(new FileInfo(ss2).Exists || new DirectoryInfo(ss2).Exists) {
status = func(pattern, begin, end - begin, arg);
}
}
return status;
}
string bytes2 = pattern;
string buf = "";
var link = new List<string>();
while(p != -1 && status == 0) {
if(bytes2[p] == '/') p++;
m = strchr(bytes2, p, end, '/');
if(HasMagic(bytes2, p, m == -1 ? end : m, flags)) {
do {
string _base = ExtractPath(bytes2, begin, p);
string dir = begin == p ? "." : _base;
string magic = ExtractElem(bytes2,p,end);
bool recursive = false;
try {
if(dir[0] == '/' || (DOSISH && 2<dir.Length && dir[1] == ':' && IsDirSep(dir[2]))) {
st = new DirectoryInfo(dir);
} else {
st = new DirectoryInfo(Path.Combine(cwd, dir));
}
} catch(Exception) {
// A clear sign that the file doesn't exist.
return status;
}
if(st.Exists) {
if(m != -1 && magic.Equals(DOUBLE_STAR)) {
int n = _base.Length;
recursive = true;
buf = _base + bytes2.Substring((_base.Length > 0 ? m : m + 1), end - (_base.Length > 0 ? m : m + 1));
status = GlobHelper(cwd, buf, 0, buf.Length, n, flags, func, arg);
if(status != 0) {
goto finalize;
}
}
} else {
return status;
}
string[] dirp = Files((DirectoryInfo)st);
for(int i=0;i<dirp.Length;i++) {
if(recursive) {
string bs = dirp[i];
if(FilenameMatch(STAR,0,1,bs,0,bs.Length,flags) != 0) {
continue;
}
buf = _base + (BASE(_base) ? SLASH : EMPTY);
buf += dirp[i];
if(buf[0] == '/' || (DOSISH && 2<buf.Length && buf[1] == ':' && IsDirSep(buf[2]))) {
st = new DirectoryInfo(buf);
} else {
st = new DirectoryInfo(Path.Combine(cwd, buf));
}
if(st.Exists && !".".Equals(dirp[i]) && !"..".Equals(dirp[i])) {
int t = buf.Length;
buf += SLASH + DOUBLE_STAR;
buf += bytes2.Substring(m, end-m);
status = GlobHelper(cwd, buf, 0, buf.Length, t, flags, func, arg);
if(status != 0) {
break;
}
}
continue;
}
string bsx = dirp[i];
if(FilenameMatch(magic,0,magic.Length,bsx,0, bsx.Length,flags) == 0) {
buf = _base + (BASE(_base) ? SLASH : EMPTY) + dirp[i];
if(m == -1) {
status = func(buf,0,buf.Length,arg);
if(status != 0) {
break;
}
continue;
}
link.Add(buf);
buf = "";
}
}
} while(false);
finalize:
if(link.Count > 0) {
foreach(string b in link) {
if(status == 0) {
if(b[0] == '/' || (DOSISH && 2<b.Length && b[1] == ':' && IsDirSep(b[2]))) {
st = new DirectoryInfo(b);
} else {
st = new DirectoryInfo(Path.Combine(cwd, b));
}
if(st.Exists) {
int len = b.Length;
buf = b + bytes2.Substring(m, end - m);
status = GlobHelper(cwd,buf,0,buf.Length,len,flags,func,arg);
}
}
}
return status;
}
}
p = m;
}
return status;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnLegajosExt class.
/// </summary>
[Serializable]
public partial class PnLegajosExtCollection : ActiveList<PnLegajosExt, PnLegajosExtCollection>
{
public PnLegajosExtCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnLegajosExtCollection</returns>
public PnLegajosExtCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnLegajosExt o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_legajos_ext table.
/// </summary>
[Serializable]
public partial class PnLegajosExt : ActiveRecord<PnLegajosExt>, IActiveRecord
{
#region .ctors and Default Settings
public PnLegajosExt()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnLegajosExt(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnLegajosExt(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnLegajosExt(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_legajos_ext", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema);
colvarIdLegajo.ColumnName = "id_legajo";
colvarIdLegajo.DataType = DbType.Int32;
colvarIdLegajo.MaxLength = 0;
colvarIdLegajo.AutoIncrement = true;
colvarIdLegajo.IsNullable = false;
colvarIdLegajo.IsPrimaryKey = true;
colvarIdLegajo.IsForeignKey = false;
colvarIdLegajo.IsReadOnly = false;
colvarIdLegajo.DefaultSetting = @"";
colvarIdLegajo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLegajo);
TableSchema.TableColumn colvarEstadoCivil = new TableSchema.TableColumn(schema);
colvarEstadoCivil.ColumnName = "estado_civil";
colvarEstadoCivil.DataType = DbType.Int16;
colvarEstadoCivil.MaxLength = 0;
colvarEstadoCivil.AutoIncrement = false;
colvarEstadoCivil.IsNullable = false;
colvarEstadoCivil.IsPrimaryKey = false;
colvarEstadoCivil.IsForeignKey = false;
colvarEstadoCivil.IsReadOnly = false;
colvarEstadoCivil.DefaultSetting = @"";
colvarEstadoCivil.ForeignKeyTableName = "";
schema.Columns.Add(colvarEstadoCivil);
TableSchema.TableColumn colvarFechaEstadoCivil = new TableSchema.TableColumn(schema);
colvarFechaEstadoCivil.ColumnName = "fecha_estado_civil";
colvarFechaEstadoCivil.DataType = DbType.DateTime;
colvarFechaEstadoCivil.MaxLength = 0;
colvarFechaEstadoCivil.AutoIncrement = false;
colvarFechaEstadoCivil.IsNullable = false;
colvarFechaEstadoCivil.IsPrimaryKey = false;
colvarFechaEstadoCivil.IsForeignKey = false;
colvarFechaEstadoCivil.IsReadOnly = false;
colvarFechaEstadoCivil.DefaultSetting = @"";
colvarFechaEstadoCivil.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaEstadoCivil);
TableSchema.TableColumn colvarCedulaIdentidad = new TableSchema.TableColumn(schema);
colvarCedulaIdentidad.ColumnName = "cedula_identidad";
colvarCedulaIdentidad.DataType = DbType.AnsiString;
colvarCedulaIdentidad.MaxLength = -1;
colvarCedulaIdentidad.AutoIncrement = false;
colvarCedulaIdentidad.IsNullable = true;
colvarCedulaIdentidad.IsPrimaryKey = false;
colvarCedulaIdentidad.IsForeignKey = false;
colvarCedulaIdentidad.IsReadOnly = false;
colvarCedulaIdentidad.DefaultSetting = @"";
colvarCedulaIdentidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarCedulaIdentidad);
TableSchema.TableColumn colvarNacionalidad = new TableSchema.TableColumn(schema);
colvarNacionalidad.ColumnName = "nacionalidad";
colvarNacionalidad.DataType = DbType.AnsiString;
colvarNacionalidad.MaxLength = -1;
colvarNacionalidad.AutoIncrement = false;
colvarNacionalidad.IsNullable = false;
colvarNacionalidad.IsPrimaryKey = false;
colvarNacionalidad.IsForeignKey = false;
colvarNacionalidad.IsReadOnly = false;
colvarNacionalidad.DefaultSetting = @"";
colvarNacionalidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarNacionalidad);
TableSchema.TableColumn colvarTipoNacionalidad = new TableSchema.TableColumn(schema);
colvarTipoNacionalidad.ColumnName = "tipo_nacionalidad";
colvarTipoNacionalidad.DataType = DbType.Int16;
colvarTipoNacionalidad.MaxLength = 0;
colvarTipoNacionalidad.AutoIncrement = false;
colvarTipoNacionalidad.IsNullable = false;
colvarTipoNacionalidad.IsPrimaryKey = false;
colvarTipoNacionalidad.IsForeignKey = false;
colvarTipoNacionalidad.IsReadOnly = false;
colvarTipoNacionalidad.DefaultSetting = @"";
colvarTipoNacionalidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoNacionalidad);
TableSchema.TableColumn colvarBajaMotivo = new TableSchema.TableColumn(schema);
colvarBajaMotivo.ColumnName = "baja_motivo";
colvarBajaMotivo.DataType = DbType.AnsiString;
colvarBajaMotivo.MaxLength = -1;
colvarBajaMotivo.AutoIncrement = false;
colvarBajaMotivo.IsNullable = true;
colvarBajaMotivo.IsPrimaryKey = false;
colvarBajaMotivo.IsForeignKey = false;
colvarBajaMotivo.IsReadOnly = false;
colvarBajaMotivo.DefaultSetting = @"";
colvarBajaMotivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarBajaMotivo);
TableSchema.TableColumn colvarBajaObservaciones = new TableSchema.TableColumn(schema);
colvarBajaObservaciones.ColumnName = "baja_observaciones";
colvarBajaObservaciones.DataType = DbType.AnsiString;
colvarBajaObservaciones.MaxLength = -1;
colvarBajaObservaciones.AutoIncrement = false;
colvarBajaObservaciones.IsNullable = true;
colvarBajaObservaciones.IsPrimaryKey = false;
colvarBajaObservaciones.IsForeignKey = false;
colvarBajaObservaciones.IsReadOnly = false;
colvarBajaObservaciones.DefaultSetting = @"";
colvarBajaObservaciones.ForeignKeyTableName = "";
schema.Columns.Add(colvarBajaObservaciones);
TableSchema.TableColumn colvarInPresentador = new TableSchema.TableColumn(schema);
colvarInPresentador.ColumnName = "in_presentador";
colvarInPresentador.DataType = DbType.AnsiString;
colvarInPresentador.MaxLength = -1;
colvarInPresentador.AutoIncrement = false;
colvarInPresentador.IsNullable = true;
colvarInPresentador.IsPrimaryKey = false;
colvarInPresentador.IsForeignKey = false;
colvarInPresentador.IsReadOnly = false;
colvarInPresentador.DefaultSetting = @"";
colvarInPresentador.ForeignKeyTableName = "";
schema.Columns.Add(colvarInPresentador);
TableSchema.TableColumn colvarInOcupacion = new TableSchema.TableColumn(schema);
colvarInOcupacion.ColumnName = "in_ocupacion";
colvarInOcupacion.DataType = DbType.AnsiString;
colvarInOcupacion.MaxLength = -1;
colvarInOcupacion.AutoIncrement = false;
colvarInOcupacion.IsNullable = true;
colvarInOcupacion.IsPrimaryKey = false;
colvarInOcupacion.IsForeignKey = false;
colvarInOcupacion.IsReadOnly = false;
colvarInOcupacion.DefaultSetting = @"";
colvarInOcupacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarInOcupacion);
TableSchema.TableColumn colvarInSueldoInicial = new TableSchema.TableColumn(schema);
colvarInSueldoInicial.ColumnName = "in_sueldo_inicial";
colvarInSueldoInicial.DataType = DbType.Decimal;
colvarInSueldoInicial.MaxLength = 0;
colvarInSueldoInicial.AutoIncrement = false;
colvarInSueldoInicial.IsNullable = true;
colvarInSueldoInicial.IsPrimaryKey = false;
colvarInSueldoInicial.IsForeignKey = false;
colvarInSueldoInicial.IsReadOnly = false;
colvarInSueldoInicial.DefaultSetting = @"";
colvarInSueldoInicial.ForeignKeyTableName = "";
schema.Columns.Add(colvarInSueldoInicial);
TableSchema.TableColumn colvarInExamenMedico = new TableSchema.TableColumn(schema);
colvarInExamenMedico.ColumnName = "in_examen_medico";
colvarInExamenMedico.DataType = DbType.AnsiStringFixedLength;
colvarInExamenMedico.MaxLength = 1;
colvarInExamenMedico.AutoIncrement = false;
colvarInExamenMedico.IsNullable = false;
colvarInExamenMedico.IsPrimaryKey = false;
colvarInExamenMedico.IsForeignKey = false;
colvarInExamenMedico.IsReadOnly = false;
colvarInExamenMedico.DefaultSetting = @"";
colvarInExamenMedico.ForeignKeyTableName = "";
schema.Columns.Add(colvarInExamenMedico);
TableSchema.TableColumn colvarInFecha = new TableSchema.TableColumn(schema);
colvarInFecha.ColumnName = "in_fecha";
colvarInFecha.DataType = DbType.DateTime;
colvarInFecha.MaxLength = 0;
colvarInFecha.AutoIncrement = false;
colvarInFecha.IsNullable = true;
colvarInFecha.IsPrimaryKey = false;
colvarInFecha.IsForeignKey = false;
colvarInFecha.IsReadOnly = false;
colvarInFecha.DefaultSetting = @"";
colvarInFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarInFecha);
TableSchema.TableColumn colvarInSector = new TableSchema.TableColumn(schema);
colvarInSector.ColumnName = "in_sector";
colvarInSector.DataType = DbType.AnsiString;
colvarInSector.MaxLength = -1;
colvarInSector.AutoIncrement = false;
colvarInSector.IsNullable = true;
colvarInSector.IsPrimaryKey = false;
colvarInSector.IsForeignKey = false;
colvarInSector.IsReadOnly = false;
colvarInSector.DefaultSetting = @"";
colvarInSector.ForeignKeyTableName = "";
schema.Columns.Add(colvarInSector);
TableSchema.TableColumn colvarInObservaciones = new TableSchema.TableColumn(schema);
colvarInObservaciones.ColumnName = "in_observaciones";
colvarInObservaciones.DataType = DbType.AnsiString;
colvarInObservaciones.MaxLength = -1;
colvarInObservaciones.AutoIncrement = false;
colvarInObservaciones.IsNullable = true;
colvarInObservaciones.IsPrimaryKey = false;
colvarInObservaciones.IsForeignKey = false;
colvarInObservaciones.IsReadOnly = false;
colvarInObservaciones.DefaultSetting = @"";
colvarInObservaciones.ForeignKeyTableName = "";
schema.Columns.Add(colvarInObservaciones);
TableSchema.TableColumn colvarInCalificacion = new TableSchema.TableColumn(schema);
colvarInCalificacion.ColumnName = "in_calificacion";
colvarInCalificacion.DataType = DbType.AnsiString;
colvarInCalificacion.MaxLength = -1;
colvarInCalificacion.AutoIncrement = false;
colvarInCalificacion.IsNullable = true;
colvarInCalificacion.IsPrimaryKey = false;
colvarInCalificacion.IsForeignKey = false;
colvarInCalificacion.IsReadOnly = false;
colvarInCalificacion.DefaultSetting = @"";
colvarInCalificacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarInCalificacion);
TableSchema.TableColumn colvarInSeguroVidaObligatorio = new TableSchema.TableColumn(schema);
colvarInSeguroVidaObligatorio.ColumnName = "in_seguro_vida_obligatorio";
colvarInSeguroVidaObligatorio.DataType = DbType.AnsiString;
colvarInSeguroVidaObligatorio.MaxLength = -1;
colvarInSeguroVidaObligatorio.AutoIncrement = false;
colvarInSeguroVidaObligatorio.IsNullable = true;
colvarInSeguroVidaObligatorio.IsPrimaryKey = false;
colvarInSeguroVidaObligatorio.IsForeignKey = false;
colvarInSeguroVidaObligatorio.IsReadOnly = false;
colvarInSeguroVidaObligatorio.DefaultSetting = @"";
colvarInSeguroVidaObligatorio.ForeignKeyTableName = "";
schema.Columns.Add(colvarInSeguroVidaObligatorio);
TableSchema.TableColumn colvarInSeguroVida = new TableSchema.TableColumn(schema);
colvarInSeguroVida.ColumnName = "in_seguro_vida";
colvarInSeguroVida.DataType = DbType.AnsiString;
colvarInSeguroVida.MaxLength = -1;
colvarInSeguroVida.AutoIncrement = false;
colvarInSeguroVida.IsNullable = true;
colvarInSeguroVida.IsPrimaryKey = false;
colvarInSeguroVida.IsForeignKey = false;
colvarInSeguroVida.IsReadOnly = false;
colvarInSeguroVida.DefaultSetting = @"";
colvarInSeguroVida.ForeignKeyTableName = "";
schema.Columns.Add(colvarInSeguroVida);
TableSchema.TableColumn colvarInArt = new TableSchema.TableColumn(schema);
colvarInArt.ColumnName = "in_art";
colvarInArt.DataType = DbType.AnsiString;
colvarInArt.MaxLength = -1;
colvarInArt.AutoIncrement = false;
colvarInArt.IsNullable = true;
colvarInArt.IsPrimaryKey = false;
colvarInArt.IsForeignKey = false;
colvarInArt.IsReadOnly = false;
colvarInArt.DefaultSetting = @"";
colvarInArt.ForeignKeyTableName = "";
schema.Columns.Add(colvarInArt);
TableSchema.TableColumn colvarInBeneficiario = new TableSchema.TableColumn(schema);
colvarInBeneficiario.ColumnName = "in_beneficiario";
colvarInBeneficiario.DataType = DbType.AnsiString;
colvarInBeneficiario.MaxLength = -1;
colvarInBeneficiario.AutoIncrement = false;
colvarInBeneficiario.IsNullable = true;
colvarInBeneficiario.IsPrimaryKey = false;
colvarInBeneficiario.IsForeignKey = false;
colvarInBeneficiario.IsReadOnly = false;
colvarInBeneficiario.DefaultSetting = @"";
colvarInBeneficiario.ForeignKeyTableName = "";
schema.Columns.Add(colvarInBeneficiario);
TableSchema.TableColumn colvarInCategoria = new TableSchema.TableColumn(schema);
colvarInCategoria.ColumnName = "in_categoria";
colvarInCategoria.DataType = DbType.Int16;
colvarInCategoria.MaxLength = 0;
colvarInCategoria.AutoIncrement = false;
colvarInCategoria.IsNullable = false;
colvarInCategoria.IsPrimaryKey = false;
colvarInCategoria.IsForeignKey = false;
colvarInCategoria.IsReadOnly = false;
colvarInCategoria.DefaultSetting = @"";
colvarInCategoria.ForeignKeyTableName = "";
schema.Columns.Add(colvarInCategoria);
TableSchema.TableColumn colvarProfesion = new TableSchema.TableColumn(schema);
colvarProfesion.ColumnName = "profesion";
colvarProfesion.DataType = DbType.AnsiString;
colvarProfesion.MaxLength = -1;
colvarProfesion.AutoIncrement = false;
colvarProfesion.IsNullable = true;
colvarProfesion.IsPrimaryKey = false;
colvarProfesion.IsForeignKey = false;
colvarProfesion.IsReadOnly = false;
colvarProfesion.DefaultSetting = @"";
colvarProfesion.ForeignKeyTableName = "";
schema.Columns.Add(colvarProfesion);
TableSchema.TableColumn colvarEstudios = new TableSchema.TableColumn(schema);
colvarEstudios.ColumnName = "estudios";
colvarEstudios.DataType = DbType.AnsiString;
colvarEstudios.MaxLength = -1;
colvarEstudios.AutoIncrement = false;
colvarEstudios.IsNullable = true;
colvarEstudios.IsPrimaryKey = false;
colvarEstudios.IsForeignKey = false;
colvarEstudios.IsReadOnly = false;
colvarEstudios.DefaultSetting = @"";
colvarEstudios.ForeignKeyTableName = "";
schema.Columns.Add(colvarEstudios);
TableSchema.TableColumn colvarCodigoPostal = new TableSchema.TableColumn(schema);
colvarCodigoPostal.ColumnName = "codigo_postal";
colvarCodigoPostal.DataType = DbType.Int16;
colvarCodigoPostal.MaxLength = 0;
colvarCodigoPostal.AutoIncrement = false;
colvarCodigoPostal.IsNullable = true;
colvarCodigoPostal.IsPrimaryKey = false;
colvarCodigoPostal.IsForeignKey = false;
colvarCodigoPostal.IsReadOnly = false;
colvarCodigoPostal.DefaultSetting = @"";
colvarCodigoPostal.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoPostal);
TableSchema.TableColumn colvarOtrosConocimientos = new TableSchema.TableColumn(schema);
colvarOtrosConocimientos.ColumnName = "otros_conocimientos";
colvarOtrosConocimientos.DataType = DbType.AnsiString;
colvarOtrosConocimientos.MaxLength = -1;
colvarOtrosConocimientos.AutoIncrement = false;
colvarOtrosConocimientos.IsNullable = true;
colvarOtrosConocimientos.IsPrimaryKey = false;
colvarOtrosConocimientos.IsForeignKey = false;
colvarOtrosConocimientos.IsReadOnly = false;
colvarOtrosConocimientos.DefaultSetting = @"";
colvarOtrosConocimientos.ForeignKeyTableName = "";
schema.Columns.Add(colvarOtrosConocimientos);
TableSchema.TableColumn colvarExhibeTitulos = new TableSchema.TableColumn(schema);
colvarExhibeTitulos.ColumnName = "exhibe_titulos";
colvarExhibeTitulos.DataType = DbType.AnsiStringFixedLength;
colvarExhibeTitulos.MaxLength = 1;
colvarExhibeTitulos.AutoIncrement = false;
colvarExhibeTitulos.IsNullable = false;
colvarExhibeTitulos.IsPrimaryKey = false;
colvarExhibeTitulos.IsForeignKey = false;
colvarExhibeTitulos.IsReadOnly = false;
colvarExhibeTitulos.DefaultSetting = @"";
colvarExhibeTitulos.ForeignKeyTableName = "";
schema.Columns.Add(colvarExhibeTitulos);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_legajos_ext",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdLegajo")]
[Bindable(true)]
public int IdLegajo
{
get { return GetColumnValue<int>(Columns.IdLegajo); }
set { SetColumnValue(Columns.IdLegajo, value); }
}
[XmlAttribute("EstadoCivil")]
[Bindable(true)]
public short EstadoCivil
{
get { return GetColumnValue<short>(Columns.EstadoCivil); }
set { SetColumnValue(Columns.EstadoCivil, value); }
}
[XmlAttribute("FechaEstadoCivil")]
[Bindable(true)]
public DateTime FechaEstadoCivil
{
get { return GetColumnValue<DateTime>(Columns.FechaEstadoCivil); }
set { SetColumnValue(Columns.FechaEstadoCivil, value); }
}
[XmlAttribute("CedulaIdentidad")]
[Bindable(true)]
public string CedulaIdentidad
{
get { return GetColumnValue<string>(Columns.CedulaIdentidad); }
set { SetColumnValue(Columns.CedulaIdentidad, value); }
}
[XmlAttribute("Nacionalidad")]
[Bindable(true)]
public string Nacionalidad
{
get { return GetColumnValue<string>(Columns.Nacionalidad); }
set { SetColumnValue(Columns.Nacionalidad, value); }
}
[XmlAttribute("TipoNacionalidad")]
[Bindable(true)]
public short TipoNacionalidad
{
get { return GetColumnValue<short>(Columns.TipoNacionalidad); }
set { SetColumnValue(Columns.TipoNacionalidad, value); }
}
[XmlAttribute("BajaMotivo")]
[Bindable(true)]
public string BajaMotivo
{
get { return GetColumnValue<string>(Columns.BajaMotivo); }
set { SetColumnValue(Columns.BajaMotivo, value); }
}
[XmlAttribute("BajaObservaciones")]
[Bindable(true)]
public string BajaObservaciones
{
get { return GetColumnValue<string>(Columns.BajaObservaciones); }
set { SetColumnValue(Columns.BajaObservaciones, value); }
}
[XmlAttribute("InPresentador")]
[Bindable(true)]
public string InPresentador
{
get { return GetColumnValue<string>(Columns.InPresentador); }
set { SetColumnValue(Columns.InPresentador, value); }
}
[XmlAttribute("InOcupacion")]
[Bindable(true)]
public string InOcupacion
{
get { return GetColumnValue<string>(Columns.InOcupacion); }
set { SetColumnValue(Columns.InOcupacion, value); }
}
[XmlAttribute("InSueldoInicial")]
[Bindable(true)]
public decimal? InSueldoInicial
{
get { return GetColumnValue<decimal?>(Columns.InSueldoInicial); }
set { SetColumnValue(Columns.InSueldoInicial, value); }
}
[XmlAttribute("InExamenMedico")]
[Bindable(true)]
public string InExamenMedico
{
get { return GetColumnValue<string>(Columns.InExamenMedico); }
set { SetColumnValue(Columns.InExamenMedico, value); }
}
[XmlAttribute("InFecha")]
[Bindable(true)]
public DateTime? InFecha
{
get { return GetColumnValue<DateTime?>(Columns.InFecha); }
set { SetColumnValue(Columns.InFecha, value); }
}
[XmlAttribute("InSector")]
[Bindable(true)]
public string InSector
{
get { return GetColumnValue<string>(Columns.InSector); }
set { SetColumnValue(Columns.InSector, value); }
}
[XmlAttribute("InObservaciones")]
[Bindable(true)]
public string InObservaciones
{
get { return GetColumnValue<string>(Columns.InObservaciones); }
set { SetColumnValue(Columns.InObservaciones, value); }
}
[XmlAttribute("InCalificacion")]
[Bindable(true)]
public string InCalificacion
{
get { return GetColumnValue<string>(Columns.InCalificacion); }
set { SetColumnValue(Columns.InCalificacion, value); }
}
[XmlAttribute("InSeguroVidaObligatorio")]
[Bindable(true)]
public string InSeguroVidaObligatorio
{
get { return GetColumnValue<string>(Columns.InSeguroVidaObligatorio); }
set { SetColumnValue(Columns.InSeguroVidaObligatorio, value); }
}
[XmlAttribute("InSeguroVida")]
[Bindable(true)]
public string InSeguroVida
{
get { return GetColumnValue<string>(Columns.InSeguroVida); }
set { SetColumnValue(Columns.InSeguroVida, value); }
}
[XmlAttribute("InArt")]
[Bindable(true)]
public string InArt
{
get { return GetColumnValue<string>(Columns.InArt); }
set { SetColumnValue(Columns.InArt, value); }
}
[XmlAttribute("InBeneficiario")]
[Bindable(true)]
public string InBeneficiario
{
get { return GetColumnValue<string>(Columns.InBeneficiario); }
set { SetColumnValue(Columns.InBeneficiario, value); }
}
[XmlAttribute("InCategoria")]
[Bindable(true)]
public short InCategoria
{
get { return GetColumnValue<short>(Columns.InCategoria); }
set { SetColumnValue(Columns.InCategoria, value); }
}
[XmlAttribute("Profesion")]
[Bindable(true)]
public string Profesion
{
get { return GetColumnValue<string>(Columns.Profesion); }
set { SetColumnValue(Columns.Profesion, value); }
}
[XmlAttribute("Estudios")]
[Bindable(true)]
public string Estudios
{
get { return GetColumnValue<string>(Columns.Estudios); }
set { SetColumnValue(Columns.Estudios, value); }
}
[XmlAttribute("CodigoPostal")]
[Bindable(true)]
public short? CodigoPostal
{
get { return GetColumnValue<short?>(Columns.CodigoPostal); }
set { SetColumnValue(Columns.CodigoPostal, value); }
}
[XmlAttribute("OtrosConocimientos")]
[Bindable(true)]
public string OtrosConocimientos
{
get { return GetColumnValue<string>(Columns.OtrosConocimientos); }
set { SetColumnValue(Columns.OtrosConocimientos, value); }
}
[XmlAttribute("ExhibeTitulos")]
[Bindable(true)]
public string ExhibeTitulos
{
get { return GetColumnValue<string>(Columns.ExhibeTitulos); }
set { SetColumnValue(Columns.ExhibeTitulos, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(short varEstadoCivil,DateTime varFechaEstadoCivil,string varCedulaIdentidad,string varNacionalidad,short varTipoNacionalidad,string varBajaMotivo,string varBajaObservaciones,string varInPresentador,string varInOcupacion,decimal? varInSueldoInicial,string varInExamenMedico,DateTime? varInFecha,string varInSector,string varInObservaciones,string varInCalificacion,string varInSeguroVidaObligatorio,string varInSeguroVida,string varInArt,string varInBeneficiario,short varInCategoria,string varProfesion,string varEstudios,short? varCodigoPostal,string varOtrosConocimientos,string varExhibeTitulos)
{
PnLegajosExt item = new PnLegajosExt();
item.EstadoCivil = varEstadoCivil;
item.FechaEstadoCivil = varFechaEstadoCivil;
item.CedulaIdentidad = varCedulaIdentidad;
item.Nacionalidad = varNacionalidad;
item.TipoNacionalidad = varTipoNacionalidad;
item.BajaMotivo = varBajaMotivo;
item.BajaObservaciones = varBajaObservaciones;
item.InPresentador = varInPresentador;
item.InOcupacion = varInOcupacion;
item.InSueldoInicial = varInSueldoInicial;
item.InExamenMedico = varInExamenMedico;
item.InFecha = varInFecha;
item.InSector = varInSector;
item.InObservaciones = varInObservaciones;
item.InCalificacion = varInCalificacion;
item.InSeguroVidaObligatorio = varInSeguroVidaObligatorio;
item.InSeguroVida = varInSeguroVida;
item.InArt = varInArt;
item.InBeneficiario = varInBeneficiario;
item.InCategoria = varInCategoria;
item.Profesion = varProfesion;
item.Estudios = varEstudios;
item.CodigoPostal = varCodigoPostal;
item.OtrosConocimientos = varOtrosConocimientos;
item.ExhibeTitulos = varExhibeTitulos;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdLegajo,short varEstadoCivil,DateTime varFechaEstadoCivil,string varCedulaIdentidad,string varNacionalidad,short varTipoNacionalidad,string varBajaMotivo,string varBajaObservaciones,string varInPresentador,string varInOcupacion,decimal? varInSueldoInicial,string varInExamenMedico,DateTime? varInFecha,string varInSector,string varInObservaciones,string varInCalificacion,string varInSeguroVidaObligatorio,string varInSeguroVida,string varInArt,string varInBeneficiario,short varInCategoria,string varProfesion,string varEstudios,short? varCodigoPostal,string varOtrosConocimientos,string varExhibeTitulos)
{
PnLegajosExt item = new PnLegajosExt();
item.IdLegajo = varIdLegajo;
item.EstadoCivil = varEstadoCivil;
item.FechaEstadoCivil = varFechaEstadoCivil;
item.CedulaIdentidad = varCedulaIdentidad;
item.Nacionalidad = varNacionalidad;
item.TipoNacionalidad = varTipoNacionalidad;
item.BajaMotivo = varBajaMotivo;
item.BajaObservaciones = varBajaObservaciones;
item.InPresentador = varInPresentador;
item.InOcupacion = varInOcupacion;
item.InSueldoInicial = varInSueldoInicial;
item.InExamenMedico = varInExamenMedico;
item.InFecha = varInFecha;
item.InSector = varInSector;
item.InObservaciones = varInObservaciones;
item.InCalificacion = varInCalificacion;
item.InSeguroVidaObligatorio = varInSeguroVidaObligatorio;
item.InSeguroVida = varInSeguroVida;
item.InArt = varInArt;
item.InBeneficiario = varInBeneficiario;
item.InCategoria = varInCategoria;
item.Profesion = varProfesion;
item.Estudios = varEstudios;
item.CodigoPostal = varCodigoPostal;
item.OtrosConocimientos = varOtrosConocimientos;
item.ExhibeTitulos = varExhibeTitulos;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdLegajoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn EstadoCivilColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn FechaEstadoCivilColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn CedulaIdentidadColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn NacionalidadColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn TipoNacionalidadColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn BajaMotivoColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn BajaObservacionesColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn InPresentadorColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn InOcupacionColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn InSueldoInicialColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn InExamenMedicoColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn InFechaColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn InSectorColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn InObservacionesColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn InCalificacionColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn InSeguroVidaObligatorioColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn InSeguroVidaColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn InArtColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn InBeneficiarioColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn InCategoriaColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn ProfesionColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn EstudiosColumn
{
get { return Schema.Columns[22]; }
}
public static TableSchema.TableColumn CodigoPostalColumn
{
get { return Schema.Columns[23]; }
}
public static TableSchema.TableColumn OtrosConocimientosColumn
{
get { return Schema.Columns[24]; }
}
public static TableSchema.TableColumn ExhibeTitulosColumn
{
get { return Schema.Columns[25]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdLegajo = @"id_legajo";
public static string EstadoCivil = @"estado_civil";
public static string FechaEstadoCivil = @"fecha_estado_civil";
public static string CedulaIdentidad = @"cedula_identidad";
public static string Nacionalidad = @"nacionalidad";
public static string TipoNacionalidad = @"tipo_nacionalidad";
public static string BajaMotivo = @"baja_motivo";
public static string BajaObservaciones = @"baja_observaciones";
public static string InPresentador = @"in_presentador";
public static string InOcupacion = @"in_ocupacion";
public static string InSueldoInicial = @"in_sueldo_inicial";
public static string InExamenMedico = @"in_examen_medico";
public static string InFecha = @"in_fecha";
public static string InSector = @"in_sector";
public static string InObservaciones = @"in_observaciones";
public static string InCalificacion = @"in_calificacion";
public static string InSeguroVidaObligatorio = @"in_seguro_vida_obligatorio";
public static string InSeguroVida = @"in_seguro_vida";
public static string InArt = @"in_art";
public static string InBeneficiario = @"in_beneficiario";
public static string InCategoria = @"in_categoria";
public static string Profesion = @"profesion";
public static string Estudios = @"estudios";
public static string CodigoPostal = @"codigo_postal";
public static string OtrosConocimientos = @"otros_conocimientos";
public static string ExhibeTitulos = @"exhibe_titulos";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.SmartContract.Iterators;
using Neo.SmartContract.Native;
using System;
using System.Linq;
namespace Neo.SmartContract
{
partial class ApplicationEngine
{
/// <summary>
/// The maximum size of storage keys.
/// </summary>
public const int MaxStorageKeySize = 64;
/// <summary>
/// The maximum size of storage values.
/// </summary>
public const int MaxStorageValueSize = ushort.MaxValue;
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.GetContext.
/// Gets the storage context for the current contract.
/// </summary>
public static readonly InteropDescriptor System_Storage_GetContext = Register("System.Storage.GetContext", nameof(GetStorageContext), 1 << 4, CallFlags.ReadStates);
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.GetReadOnlyContext.
/// Gets the readonly storage context for the current contract.
/// </summary>
public static readonly InteropDescriptor System_Storage_GetReadOnlyContext = Register("System.Storage.GetReadOnlyContext", nameof(GetReadOnlyContext), 1 << 4, CallFlags.ReadStates);
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.AsReadOnly.
/// Converts the specified storage context to a new readonly storage context.
/// </summary>
public static readonly InteropDescriptor System_Storage_AsReadOnly = Register("System.Storage.AsReadOnly", nameof(AsReadOnly), 1 << 4, CallFlags.ReadStates);
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.Get.
/// Gets the entry with the specified key from the storage.
/// </summary>
public static readonly InteropDescriptor System_Storage_Get = Register("System.Storage.Get", nameof(Get), 1 << 15, CallFlags.ReadStates);
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.Find.
/// Finds the entries from the storage.
/// </summary>
public static readonly InteropDescriptor System_Storage_Find = Register("System.Storage.Find", nameof(Find), 1 << 15, CallFlags.ReadStates);
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.Put.
/// Puts a new entry into the storage.
/// </summary>
public static readonly InteropDescriptor System_Storage_Put = Register("System.Storage.Put", nameof(Put), 1 << 15, CallFlags.WriteStates);
/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Storage.Delete.
/// Deletes an entry from the storage.
/// </summary>
public static readonly InteropDescriptor System_Storage_Delete = Register("System.Storage.Delete", nameof(Delete), 1 << 15, CallFlags.WriteStates);
/// <summary>
/// The implementation of System.Storage.GetContext.
/// Gets the storage context for the current contract.
/// </summary>
/// <returns>The storage context for the current contract.</returns>
protected internal StorageContext GetStorageContext()
{
ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash);
return new StorageContext
{
Id = contract.Id,
IsReadOnly = false
};
}
/// <summary>
/// The implementation of System.Storage.GetReadOnlyContext.
/// Gets the readonly storage context for the current contract.
/// </summary>
/// <returns>The storage context for the current contract.</returns>
protected internal StorageContext GetReadOnlyContext()
{
ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash);
return new StorageContext
{
Id = contract.Id,
IsReadOnly = true
};
}
/// <summary>
/// The implementation of System.Storage.AsReadOnly.
/// Converts the specified storage context to a new readonly storage context.
/// </summary>
/// <param name="context">The storage context to convert.</param>
/// <returns>The readonly storage context.</returns>
internal protected static StorageContext AsReadOnly(StorageContext context)
{
if (!context.IsReadOnly)
context = new StorageContext
{
Id = context.Id,
IsReadOnly = true
};
return context;
}
/// <summary>
/// The implementation of System.Storage.Get.
/// Gets the entry with the specified key from the storage.
/// </summary>
/// <param name="context">The context of the storage.</param>
/// <param name="key">The key of the entry.</param>
/// <returns>The value of the entry. Or <see langword="null"/> if the entry doesn't exist.</returns>
protected internal byte[] Get(StorageContext context, byte[] key)
{
return Snapshot.TryGet(new StorageKey
{
Id = context.Id,
Key = key.ToArray()
})?.Value;
}
/// <summary>
/// The implementation of System.Storage.Find.
/// Finds the entries from the storage.
/// </summary>
/// <param name="context">The context of the storage.</param>
/// <param name="prefix">The prefix of keys to find.</param>
/// <param name="options">The options of the search.</param>
/// <returns>An iterator for the results.</returns>
protected internal IIterator Find(StorageContext context, byte[] prefix, FindOptions options)
{
if ((options & ~FindOptions.All) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
if (options.HasFlag(FindOptions.KeysOnly) && (options.HasFlag(FindOptions.ValuesOnly) || options.HasFlag(FindOptions.DeserializeValues) || options.HasFlag(FindOptions.PickField0) || options.HasFlag(FindOptions.PickField1)))
throw new ArgumentException(null, nameof(options));
if (options.HasFlag(FindOptions.ValuesOnly) && (options.HasFlag(FindOptions.KeysOnly) || options.HasFlag(FindOptions.RemovePrefix)))
throw new ArgumentException(null, nameof(options));
if (options.HasFlag(FindOptions.PickField0) && options.HasFlag(FindOptions.PickField1))
throw new ArgumentException(null, nameof(options));
if ((options.HasFlag(FindOptions.PickField0) || options.HasFlag(FindOptions.PickField1)) && !options.HasFlag(FindOptions.DeserializeValues))
throw new ArgumentException(null, nameof(options));
byte[] prefix_key = StorageKey.CreateSearchPrefix(context.Id, prefix);
return new StorageIterator(Snapshot.Find(prefix_key).GetEnumerator(), prefix.Length, options, ReferenceCounter);
}
/// <summary>
/// The implementation of System.Storage.Put.
/// Puts a new entry into the storage.
/// </summary>
/// <param name="context">The context of the storage.</param>
/// <param name="key">The key of the entry.</param>
/// <param name="value">The value of the entry.</param>
protected internal void Put(StorageContext context, byte[] key, byte[] value)
{
if (key.Length > MaxStorageKeySize || value.Length > MaxStorageValueSize || context.IsReadOnly)
throw new ArgumentException();
int newDataSize;
StorageKey skey = new()
{
Id = context.Id,
Key = key
};
StorageItem item = Snapshot.GetAndChange(skey);
if (item is null)
{
newDataSize = key.Length + value.Length;
Snapshot.Add(skey, item = new StorageItem());
}
else
{
if (value.Length == 0)
newDataSize = 0;
else if (value.Length <= item.Value.Length)
newDataSize = (value.Length - 1) / 4 + 1;
else if (item.Value.Length == 0)
newDataSize = value.Length;
else
newDataSize = (item.Value.Length - 1) / 4 + 1 + value.Length - item.Value.Length;
}
AddGas(newDataSize * StoragePrice);
item.Value = value;
}
/// <summary>
/// The implementation of System.Storage.Delete.
/// Deletes an entry from the storage.
/// </summary>
/// <param name="context">The context of the storage.</param>
/// <param name="key">The key of the entry.</param>
protected internal void Delete(StorageContext context, byte[] key)
{
if (context.IsReadOnly) throw new ArgumentException(null, nameof(context));
Snapshot.Delete(new StorageKey
{
Id = context.Id,
Key = key
});
}
}
}
| |
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 WebApplication.Api.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Runtime.Serialization;
using System.Windows.Forms;
namespace WitsWay.TempTests.RemainProcessTest.PlanUI.DrawObjects
{
/// <summary>
/// Rectangle graphic object
/// </summary>
//[Serializable]
public class DrawText : DrawObject
{
private Rectangle _rectangle;
private string _theText;
private Font _font;
protected string TheText
{
get { return _theText; }
set
{
_theText = value;
TipText = value;
}
}
public Font TheFont
{
get { return _font; }
set { _font = value; }
}
private const string EntryRectangle = "Rect";
private const string EntryText = "Text";
private const string EntryFontName = "FontName";
private const string EntryFontBold = "FontBold";
private const string EntryFontItalic = "FontItalic";
private const string EntryFontSize = "FontSize";
private const string EntryFontStrikeout = "FontStrikeout";
private const string EntryFontUnderline = "FontUnderline";
protected Rectangle Rectangle
{
get { return _rectangle; }
set { _rectangle = value; }
}
public DrawText()
{
//SetRectangle(0, 0, 1,1);
_theText = "";
Initialize();
}
/// <summary>
/// Clone this instance
/// </summary>
public override DrawObject Clone()
{
DrawText drawText = new DrawText();
drawText._font = _font;
drawText._theText = _theText;
drawText._rectangle = _rectangle;
FillDrawObjectFields(drawText);
return drawText;
}
public DrawText(int x, int y, string textToDraw, Font textFont, Color textColor)
{
_rectangle.X = x;
_rectangle.Y = y;
_theText = textToDraw;
_font = textFont;
Color = textColor;
Initialize();
}
/// <summary>
/// Draw rectangle
/// </summary>
/// <param name="g"></param>
public override void Draw(Graphics g)
{
Pen pen = new Pen(Color);
//Brush b = new SolidBrush(Color);
//g.DrawString(_theText, _font, b, new PointF(Rectangle.X, Rectangle.Y));
GraphicsPath gp = new GraphicsPath();
StringFormat format = StringFormat.GenericDefault;
gp.AddString(_theText, _font.FontFamily, (int)_font.Style, _font.SizeInPoints,
new PointF(Rectangle.X, Rectangle.Y), format);
// Rotate the path about it's center if necessary
if (Rotation != 0)
{
RectangleF pathBounds = gp.GetBounds();
Matrix m = new Matrix();
m.RotateAt(Rotation, new PointF(pathBounds.Left + (pathBounds.Width / 2), pathBounds.Top + (pathBounds.Height / 2)),
MatrixOrder.Append);
gp.Transform(m);
}
g.DrawPath(pen, gp);
_rectangle.Size = g.MeasureString(_theText, _font).ToSize();
pen.Dispose();
}
/// <summary>
/// Get number of handles
/// </summary>
public override int HandleCount => 8;
/// <summary>
/// Get handle point by 1-based number
/// </summary>
/// <param name="handleNumber"></param>
/// <returns></returns>
public override Point GetHandle(int handleNumber)
{
int x, y, xCenter, yCenter;
xCenter = _rectangle.X + _rectangle.Width / 2;
yCenter = _rectangle.Y + _rectangle.Height / 2;
x = _rectangle.X;
y = _rectangle.Y;
switch (handleNumber)
{
case 1:
x = _rectangle.X;
y = _rectangle.Y;
break;
case 2:
x = xCenter;
y = _rectangle.Y;
break;
case 3:
x = _rectangle.Right;
y = _rectangle.Y;
break;
case 4:
x = _rectangle.Right;
y = yCenter;
break;
case 5:
x = _rectangle.Right;
y = _rectangle.Bottom;
break;
case 6:
x = xCenter;
y = _rectangle.Bottom;
break;
case 7:
x = _rectangle.X;
y = _rectangle.Bottom;
break;
case 8:
x = _rectangle.X;
y = yCenter;
break;
}
return new Point(x, y);
}
/// <summary>
/// Hit test.
/// Return value: -1 - no hit
/// 0 - hit anywhere
/// > 1 - handle number
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public override int HitTest(Point point)
{
if (Selected)
{
for (int i = 1; i <= HandleCount; i++)
{
if (GetHandleRectangle(i).Contains(point))
return i;
}
}
if (PointInObject(point))
return 0;
return -1;
}
protected override bool PointInObject(Point point)
{
return _rectangle.Contains(point);
}
/// <summary>
/// Get cursor for the handle
/// </summary>
/// <param name="handleNumber"></param>
/// <returns></returns>
public override Cursor GetHandleCursor(int handleNumber)
{
//switch ( handleNumber )
//{
// case 1:
// return Cursors.SizeNWSE;
// case 2:
// return Cursors.SizeNS;
// case 3:
// return Cursors.SizeNESW;
// case 4:
// return Cursors.SizeWE;
// case 5:
// return Cursors.SizeNWSE;
// case 6:
// return Cursors.SizeNS;
// case 7:
// return Cursors.SizeNESW;
// case 8:
// return Cursors.SizeWE;
// default:
return Cursors.Default;
//}
}
/// <summary>
/// Move handle to new point (resizing)
/// </summary>
/// <param name="point"></param>
/// <param name="handleNumber"></param>
public override void MoveHandleTo(Point point, int handleNumber)
{
//int left = Rectangle.Left;
//int top = Rectangle.Top;
//int right = Rectangle.Right;
//int bottom = Rectangle.Bottom;
//switch ( handleNumber )
//{
// case 1:
// left = point.X;
// top = point.Y;
// break;
// case 2:
// top = point.Y;
// break;
// case 3:
// right = point.X;
// top = point.Y;
// break;
// case 4:
// right = point.X;
// break;
// case 5:
// right = point.X;
// bottom = point.Y;
// break;
// case 6:
// bottom = point.Y;
// break;
// case 7:
// left = point.X;
// bottom = point.Y;
// break;
// case 8:
// left = point.X;
// break;
//}
//SetRectangle(left, top, right - left, bottom - top);
}
public override bool IntersectsWith(Rectangle rectangle)
{
return Rectangle.IntersectsWith(rectangle);
}
/// <summary>
/// Move object
/// </summary>
/// <param name="deltaX"></param>
/// <param name="deltaY"></param>
public override void Move(int deltaX, int deltaY)
{
_rectangle.X += deltaX;
_rectangle.Y += deltaY;
Dirty = true;
}
public override void Dump()
{
//base.Dump ();
//Trace.WriteLine("rectangle.X = " + rectangle.X.ToString(CultureInfo.InvariantCulture));
//Trace.WriteLine("rectangle.Y = " + rectangle.Y.ToString(CultureInfo.InvariantCulture));
//Trace.WriteLine("rectangle.Width = " + rectangle.Width.ToString(CultureInfo.InvariantCulture));
//Trace.WriteLine("rectangle.Height = " + rectangle.Height.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Normalize rectangle
/// </summary>
public override void Normalize()
{
//rectangle = DrawRectangle.GetNormalizedRectangle(rectangle);
}
/// <summary>
/// Save objevt to serialization stream
/// </summary>
/// <param name="info"></param>
/// <param name="orderNumber">Index of the Layer being saved</param>
/// <param name="objectIndex">Index of this object in the Layer</param>
public override void SaveToStream(SerializationInfo info, int orderNumber, int objectIndex)
{
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryRectangle, orderNumber, objectIndex),
_rectangle);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryText, orderNumber, objectIndex),
_theText);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontName, orderNumber, objectIndex),
_font.Name);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontBold, orderNumber, objectIndex),
_font.Bold);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontItalic, orderNumber, objectIndex),
_font.Italic);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontSize, orderNumber, objectIndex),
_font.Size);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontStrikeout, orderNumber, objectIndex),
_font.Strikeout);
info.AddValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontUnderline, orderNumber, objectIndex),
_font.Underline);
base.SaveToStream(info, orderNumber, objectIndex);
}
/// <summary>
/// LOad object from serialization stream
/// </summary>
/// <param name="info"></param>
/// <param name="orderNumber"></param>
/// <param name="objectIndex"></param>
public override void LoadFromStream(SerializationInfo info, int orderNumber, int objectIndex)
{
_rectangle = (Rectangle)info.GetValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryRectangle, orderNumber, objectIndex),
typeof(Rectangle));
_theText = info.GetString(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryText, orderNumber, objectIndex));
string name = info.GetString(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontName, orderNumber, objectIndex));
bool bold = info.GetBoolean(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontBold, orderNumber, objectIndex));
bool italic = info.GetBoolean(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontItalic, orderNumber, objectIndex));
float size = (float)info.GetValue(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontSize, orderNumber, objectIndex),
typeof(float));
bool strikeout = info.GetBoolean(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontStrikeout, orderNumber, objectIndex));
bool underline = info.GetBoolean(
String.Format(CultureInfo.InvariantCulture,
"{0}{1}-{2}",
EntryFontUnderline, orderNumber, objectIndex));
FontStyle fs = FontStyle.Regular;
if (bold)
fs |= FontStyle.Bold;
if (italic)
fs |= FontStyle.Italic;
if (strikeout)
fs |= FontStyle.Strikeout;
if (underline)
fs |= FontStyle.Underline;
_font = new Font(name, size, fs);
base.LoadFromStream(info, orderNumber, objectIndex);
}
#region Helper Functions
//public static Rectangle GetNormalizedRectangle(int x1, int y1, int x2, int y2)
//{
//if ( x2 < x1 )
//{
// int tmp = x2;
// x2 = x1;
// x1 = tmp;
//}
//if ( y2 < y1 )
//{
// int tmp = y2;
// y2 = y1;
// y1 = tmp;
//}
//return new Rectangle(x1, y1, x2 - x1, y2 - y1);
//}
//public static Rectangle GetNormalizedRectangle(Point p1, Point p2)
//{
//return GetNormalizedRectangle(p1.X, p1.Y, p2.X, p2.Y);
//}
//public static Rectangle GetNormalizedRectangle(Rectangle r)
//{
//return GetNormalizedRectangle(r.X, r.Y, r.X + r.Width, r.Y + r.Height);
//}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using NAudio.Wave.SampleProviders;
namespace NAudio.Wave
{
/// <summary>
/// Represents Channel for the WaveMixerStream
/// 32 bit output and 16 bit input
/// It's output is always stereo
/// The input stream can be panned
/// </summary>
public class WaveChannel32 : WaveStream, ISampleNotifier
{
private WaveStream sourceStream;
private readonly WaveFormat waveFormat;
private readonly long length;
private readonly int destBytesPerSample;
private readonly int sourceBytesPerSample;
private volatile float volume;
private volatile float pan;
private long position;
private ISampleChunkConverter sampleProvider;
/// <summary>
/// Creates a new WaveChannel32
/// </summary>
/// <param name="sourceStream">the source stream</param>
/// <param name="volume">stream volume (1 is 0dB)</param>
/// <param name="pan">pan control (-1 to 1)</param>
public WaveChannel32(WaveStream sourceStream, float volume, float pan)
{
PadWithZeroes = true;
var providers = new ISampleChunkConverter[]
{
new Mono8SampleChunkConverter(),
new Stereo8SampleChunkConverter(),
new Mono16SampleChunkConverter(),
new Stereo16SampleChunkConverter(),
new Mono24SampleChunkConverter(),
new Stereo24SampleChunkConverter(),
new MonoFloatSampleChunkConverter(),
new StereoFloatSampleChunkConverter(),
};
foreach (var provider in providers)
{
if (provider.Supports(sourceStream.WaveFormat))
{
this.sampleProvider = provider;
break;
}
}
if (this.sampleProvider == null)
{
throw new ArgumentException("Unsupported sourceStream format");
}
// always outputs stereo 32 bit
waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sourceStream.WaveFormat.SampleRate, 2);
destBytesPerSample = 8; // includes stereo factoring
this.sourceStream = sourceStream;
this.volume = volume;
this.pan = pan;
sourceBytesPerSample = sourceStream.WaveFormat.Channels * sourceStream.WaveFormat.BitsPerSample / 8;
length = SourceToDest(sourceStream.Length);
position = 0;
}
private long SourceToDest(long sourceBytes)
{
return (sourceBytes / sourceBytesPerSample) * destBytesPerSample;
}
private long DestToSource(long destBytes)
{
return (destBytes / destBytesPerSample) * sourceBytesPerSample;
}
/// <summary>
/// Creates a WaveChannel32 with default settings
/// </summary>
/// <param name="sourceStream">The source stream</param>
public WaveChannel32(WaveStream sourceStream)
:
this(sourceStream, 1.0f, 0.0f)
{
}
/// <summary>
/// Gets the block alignment for this WaveStream
/// </summary>
public override int BlockAlign
{
get
{
return (int)SourceToDest(sourceStream.BlockAlign);
}
}
/// <summary>
/// Returns the stream length
/// </summary>
public override long Length
{
get
{
return length;
}
}
/// <summary>
/// Gets or sets the current position in the stream
/// </summary>
public override long Position
{
get
{
return position;
}
set
{
lock (this)
{
// make sure we don't get out of sync
value -= (value % BlockAlign);
if (value < 0)
{
sourceStream.Position = 0;
}
else
{
sourceStream.Position = DestToSource(value);
}
// source stream may not have accepted the reposition we gave it
position = SourceToDest(sourceStream.Position);
}
}
}
/// <summary>
/// Reads bytes from this wave stream
/// </summary>
/// <param name="destBuffer">The destination buffer</param>
/// <param name="offset">Offset into the destination buffer</param>
/// <param name="numBytes">Number of bytes read</param>
/// <returns>Number of bytes read.</returns>
public override int Read(byte[] destBuffer, int offset, int numBytes)
{
int bytesWritten = 0;
WaveBuffer destWaveBuffer = new WaveBuffer(destBuffer);
// 1. fill with silence
if (position < 0)
{
bytesWritten = (int)Math.Min(numBytes, 0 - position);
for (int n = 0; n < bytesWritten; n++)
destBuffer[n + offset] = 0;
}
if (bytesWritten < numBytes)
{
this.sampleProvider.LoadNextChunk(sourceStream, (numBytes - bytesWritten) / 8);
float left, right;
int outIndex = (offset / 4) + bytesWritten / 4;
while (this.sampleProvider.GetNextSample(out left, out right) && bytesWritten < numBytes)
{
// implement better panning laws.
left = (pan <= 0) ? left : (left * (1 - pan) / 2.0f);
right = (pan >= 0) ? right : (right * (pan + 1) / 2.0f);
left *= volume;
right *= volume;
destWaveBuffer.FloatBuffer[outIndex++] = left;
destWaveBuffer.FloatBuffer[outIndex++] = right;
bytesWritten += 8;
if (Sample != null) RaiseSample(left, right);
}
}
// 3. Fill out with zeroes
if (PadWithZeroes && bytesWritten < numBytes)
{
Array.Clear(destBuffer, offset + bytesWritten, numBytes - bytesWritten);
bytesWritten = numBytes;
}
position += bytesWritten;
return bytesWritten;
}
/// <summary>
/// If true, Read always returns the number of bytes requested
/// </summary>
public bool PadWithZeroes { get; set; }
/// <summary>
/// <see cref="WaveStream.WaveFormat"/>
/// </summary>
public override WaveFormat WaveFormat
{
get
{
return waveFormat;
}
}
/// <summary>
/// Volume of this channel. 1.0 = full scale
/// </summary>
public float Volume
{
get { return volume; }
set { volume = value; }
}
/// <summary>
/// Pan of this channel (from -1 to 1)
/// </summary>
public float Pan
{
get { return pan; }
set { pan = value; }
}
/// <summary>
/// Determines whether this channel has any data to play
/// to allow optimisation to not read, but bump position forward
/// </summary>
public override bool HasData(int count)
{
// Check whether the source stream has data.
bool sourceHasData = sourceStream.HasData(count);
if (sourceHasData)
{
if (position + count < 0)
return false;
return (position < length) && (volume != 0);
}
return false;
}
/// <summary>
/// Disposes this WaveStream
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (sourceStream != null)
{
sourceStream.Dispose();
sourceStream = null;
}
}
else
{
System.Diagnostics.Debug.Assert(false, "WaveChannel32 was not Disposed");
}
base.Dispose(disposing);
}
/// <summary>
/// Sample
/// </summary>
public event EventHandler<SampleEventArgs> Sample;
// reuse the same object every time to avoid making lots of work for the garbage collector
private SampleEventArgs sampleEventArgs = new SampleEventArgs(0,0);
/// <summary>
/// Raise the sample event (no check for null because it has already been done)
/// </summary>
private void RaiseSample(float left, float right)
{
sampleEventArgs.Left = left;
sampleEventArgs.Right = right;
Sample(this, sampleEventArgs);
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.GtkUtilidades
{
public partial class TecladoAlfavetico
{
private global::Gtk.VBox vbox1;
private global::Valle.GtkUtilidades.MiLabel lbltitulo;
private global::Gtk.HBox hbox1;
private global::Valle.GtkUtilidades.MiLabel txtCadena;
private global::Gtk.HButtonBox hbuttonbox1;
private global::Gtk.Button btnBackSp;
private global::Gtk.Button btnCancelar;
private global::Gtk.Table pneTeclado;
private global::Gtk.Button btnA;
private global::Gtk.Label label1;
private global::Gtk.Button btnA1;
private global::Gtk.Label label2;
private global::Gtk.Button btnA11;
private global::Gtk.Label label12;
private global::Gtk.Button btnA12;
private global::Gtk.Label label13;
private global::Gtk.Button btnA13;
private global::Gtk.Label label14;
private global::Gtk.Button btnA14;
private global::Gtk.Label label15;
private global::Gtk.Button btnA15;
private global::Gtk.Label label16;
private global::Gtk.Button btnA16;
private global::Gtk.Label label17;
private global::Gtk.Button btnA17;
private global::Gtk.Label label18;
private global::Gtk.Button btnA18;
private global::Gtk.Label label19;
private global::Gtk.Button btnA19;
private global::Gtk.Label label20;
private global::Gtk.Button btnA2;
private global::Gtk.Label label3;
private global::Gtk.Button btnA20;
private global::Gtk.Label label21;
private global::Gtk.Button btnA22;
private global::Gtk.Label label23;
private global::Gtk.Button btnA23;
private global::Gtk.Label label24;
private global::Gtk.Button btnA24;
private global::Gtk.Label label25;
private global::Gtk.Button btnA25;
private global::Gtk.Label label26;
private global::Gtk.Button btnA26;
private global::Gtk.Label label27;
private global::Gtk.Button btnA27;
private global::Gtk.Label label28;
private global::Gtk.Button btnA28;
private global::Gtk.Label label29;
private global::Gtk.Button btnA29;
private global::Gtk.Label label30;
private global::Gtk.Button btnA3;
private global::Gtk.Label label4;
private global::Gtk.Button btnA30;
private global::Gtk.Label label31;
private global::Gtk.Button btnA31;
private global::Gtk.Label label32;
private global::Gtk.Button btnA4;
private global::Gtk.Label label5;
private global::Gtk.Button btnA5;
private global::Gtk.Label label6;
private global::Gtk.Button btnA6;
private global::Gtk.Label label7;
private global::Gtk.Button btnA7;
private global::Gtk.Label label8;
private global::Gtk.Button btnA8;
private global::Gtk.Label label9;
private global::Gtk.Button btnA9;
private global::Gtk.Label label10;
private global::Gtk.Button btnEcho;
private global::Gtk.Button btnEspaciador;
private global::Gtk.Label label38;
private global::Gtk.ToggleButton btnEspecial;
private global::Gtk.ToggleButton btnMayuFija;
private global::Gtk.ToggleButton btnMayUnpos;
protected virtual void Init ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.GtkUtilidades.TecladoAlfavetico
this.Name = "Valle.GtkUtilidades.TecladoAlfavetico";
this.Title = global::Mono.Unix.Catalog.GetString ("TecladoAlfavetico");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child Valle.GtkUtilidades.TecladoAlfavetico.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
this.vbox1.BorderWidth = ((uint)(15));
// Container child vbox1.Gtk.Box+BoxChild
this.lbltitulo = new global::Valle.GtkUtilidades.MiLabel ();
this.lbltitulo.HeightRequest = 30;
this.lbltitulo.Events = ((global::Gdk.EventMask)(256));
this.lbltitulo.Name = "lbltitulo";
this.vbox1.Add (this.lbltitulo);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lbltitulo]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.txtCadena = new global::Valle.GtkUtilidades.MiLabel ();
this.txtCadena.Events = ((global::Gdk.EventMask)(256));
this.txtCadena.Name = "txtCadena";
this.hbox1.Add (this.txtCadena);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.txtCadena]));
w2.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.hbuttonbox1 = new global::Gtk.HButtonBox ();
this.hbuttonbox1.Name = "hbuttonbox1";
this.hbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnBackSp = new global::Gtk.Button ();
this.btnBackSp.WidthRequest = 80;
this.btnBackSp.HeightRequest = 80;
this.btnBackSp.CanFocus = true;
this.btnBackSp.Name = "btnBackSp";
this.btnBackSp.UseUnderline = true;
// Container child btnBackSp.Gtk.Container+ContainerChild
global::Gtk.Alignment w3 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w4 = new global::Gtk.HBox ();
w4.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w5 = new global::Gtk.Image ();
w5.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-goto-first", global::Gtk.IconSize.Dialog);
w4.Add (w5);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w7 = new global::Gtk.Label ();
w4.Add (w7);
w3.Add (w4);
this.btnBackSp.Add (w3);
this.hbuttonbox1.Add (this.btnBackSp);
global::Gtk.ButtonBox.ButtonBoxChild w11 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnBackSp]));
w11.Expand = false;
w11.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnCancelar = new global::Gtk.Button ();
this.btnCancelar.CanFocus = true;
this.btnCancelar.Name = "btnCancelar";
this.btnCancelar.UseUnderline = true;
// Container child btnCancelar.Gtk.Container+ContainerChild
global::Gtk.Alignment w12 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w13 = new global::Gtk.HBox ();
w13.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w14 = new global::Gtk.Image ();
w14.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog);
w13.Add (w14);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w16 = new global::Gtk.Label ();
w13.Add (w16);
w12.Add (w13);
this.btnCancelar.Add (w12);
this.hbuttonbox1.Add (this.btnCancelar);
global::Gtk.ButtonBox.ButtonBoxChild w20 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnCancelar]));
w20.Position = 1;
w20.Expand = false;
w20.Fill = false;
this.hbox1.Add (this.hbuttonbox1);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.hbuttonbox1]));
w21.PackType = ((global::Gtk.PackType)(1));
w21.Position = 1;
w21.Expand = false;
this.vbox1.Add (this.hbox1);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.pneTeclado = new global::Gtk.Table (((uint)(4)), ((uint)(10)), false);
this.pneTeclado.Name = "pneTeclado";
this.pneTeclado.RowSpacing = ((uint)(6));
this.pneTeclado.ColumnSpacing = ((uint)(6));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA = new global::Gtk.Button ();
this.btnA.WidthRequest = 80;
this.btnA.HeightRequest = 80;
this.btnA.CanFocus = true;
this.btnA.Name = "btnA";
// Container child btnA.Gtk.Container+ContainerChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='xx-large'>q</span>");
this.label1.UseMarkup = true;
this.btnA.Add (this.label1);
this.btnA.Label = null;
this.pneTeclado.Add (this.btnA);
global::Gtk.Table.TableChild w24 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA]));
w24.XOptions = ((global::Gtk.AttachOptions)(4));
w24.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA1 = new global::Gtk.Button ();
this.btnA1.WidthRequest = 80;
this.btnA1.HeightRequest = 80;
this.btnA1.CanFocus = true;
this.btnA1.Name = "btnA1";
// Container child btnA1.Gtk.Container+ContainerChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA1.Add (this.label2);
this.btnA1.Label = null;
this.pneTeclado.Add (this.btnA1);
global::Gtk.Table.TableChild w26 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA1]));
w26.LeftAttach = ((uint)(1));
w26.RightAttach = ((uint)(2));
w26.XOptions = ((global::Gtk.AttachOptions)(4));
w26.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA11 = new global::Gtk.Button ();
this.btnA11.WidthRequest = 80;
this.btnA11.HeightRequest = 80;
this.btnA11.CanFocus = true;
this.btnA11.Name = "btnA11";
// Container child btnA11.Gtk.Container+ContainerChild
this.label12 = new global::Gtk.Label ();
this.label12.Name = "label12";
this.label12.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA11.Add (this.label12);
this.btnA11.Label = null;
this.pneTeclado.Add (this.btnA11);
global::Gtk.Table.TableChild w28 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA11]));
w28.TopAttach = ((uint)(1));
w28.BottomAttach = ((uint)(2));
w28.XOptions = ((global::Gtk.AttachOptions)(4));
w28.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA12 = new global::Gtk.Button ();
this.btnA12.WidthRequest = 80;
this.btnA12.HeightRequest = 80;
this.btnA12.CanFocus = true;
this.btnA12.Name = "btnA12";
// Container child btnA12.Gtk.Container+ContainerChild
this.label13 = new global::Gtk.Label ();
this.label13.Name = "label13";
this.label13.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA12.Add (this.label13);
this.btnA12.Label = null;
this.pneTeclado.Add (this.btnA12);
global::Gtk.Table.TableChild w30 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA12]));
w30.TopAttach = ((uint)(1));
w30.BottomAttach = ((uint)(2));
w30.LeftAttach = ((uint)(1));
w30.RightAttach = ((uint)(2));
w30.XOptions = ((global::Gtk.AttachOptions)(4));
w30.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA13 = new global::Gtk.Button ();
this.btnA13.WidthRequest = 80;
this.btnA13.HeightRequest = 80;
this.btnA13.CanFocus = true;
this.btnA13.Name = "btnA13";
// Container child btnA13.Gtk.Container+ContainerChild
this.label14 = new global::Gtk.Label ();
this.label14.Name = "label14";
this.label14.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA13.Add (this.label14);
this.btnA13.Label = null;
this.pneTeclado.Add (this.btnA13);
global::Gtk.Table.TableChild w32 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA13]));
w32.TopAttach = ((uint)(1));
w32.BottomAttach = ((uint)(2));
w32.LeftAttach = ((uint)(2));
w32.RightAttach = ((uint)(3));
w32.XOptions = ((global::Gtk.AttachOptions)(4));
w32.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA14 = new global::Gtk.Button ();
this.btnA14.WidthRequest = 80;
this.btnA14.HeightRequest = 80;
this.btnA14.CanFocus = true;
this.btnA14.Name = "btnA14";
// Container child btnA14.Gtk.Container+ContainerChild
this.label15 = new global::Gtk.Label ();
this.label15.Name = "label15";
this.label15.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA14.Add (this.label15);
this.btnA14.Label = null;
this.pneTeclado.Add (this.btnA14);
global::Gtk.Table.TableChild w34 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA14]));
w34.TopAttach = ((uint)(1));
w34.BottomAttach = ((uint)(2));
w34.LeftAttach = ((uint)(3));
w34.RightAttach = ((uint)(4));
w34.XOptions = ((global::Gtk.AttachOptions)(4));
w34.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA15 = new global::Gtk.Button ();
this.btnA15.WidthRequest = 80;
this.btnA15.HeightRequest = 80;
this.btnA15.CanFocus = true;
this.btnA15.Name = "btnA15";
// Container child btnA15.Gtk.Container+ContainerChild
this.label16 = new global::Gtk.Label ();
this.label16.Name = "label16";
this.label16.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA15.Add (this.label16);
this.btnA15.Label = null;
this.pneTeclado.Add (this.btnA15);
global::Gtk.Table.TableChild w36 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA15]));
w36.TopAttach = ((uint)(1));
w36.BottomAttach = ((uint)(2));
w36.LeftAttach = ((uint)(4));
w36.RightAttach = ((uint)(5));
w36.XOptions = ((global::Gtk.AttachOptions)(4));
w36.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA16 = new global::Gtk.Button ();
this.btnA16.WidthRequest = 80;
this.btnA16.HeightRequest = 80;
this.btnA16.CanFocus = true;
this.btnA16.Name = "btnA16";
// Container child btnA16.Gtk.Container+ContainerChild
this.label17 = new global::Gtk.Label ();
this.label17.Name = "label17";
this.label17.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA16.Add (this.label17);
this.btnA16.Label = null;
this.pneTeclado.Add (this.btnA16);
global::Gtk.Table.TableChild w38 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA16]));
w38.TopAttach = ((uint)(1));
w38.BottomAttach = ((uint)(2));
w38.LeftAttach = ((uint)(5));
w38.RightAttach = ((uint)(6));
w38.XOptions = ((global::Gtk.AttachOptions)(4));
w38.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA17 = new global::Gtk.Button ();
this.btnA17.WidthRequest = 80;
this.btnA17.HeightRequest = 80;
this.btnA17.CanFocus = true;
this.btnA17.Name = "btnA17";
// Container child btnA17.Gtk.Container+ContainerChild
this.label18 = new global::Gtk.Label ();
this.label18.Name = "label18";
this.label18.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA17.Add (this.label18);
this.btnA17.Label = null;
this.pneTeclado.Add (this.btnA17);
global::Gtk.Table.TableChild w40 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA17]));
w40.TopAttach = ((uint)(1));
w40.BottomAttach = ((uint)(2));
w40.LeftAttach = ((uint)(6));
w40.RightAttach = ((uint)(7));
w40.XOptions = ((global::Gtk.AttachOptions)(4));
w40.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA18 = new global::Gtk.Button ();
this.btnA18.WidthRequest = 80;
this.btnA18.HeightRequest = 80;
this.btnA18.CanFocus = true;
this.btnA18.Name = "btnA18";
// Container child btnA18.Gtk.Container+ContainerChild
this.label19 = new global::Gtk.Label ();
this.label19.Name = "label19";
this.label19.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA18.Add (this.label19);
this.btnA18.Label = null;
this.pneTeclado.Add (this.btnA18);
global::Gtk.Table.TableChild w42 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA18]));
w42.TopAttach = ((uint)(1));
w42.BottomAttach = ((uint)(2));
w42.LeftAttach = ((uint)(7));
w42.RightAttach = ((uint)(8));
w42.XOptions = ((global::Gtk.AttachOptions)(4));
w42.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA19 = new global::Gtk.Button ();
this.btnA19.WidthRequest = 80;
this.btnA19.HeightRequest = 80;
this.btnA19.CanFocus = true;
this.btnA19.Name = "btnA19";
// Container child btnA19.Gtk.Container+ContainerChild
this.label20 = new global::Gtk.Label ();
this.label20.Name = "label20";
this.label20.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA19.Add (this.label20);
this.btnA19.Label = null;
this.pneTeclado.Add (this.btnA19);
global::Gtk.Table.TableChild w44 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA19]));
w44.TopAttach = ((uint)(1));
w44.BottomAttach = ((uint)(2));
w44.LeftAttach = ((uint)(8));
w44.RightAttach = ((uint)(9));
w44.XOptions = ((global::Gtk.AttachOptions)(4));
w44.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA2 = new global::Gtk.Button ();
this.btnA2.WidthRequest = 80;
this.btnA2.HeightRequest = 80;
this.btnA2.CanFocus = true;
this.btnA2.Name = "btnA2";
// Container child btnA2.Gtk.Container+ContainerChild
this.label3 = new global::Gtk.Label ();
this.label3.Name = "label3";
this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA2.Add (this.label3);
this.btnA2.Label = null;
this.pneTeclado.Add (this.btnA2);
global::Gtk.Table.TableChild w46 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA2]));
w46.LeftAttach = ((uint)(2));
w46.RightAttach = ((uint)(3));
w46.XOptions = ((global::Gtk.AttachOptions)(4));
w46.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA20 = new global::Gtk.Button ();
this.btnA20.WidthRequest = 80;
this.btnA20.HeightRequest = 80;
this.btnA20.CanFocus = true;
this.btnA20.Name = "btnA20";
// Container child btnA20.Gtk.Container+ContainerChild
this.label21 = new global::Gtk.Label ();
this.label21.Name = "label21";
this.label21.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA20.Add (this.label21);
this.btnA20.Label = null;
this.pneTeclado.Add (this.btnA20);
global::Gtk.Table.TableChild w48 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA20]));
w48.TopAttach = ((uint)(1));
w48.BottomAttach = ((uint)(2));
w48.LeftAttach = ((uint)(9));
w48.RightAttach = ((uint)(10));
w48.XOptions = ((global::Gtk.AttachOptions)(4));
w48.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA22 = new global::Gtk.Button ();
this.btnA22.WidthRequest = 80;
this.btnA22.HeightRequest = 80;
this.btnA22.CanFocus = true;
this.btnA22.Name = "btnA22";
// Container child btnA22.Gtk.Container+ContainerChild
this.label23 = new global::Gtk.Label ();
this.label23.Name = "label23";
this.label23.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA22.Add (this.label23);
this.btnA22.Label = null;
this.pneTeclado.Add (this.btnA22);
global::Gtk.Table.TableChild w50 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA22]));
w50.TopAttach = ((uint)(2));
w50.BottomAttach = ((uint)(3));
w50.XOptions = ((global::Gtk.AttachOptions)(4));
w50.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA23 = new global::Gtk.Button ();
this.btnA23.WidthRequest = 80;
this.btnA23.HeightRequest = 80;
this.btnA23.CanFocus = true;
this.btnA23.Name = "btnA23";
// Container child btnA23.Gtk.Container+ContainerChild
this.label24 = new global::Gtk.Label ();
this.label24.Name = "label24";
this.label24.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA23.Add (this.label24);
this.btnA23.Label = null;
this.pneTeclado.Add (this.btnA23);
global::Gtk.Table.TableChild w52 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA23]));
w52.TopAttach = ((uint)(2));
w52.BottomAttach = ((uint)(3));
w52.LeftAttach = ((uint)(1));
w52.RightAttach = ((uint)(2));
w52.XOptions = ((global::Gtk.AttachOptions)(4));
w52.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA24 = new global::Gtk.Button ();
this.btnA24.WidthRequest = 80;
this.btnA24.HeightRequest = 80;
this.btnA24.CanFocus = true;
this.btnA24.Name = "btnA24";
// Container child btnA24.Gtk.Container+ContainerChild
this.label25 = new global::Gtk.Label ();
this.label25.Name = "label25";
this.label25.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA24.Add (this.label25);
this.btnA24.Label = null;
this.pneTeclado.Add (this.btnA24);
global::Gtk.Table.TableChild w54 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA24]));
w54.TopAttach = ((uint)(2));
w54.BottomAttach = ((uint)(3));
w54.LeftAttach = ((uint)(2));
w54.RightAttach = ((uint)(3));
w54.XOptions = ((global::Gtk.AttachOptions)(4));
w54.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA25 = new global::Gtk.Button ();
this.btnA25.WidthRequest = 80;
this.btnA25.HeightRequest = 80;
this.btnA25.CanFocus = true;
this.btnA25.Name = "btnA25";
// Container child btnA25.Gtk.Container+ContainerChild
this.label26 = new global::Gtk.Label ();
this.label26.Name = "label26";
this.label26.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA25.Add (this.label26);
this.btnA25.Label = null;
this.pneTeclado.Add (this.btnA25);
global::Gtk.Table.TableChild w56 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA25]));
w56.TopAttach = ((uint)(2));
w56.BottomAttach = ((uint)(3));
w56.LeftAttach = ((uint)(3));
w56.RightAttach = ((uint)(4));
w56.XOptions = ((global::Gtk.AttachOptions)(4));
w56.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA26 = new global::Gtk.Button ();
this.btnA26.WidthRequest = 80;
this.btnA26.HeightRequest = 80;
this.btnA26.CanFocus = true;
this.btnA26.Name = "btnA26";
// Container child btnA26.Gtk.Container+ContainerChild
this.label27 = new global::Gtk.Label ();
this.label27.Name = "label27";
this.label27.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA26.Add (this.label27);
this.btnA26.Label = null;
this.pneTeclado.Add (this.btnA26);
global::Gtk.Table.TableChild w58 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA26]));
w58.TopAttach = ((uint)(2));
w58.BottomAttach = ((uint)(3));
w58.LeftAttach = ((uint)(4));
w58.RightAttach = ((uint)(5));
w58.XOptions = ((global::Gtk.AttachOptions)(4));
w58.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA27 = new global::Gtk.Button ();
this.btnA27.WidthRequest = 80;
this.btnA27.HeightRequest = 80;
this.btnA27.CanFocus = true;
this.btnA27.Name = "btnA27";
// Container child btnA27.Gtk.Container+ContainerChild
this.label28 = new global::Gtk.Label ();
this.label28.Name = "label28";
this.label28.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA27.Add (this.label28);
this.btnA27.Label = null;
this.pneTeclado.Add (this.btnA27);
global::Gtk.Table.TableChild w60 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA27]));
w60.TopAttach = ((uint)(2));
w60.BottomAttach = ((uint)(3));
w60.LeftAttach = ((uint)(5));
w60.RightAttach = ((uint)(6));
w60.XOptions = ((global::Gtk.AttachOptions)(4));
w60.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA28 = new global::Gtk.Button ();
this.btnA28.WidthRequest = 80;
this.btnA28.HeightRequest = 80;
this.btnA28.CanFocus = true;
this.btnA28.Name = "btnA28";
// Container child btnA28.Gtk.Container+ContainerChild
this.label29 = new global::Gtk.Label ();
this.label29.Name = "label29";
this.label29.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA28.Add (this.label29);
this.btnA28.Label = null;
this.pneTeclado.Add (this.btnA28);
global::Gtk.Table.TableChild w62 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA28]));
w62.TopAttach = ((uint)(2));
w62.BottomAttach = ((uint)(3));
w62.LeftAttach = ((uint)(6));
w62.RightAttach = ((uint)(7));
w62.XOptions = ((global::Gtk.AttachOptions)(4));
w62.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA29 = new global::Gtk.Button ();
this.btnA29.WidthRequest = 80;
this.btnA29.HeightRequest = 80;
this.btnA29.CanFocus = true;
this.btnA29.Name = "btnA29";
// Container child btnA29.Gtk.Container+ContainerChild
this.label30 = new global::Gtk.Label ();
this.label30.Name = "label30";
this.label30.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA29.Add (this.label30);
this.btnA29.Label = null;
this.pneTeclado.Add (this.btnA29);
global::Gtk.Table.TableChild w64 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA29]));
w64.TopAttach = ((uint)(2));
w64.BottomAttach = ((uint)(3));
w64.LeftAttach = ((uint)(7));
w64.RightAttach = ((uint)(8));
w64.XOptions = ((global::Gtk.AttachOptions)(4));
w64.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA3 = new global::Gtk.Button ();
this.btnA3.WidthRequest = 80;
this.btnA3.HeightRequest = 80;
this.btnA3.CanFocus = true;
this.btnA3.Name = "btnA3";
// Container child btnA3.Gtk.Container+ContainerChild
this.label4 = new global::Gtk.Label ();
this.label4.Name = "label4";
this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA3.Add (this.label4);
this.btnA3.Label = null;
this.pneTeclado.Add (this.btnA3);
global::Gtk.Table.TableChild w66 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA3]));
w66.LeftAttach = ((uint)(3));
w66.RightAttach = ((uint)(4));
w66.XOptions = ((global::Gtk.AttachOptions)(4));
w66.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA30 = new global::Gtk.Button ();
this.btnA30.WidthRequest = 80;
this.btnA30.HeightRequest = 80;
this.btnA30.CanFocus = true;
this.btnA30.Name = "btnA30";
// Container child btnA30.Gtk.Container+ContainerChild
this.label31 = new global::Gtk.Label ();
this.label31.Name = "label31";
this.label31.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA30.Add (this.label31);
this.btnA30.Label = null;
this.pneTeclado.Add (this.btnA30);
global::Gtk.Table.TableChild w68 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA30]));
w68.TopAttach = ((uint)(2));
w68.BottomAttach = ((uint)(3));
w68.LeftAttach = ((uint)(8));
w68.RightAttach = ((uint)(9));
w68.XOptions = ((global::Gtk.AttachOptions)(4));
w68.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA31 = new global::Gtk.Button ();
this.btnA31.WidthRequest = 80;
this.btnA31.HeightRequest = 80;
this.btnA31.CanFocus = true;
this.btnA31.Name = "btnA31";
// Container child btnA31.Gtk.Container+ContainerChild
this.label32 = new global::Gtk.Label ();
this.label32.Name = "label32";
this.label32.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA31.Add (this.label32);
this.btnA31.Label = null;
this.pneTeclado.Add (this.btnA31);
global::Gtk.Table.TableChild w70 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA31]));
w70.TopAttach = ((uint)(2));
w70.BottomAttach = ((uint)(3));
w70.LeftAttach = ((uint)(9));
w70.RightAttach = ((uint)(10));
w70.XOptions = ((global::Gtk.AttachOptions)(4));
w70.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA4 = new global::Gtk.Button ();
this.btnA4.WidthRequest = 80;
this.btnA4.HeightRequest = 80;
this.btnA4.CanFocus = true;
this.btnA4.Name = "btnA4";
// Container child btnA4.Gtk.Container+ContainerChild
this.label5 = new global::Gtk.Label ();
this.label5.Name = "label5";
this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA4.Add (this.label5);
this.btnA4.Label = null;
this.pneTeclado.Add (this.btnA4);
global::Gtk.Table.TableChild w72 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA4]));
w72.LeftAttach = ((uint)(4));
w72.RightAttach = ((uint)(5));
w72.XOptions = ((global::Gtk.AttachOptions)(4));
w72.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA5 = new global::Gtk.Button ();
this.btnA5.WidthRequest = 80;
this.btnA5.HeightRequest = 80;
this.btnA5.CanFocus = true;
this.btnA5.Name = "btnA5";
// Container child btnA5.Gtk.Container+ContainerChild
this.label6 = new global::Gtk.Label ();
this.label6.Name = "label6";
this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA5.Add (this.label6);
this.btnA5.Label = null;
this.pneTeclado.Add (this.btnA5);
global::Gtk.Table.TableChild w74 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA5]));
w74.LeftAttach = ((uint)(5));
w74.RightAttach = ((uint)(6));
w74.XOptions = ((global::Gtk.AttachOptions)(4));
w74.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA6 = new global::Gtk.Button ();
this.btnA6.WidthRequest = 80;
this.btnA6.HeightRequest = 80;
this.btnA6.CanFocus = true;
this.btnA6.Name = "btnA6";
// Container child btnA6.Gtk.Container+ContainerChild
this.label7 = new global::Gtk.Label ();
this.label7.Name = "label7";
this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA6.Add (this.label7);
this.btnA6.Label = null;
this.pneTeclado.Add (this.btnA6);
global::Gtk.Table.TableChild w76 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA6]));
w76.LeftAttach = ((uint)(6));
w76.RightAttach = ((uint)(7));
w76.XOptions = ((global::Gtk.AttachOptions)(4));
w76.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA7 = new global::Gtk.Button ();
this.btnA7.WidthRequest = 80;
this.btnA7.HeightRequest = 80;
this.btnA7.CanFocus = true;
this.btnA7.Name = "btnA7";
// Container child btnA7.Gtk.Container+ContainerChild
this.label8 = new global::Gtk.Label ();
this.label8.Name = "label8";
this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA7.Add (this.label8);
this.btnA7.Label = null;
this.pneTeclado.Add (this.btnA7);
global::Gtk.Table.TableChild w78 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA7]));
w78.LeftAttach = ((uint)(7));
w78.RightAttach = ((uint)(8));
w78.XOptions = ((global::Gtk.AttachOptions)(4));
w78.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA8 = new global::Gtk.Button ();
this.btnA8.WidthRequest = 80;
this.btnA8.HeightRequest = 80;
this.btnA8.CanFocus = true;
this.btnA8.Name = "btnA8";
// Container child btnA8.Gtk.Container+ContainerChild
this.label9 = new global::Gtk.Label ();
this.label9.Name = "label9";
this.label9.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA8.Add (this.label9);
this.btnA8.Label = null;
this.pneTeclado.Add (this.btnA8);
global::Gtk.Table.TableChild w80 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA8]));
w80.LeftAttach = ((uint)(8));
w80.RightAttach = ((uint)(9));
w80.XOptions = ((global::Gtk.AttachOptions)(4));
w80.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnA9 = new global::Gtk.Button ();
this.btnA9.WidthRequest = 80;
this.btnA9.HeightRequest = 80;
this.btnA9.CanFocus = true;
this.btnA9.Name = "btnA9";
// Container child btnA9.Gtk.Container+ContainerChild
this.label10 = new global::Gtk.Label ();
this.label10.Name = "label10";
this.label10.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.btnA9.Add (this.label10);
this.btnA9.Label = null;
this.pneTeclado.Add (this.btnA9);
global::Gtk.Table.TableChild w82 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA9]));
w82.LeftAttach = ((uint)(9));
w82.RightAttach = ((uint)(10));
w82.XOptions = ((global::Gtk.AttachOptions)(4));
w82.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnEcho = new global::Gtk.Button ();
this.btnEcho.WidthRequest = 80;
this.btnEcho.HeightRequest = 80;
this.btnEcho.CanFocus = true;
this.btnEcho.Name = "btnEcho";
// Container child btnEcho.Gtk.Container+ContainerChild
global::Gtk.Alignment w83 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w84 = new global::Gtk.HBox ();
w84.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w85 = new global::Gtk.Image ();
w85.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Dialog);
w84.Add (w85);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w87 = new global::Gtk.Label ();
w84.Add (w87);
w83.Add (w84);
this.btnEcho.Add (w83);
this.pneTeclado.Add (this.btnEcho);
global::Gtk.Table.TableChild w91 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnEcho]));
w91.TopAttach = ((uint)(3));
w91.BottomAttach = ((uint)(4));
w91.LeftAttach = ((uint)(9));
w91.RightAttach = ((uint)(10));
w91.XOptions = ((global::Gtk.AttachOptions)(4));
w91.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnEspaciador = new global::Gtk.Button ();
this.btnEspaciador.WidthRequest = 80;
this.btnEspaciador.HeightRequest = 80;
this.btnEspaciador.CanFocus = true;
this.btnEspaciador.Name = "btnEspaciador";
// Container child btnEspaciador.Gtk.Container+ContainerChild
this.label38 = new global::Gtk.Label ();
this.label38.Name = "label38";
this.label38.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='xx-large' >ESPACIO</span>");
this.label38.UseMarkup = true;
this.btnEspaciador.Add (this.label38);
this.btnEspaciador.Label = null;
this.pneTeclado.Add (this.btnEspaciador);
global::Gtk.Table.TableChild w93 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnEspaciador]));
w93.TopAttach = ((uint)(3));
w93.BottomAttach = ((uint)(4));
w93.LeftAttach = ((uint)(2));
w93.RightAttach = ((uint)(8));
w93.XOptions = ((global::Gtk.AttachOptions)(4));
w93.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnEspecial = new global::Gtk.ToggleButton ();
this.btnEspecial.CanFocus = true;
this.btnEspecial.Name = "btnEspecial";
this.btnEspecial.UseUnderline = true;
// Container child btnEspecial.Gtk.Container+ContainerChild
global::Gtk.Alignment w94 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w95 = new global::Gtk.HBox ();
w95.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w96 = new global::Gtk.Image ();
w96.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.GtkUtilidades.iconos.charEsp.png");
w95.Add (w96);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w98 = new global::Gtk.Label ();
w95.Add (w98);
w94.Add (w95);
this.btnEspecial.Add (w94);
this.pneTeclado.Add (this.btnEspecial);
global::Gtk.Table.TableChild w102 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnEspecial]));
w102.TopAttach = ((uint)(3));
w102.BottomAttach = ((uint)(4));
w102.LeftAttach = ((uint)(8));
w102.RightAttach = ((uint)(9));
w102.XOptions = ((global::Gtk.AttachOptions)(4));
w102.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnMayuFija = new global::Gtk.ToggleButton ();
this.btnMayuFija.CanFocus = true;
this.btnMayuFija.Name = "btnMayuFija";
this.btnMayuFija.UseUnderline = true;
// Container child btnMayuFija.Gtk.Container+ContainerChild
global::Gtk.Alignment w103 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w104 = new global::Gtk.HBox ();
w104.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w105 = new global::Gtk.Image ();
w105.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "stock_lock", global::Gtk.IconSize.Dialog);
w104.Add (w105);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w107 = new global::Gtk.Label ();
w104.Add (w107);
w103.Add (w104);
this.btnMayuFija.Add (w103);
this.pneTeclado.Add (this.btnMayuFija);
global::Gtk.Table.TableChild w111 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnMayuFija]));
w111.TopAttach = ((uint)(3));
w111.BottomAttach = ((uint)(4));
w111.LeftAttach = ((uint)(1));
w111.RightAttach = ((uint)(2));
w111.XOptions = ((global::Gtk.AttachOptions)(4));
w111.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneTeclado.Gtk.Table+TableChild
this.btnMayUnpos = new global::Gtk.ToggleButton ();
this.btnMayUnpos.CanFocus = true;
this.btnMayUnpos.Name = "btnMayUnpos";
this.btnMayUnpos.UseUnderline = true;
// Container child btnMayUnpos.Gtk.Container+ContainerChild
global::Gtk.Alignment w112 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w113 = new global::Gtk.HBox ();
w113.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w114 = new global::Gtk.Image ();
w114.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-goto-top", global::Gtk.IconSize.Dialog);
w113.Add (w114);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w116 = new global::Gtk.Label ();
w113.Add (w116);
w112.Add (w113);
this.btnMayUnpos.Add (w112);
this.pneTeclado.Add (this.btnMayUnpos);
global::Gtk.Table.TableChild w120 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnMayUnpos]));
w120.TopAttach = ((uint)(3));
w120.BottomAttach = ((uint)(4));
w120.XOptions = ((global::Gtk.AttachOptions)(4));
w120.YOptions = ((global::Gtk.AttachOptions)(4));
this.vbox1.Add (this.pneTeclado);
global::Gtk.Box.BoxChild w121 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.pneTeclado]));
w121.Position = 2;
w121.Expand = false;
w121.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 886;
this.DefaultHeight = 538;
this.btnBackSp.Clicked += new global::System.EventHandler (this.btnBackSp_Click_1);
this.btnCancelar.Clicked += new global::System.EventHandler (this.btnCancelar_Click);
this.btnMayUnpos.Clicked += new global::System.EventHandler (this.btnMayUnpos_Click);
this.btnMayuFija.Clicked += new global::System.EventHandler (this.btnMayuFija_Click);
this.btnEspecial.Clicked += new global::System.EventHandler (this.btnSpecial_Click);
this.btnEspaciador.Clicked += new global::System.EventHandler (this.btnEspaciador_Click);
this.btnEcho.Clicked += new global::System.EventHandler (this.btnAceptar_Click);
this.btnA9.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA8.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA7.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA6.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA5.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA4.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA31.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA30.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA3.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA29.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA28.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA27.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA26.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA25.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA24.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA23.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA22.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA20.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA2.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA19.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA18.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA17.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA16.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA15.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA14.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA13.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA12.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA11.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA1.Clicked += new global::System.EventHandler (this.Tecla_clik);
this.btnA.Clicked += new global::System.EventHandler (this.Tecla_clik);
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Gaming.V1Beta.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedGameServerDeploymentsServiceClientTest
{
[xunit::FactAttribute]
public void GetGameServerDeploymentRequestObject()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeployment expectedResponse = new GameServerDeployment
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeployment response = client.GetGameServerDeployment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerDeploymentRequestObjectAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeployment expectedResponse = new GameServerDeployment
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeployment responseCallSettings = await client.GetGameServerDeploymentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerDeployment responseCancellationToken = await client.GetGameServerDeploymentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerDeployment()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeployment expectedResponse = new GameServerDeployment
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeployment response = client.GetGameServerDeployment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerDeploymentAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeployment expectedResponse = new GameServerDeployment
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeployment responseCallSettings = await client.GetGameServerDeploymentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerDeployment responseCancellationToken = await client.GetGameServerDeploymentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerDeploymentResourceNames()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeployment expectedResponse = new GameServerDeployment
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeployment response = client.GetGameServerDeployment(request.GameServerDeploymentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerDeploymentResourceNamesAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeployment expectedResponse = new GameServerDeployment
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeployment responseCallSettings = await client.GetGameServerDeploymentAsync(request.GameServerDeploymentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerDeployment responseCancellationToken = await client.GetGameServerDeploymentAsync(request.GameServerDeploymentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerDeploymentRolloutRequestObject()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout
{
GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DefaultGameServerConfig = "default_game_server_config2214de2f",
GameServerConfigOverrides =
{
new GameServerConfigOverride(),
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeploymentRollout response = client.GetGameServerDeploymentRollout(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerDeploymentRolloutRequestObjectAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout
{
GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DefaultGameServerConfig = "default_game_server_config2214de2f",
GameServerConfigOverrides =
{
new GameServerConfigOverride(),
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeploymentRollout>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeploymentRollout responseCallSettings = await client.GetGameServerDeploymentRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerDeploymentRollout responseCancellationToken = await client.GetGameServerDeploymentRolloutAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerDeploymentRollout()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout
{
GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DefaultGameServerConfig = "default_game_server_config2214de2f",
GameServerConfigOverrides =
{
new GameServerConfigOverride(),
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeploymentRollout response = client.GetGameServerDeploymentRollout(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerDeploymentRolloutAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout
{
GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DefaultGameServerConfig = "default_game_server_config2214de2f",
GameServerConfigOverrides =
{
new GameServerConfigOverride(),
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeploymentRollout>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeploymentRollout responseCallSettings = await client.GetGameServerDeploymentRolloutAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerDeploymentRollout responseCancellationToken = await client.GetGameServerDeploymentRolloutAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerDeploymentRolloutResourceNames()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout
{
GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DefaultGameServerConfig = "default_game_server_config2214de2f",
GameServerConfigOverrides =
{
new GameServerConfigOverride(),
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeploymentRollout response = client.GetGameServerDeploymentRollout(request.GameServerDeploymentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerDeploymentRolloutResourceNamesAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout
{
GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DefaultGameServerConfig = "default_game_server_config2214de2f",
GameServerConfigOverrides =
{
new GameServerConfigOverride(),
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeploymentRollout>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
GameServerDeploymentRollout responseCallSettings = await client.GetGameServerDeploymentRolloutAsync(request.GameServerDeploymentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerDeploymentRollout responseCancellationToken = await client.GetGameServerDeploymentRolloutAsync(request.GameServerDeploymentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PreviewGameServerDeploymentRolloutRequestObject()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest
{
Rollout = new GameServerDeploymentRollout(),
UpdateMask = new wkt::FieldMask(),
PreviewTime = new wkt::Timestamp(),
};
PreviewGameServerDeploymentRolloutResponse expectedResponse = new PreviewGameServerDeploymentRolloutResponse
{
Unavailable =
{
"unavailable48e06070",
},
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
PreviewGameServerDeploymentRolloutResponse response = client.PreviewGameServerDeploymentRollout(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewGameServerDeploymentRolloutRequestObjectAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest
{
Rollout = new GameServerDeploymentRollout(),
UpdateMask = new wkt::FieldMask(),
PreviewTime = new wkt::Timestamp(),
};
PreviewGameServerDeploymentRolloutResponse expectedResponse = new PreviewGameServerDeploymentRolloutResponse
{
Unavailable =
{
"unavailable48e06070",
},
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PreviewGameServerDeploymentRolloutResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
PreviewGameServerDeploymentRolloutResponse responseCallSettings = await client.PreviewGameServerDeploymentRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PreviewGameServerDeploymentRolloutResponse responseCancellationToken = await client.PreviewGameServerDeploymentRolloutAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void FetchDeploymentStateRequestObject()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchDeploymentStateRequest request = new FetchDeploymentStateRequest
{
Name = "name1c9368b0",
};
FetchDeploymentStateResponse expectedResponse = new FetchDeploymentStateResponse
{
ClusterState =
{
new FetchDeploymentStateResponse.Types.DeployedClusterState(),
},
Unavailable =
{
"unavailable48e06070",
},
};
mockGrpcClient.Setup(x => x.FetchDeploymentState(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
FetchDeploymentStateResponse response = client.FetchDeploymentState(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task FetchDeploymentStateRequestObjectAsync()
{
moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchDeploymentStateRequest request = new FetchDeploymentStateRequest
{
Name = "name1c9368b0",
};
FetchDeploymentStateResponse expectedResponse = new FetchDeploymentStateResponse
{
ClusterState =
{
new FetchDeploymentStateResponse.Types.DeployedClusterState(),
},
Unavailable =
{
"unavailable48e06070",
},
};
mockGrpcClient.Setup(x => x.FetchDeploymentStateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchDeploymentStateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null);
FetchDeploymentStateResponse responseCallSettings = await client.FetchDeploymentStateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FetchDeploymentStateResponse responseCancellationToken = await client.FetchDeploymentStateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Attributes.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Akka.Event;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.Supervision;
namespace Akka.Streams
{
/// <summary>
/// Holds attributes which can be used to alter <see cref="Flow{TIn,TOut,TMat}"/>
/// or <see cref="GraphDsl"/> materialization.
///
/// Note that more attributes for the <see cref="ActorMaterializer"/> are defined in <see cref="ActorAttributes"/>.
/// </summary>
public sealed class Attributes
{
/// <summary>
/// TBD
/// </summary>
public interface IAttribute { }
/// <summary>
/// TBD
/// </summary>
public sealed class Name : IAttribute, IEquatable<Name>
{
/// <summary>
/// TBD
/// </summary>
public readonly string Value;
/// <summary>
/// TBD
/// </summary>
/// <param name="value">TBD</param>
/// <exception cref="ArgumentNullException">TBD</exception>
public Name(string value)
{
if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value), "Name attribute cannot be empty");
Value = value;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public bool Equals(Name other) => !ReferenceEquals(other, null) && Equals(Value, other.Value);
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <returns>TBD</returns>
public override bool Equals(object obj) => obj is Name && Equals((Name)obj);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override int GetHashCode() => Value.GetHashCode();
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"Name({Value})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class InputBuffer : IAttribute, IEquatable<InputBuffer>
{
/// <summary>
/// TBD
/// </summary>
public readonly int Initial;
/// <summary>
/// TBD
/// </summary>
public readonly int Max;
/// <summary>
/// TBD
/// </summary>
/// <param name="initial">TBD</param>
/// <param name="max">TBD</param>
public InputBuffer(int initial, int max)
{
Initial = initial;
Max = max;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public bool Equals(InputBuffer other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(other, this)) return true;
return Initial == other.Initial && Max == other.Max;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <returns>TBD</returns>
public override bool Equals(object obj) => obj is InputBuffer && Equals((InputBuffer) obj);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override int GetHashCode()
{
unchecked
{
return (Initial*397) ^ Max;
}
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"InputBuffer(initial={Initial}, max={Max})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class LogLevels : IAttribute, IEquatable<LogLevels>
{
/// <summary>
/// Use to disable logging on certain operations when configuring <see cref="LogLevels"/>
/// </summary>
public static readonly LogLevel Off = Logging.LogLevelFor("off");
/// <summary>
/// TBD
/// </summary>
public readonly LogLevel OnElement;
/// <summary>
/// TBD
/// </summary>
public readonly LogLevel OnFinish;
/// <summary>
/// TBD
/// </summary>
public readonly LogLevel OnFailure;
/// <summary>
/// TBD
/// </summary>
/// <param name="onElement">TBD</param>
/// <param name="onFinish">TBD</param>
/// <param name="onFailure">TBD</param>
public LogLevels(LogLevel onElement, LogLevel onFinish, LogLevel onFailure)
{
OnElement = onElement;
OnFinish = onFinish;
OnFailure = onFailure;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public bool Equals(LogLevels other)
{
if (ReferenceEquals(other, null))
return false;
if (ReferenceEquals(other, this))
return true;
return OnElement == other.OnElement && OnFinish == other.OnFinish && OnFailure == other.OnFailure;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <returns>TBD</returns>
public override bool Equals(object obj) => obj is LogLevels && Equals((LogLevels) obj);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override int GetHashCode()
{
unchecked
{
var hashCode = (int) OnElement;
hashCode = (hashCode*397) ^ (int) OnFinish;
hashCode = (hashCode*397) ^ (int) OnFailure;
return hashCode;
}
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"LogLevel(element={OnElement}, finish={OnFinish}, failure={OnFailure})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class AsyncBoundary : IAttribute, IEquatable<AsyncBoundary>
{
/// <summary>
/// TBD
/// </summary>
public static readonly AsyncBoundary Instance = new AsyncBoundary();
private AsyncBoundary() { }
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public bool Equals(AsyncBoundary other) => true;
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <returns>TBD</returns>
public override bool Equals(object obj) => obj is AsyncBoundary;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "AsyncBoundary";
}
/// <summary>
/// TBD
/// </summary>
public static readonly Attributes None = new Attributes();
private readonly IAttribute[] _attributes;
/// <summary>
/// TBD
/// </summary>
/// <param name="attributes">TBD</param>
public Attributes(params IAttribute[] attributes)
{
_attributes = attributes ?? new IAttribute[0];
}
/// <summary>
/// TBD
/// </summary>
public IEnumerable<IAttribute> AttributeList => _attributes;
/// <summary>
/// Get all attributes of a given type or subtype thereof
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <returns>TBD</returns>
public IEnumerable<TAttr> GetAttributeList<TAttr>() where TAttr : IAttribute
=> _attributes.Length == 0 ? Enumerable.Empty<TAttr>() : _attributes.Where(a => a is TAttr).Cast<TAttr>();
/// <summary>
/// Get the last (most specific) attribute of a given type or subtype thereof.
/// If no such attribute exists the default value is returned.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public TAttr GetAttribute<TAttr>(TAttr defaultIfNotFound) where TAttr : class, IAttribute
=> GetAttribute<TAttr>() ?? defaultIfNotFound;
/// <summary>
/// Get the first (least specific) attribute of a given type or subtype thereof.
/// If no such attribute exists the default value is returned.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public TAttr GetFirstAttribute<TAttr>(TAttr defaultIfNotFound) where TAttr : class, IAttribute
=> GetFirstAttribute<TAttr>() ?? defaultIfNotFound;
/// <summary>
/// Get the last (most specific) attribute of a given type or subtype thereof.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <returns>TBD</returns>
public TAttr GetAttribute<TAttr>() where TAttr : class, IAttribute
=> _attributes.LastOrDefault(attr => attr is TAttr) as TAttr;
/// <summary>
/// Get the first (least specific) attribute of a given type or subtype thereof.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <returns>TBD</returns>
public TAttr GetFirstAttribute<TAttr>() where TAttr : class, IAttribute
=> _attributes.FirstOrDefault(attr => attr is TAttr) as TAttr;
/// <summary>
/// Adds given attributes to the end of these attributes.
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public Attributes And(Attributes other)
{
if (_attributes.Length == 0)
return other;
if (!other.AttributeList.Any())
return this;
return new Attributes(_attributes.Concat(other.AttributeList).ToArray());
}
/// <summary>
/// Adds given attribute to the end of these attributes.
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public Attributes And(IAttribute other) => new Attributes(_attributes.Concat(new[] { other }).ToArray());
/// <summary>
/// Extracts Name attributes and concatenates them.
/// </summary>
/// <returns>TBD</returns>
public string GetNameLifted() => GetNameOrDefault(null);
/// <summary>
/// TBD
/// </summary>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public string GetNameOrDefault(string defaultIfNotFound = "unknown-operation")
{
if (_attributes.Length == 0)
return null;
var sb = new StringBuilder();
foreach (var nameAttribute in _attributes.OfType<Name>())
{
// FIXME this UrlEncode is a bug IMO, if that format is important then that is how it should be store in Name
var encoded = Uri.EscapeDataString(nameAttribute.Value);
if (sb.Length != 0)
sb.Append('-');
sb.Append(encoded);
}
return sb.Length == 0 ? defaultIfNotFound : sb.ToString();
}
/// <summary>
/// Test whether the given attribute is contained within this attributes list.
/// </summary>
/// <typeparam name="TAttr">TBD</typeparam>
/// <param name="attribute">TBD</param>
/// <returns>TBD</returns>
public bool Contains<TAttr>(TAttr attribute) where TAttr : IAttribute => _attributes.Contains(attribute);
/// <summary>
/// Specifies the name of the operation.
/// If the name is null or empty the name is ignored, i.e. <see cref="None"/> is returned.
/// </summary>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateName(string name)
=> string.IsNullOrEmpty(name) ? None : new Attributes(new Name(name));
/// <summary>
/// Specifies the initial and maximum size of the input buffer.
/// </summary>
/// <param name="initial">TBD</param>
/// <param name="max">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateInputBuffer(int initial, int max) => new Attributes(new InputBuffer(initial, max));
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public static Attributes CreateAsyncBoundary() => new Attributes(AsyncBoundary.Instance);
///<summary>
/// Configures <see cref="FlowOperations.Log{TIn,TOut,TMat}"/> stage log-levels to be used when logging.
/// Logging a certain operation can be completely disabled by using <see cref="LogLevels.Off"/>
///
/// Passing in null as any of the arguments sets the level to its default value, which is:
/// <see cref="LogLevel.DebugLevel"/> for <paramref name="onElement"/> and <paramref name="onFinish"/>, and <see cref="LogLevel.ErrorLevel"/> for <paramref name="onError"/>.
///</summary>
/// <param name="onElement">TBD</param>
/// <param name="onFinish">TBD</param>
/// <param name="onError">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateLogLevels(LogLevel onElement = LogLevel.DebugLevel,
LogLevel onFinish = LogLevel.DebugLevel, LogLevel onError = LogLevel.ErrorLevel)
=> new Attributes(new LogLevels(onElement, onFinish, onError));
/// <summary>
/// Compute a name by concatenating all Name attributes that the given module
/// has, returning the given default value if none are found.
/// </summary>
/// <param name="module">TBD</param>
/// <param name="defaultIfNotFound">TBD</param>
/// <returns>TBD</returns>
public static string ExtractName(IModule module, string defaultIfNotFound)
{
var copy = module as CopiedModule;
return copy != null
? copy.Attributes.And(copy.CopyOf.Attributes).GetNameOrDefault(defaultIfNotFound)
: module.Attributes.GetNameOrDefault(defaultIfNotFound);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"Attributes({string.Join(", ", _attributes as IEnumerable<IAttribute>)})";
}
/// <summary>
/// Attributes for the <see cref="ActorMaterializer"/>. Note that more attributes defined in <see cref="ActorAttributes"/>.
/// </summary>
public static class ActorAttributes
{
/// <summary>
/// TBD
/// </summary>
public sealed class Dispatcher : Attributes.IAttribute, IEquatable<Dispatcher>
{
/// <summary>
/// TBD
/// </summary>
public readonly string Name;
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public Dispatcher(string name)
{
Name = name;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public bool Equals(Dispatcher other)
{
if (ReferenceEquals(other, null))
return false;
if (ReferenceEquals(other, this))
return true;
return Equals(Name, other.Name);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <returns>TBD</returns>
public override bool Equals(object obj) => obj is Dispatcher && Equals((Dispatcher) obj);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override int GetHashCode() => Name?.GetHashCode() ?? 0;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"Dispatcher({Name})";
}
/// <summary>
/// TBD
/// </summary>
public sealed class SupervisionStrategy : Attributes.IAttribute
{
/// <summary>
/// TBD
/// </summary>
public readonly Decider Decider;
/// <summary>
/// TBD
/// </summary>
/// <param name="decider">TBD</param>
public SupervisionStrategy(Decider decider)
{
Decider = decider;
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "SupervisionStrategy";
}
/// <summary>
/// Specifies the name of the dispatcher.
/// </summary>
/// <param name="dispatcherName">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateDispatcher(string dispatcherName) => new Attributes(new Dispatcher(dispatcherName));
/// <summary>
/// Specifies the SupervisionStrategy.
/// Decides how exceptions from user are to be handled
/// </summary>
/// <param name="strategy">TBD</param>
/// <returns>TBD</returns>
public static Attributes CreateSupervisionStrategy(Decider strategy)
=> new Attributes(new SupervisionStrategy(strategy));
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Citrina
{
public class NewsfeedNewsfeedItem
{
/// <summary>
/// type of digest.
/// </summary>
public enum Template
{
[EnumMember(Value = "list")]
List,
[EnumMember(Value = "grid")]
Grid,
}
public enum BlockType
{
[EnumMember(Value = "local")]
Local,
[EnumMember(Value = "remote")]
Remote,
}
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedEventActivity Activity { get; set; }
public IEnumerable<WallWallpostAttachment> Attachments { get; set; }
public BaseCommentsInfo Comments { get; set; }
public IEnumerable<WallWallpost> CopyHistory { get; set; }
public BaseGeo Geo { get; set; }
public BaseLikesInfo Likes { get; set; }
/// <summary>
/// Post ID.
/// </summary>
public int? PostId { get; set; }
public WallPostSource PostSource { get; set; }
public string PostType { get; set; }
public BaseRepostsInfo Reposts { get; set; }
/// <summary>
/// Post text.
/// </summary>
public string Text { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedItemPhotoPhotos Photos { get; set; }
/// <summary>
/// Post ID.
/// </summary>
public int? PostId { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedItemPhotoTagPhotoTags PhotoTags { get; set; }
/// <summary>
/// Post ID.
/// </summary>
public int? PostId { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedItemFriendFriends Friends { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedItemNoteNotes Notes { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedItemAudioAudio Audio { get; set; }
/// <summary>
/// Post ID.
/// </summary>
public int? PostId { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public NewsfeedItemVideoVideo Video { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public BaseCommentsInfo Comments { get; set; }
public BaseLikesInfo Likes { get; set; }
/// <summary>
/// Topic post ID.
/// </summary>
public int? PostId { get; set; }
/// <summary>
/// Post text.
/// </summary>
public string Text { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public string ButtonText { get; set; }
/// <summary>
/// id of feed in digest.
/// </summary>
public string FeedId { get; set; }
public IEnumerable<WallWallpost> Items { get; set; }
public IEnumerable<string> MainPostIds { get; set; }
public string Title { get; set; }
public string TrackCode { get; set; }
public string Type { get; set; }
/// <summary>
/// Item source ID.
/// </summary>
public int? SourceId { get; set; }
/// <summary>
/// Date when item has been added in Unixtime.
/// </summary>
public int? Date { get; set; }
public IEnumerable<StoriesStory> Stories { get; set; }
public string Title { get; set; }
public string TrackCode { get; set; }
}
}
| |
// Copyright 2004-2012 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if FEATURE_SERIALIZATION
namespace Telerik.JustMock.Core.Castle.DynamicProxy.Serialization
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
#if DOTNET40
using System.Security;
#endif
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
/// <summary>
/// Handles the deserialization of proxies.
/// </summary>
[Serializable]
internal class ProxyObjectReference : IObjectReference, ISerializable, IDeserializationCallback
{
private static ModuleScope scope = new ModuleScope();
private readonly SerializationInfo info;
private readonly StreamingContext context;
private readonly Type baseType;
private readonly Type[] interfaces;
private readonly object proxy;
private readonly ProxyGenerationOptions proxyGenerationOptions;
private bool isInterfaceProxy;
private bool delegateToBase;
/// <summary>
/// Resets the <see cref="ModuleScope" /> used for deserialization to a new scope.
/// </summary>
/// <remarks>
/// This is useful for test cases.
/// </remarks>
public static void ResetScope()
{
SetScope(new ModuleScope());
}
/// <summary>
/// Resets the <see cref="ModuleScope" /> used for deserialization to a given <paramref name="scope" />.
/// </summary>
/// <param name="scope"> The scope to be used for deserialization. </param>
/// <remarks>
/// By default, the deserialization process uses a different scope than the rest of the application, which can lead to multiple proxies
/// being generated for the same type. By explicitly setting the deserialization scope to the application's scope, this can be avoided.
/// </remarks>
public static void SetScope(ModuleScope scope)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
ProxyObjectReference.scope = scope;
}
/// <summary>
/// Gets the <see cref="ModuleScope" /> used for deserialization.
/// </summary>
/// <value> As <see cref="ProxyObjectReference" /> has no way of automatically determining the scope used by the application (and the application might use more than one scope at the same time), <see
/// cref="ProxyObjectReference" /> uses a dedicated scope instance for deserializing proxy types. This instance can be reset and set to a specific value via <see
/// cref="ResetScope" /> and <see cref="SetScope" /> . </value>
public static ModuleScope ModuleScope
{
get { return scope; }
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
protected ProxyObjectReference(SerializationInfo info, StreamingContext context)
{
this.info = info;
this.context = context;
baseType = DeserializeTypeFromString("__baseType");
var _interfaceNames = (String[])info.GetValue("__interfaces", typeof(String[]));
interfaces = new Type[_interfaceNames.Length];
for (var i = 0; i < _interfaceNames.Length; i++)
{
interfaces[i] = Type.GetType(_interfaceNames[i]);
}
proxyGenerationOptions =
(ProxyGenerationOptions)info.GetValue("__proxyGenerationOptions", typeof(ProxyGenerationOptions));
proxy = RecreateProxy();
// We'll try to deserialize as much of the proxy state as possible here. This is just best effort; due to deserialization dependency reasons,
// we need to repeat this in OnDeserialization to guarantee correct state deserialization.
DeserializeProxyState();
}
private Type DeserializeTypeFromString(string key)
{
return Type.GetType(info.GetString(key), true, false);
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
protected virtual object RecreateProxy()
{
var generatorType = GetValue<string>("__proxyTypeId");
if (generatorType.Equals(ProxyTypeConstants.Class))
{
isInterfaceProxy = false;
return RecreateClassProxy();
}
if (generatorType.Equals(ProxyTypeConstants.ClassWithTarget))
{
isInterfaceProxy = false;
return RecreateClassProxyWithTarget();
}
isInterfaceProxy = true;
return RecreateInterfaceProxy(generatorType);
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
private object RecreateClassProxyWithTarget()
{
var generator = new ClassProxyWithTargetGenerator(scope, baseType, interfaces, proxyGenerationOptions);
var proxyType = generator.GetGeneratedType();
return InstantiateClassProxy(proxyType);
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
public object RecreateInterfaceProxy(string generatorType)
{
var @interface = DeserializeTypeFromString("__theInterface");
var targetType = DeserializeTypeFromString("__targetFieldType");
InterfaceProxyWithTargetGenerator generator;
if (generatorType == ProxyTypeConstants.InterfaceWithTarget)
{
generator = new InterfaceProxyWithTargetGenerator(scope, @interface);
}
else if (generatorType == ProxyTypeConstants.InterfaceWithoutTarget)
{
generator = new InterfaceProxyWithoutTargetGenerator(scope, @interface);
}
else if (generatorType == ProxyTypeConstants.InterfaceWithTargetInterface)
{
generator = new InterfaceProxyWithTargetInterfaceGenerator(scope, @interface);
}
else
{
throw new InvalidOperationException(
string.Format(
"Got value {0} for the interface generator type, which is not known for the purpose of serialization.",
generatorType));
}
var proxyType = generator.GenerateCode(targetType, interfaces, proxyGenerationOptions);
return FormatterServices.GetSafeUninitializedObject(proxyType);
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
public object RecreateClassProxy()
{
var generator = new ClassProxyGenerator(scope, baseType);
var proxyType = generator.GenerateCode(interfaces, proxyGenerationOptions);
return InstantiateClassProxy(proxyType);
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
private object InstantiateClassProxy(Type proxy_type)
{
delegateToBase = GetValue<bool>("__delegateToBase");
if (delegateToBase)
{
return Activator.CreateInstance(proxy_type, new object[] { info, context });
}
else
{
return FormatterServices.GetSafeUninitializedObject(proxy_type);
}
}
protected void InvokeCallback(object target)
{
if (target is IDeserializationCallback)
{
(target as IDeserializationCallback).OnDeserialization(this);
}
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
public object GetRealObject(StreamingContext context)
{
return proxy;
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// There is no need to implement this method as
// this class would never be serialized.
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecuritySafeCritical]
#endif
public void OnDeserialization(object sender)
{
var interceptors = GetValue<IInterceptor[]>("__interceptors");
SetInterceptors(interceptors);
DeserializeProxyMembers();
// Get the proxy state again, to get all those members we couldn't get in the constructor due to deserialization ordering.
DeserializeProxyState();
InvokeCallback(proxy);
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
private void DeserializeProxyMembers()
{
var proxyType = proxy.GetType();
var members = FormatterServices.GetSerializableMembers(proxyType);
var deserializedMembers = new List<MemberInfo>();
var deserializedValues = new List<Object>();
for (var i = 0; i < members.Length; i++)
{
var member = members[i] as FieldInfo;
// we get some inherited members...
if (member.DeclaringType != proxyType)
{
continue;
}
Debug.Assert(member != null);
var value = info.GetValue(member.Name, member.FieldType);
deserializedMembers.Add(member);
deserializedValues.Add(value);
}
FormatterServices.PopulateObjectMembers(proxy, deserializedMembers.ToArray(), deserializedValues.ToArray());
}
#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
[SecurityCritical]
#endif
private void DeserializeProxyState()
{
if (isInterfaceProxy)
{
var target = GetValue<object>("__target");
SetTarget(target);
}
else if (!delegateToBase)
{
var baseMemberData = GetValue<object[]>("__data");
var members = FormatterServices.GetSerializableMembers(baseType);
// Sort to keep order on both serialize and deserialize side the same, c.f DYNPROXY-ISSUE-127
members = TypeUtil.Sort(members);
FormatterServices.PopulateObjectMembers(proxy, members, baseMemberData);
}
}
private void SetTarget(object target)
{
var targetField = proxy.GetType().GetField("__target", BindingFlags.Instance | BindingFlags.NonPublic);
if (targetField == null)
{
throw new SerializationException(
"The SerializationInfo specifies an invalid interface proxy type, which has no __target field.");
}
targetField.SetValue(proxy, target);
}
private void SetInterceptors(IInterceptor[] interceptors)
{
var interceptorField = proxy.GetType().GetField("__interceptors", BindingFlags.Instance | BindingFlags.NonPublic);
if (interceptorField == null)
{
throw new SerializationException(
"The SerializationInfo specifies an invalid proxy type, which has no __interceptors field.");
}
interceptorField.SetValue(proxy, interceptors);
}
private T GetValue<T>(string name)
{
return (T)info.GetValue(name, typeof(T));
}
}
}
#endif
| |
// <copyright file="Program.cs" company="OSIsoft, LLC">
//
//Copyright 2019 OSIsoft, LLC
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//<http://www.apache.org/licenses/LICENSE-2.0>
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
namespace SdsRestApiCore
{
public class Program
{
public static void Main() => MainAsync().GetAwaiter().GetResult();
public static async Task<bool> MainAsync(bool test = false)
{
bool success = true;
Exception toThrow = null;
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.test.json", optional: true);
IConfiguration configuration = builder.Build();
// ==== Client constants ====
string tenantId = configuration["TenantId"];
string namespaceId = configuration["NamespaceId"];
string resource = configuration["Resource"];
string clientId = configuration["ClientId"];
string clientKey = configuration["ClientKey"];
string apiVersion = configuration["ApiVersion"];
// ==== Metadata IDs ====
string StreamId = "WaveStreamId";
string TypeId = "WaveDataTypeId";
string TargetTypeId = "WaveDataTargetTypeId";
string TargetIntTypeId = "WaveDataTargetIntTypeId";
string AutoStreamViewId = "WaveDataAutoStreamViewId";
string ManualStreamViewId = "WaveDataManualStreamViewId";
string compoundTypeId = "SampleType_Compound";
string streamIdSecondary = "SampleStream_Secondary";
string streamIdCompound = "SampleStream_Compound";
// Step 1
SdsSecurityHandler securityHandler = new SdsSecurityHandler(resource, clientId, clientKey);
HttpClient httpClient = new HttpClient(securityHandler)
{
BaseAddress = new Uri(resource)
};
Console.WriteLine(@"-------------------------------------------------------");
Console.WriteLine(@" _________ .___ _____________________ ____________________");
Console.WriteLine(@" / _____/ __| _/_____\______ \_ _____// _____/\__ ___/");
Console.WriteLine(@" \_____ \ / __ |/ ___/| _/| __)_ \_____ \ | | ");
Console.WriteLine(@" / \/ /_/ |\___ \ | | \| \/ \ | | ");
Console.WriteLine(@"/_______ /\____ /____ >|____|_ /_______ /_______ / |____| ");
Console.WriteLine(@" \/ \/ \/ \/ \/ \/ ");
Console.WriteLine(@"-------------------------------------------------------");
Console.WriteLine();
Console.WriteLine($"Sds endpoint at {resource}");
Console.WriteLine();
try
{
// Step 2
// create a SdsType
Console.WriteLine("Creating a SdsType");
SdsType waveType = BuildWaveDataType(TypeId);
HttpResponseMessage response =
await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{waveType.Id}",
new StringContent(JsonConvert.SerializeObject(waveType)));
CheckIfResponseWasSuccessful(response);
// Step 3
// create a SdsStream
Console.WriteLine("Creating a SdsStream");
SdsStream waveStream = new SdsStream
{
Id = StreamId,
Name = "WaveStream",
TypeId = waveType.Id
};
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}",
new StringContent(JsonConvert.SerializeObject(waveStream)));
CheckIfResponseWasSuccessful(response);
// Step 4
// insert data
Console.WriteLine("Inserting data");
// insert a single event
var singleWaveList = new List<WaveData>();
WaveData wave = GetWave(0, 1, 2.0);
singleWaveList.Add(wave);
response = await httpClient.PostAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data",
new StringContent(JsonConvert.SerializeObject(singleWaveList)));
CheckIfResponseWasSuccessful(response);
// insert a list of events
List<WaveData> waves = new List<WaveData>();
for (int i = 2; i < 20; i += 2)
{
WaveData newEvent = GetWave(i, 2, 2.0);
waves.Add(newEvent);
}
response = await httpClient.PostAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data",
new StringContent(JsonConvert.SerializeObject(waves)));
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException();
}
// Step 5
// get last event
Console.WriteLine("Getting latest event");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data/Last");
CheckIfResponseWasSuccessful(response);
WaveData retrieved =
JsonConvert.DeserializeObject<WaveData>(await response.Content.ReadAsStringAsync());
Console.WriteLine(retrieved.ToString());
Console.WriteLine();
// get all events
Console.WriteLine("Getting all events");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex=0&endIndex={waves[waves.Count - 1].Order}");
CheckIfResponseWasSuccessful(response);
List<WaveData> retrievedList =
JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"Total events found: {retrievedList.Count}");
foreach (var evnt in retrievedList)
{
Console.WriteLine(evnt.ToString());
}
Console.WriteLine();
// Step 6
// get all events in table header format
Console.WriteLine("Getting all events in table header format");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex=0&endIndex={waves[waves.Count - 1].Order}&form=tableh");
CheckIfResponseWasSuccessful(response);
string retrievedEventWithHeaders = (await response.Content.ReadAsStringAsync());
Console.WriteLine(retrievedEventWithHeaders);
Console.WriteLine();
// Step 7
// update events
Console.WriteLine("Updating events");
// update one event
var updateEvent = retrieved;
updateEvent.Sin = 1 / 2.0;
updateEvent.Cos = Math.Sqrt(3) / 2;
updateEvent.Tan = 1;
List<WaveData> updateWave = new List<WaveData>();
updateWave.Add(updateEvent);
response = await httpClient.PutAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data",
new StringContent(JsonConvert.SerializeObject(updateWave)));
CheckIfResponseWasSuccessful(response);
// update all events, adding ten more
List<WaveData> updateWaves = new List<WaveData>();
for (int i = 0; i < 40; i += 2)
{
WaveData newEvent = GetWave(i, 4, 6.0);
updateWaves.Add(newEvent);
}
response = await httpClient.PutAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data",
new StringContent(JsonConvert.SerializeObject(updateWaves)));
CheckIfResponseWasSuccessful(response);
Console.WriteLine("Getting updated events");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex={updateWaves[0].Order}&endIndex={updateWaves[updateWaves.Count - 1].Order}");
retrievedList =
JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"Total events found: {retrievedList.Count}");
foreach (var evnt in retrievedList)
{
Console.WriteLine(evnt.ToString());
}
Console.WriteLine();
// Step 8
// replacing events
Console.WriteLine("Replacing events");
// replace one event
var replaceSingleWaveList = new List<WaveData>();
var replaceEvent = retrievedList[0];
replaceEvent.Sin = 4 * (Math.Sqrt(2) / 2) + replaceEvent.Radians;
replaceEvent.Cos = 4 * (Math.Sqrt(2) / 2) - replaceEvent.Radians;
replaceEvent.Tan = 4;
replaceSingleWaveList.Add(replaceEvent);
response = await httpClient.PutAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?allowCreate=false",
new StringContent(JsonConvert.SerializeObject(replaceSingleWaveList)));
CheckIfResponseWasSuccessful(response);
// replace all events
var replaceEvents = retrievedList;
foreach (var evnt in replaceEvents)
{
evnt.Sin = 6 * (Math.Sqrt(2) / 2) + evnt.Radians;
evnt.Cos = 6 * (Math.Sqrt(2) / 2) - evnt.Radians;
evnt.Tan = 6;
}
response = await httpClient.PutAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?allowCreate=false",
new StringContent(JsonConvert.SerializeObject(replaceEvents)));
CheckIfResponseWasSuccessful(response);
// Step 9
Console.WriteLine("Getting replaced events");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex={updateWaves[0].Order}&endIndex={updateWaves[updateWaves.Count - 1].Order}");
retrievedList =
JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"Total events found: {retrievedList.Count}");
foreach (var evnt in retrievedList)
{
Console.WriteLine(evnt.ToString());
}
Console.WriteLine();
// Property Overrides
Console.WriteLine("Property Overrides");
Console.WriteLine("Sds can interpolate or extrapolate data at an index location where data does not explicitly exist:");
Console.WriteLine();
// We will retrieve three events using the default behavior, Continuous
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data/Transform?startIndex={1}&count={3}&boundaryType={SdsBoundaryType.ExactOrCalculated}");
CheckIfResponseWasSuccessful(response);
List<WaveData> rangeValuesContinuous =
JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
Console.WriteLine("Default (Continuous) stream read behavior, requesting data starting at index location '1', Sds will interpolate this value:");
foreach (var waveData in rangeValuesContinuous)
{
Console.WriteLine($"Order: {waveData.Order}, Radians: {waveData.Radians}, Cos: {waveData.Cos}");
}
Console.WriteLine();
// Step 10
// We will retrieve events filtered to only get the ones where the radians are less than 50. Note, this can be done on index properties too.
Console.WriteLine("Getting replaced events");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex={updateWaves[0].Order}&endIndex={updateWaves[updateWaves.Count - 1].Order}&filter=Radians lt 50");
var retrievedFilteredList =
JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"Total events found: {retrievedFilteredList.Count}");
foreach (var evnt in retrievedFilteredList)
{
Console.WriteLine(evnt.ToString());
}
Console.WriteLine();
// Step 11
// Create a Discrete stream PropertyOverride indicating that we do not want Sds to calculate a value for Radians and update our stream
SdsStreamPropertyOverride propertyOverride = new SdsStreamPropertyOverride
{
SdsTypePropertyId = "Radians",
InterpolationMode = SdsInterpolationMode.Discrete
};
var propertyOverrides = new List<SdsStreamPropertyOverride>() { propertyOverride };
// update the stream
waveStream.PropertyOverrides = propertyOverrides;
response = await httpClient.PutAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}",
new StringContent(JsonConvert.SerializeObject(waveStream)));
CheckIfResponseWasSuccessful(response);
Console.WriteLine("We can override this read behavior on a property by property basis, here we override the Radians property instructing Sds not to interpolate.");
Console.WriteLine("Sds will now return the default value for the data type:");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data/Transform?startIndex={1}&count={3}&boundaryType={SdsBoundaryType.ExactOrCalculated}");
CheckIfResponseWasSuccessful(response);
List<WaveData> rangeValuesDiscrete =
JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
foreach (var waveData in rangeValuesDiscrete)
{
Console.WriteLine($"Order: {waveData.Order}, Radians: {waveData.Radians}, Cos: {waveData.Cos}");
}
Console.WriteLine();
// Step 12
// Stream views
Console.WriteLine("SdsStreamViews");
// create target types
var targetType = BuildWaveDataTargetType(TargetTypeId);
var targetIntType = BuildWaveDataTargetIntType(TargetIntTypeId);
HttpResponseMessage targetTypeResponse =
await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{TargetTypeId}",
new StringContent(JsonConvert.SerializeObject(targetType)));
if (!targetTypeResponse.IsSuccessStatusCode)
{
throw new HttpRequestException(response.ToString());
}
HttpResponseMessage targetIntTypeResponse =
await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{TargetIntTypeId}",
new StringContent(JsonConvert.SerializeObject(targetIntType)));
if (!targetIntTypeResponse.IsSuccessStatusCode)
{
throw new HttpRequestException(response.ToString());
}
// create StreamViews
var autoStreamView = new SdsStreamView()
{
Id = AutoStreamViewId,
SourceTypeId = TypeId,
TargetTypeId = TargetTypeId
};
// create explicit mappings
var vp1 = new SdsStreamViewProperty() { SourceId = "Order", TargetId = "OrderTarget" };
var vp2 = new SdsStreamViewProperty() { SourceId = "Sin", TargetId = "SinInt" };
var vp3 = new SdsStreamViewProperty() { SourceId = "Cos", TargetId = "CosInt" };
var vp4 = new SdsStreamViewProperty() { SourceId = "Tan", TargetId = "TanInt" };
var manualStreamView = new SdsStreamView()
{
Id = ManualStreamViewId,
SourceTypeId = TypeId,
TargetTypeId = TargetIntTypeId,
Properties = new List<SdsStreamViewProperty>() { vp1, vp2, vp3, vp4 }
};
response =
await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/StreamViews/{AutoStreamViewId}",
new StringContent(JsonConvert.SerializeObject(autoStreamView)));
CheckIfResponseWasSuccessful(response);
response =
await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/StreamViews/{ManualStreamViewId}",
new StringContent(JsonConvert.SerializeObject(manualStreamView)));
CheckIfResponseWasSuccessful(response);
Console.WriteLine("Here is some of our data as it is stored on the server:");
foreach (var evnt in rangeValuesDiscrete)
{
Console.WriteLine($"Sin: {evnt.Sin}, Cos: {evnt.Cos}, Tan {evnt.Tan}");
}
Console.WriteLine();
// get data with autoStreamView
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data/Transform?startIndex={1}&count={3}&boundaryType={SdsBoundaryType.ExactOrCalculated}&streamViewId={AutoStreamViewId}");
CheckIfResponseWasSuccessful(response);
List<WaveDataTarget> autoStreamViewData =
JsonConvert.DeserializeObject<List<WaveDataTarget>>(await response.Content.ReadAsStringAsync());
Console.WriteLine("Specifying a StreamView with a SdsType of the same shape returns values that are automatically mapped to the target SdsType's properties:");
foreach (var value in autoStreamViewData)
{
Console.WriteLine($"SinTarget: {value.SinTarget} CosTarget: {value.CosTarget} TanTarget: {value.TanTarget}");
}
Console.WriteLine();
Console.WriteLine("SdsStreamViews can also convert certain types of data, here we return integers where the original values were doubles:");
// get data with manualStreamView
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data/Transform?startIndex={1}&count={3}&boundaryType={SdsBoundaryType.ExactOrCalculated}&streamViewId={ManualStreamViewId}");
CheckIfResponseWasSuccessful(response);
List<WaveDataInteger> manualStreamViewData =
JsonConvert.DeserializeObject<List<WaveDataInteger>>(await response.Content.ReadAsStringAsync());
foreach (var value in manualStreamViewData)
{
Console.WriteLine($"SinInt: {value.SinInt} CosInt: {value.CosInt} TanInt: {value.TanInt}");
}
Console.WriteLine();
// get SdsStreamViewMap
Console.WriteLine("We can query Sds to return the SdsStreamViewMap for our SdsStreamView, here is the one generated automatically:");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/StreamViews/{AutoStreamViewId}/Map");
CheckIfResponseWasSuccessful(response);
SdsStreamViewMap sdsStreamViewMap =
JsonConvert.DeserializeObject<SdsStreamViewMap>(await response.Content.ReadAsStringAsync());
PrintStreamViewMapProperties(sdsStreamViewMap);
Console.WriteLine("Here is our explicit mapping, note SdsStreamViewMap will return all properties of the Source Type, even those without a corresponding Target property:");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/StreamViews/{ManualStreamViewId}/Map");
CheckIfResponseWasSuccessful(response);
sdsStreamViewMap = JsonConvert.DeserializeObject<SdsStreamViewMap>(await response.Content.ReadAsStringAsync());
PrintStreamViewMapProperties(sdsStreamViewMap);
// Step 13
// Update Stream Type based on SdsStreamView
Console.WriteLine("We will now update the stream type based on the streamview");
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data/Last");
CheckIfResponseWasSuccessful(response);
WaveData lastData = JsonConvert.DeserializeObject<WaveData>(await response.Content.ReadAsStringAsync());
response = await httpClient.PutAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Type?streamViewId={AutoStreamViewId}", null);
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}");
CheckIfResponseWasSuccessful(response);
SdsStream steamnew = JsonConvert.DeserializeObject<SdsStream>(await response.Content.ReadAsStringAsync());
WaveDataTarget lastDataUpdated = JsonConvert.DeserializeObject<WaveDataTarget>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"The new type id {steamnew.TypeId} compared to the original one {waveStream.TypeId}.");
Console.WriteLine($"The new type value {lastDataUpdated.ToString()} compared to the original one {lastData.ToString()}.");
// Step 14
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types");
CheckIfResponseWasSuccessful(response);
List<SdsType> types = JsonConvert.DeserializeObject<List<SdsType>>(await response.Content.ReadAsStringAsync());
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types?filter=contains(Id, 'Target')");
CheckIfResponseWasSuccessful(response);
List<SdsType> typesFiltered = JsonConvert.DeserializeObject<List<SdsType>>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"The number of types returned without filtering: {types.Count}. With filtering {typesFiltered.Count}.");
// Step 15
// tags and metadata
Console.WriteLine("Let's add some Tags and Metadata to our stream:");
var tags = new List<string> { "waves", "periodic", "2018", "validated" };
var metadata = new Dictionary<string, string>() { { "Region", "North America" }, { "Country", "Canada" }, { "Province", "Quebec" } };
response =
await httpClient.PutAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}/Tags",
new StringContent(JsonConvert.SerializeObject(tags)));
CheckIfResponseWasSuccessful(response);
response =
await httpClient.PutAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}/Metadata",
new StringContent(JsonConvert.SerializeObject(metadata)));
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}/Tags");
CheckIfResponseWasSuccessful(response);
tags = JsonConvert.DeserializeObject<List<string>>(await response.Content.ReadAsStringAsync());
Console.WriteLine();
Console.WriteLine($"Tags now associated with {StreamId}:");
foreach (var tag in tags)
{
Console.WriteLine(tag);
}
Console.WriteLine();
Console.WriteLine($"Metadata now associated with {StreamId}:");
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}/Metadata/Region");
CheckIfResponseWasSuccessful(response);
var region = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}/Metadata/Country");
CheckIfResponseWasSuccessful(response);
var country = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}/Metadata/Province");
CheckIfResponseWasSuccessful(response);
var province = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
Console.WriteLine("Metadata key Region: " + region);
Console.WriteLine("Metadata key Country: " + country);
Console.WriteLine("Metadata key Province: " + province);
Console.WriteLine();
Console.WriteLine("Deleting values from the SdsStream");
// Step 16
// delete one event
response = await httpClient.DeleteAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?index=0");
CheckIfResponseWasSuccessful(response);
// delete all Events
response = await httpClient.DeleteAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex=0&endIndex=40");
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync(
$"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}/Data?startIndex=0&endIndex=40");
retrievedList = JsonConvert.DeserializeObject<List<WaveData>>(await response.Content.ReadAsStringAsync());
if (retrievedList.Count == 0)
{
Console.WriteLine("All values deleted successfully!");
}
Console.WriteLine();
// Step 17
Console.WriteLine("Creating a SdsStream with secondary index");
SdsStreamIndex measurementIndex = new SdsStreamIndex()
{
SdsTypePropertyId = waveType.Properties.First(p => p.Id.Equals("Radians")).Id
};
SdsStream waveStreamSecond = new SdsStream
{
Id = streamIdSecondary,
Name = "WaveStream_Secondary",
TypeId = waveType.Id,
Indexes = new List<SdsStreamIndex>()
{
measurementIndex
}
};
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStreamSecond.Id}",
new StringContent(JsonConvert.SerializeObject(waveStreamSecond)));
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStreamSecond.Id}");
CheckIfResponseWasSuccessful(response);
waveStreamSecond = JsonConvert.DeserializeObject<SdsStream>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"Secondary indexes on streams. {waveStream.Id}:{waveStream.Indexes?.Count()}. {waveStreamSecond.Id}:{waveStreamSecond.Indexes.Count()}. ");
Console.WriteLine();
Console.WriteLine("Modifying a stream to have a secondary index.");
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}");
CheckIfResponseWasSuccessful(response);
waveStream = JsonConvert.DeserializeObject<SdsStream>(await response.Content.ReadAsStringAsync());
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{waveStream.TypeId}");
CheckIfResponseWasSuccessful(response);
waveType = JsonConvert.DeserializeObject<SdsType>(await response.Content.ReadAsStringAsync());
measurementIndex = new SdsStreamIndex()
{
SdsTypePropertyId = waveType.Properties.First(p => p.Id.Equals("RadiansTarget")).Id
};
waveStream.Indexes = new List<SdsStreamIndex>() { measurementIndex };
response = await httpClient.PutAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}",
new StringContent(JsonConvert.SerializeObject(waveStream)));
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStream.Id}");
CheckIfResponseWasSuccessful(response);
waveStream = JsonConvert.DeserializeObject<SdsStream>(await response.Content.ReadAsStringAsync());
Console.WriteLine("Removing a secondary index from a stream.");
waveStreamSecond.Indexes = null;
response = await httpClient.PutAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStreamSecond.Id}",
new StringContent(JsonConvert.SerializeObject(waveStreamSecond)));
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{waveStreamSecond.Id}");
CheckIfResponseWasSuccessful(response);
waveStreamSecond = JsonConvert.DeserializeObject<SdsStream>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"Secondary indexes on streams. {waveStream.Id}:{waveStream.Indexes?.Count()}. {waveStreamSecond.Id}:{waveStreamSecond.Indexes.Count()}. ");
Console.WriteLine();
// Step 18
Console.WriteLine("Creating a SdsType with a compound index");
SdsType waveCompound = BuildWaveDataCompoundType(compoundTypeId);
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{waveCompound.Id}",
new StringContent(JsonConvert.SerializeObject(waveCompound)));
CheckIfResponseWasSuccessful(response);
// create an SdsStream
Console.WriteLine("Creating an SdsStream off of type with compound index");
var streamCompound = new SdsStream
{
Id = streamIdCompound,
Name = "Wave Data Sample",
TypeId = waveCompound.Id,
Description = "This is a sample SdsStream for storing WaveData type measurements"
};
response = await httpClient.PutAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}",
new StringContent(JsonConvert.SerializeObject(streamCompound)));
CheckIfResponseWasSuccessful(response);
// Step 19
Console.WriteLine("Inserting data");
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data", new StringContent(JsonConvert.SerializeObject(new List<WaveDataCompound>() { GetWaveMultiplier(1, 10) })));
CheckIfResponseWasSuccessful(response);
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data", new StringContent(JsonConvert.SerializeObject(new List<WaveDataCompound>() { GetWaveMultiplier(2, 2) })));
CheckIfResponseWasSuccessful(response);
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data", new StringContent(JsonConvert.SerializeObject(new List<WaveDataCompound>() { GetWaveMultiplier(3, 2) })));
CheckIfResponseWasSuccessful(response);
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data", new StringContent(JsonConvert.SerializeObject(new List<WaveDataCompound>() { GetWaveMultiplier(10, 3) })));
CheckIfResponseWasSuccessful(response);
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data", new StringContent(JsonConvert.SerializeObject(new List<WaveDataCompound>() { GetWaveMultiplier(10, 8) })));
CheckIfResponseWasSuccessful(response);
response = await httpClient.PostAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data", new StringContent(JsonConvert.SerializeObject(new List<WaveDataCompound>() { GetWaveMultiplier(10, 10) })));
CheckIfResponseWasSuccessful(response);
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data/Last");
CheckIfResponseWasSuccessful(response);
WaveDataCompound lastCompound = JsonConvert.DeserializeObject<WaveDataCompound>(await response.Content.ReadAsStringAsync());
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data/First");
CheckIfResponseWasSuccessful(response);
WaveDataCompound firstCompound = JsonConvert.DeserializeObject<WaveDataCompound>(await response.Content.ReadAsStringAsync());
var startIndex = "2|1";
var endIndex = "10|8";
response = await httpClient.GetAsync($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamCompound.Id}/Data/Transform?startIndex={startIndex}&endIndex={endIndex}");
CheckIfResponseWasSuccessful(response);
List<WaveDataCompound> data = JsonConvert.DeserializeObject<List<WaveDataCompound>>(await response.Content.ReadAsStringAsync());
Console.WriteLine($"First data: {firstCompound.ToString()}. Latest data: {lastCompound.ToString()}.");
Console.WriteLine();
Console.WriteLine("Window Data:");
foreach (var evnt in data)
{
Console.WriteLine(evnt.ToString());
}
}
catch (Exception e)
{
success = false;
Console.WriteLine(e.Message);
toThrow = e;
}
finally
{
// Step 20
Console.WriteLine("Cleaning up");
// Delete the stream, types and streamViews
Console.WriteLine("Deleting stream");
RunInTryCatch(httpClient.DeleteAsync, $"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{StreamId}");
RunInTryCatch(httpClient.DeleteAsync, $"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamIdSecondary}");
RunInTryCatch(httpClient.DeleteAsync, $"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Streams/{streamIdCompound}");
Console.WriteLine("Deleting streamViews");
RunInTryCatch(httpClient.DeleteAsync, ($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/StreamViews/{AutoStreamViewId}"));
RunInTryCatch(httpClient.DeleteAsync,($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/StreamViews/{ManualStreamViewId}"));
Console.WriteLine("Deleting types");
RunInTryCatch(httpClient.DeleteAsync,($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{TypeId}"));
RunInTryCatch(httpClient.DeleteAsync, ($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{compoundTypeId}"));
RunInTryCatch(httpClient.DeleteAsync,($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{TargetTypeId}"));
RunInTryCatch(httpClient.DeleteAsync,($"api/{apiVersion}/Tenants/{tenantId}/Namespaces/{namespaceId}/Types/{TargetIntTypeId}"));
Console.WriteLine("done");
}
if (test && !success)
throw toThrow;
return success;
}
private static void CheckIfResponseWasSuccessful(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(response.ToString());
}
}
/// <summary>
/// Use this to run a method that you don't want to stop the program if there is an error and you don't want to report the error
/// </summary>
/// <param name="methodToRun">The method to run.</param>
/// <param name="value">The value to put into the method to run</param>
private static async void RunInTryCatch(Func<string, Task> methodToRun, string value)
{
try
{
await methodToRun(value);
}
catch (Exception ex)
{
Console.WriteLine($"Got error in {methodToRun.Method.Name} with value {value} but continued on:" + ex.Message);
}
}
private static void PrintStreamViewMapProperties(SdsStreamViewMap sdsStreamViewMap)
{
foreach (var prop in sdsStreamViewMap.Properties)
{
if (prop.TargetId != null)
{
Console.WriteLine($"{prop.SourceId} => {prop.TargetId}");
}
else
{
Console.WriteLine($"{prop.SourceId} => Not Mapped");
}
}
Console.WriteLine();
}
private static SdsType BuildWaveDataType(string id)
{
SdsType intSdsType = new SdsType
{
Id = "intSdsType",
SdsTypeCode = SdsTypeCode.Int32
};
SdsType doubleSdsType = new SdsType
{
Id = "doubleSdsType",
SdsTypeCode = SdsTypeCode.Double
};
SdsTypeProperty orderProperty = new SdsTypeProperty
{
Id = "Order",
SdsType = intSdsType,
IsKey = true
};
SdsTypeProperty tauProperty = new SdsTypeProperty
{
Id = "Tau",
SdsType = doubleSdsType
};
SdsTypeProperty radiansProperty = new SdsTypeProperty
{
Id = "Radians",
SdsType = doubleSdsType
};
SdsTypeProperty sinProperty = new SdsTypeProperty
{
Id = "Sin",
SdsType = doubleSdsType
};
SdsTypeProperty cosProperty = new SdsTypeProperty
{
Id = "Cos",
SdsType = doubleSdsType
};
SdsTypeProperty tanProperty = new SdsTypeProperty
{
Id = "Tan",
SdsType = doubleSdsType
};
SdsTypeProperty sinhProperty = new SdsTypeProperty
{
Id = "Sinh",
SdsType = doubleSdsType
};
SdsTypeProperty coshProperty = new SdsTypeProperty
{
Id = "Cosh",
SdsType = doubleSdsType
};
SdsTypeProperty tanhProperty = new SdsTypeProperty
{
Id = "Tanh",
SdsType = doubleSdsType
};
SdsType waveType = new SdsType
{
Id = id,
Name = "WaveData",
Properties = new List<SdsTypeProperty>
{
orderProperty,
tauProperty,
radiansProperty,
sinProperty,
cosProperty,
tanProperty,
sinhProperty,
coshProperty,
tanhProperty
},
SdsTypeCode = SdsTypeCode.Object
};
return waveType;
}
private static SdsType BuildWaveDataTargetType(string id)
{
SdsType intSdsType = new SdsType
{
Id = "intSdsType",
SdsTypeCode = SdsTypeCode.Int32
};
SdsType doubleSdsType = new SdsType
{
Id = "doubleSdsType",
SdsTypeCode = SdsTypeCode.Double
};
SdsTypeProperty orderTargetProperty = new SdsTypeProperty
{
Id = "OrderTarget",
SdsType = intSdsType,
IsKey = true
};
SdsTypeProperty tauTargetProperty = new SdsTypeProperty
{
Id = "TauTarget",
SdsType = doubleSdsType
};
SdsTypeProperty radiansTargetProperty = new SdsTypeProperty
{
Id = "RadiansTarget",
SdsType = doubleSdsType
};
SdsTypeProperty sinTargetProperty = new SdsTypeProperty
{
Id = "SinTarget",
SdsType = doubleSdsType
};
SdsTypeProperty cosTargetProperty = new SdsTypeProperty
{
Id = "CosTarget",
SdsType = doubleSdsType
};
SdsTypeProperty tanTargetProperty = new SdsTypeProperty
{
Id = "TanTarget",
SdsType = doubleSdsType
};
SdsTypeProperty sinhTargetProperty = new SdsTypeProperty
{
Id = "SinhTarget",
SdsType = doubleSdsType
};
SdsTypeProperty coshTargetProperty = new SdsTypeProperty
{
Id = "CoshTarget",
SdsType = doubleSdsType
};
SdsTypeProperty tanhTargetProperty = new SdsTypeProperty
{
Id = "TanhTarget",
SdsType = doubleSdsType
};
SdsType waveType = new SdsType
{
Id = id,
Name = "WaveData",
Properties = new List<SdsTypeProperty>
{
orderTargetProperty,
tauTargetProperty,
radiansTargetProperty,
sinTargetProperty,
cosTargetProperty,
tanTargetProperty,
sinhTargetProperty,
coshTargetProperty,
tanhTargetProperty
},
SdsTypeCode = SdsTypeCode.Object
};
return waveType;
}
private static SdsType BuildWaveDataTargetIntType(string id)
{
SdsType intSdsType = new SdsType
{
Id = "intSdsType",
SdsTypeCode = SdsTypeCode.Int32
};
SdsTypeProperty orderTargetProperty = new SdsTypeProperty
{
Id = "OrderTarget",
SdsType = intSdsType,
IsKey = true
};
SdsTypeProperty sinIntProperty = new SdsTypeProperty
{
Id = "SinInt",
SdsType = intSdsType
};
SdsTypeProperty cosIntProperty = new SdsTypeProperty
{
Id = "CosInt",
SdsType = intSdsType
};
SdsTypeProperty tanIntProperty = new SdsTypeProperty
{
Id = "TanInt",
SdsType = intSdsType
};
SdsType waveTargetIntType = new SdsType
{
Id = id,
Name = "WaveData",
Properties = new List<SdsTypeProperty>
{
orderTargetProperty,
sinIntProperty,
cosIntProperty,
tanIntProperty,
},
SdsTypeCode = SdsTypeCode.Object
};
return waveTargetIntType;
}
private static SdsType BuildWaveDataCompoundType(string id)
{
SdsType intSdsType = new SdsType
{
Id = "intSdsType",
SdsTypeCode = SdsTypeCode.Int32
};
SdsType doubleSdsType = new SdsType
{
Id = "doubleSdsType",
SdsTypeCode = SdsTypeCode.Double
};
SdsTypeProperty orderProperty = new SdsTypeProperty
{
Id = "Order",
SdsType = intSdsType,
IsKey = true,
Order = 0
};
SdsTypeProperty multiplierProperty = new SdsTypeProperty
{
Id = "Multiplier",
SdsType = intSdsType,
IsKey = true,
Order = 1
};
SdsTypeProperty tauProperty = new SdsTypeProperty
{
Id = "Tau",
SdsType = doubleSdsType
};
SdsTypeProperty radiansProperty = new SdsTypeProperty
{
Id = "Radians",
SdsType = doubleSdsType
};
SdsTypeProperty sinProperty = new SdsTypeProperty
{
Id = "Sin",
SdsType = doubleSdsType
};
SdsTypeProperty cosProperty = new SdsTypeProperty
{
Id = "Cos",
SdsType = doubleSdsType
};
SdsTypeProperty tanProperty = new SdsTypeProperty
{
Id = "Tan",
SdsType = doubleSdsType
};
SdsTypeProperty sinhProperty = new SdsTypeProperty
{
Id = "Sinh",
SdsType = doubleSdsType
};
SdsTypeProperty coshProperty = new SdsTypeProperty
{
Id = "Cosh",
SdsType = doubleSdsType
};
SdsTypeProperty tanhProperty = new SdsTypeProperty
{
Id = "Tanh",
SdsType = doubleSdsType
};
SdsType waveType = new SdsType
{
Id = id,
Name = "WaveData",
Properties = new List<SdsTypeProperty>
{
orderProperty,
multiplierProperty,
tauProperty,
radiansProperty,
sinProperty,
cosProperty,
tanProperty,
sinhProperty,
coshProperty,
tanhProperty
},
SdsTypeCode = SdsTypeCode.Object
};
return waveType;
}
private static WaveData GetWave(int order, int range, double multiplier)
{
Random random = new Random();
var radians = ( random.Next(1,100)* 2 * Math.PI) % 2*Math.PI;
return new WaveData
{
Order = order,
Radians = radians,
Tau = radians / (2 * Math.PI),
Sin = multiplier * Math.Sin(radians),
Cos = multiplier * Math.Cos(radians),
Tan = multiplier * Math.Tan(radians),
Sinh = multiplier * Math.Sinh(radians),
Cosh = multiplier * Math.Cosh(radians),
Tanh = multiplier * Math.Tanh(radians),
};
}
private static WaveDataCompound GetWaveMultiplier(int order, int multiplier)
{
Random random = new Random();
var radians = (random.Next(1, 100) * 2 * Math.PI) % 2 * Math.PI;
return new WaveDataCompound
{
Order = order,
Radians = radians,
Tau = radians / (2 * Math.PI),
Sin = multiplier * Math.Sin(radians),
Cos = multiplier * Math.Cos(radians),
Tan = multiplier * Math.Tan(radians),
Sinh = multiplier * Math.Sinh(radians),
Cosh = multiplier * Math.Cosh(radians),
Tanh = multiplier * Math.Tanh(radians),
Multiplier = multiplier
};
}
}
}
| |
using System;
using System.Windows.Forms;
using System.ComponentModel;
using GuruComponents.Netrix;
using GuruComponents.Netrix.WebEditing.HighLighting;
using GuruComponents.Netrix.SpellChecker.NetSpell;
using System.Collections;
using System.Globalization;
using System.Drawing;
using System.Collections.Generic;
namespace GuruComponents.Netrix.SpellChecker
{
/// <summary>
/// This class collects the properties used to configure the spell checker as well as the spell checker dialog.
/// </summary>
/// <remarks>
/// The direct usage of this class is not recommended. Instead, the Extenderprovider class <see cref="SpellChecker"/>
/// should be used to set the properties using the VS.NET designer. The properties will appear in the NetRix Component
/// group as "SpellChecker on spellchecker1" behind the plus sign (other languages may have other descriptions and
/// the name depends on the name the developer gave the extender).
/// </remarks>
[Serializable()]
[DefaultValue("0 properties changed")]
public class SpellCheckerProperties
{
private string dictionary;
[NonSerialized()]
private DocumentSpellChecker documentSpellChecker;
private bool mainMenuVisible, toolStripVisible;
/// <summary>
/// Set main menu.
/// </summary>
[Category("NetRix Speller UI")]
public bool MainMenuVisible
{
// Add parent dropdown
set
{ mainMenuVisible = value; }
get { return mainMenuVisible; }
}
/// <summary>
/// Set toolstrip.
/// </summary>
[Category("NetRix Speller UI")]
public bool ToolStripVisible
{
set { toolStripVisible = value; }
get { return toolStripVisible; }
}
/// <summary>
/// Path to the dictionary being used for current spell process.
/// </summary>
[Browsable(true)]
[CategoryAttribute("Options")]
[Description("List of words being automatically replaced.")]
[DefaultValue("en-US")]
public string Dictionary
{
get { return dictionary; }
set
{
dictionary = value;
if (!String.IsNullOrEmpty(dictionary))
{
if (dictionary.EndsWith(".dic"))
{
dictionary = dictionary.Replace(".dic", "");
}
}
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.Dictionary.DictionaryFile = dictionary + ".dic";
}
}
}
private Dictionary<string, string> replaceList;
/// <summary>
/// List of words being automatically replaced.
/// </summary>
[Browsable(false)]
[CategoryAttribute("Options")]
[Description("List of words being automatically replaced.")]
public Dictionary<string,string> ReplaceList
{
get {return replaceList;}
set
{
replaceList = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.ReplaceList.Clear();
if (value != null)
{
foreach (KeyValuePair<string,string> de in value)
{
documentSpellChecker.Spelling.ReplaceList.Add(de.Key, de.Value);
}
}
}
}
}
private List<string> ignoreList;
/// <summary>
/// List of words being ignored during check procedure.
/// </summary>
[Browsable(false)]
[CategoryAttribute("Options")]
[Description("List of words being ignored.")]
public List<string> IgnoreList
{
get {return ignoreList;}
set
{
ignoreList = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.IgnoreList.Clear();
if (value != null)
{
documentSpellChecker.Spelling.IgnoreList.AddRange(value.ToArray());
}
}
}
}
private bool ignoreHtml;
/// <summary>
/// Ignore html tags when spell checking.
/// </summary>
[DefaultValue(true)]
[CategoryAttribute("Options")]
[Description("Ignore html tags when spell checking")]
public bool IgnoreHtml
{
get {return ignoreHtml;}
set
{
ignoreHtml = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.IgnoreHtml = value;
}
}
}
CultureInfo languageType;
/// <summary>
/// Language (Culture) from list of supported languages.
/// </summary>
/// <remarks>
/// The component will seek for a dictionary according to the settings. If the culture is set to
/// "de-DE" the component will look for "de-DE.dic" in the default or defined folder. There is no
/// fallback to another language or base language.
/// </remarks>
[Browsable(true)]
[Description("Language (Culture) from list of supported languages.")]
public CultureInfo LanguageType
{
get { return languageType; }
set
{
languageType = value;
}
}
string dictionaryPath;
/// <summary>
/// Path to the dictionaries.
/// </summary>
/// <remarks>
/// </remarks>
[Browsable(false)]
[Description("Path to the dictionaries.")]
[DefaultValue("")]
public string DictionaryPath
{
get { return dictionaryPath; }
set
{
dictionaryPath = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.Dictionary.DictionaryFolder = value;
}
}
}
bool ignoreWordsWithDigits;
/// <summary>
/// Ignore words with digits when spell checking.
/// </summary>
[DefaultValue(true)]
[Browsable(true)]
[Description("Ignore words with digits when spell checking.")]
public bool IgnoreWordsWithDigits
{
get { return ignoreWordsWithDigits; }
set
{
ignoreWordsWithDigits = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.IgnoreWordsWithDigits = value;
}
}
}
bool ignoreUpperCaseWords;
/// <summary>
/// Whether or not ognore uppercase words.
/// </summary>
/// <remarks>
/// If set to <c>true</c> the speller will ignore words which consists of upper case letters only.
/// </remarks>
[DefaultValue(true)]
[Browsable(true)]
[Description("Whether or not ognore uppercase words.")]
public bool IgnoreUpperCaseWords
{
get { return ignoreUpperCaseWords; }
set
{
ignoreUpperCaseWords = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.IgnoreAllCapsWords = value;
}
}
}
int maxSuggestionsCount;
/// <summary>
/// The maximum number of suggestions to generate. Default is 25.
/// </summary>
/// <remarks>
/// Suggestions can be used to create a context menu or dialog where the user could choose
/// suggestions from. Suggestions are create based on current word and pulled from the current
/// dictionary.
/// </remarks>
[DefaultValue(25)]
[Browsable(true)]
[Description("The maximum number of suggestions to generate. Default is 25.")]
public int MaxSuggestionsCount
{
get { return maxSuggestionsCount; }
set
{
maxSuggestionsCount = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.MaxSuggestions = value;
}
}
}
/// <summary>
/// The style used to format wrongly spelled words.
/// </summary>
/// <remarks>
/// By default a red waved line is being used.
/// </remarks>
[Browsable(true)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public IHighLightStyle HighLightStyle
{
get
{
if (documentSpellChecker != null)
{
return documentSpellChecker.HighLightStyle;
}
return null;
}
set
{
if (documentSpellChecker != null)
{
documentSpellChecker.HighLightStyle = value;
}
}
}
SuggestionEnum suggestionType;
/// <summary>
/// The suggestion strategy to use when generating suggestions.
/// </summary>
[Browsable(true)]
[Description("The suggestion strategy to use when generating suggestions.")]
[DefaultValue(typeof(SuggestionEnum), "PhoneticNearMiss")]
public SuggestionEnum SuggestionType
{
get { return suggestionType; }
set
{
suggestionType = value;
if (documentSpellChecker != null)
{
documentSpellChecker.Spelling.SuggestionMode = value;
}
}
}
bool checkInternal;
/// <summary>
/// Activates the internal spell checker, based on NetSpell.
/// </summary>
///<remarks>
/// If the internal spell checker is used the NetRix Spell events are disabled.
///</remarks>
[Browsable(true)]
[DefaultValue(true)]
[Description("Activates the internal spell checker, based on NetSpell.")]
public bool CheckInternal
{
get { return checkInternal; }
set
{
checkInternal = value;
if (documentSpellChecker != null)
{
documentSpellChecker.CheckInternal = value;
}
}
}
/// <summary>
/// Constructor for properties with backreference parameter to spellchecker instance.
/// </summary>
/// <param name="documentSpellChecker">Spellchecker instance this property instance refers to.</param>
public SpellCheckerProperties(IDocumentSpellChecker documentSpellChecker)
{
this.documentSpellChecker = (DocumentSpellChecker) documentSpellChecker;
// default for spellchecking
HighlightColor hc = HighlightColor.Color(Color.Red);
UnderlineStyle us = UnderlineStyle.Wave;
IHighLightStyle hs = new HighLightStyle();
hs.LineColor = hc;
hs.UnderlineStyle = us;
this.documentSpellChecker.HighLightStyle = hs;
ignoreWordsWithDigits = true;
ignoreUpperCaseWords = true;
maxSuggestionsCount = 25;
ignoreHtml = true;
ignoreList = new List<string>();
replaceList = new Dictionary<string,string>();
checkInternal = true;
if (String.IsNullOrEmpty(this.Dictionary))
{
this.Dictionary = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
}
}
/// <summary>
/// Overridden to support design time features.
/// </summary>
/// <returns></returns>
public override string ToString()
{
int changes = 0;
changes += (checkInternal == true) ? 0 : 1;
changes += (ignoreHtml == true) ? 0 : 1;
changes += (ignoreWordsWithDigits == true) ? 0 : 1;
changes += (maxSuggestionsCount == 25) ? 0 : 1;
changes += (ignoreUpperCaseWords == true) ? 0 : 1;
changes += (suggestionType == SuggestionEnum.PhoneticNearMiss) ? 0 : 1;
changes += (Dictionary == System.Threading.Thread.CurrentThread.CurrentUICulture.Name) ? 0 : 1;
changes += (MainMenuVisible) ? 1 : 0;
changes += (ToolStripVisible) ? 1 : 0;
return String.Format("{0} propert{1} changed", changes, (changes == 1) ? "y" : "ies");
}
}
}
| |
namespace Fonet.Render.Pdf.Fonts {
internal class CourierBoldOblique : Base14Font {
private static readonly int[] CodePointWidths;
private static readonly CodePointMapping DefaultMapping
= CodePointMapping.GetMapping("WinAnsiEncoding");
public CourierBoldOblique()
: base("Courier-BoldOblique", "WinAnsiEncoding", 562, 626, -142, 32, 255, CodePointWidths, DefaultMapping) {}
static CourierBoldOblique() {
CodePointWidths = new int[256];
CodePointWidths[0x0041] = 600;
CodePointWidths[0x00C6] = 600;
CodePointWidths[0x00C1] = 600;
CodePointWidths[0x00C2] = 600;
CodePointWidths[0x00C4] = 600;
CodePointWidths[0x00C0] = 600;
CodePointWidths[0x00C5] = 600;
CodePointWidths[0x00C3] = 600;
CodePointWidths[0x0042] = 600;
CodePointWidths[0x0043] = 600;
CodePointWidths[0x00C7] = 600;
CodePointWidths[0x0044] = 600;
CodePointWidths[0x0045] = 600;
CodePointWidths[0x00C9] = 600;
CodePointWidths[0x00CA] = 600;
CodePointWidths[0x00CB] = 600;
CodePointWidths[0x00C8] = 600;
CodePointWidths[0x00D0] = 600;
CodePointWidths[0x0080] = 600;
CodePointWidths[0x0046] = 600;
CodePointWidths[0x0047] = 600;
CodePointWidths[0x0048] = 600;
CodePointWidths[0x0049] = 600;
CodePointWidths[0x00CD] = 600;
CodePointWidths[0x00CE] = 600;
CodePointWidths[0x00CF] = 600;
CodePointWidths[0x00CC] = 600;
CodePointWidths[0x004A] = 600;
CodePointWidths[0x004B] = 600;
CodePointWidths[0x004C] = 600;
CodePointWidths[0x004D] = 600;
CodePointWidths[0x004E] = 600;
CodePointWidths[0x00D1] = 600;
CodePointWidths[0x004F] = 600;
CodePointWidths[0x008C] = 600;
CodePointWidths[0x00D3] = 600;
CodePointWidths[0x00D4] = 600;
CodePointWidths[0x00D6] = 600;
CodePointWidths[0x00D2] = 600;
CodePointWidths[0x00D8] = 600;
CodePointWidths[0x00D5] = 600;
CodePointWidths[0x0050] = 600;
CodePointWidths[0x0051] = 600;
CodePointWidths[0x0052] = 600;
CodePointWidths[0x0053] = 600;
CodePointWidths[0x008A] = 600;
CodePointWidths[0x0054] = 600;
CodePointWidths[0x00DE] = 600;
CodePointWidths[0x0055] = 600;
CodePointWidths[0x00DA] = 600;
CodePointWidths[0x00DB] = 600;
CodePointWidths[0x00DC] = 600;
CodePointWidths[0x00D9] = 600;
CodePointWidths[0x0056] = 600;
CodePointWidths[0x0057] = 600;
CodePointWidths[0x0058] = 600;
CodePointWidths[0x0059] = 600;
CodePointWidths[0x00DD] = 600;
CodePointWidths[0x009F] = 600;
CodePointWidths[0x005A] = 600;
CodePointWidths[0x0061] = 600;
CodePointWidths[0x00E1] = 600;
CodePointWidths[0x00E2] = 600;
CodePointWidths[0x00B4] = 600;
CodePointWidths[0x00E4] = 600;
CodePointWidths[0x00E6] = 600;
CodePointWidths[0x00E0] = 600;
CodePointWidths[0x0026] = 600;
CodePointWidths[0x00E5] = 600;
CodePointWidths[0xAB] = 600;
CodePointWidths[0xAF] = 600;
CodePointWidths[0xAC] = 600;
CodePointWidths[0xAE] = 600;
CodePointWidths[0xAD] = 600;
CodePointWidths[0x005E] = 600;
CodePointWidths[0x007E] = 600;
CodePointWidths[0x002A] = 600;
CodePointWidths[0x0040] = 600;
CodePointWidths[0x00E3] = 600;
CodePointWidths[0x0062] = 600;
CodePointWidths[0x005C] = 600;
CodePointWidths[0x007C] = 600;
CodePointWidths[0x007B] = 600;
CodePointWidths[0x007D] = 600;
CodePointWidths[0x005B] = 600;
CodePointWidths[0x005D] = 600;
CodePointWidths[0x00A6] = 600;
CodePointWidths[0x0095] = 600;
CodePointWidths[0x0063] = 600;
CodePointWidths[0x00E7] = 600;
CodePointWidths[0x00B8] = 600;
CodePointWidths[0x00A2] = 600;
CodePointWidths[0x0088] = 600;
CodePointWidths[0x003A] = 600;
CodePointWidths[0x002C] = 600;
CodePointWidths[0x00A9] = 600;
CodePointWidths[0x00A4] = 600;
CodePointWidths[0x0064] = 600;
CodePointWidths[0x0086] = 600;
CodePointWidths[0x0087] = 600;
CodePointWidths[0x00B0] = 600;
CodePointWidths[0x00A8] = 600;
CodePointWidths[0x00F7] = 600;
CodePointWidths[0x0024] = 600;
CodePointWidths[0x0065] = 600;
CodePointWidths[0x00E9] = 600;
CodePointWidths[0x00EA] = 600;
CodePointWidths[0x00EB] = 600;
CodePointWidths[0x00E8] = 600;
CodePointWidths[0x0038] = 600;
CodePointWidths[0x0085] = 600;
CodePointWidths[0x0097] = 600;
CodePointWidths[0x0096] = 600;
CodePointWidths[0x003D] = 600;
CodePointWidths[0x00F0] = 600;
CodePointWidths[0x0021] = 600;
CodePointWidths[0x00A1] = 600;
CodePointWidths[0x0066] = 600;
CodePointWidths[0x0035] = 600;
CodePointWidths[0x0083] = 600;
CodePointWidths[0x0034] = 600;
CodePointWidths[0xA4] = 600;
CodePointWidths[0x0067] = 600;
CodePointWidths[0x00DF] = 600;
CodePointWidths[0x0060] = 600;
CodePointWidths[0x003E] = 600;
CodePointWidths[0x00AB] = 600;
CodePointWidths[0x00BB] = 600;
CodePointWidths[0x008B] = 600;
CodePointWidths[0x009B] = 600;
CodePointWidths[0x0068] = 600;
CodePointWidths[0x002D] = 600;
CodePointWidths[0x0069] = 600;
CodePointWidths[0x00ED] = 600;
CodePointWidths[0x00EE] = 600;
CodePointWidths[0x00EF] = 600;
CodePointWidths[0x00EC] = 600;
CodePointWidths[0x006A] = 600;
CodePointWidths[0x006B] = 600;
CodePointWidths[0x006C] = 600;
CodePointWidths[0x003C] = 600;
CodePointWidths[0x00AC] = 600;
CodePointWidths[0x006D] = 600;
CodePointWidths[0x00AF] = 600;
CodePointWidths[0x2D] = 600;
CodePointWidths[0x00B5] = 600;
CodePointWidths[0x00D7] = 600;
CodePointWidths[0x006E] = 600;
CodePointWidths[0x0039] = 600;
CodePointWidths[0x00F1] = 600;
CodePointWidths[0x0023] = 600;
CodePointWidths[0x006F] = 600;
CodePointWidths[0x00F3] = 600;
CodePointWidths[0x00F4] = 600;
CodePointWidths[0x00F6] = 600;
CodePointWidths[0x009C] = 600;
CodePointWidths[0x00F2] = 600;
CodePointWidths[0x0031] = 600;
CodePointWidths[0x00BD] = 600;
CodePointWidths[0x00BC] = 600;
CodePointWidths[0x00B9] = 600;
CodePointWidths[0x00AA] = 600;
CodePointWidths[0x00BA] = 600;
CodePointWidths[0x00F8] = 600;
CodePointWidths[0x00F5] = 600;
CodePointWidths[0x0070] = 600;
CodePointWidths[0x00B6] = 600;
CodePointWidths[0x0028] = 600;
CodePointWidths[0x0029] = 600;
CodePointWidths[0x0025] = 600;
CodePointWidths[0x002E] = 600;
CodePointWidths[0x00B7] = 600;
CodePointWidths[0x0089] = 600;
CodePointWidths[0x002B] = 600;
CodePointWidths[0x00B1] = 600;
CodePointWidths[0x0071] = 600;
CodePointWidths[0x003F] = 600;
CodePointWidths[0x00BF] = 600;
CodePointWidths[0x0022] = 600;
CodePointWidths[0x0084] = 600;
CodePointWidths[0x0093] = 600;
CodePointWidths[0x0094] = 600;
CodePointWidths[0x0091] = 600;
CodePointWidths[0x0092] = 600;
CodePointWidths[0x0082] = 600;
CodePointWidths[0x0027] = 600;
CodePointWidths[0x0072] = 600;
CodePointWidths[0x00AE] = 600;
CodePointWidths[0x0073] = 600;
CodePointWidths[0x009A] = 600;
CodePointWidths[0x00A7] = 600;
CodePointWidths[0x003B] = 600;
CodePointWidths[0x0037] = 600;
CodePointWidths[0x0036] = 600;
CodePointWidths[0x002F] = 600;
CodePointWidths[0x0020] = 600;
CodePointWidths[0x00A0] = 600;
CodePointWidths[0x00A3] = 600;
CodePointWidths[0x0074] = 600;
CodePointWidths[0x00FE] = 600;
CodePointWidths[0x0033] = 600;
CodePointWidths[0x00BE] = 600;
CodePointWidths[0x00B3] = 600;
CodePointWidths[0x0098] = 600;
CodePointWidths[0x0099] = 600;
CodePointWidths[0x0032] = 600;
CodePointWidths[0x00B2] = 600;
CodePointWidths[0x0075] = 600;
CodePointWidths[0x00FA] = 600;
CodePointWidths[0x00FB] = 600;
CodePointWidths[0x00FC] = 600;
CodePointWidths[0x00F9] = 600;
CodePointWidths[0x005F] = 600;
CodePointWidths[0x0076] = 600;
CodePointWidths[0x0077] = 600;
CodePointWidths[0x0078] = 600;
CodePointWidths[0x0079] = 600;
CodePointWidths[0x00FD] = 600;
CodePointWidths[0x00FF] = 600;
CodePointWidths[0x00A5] = 600;
CodePointWidths[0x007A] = 600;
CodePointWidths[0x0030] = 600;
}
}
}
| |
// 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.
// Regression test for VSW 543506
/*
Testing that generic argument types for co/contravariant generic types are boxed
(VSW 543506)
Test: under Loader\ClassLoader\Generics\Variance\IL
Positive and negative tests on casting valuetype instantiations such as
Positive:
" IPos<int> is castable to IPos<int> (exact match on value types)
Negative
" IPos<int> is not castable to IPos<unsigned int>
IPos<int> is not castable to IPos<MyEnum>
*/
using System;
public class C<T> : IPos<T>, INeg<T>
{
public T produce()
{
return default(T);
}
public void consume(T t)
{
}
}
enum intEnum : int {}
enum uintEnum : uint {}
class Test
{
public static bool pass;
public static void IsInstShouldFail<T>(object o)
{
Console.WriteLine("cast from " + o.GetType() + " to " + typeof(T));
if (o is T)
{
Console.WriteLine("isinst on object of type " + o.GetType() + " to " + typeof(T) + " succeeded. Expected failure");
pass = false;
}
}
public static void IsInstShouldWork<T>(object o)
{
Console.WriteLine("cast from " + o.GetType() + " to " + typeof(T));
if (!(o is T))
{
Console.WriteLine("isinst on object of type " + o.GetType() + " to " + typeof(T) + " failed. Expected success");
pass = false;
}
}
public static void CastClassShouldFail<T>(object o)
{
Console.WriteLine("cast from " + o.GetType() + " to " + typeof(T));
try
{
T obj = (T)o;
Console.WriteLine("cast on object of type " + o.GetType() + " to " + typeof(T) + " succeeded. Expected failure");
pass = false;
}
catch (InvalidCastException)
{
// expecting to get an InvalidCastException
}
catch (Exception e)
{
Console.WriteLine("Caught unexpected exception: " + e);
pass = false;
}
}
public static void CastClassShouldWork<T>(object o)
{
Console.WriteLine("cast from " + o.GetType() + " to " + typeof(T));
try
{
T obj = (T)o;
}
catch (Exception e)
{
Console.WriteLine("cast on object of type " + o.GetType() + " to " + typeof(T) + " failed. Expected success");
Console.WriteLine(e);
pass = false;
}
}
public static int Main()
{
pass = true;
C<long> cl = new C<long>();
C<object> co = new C<object>();
C<IComparable> ci = new C<IComparable>();
// Primitives
C<uint> cui = new C<uint>();
C<intEnum> ciEnum = new C<intEnum>();
C<uintEnum> cuiEnum = new C<uintEnum>();
C<int> cint = new C<int>();
// ==============================
// TESTS for IsInst
// ==============================
Console.WriteLine("\n================================");
Console.WriteLine(" Positive tests for IsInst:");
Console.WriteLine("================================\n");
// Exact match on value types
IsInstShouldWork<IPos<int>>(cint);
IsInstShouldWork<IPos<long>>(cl);
IsInstShouldWork<IPos<uint>>(cui);
IsInstShouldWork<INeg<int>>(cint);
IsInstShouldWork<INeg<long>>(cl);
IsInstShouldWork<INeg<uint>>(cui);
// Runtime type tests
IsInstShouldWork<IPos<object>>(ci);
IsInstShouldWork<INeg<string>>(ci);
Console.WriteLine("\n================================");
Console.WriteLine(" Negative tests for IsInst:");
Console.WriteLine("================================\n");
IsInstShouldFail<IPos<object>>(cl);
IsInstShouldFail<INeg<long>>(ci);
// IPos<unit> --> IPos<int>
IsInstShouldFail<IPos<int>>(cui);
// IPos<IComparable> --> IPos<uint>
IsInstShouldFail<IPos<uint>>(ci);
// IPos<intEnum> --> IPos<int>
IsInstShouldFail<IPos<int>>(ciEnum);
// IPos<IComparable> --> IPos<intEnum>
IsInstShouldFail<IPos<intEnum>>(ci);
// IPos<uintEnum> --> IPos<uint>
IsInstShouldFail<IPos<uint>>(cuiEnum);
// IPos<uint> --> IPos<uintEnum>
IsInstShouldFail<IPos<uintEnum>>(cui);
// IPos<intEnum> --> IPos<uint>
IsInstShouldFail<IPos<uint>>(ciEnum);
// IPos<uint> --> IPos<intEnum>
IsInstShouldFail<IPos<intEnum>>(cui);
// IPos<int> --> IPos<intEnum>
IsInstShouldFail<IPos<intEnum>>(cint);
// IPos<int> --> IPos<uint>
IsInstShouldFail<IPos<uint>>(cint);
// same for INeg<>
IsInstShouldFail<IPos<int>>(cui);
IsInstShouldFail<IPos<uint>>(ci);
IsInstShouldFail<IPos<int>>(ciEnum);
IsInstShouldFail<IPos<intEnum>>(ci);
IsInstShouldFail<IPos<uint>>(cuiEnum);
IsInstShouldFail<IPos<uintEnum>>(cui);
IsInstShouldFail<IPos<uint>>(ciEnum);
IsInstShouldFail<IPos<intEnum>>(cui);
IsInstShouldFail<IPos<intEnum>>(cint);
IsInstShouldFail<IPos<uint>>(cint);
// ==============================
// TESTS for CastClass
// ==============================
Console.WriteLine("\n================================");
Console.WriteLine(" Positive tests for CastClass:");
Console.WriteLine("================================\n");
CastClassShouldWork<IPos<object>>(ci);
CastClassShouldWork<INeg<string>>(ci);
CastClassShouldWork<IPos<int>>(cint);
CastClassShouldWork<IPos<long>>(cl);
CastClassShouldWork<IPos<uint>>(cui);
Console.WriteLine("\n================================");
Console.WriteLine(" Negative tests for CastClass:");
Console.WriteLine("================================\n");
CastClassShouldFail<IPos<int>>(cui);
CastClassShouldFail<IPos<uint>>(ci);
CastClassShouldFail<IPos<int>>(ciEnum);
CastClassShouldFail<IPos<intEnum>>(ci);
CastClassShouldFail<IPos<uint>>(cuiEnum);
CastClassShouldFail<IPos<uintEnum>>(cui);
CastClassShouldFail<IPos<uint>>(ciEnum);
CastClassShouldFail<IPos<intEnum>>(cui);
CastClassShouldFail<IPos<intEnum>>(cint);
CastClassShouldFail<IPos<uint>>(cint);
CastClassShouldFail<INeg<int>>(cui);
CastClassShouldFail<INeg<uint>>(ci);
CastClassShouldFail<INeg<int>>(ciEnum);
CastClassShouldFail<INeg<intEnum>>(ci);
CastClassShouldFail<INeg<uint>>(cuiEnum);
CastClassShouldFail<INeg<uintEnum>>(cui);
CastClassShouldFail<INeg<uint>>(ciEnum);
CastClassShouldFail<INeg<intEnum>>(cui);
CastClassShouldFail<INeg<intEnum>>(cint);
CastClassShouldFail<INeg<uint>>(cint);
if (pass)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 101;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: MiniAssembly
**
** Purpose: Wraps an assembly, using a managed PE reader to
** interpret the metadata.
**
===========================================================*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.AddIn.MiniReflection.MetadataReader;
using System.Diagnostics;
using System.AddIn.Hosting;
using System.Diagnostics.Contracts;
namespace System.AddIn.MiniReflection
{
[Serializable]
internal sealed class MiniAssembly : MiniModule
{
private enum Representation {
PEFileReader = 1,
ReflectionAssembly = 2,
}
// When loading other assemblies, which directory should we look in?
private List<String> _dependencyDirs;
private Representation _representation;
private System.Reflection.Assembly _reflectionAssembly;
private String _fullName;
public MiniAssembly(String peFileName) : base(peFileName)
{
_dependencyDirs = new List<String>();
_dependencyDirs.Add(Path.GetDirectoryName(peFileName));
Assembly = this;
_representation = Representation.PEFileReader;
}
public MiniAssembly(System.Reflection.Assembly assembly)
{
System.Diagnostics.Contracts.Contract.Requires(assembly != null);
_reflectionAssembly = assembly;
_representation = Representation.ReflectionAssembly;
}
public List<String> DependencyDirs
{
get { return _dependencyDirs; }
}
internal bool IsReflectionAssembly {
get { return (_representation & Representation.ReflectionAssembly) != 0; }
}
public MiniModule[] GetModules()
{
// There are two forms of "multiple module" assemblies. The first is a
// multi-module assembly where the assembly's ModuleRef lists multiple
// different modules. The second is a multi-file assembly, where an
// entry in the File metadata table refers to another file on disk and
// explicitly declares the file contains metadata (and potentially types).
// ALink can produce .netmodules, which seem to show up as multi-file
// assemblies.
MDTables metaData = _peFile.MetaData;
for(uint i=0; i<metaData.RowsInTable(MDTables.Tables.File); i++)
{
metaData.SeekToRowOfTable(MDTables.Tables.File, i);
MDFileAttributes attrs = (MDFileAttributes) metaData.B.ReadUInt32();
if ((attrs & MDFileAttributes.ContainsNoMetaData) != 0)
continue;
System.Diagnostics.Contracts.Contract.Assert(attrs == MDFileAttributes.ContainsMetaData);
throw new NotImplementedException(String.Format(CultureInfo.CurrentCulture, Res.MultiFileAssembliesNotSupported, FullName));
}
return new MiniModule[] { this };
}
// Only returns public types.
public IList<TypeInfo> GetTypesWithAttribute(Type customAttribute)
{
return GetTypesWithAttribute(customAttribute, false);
}
public TypeInfo FindTypeInfo(String typeName, String nameSpace)
{
System.Diagnostics.Contracts.Contract.Assert(!IsReflectionAssembly); // Can be implemented using Assembly.GetType
MetadataToken token = FindTypeDef(_peFile, _peFile.MetaData, typeName, nameSpace);
return new TypeInfo(token, this, typeName, nameSpace);
}
private static MetadataToken FindTypeDef(PEFileReader peFile, MDTables mdScope, String typeName, String nameSpace)
{
System.Diagnostics.Contracts.Contract.Requires(typeName != null);
uint numTypeDefs = mdScope.RowsInTable(MDTables.Tables.TypeDef);
for (uint i = 0; i < numTypeDefs; i++) {
mdScope.SeekToRowOfTable(MDTables.Tables.TypeDef, i);
peFile.B.ReadUInt32(); // TypeAttributes
String rowTypeName = mdScope.ReadString();
if (!String.Equals(typeName, rowTypeName))
continue;
String rowNameSpace= mdScope.ReadString();
if (!String.Equals(nameSpace, rowNameSpace))
continue;
return new MetadataToken(MDTables.Tables.TypeDef, i + 1);
}
throw new TypeLoadException(String.Format(CultureInfo.CurrentCulture, Res.CantFindTypeName, nameSpace, typeName));
}
// For each module in the assembly, give back all types with the
// given attribute, possibly respecting the type's visibility.
public IList<TypeInfo> GetTypesWithAttribute(Type customAttribute, bool includePrivate)
{
if (IsDisposed)
throw new ObjectDisposedException(null);
if (customAttribute == null)
throw new ArgumentNullException("customAttribute");
System.Diagnostics.Contracts.Contract.EndContractBlock();
List<TypeInfo> types = new List<TypeInfo>();
foreach (MiniModule module in GetModules())
{
IList<TypeInfo> newTypes = module.GetTypesWithAttributeInModule(customAttribute, includePrivate);
types.AddRange(newTypes);
}
return types;
}
public MiniAssembly ResolveAssemblyRef(MetadataToken token, bool throwOnError)
{
System.Diagnostics.Contracts.Contract.Requires(token.Table == MDTables.Tables.AssemblyRef);
PEFileReader peFile = this.PEFileReader;
MDTables metaData = peFile.MetaData;
metaData.SeekToMDToken(token);
peFile.B.ReadUInt64(); // Skip 4 parts of the version number.
peFile.B.ReadUInt32(); // AssemblyFlags
byte[] publicKeyOrToken = metaData.ReadBlob(); // Public key or token
String assemblySimpleName = metaData.ReadString(); // simple name
String cultureName = metaData.ReadString(); // assembly culture
if (!String.IsNullOrEmpty(cultureName))
throw new BadImageFormatException(Res.UnexpectedlyLoadingASatellite, FullName);
if (assemblySimpleName == "mscorlib" && (cultureName.Length == 0 || cultureName == "neutral"))
return new MiniAssembly(typeof(Object).Assembly);
MiniAssembly loadedAssembly = Open(assemblySimpleName, _dependencyDirs, throwOnError);
if (loadedAssembly != null)
{
// Check whether the reference to the assembly matches what we actually loaded.
// We don't respect the "throwOnError" parameter here because if someone does
// violate this, they've either severely messed up their deployment, or they're
// attempting a security exploit.
System.Reflection.AssemblyName loadedAssemblyName =
new System.Reflection.AssemblyName(loadedAssembly.FullName);
if (!Utils.PublicKeyMatches(loadedAssemblyName, publicKeyOrToken))
{
throw new FileLoadException(String.Format(CultureInfo.CurrentCulture, Res.AssemblyLoadRefDefMismatch,
assemblySimpleName, publicKeyOrToken, loadedAssemblyName.GetPublicKeyToken()));
}
if (!String.IsNullOrEmpty(loadedAssemblyName.CultureInfo.Name))
{
throw new FileLoadException(String.Format(CultureInfo.CurrentCulture, Res.AssemblyLoadRefDefMismatch,
assemblySimpleName, String.Empty, loadedAssemblyName.CultureInfo.Name));
}
}
return loadedAssembly;
}
public static MiniAssembly Open(String simpleName, IList<String> dependencyDirs, bool throwOnError)
{
String fileName = FindAssembly(simpleName, dependencyDirs, throwOnError);
if (!throwOnError && fileName == null)
return null;
return new MiniAssembly(fileName);
}
private static String FindAssembly(String simpleName, IList<String> searchDirs, bool throwOnError)
{
System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(simpleName));
System.Diagnostics.Contracts.Contract.Requires(searchDirs != null);
String libName = simpleName + ".dll";
String exeName = simpleName + ".exe";
foreach (String dir in searchDirs)
{
String fileName = Path.Combine(dir, libName);
if (File.Exists(fileName))
return fileName;
fileName = Path.Combine(dir, exeName);
if (File.Exists(fileName))
return fileName;
}
if (throwOnError)
throw new FileNotFoundException(String.Format(CultureInfo.CurrentCulture, Res.FileNotFoundForInspection, simpleName), libName);
else
return null;
}
internal String FullName {
get {
if ((_representation & Representation.ReflectionAssembly) != 0)
return AppDomain.CurrentDomain.ApplyPolicy(_reflectionAssembly.FullName);
if (_fullName == null) {
AssemblyInfo assemblyInfo = new AssemblyInfo();
_peFile.GetAssemblyInfo(ref assemblyInfo);
_fullName = AppDomain.CurrentDomain.ApplyPolicy(assemblyInfo.ToString());
}
return _fullName;
}
}
public override bool Equals(object obj)
{
MiniAssembly thatAssembly = obj as MiniAssembly;
if (thatAssembly == null)
return false;
// Note that assembly binding redirects and publisher policy will affect
// versioning (ie binds to 2.0.0.0 redirected to 2.0.1.5). But for
// the Orcas release, we're only planning on using our existing
// directory structure, which does not have a great servicing story.
// As long as we use ReflectionOnlyLoad during discovery, we should
// be fetching the exact assembly on disk used to build the entire
// pipeline (modulo in-place updates which must keep the same
// assembly version number), and we'll load the right version
// during activation time. That should work for Orcas.
// Long term, we may need an approximately-equals method that gets
// the assembly info and compares the version number w.r.t. policy.
return Utils.AssemblyDefEqualsDef(FullName, thatAssembly.FullName);
}
// See the comments in Equals - we're doing string comparisons here
// to compare full type names.
public static bool Equals(MiniAssembly assemblyA, PEFileReader peFileB, MetadataToken assemblyRefB)
{
System.Diagnostics.Contracts.Contract.Requires(assemblyA != null);
System.Diagnostics.Contracts.Contract.Requires(peFileB != null);
System.Diagnostics.Contracts.Contract.Requires(assemblyRefB.Table == MDTables.Tables.AssemblyRef);
String nameA, nameRefB;
if (assemblyA.IsReflectionAssembly)
nameA = AppDomain.CurrentDomain.ApplyPolicy(assemblyA._reflectionAssembly.FullName);
else
{
AssemblyInfo assemblyInfoA = new AssemblyInfo();
assemblyA._peFile.GetAssemblyInfo(ref assemblyInfoA);
nameA = AppDomain.CurrentDomain.ApplyPolicy(assemblyInfoA.ToString());
}
AssemblyInfo assemblyInfoB = ReadAssemblyRef(peFileB, assemblyRefB);
nameRefB = AppDomain.CurrentDomain.ApplyPolicy(assemblyInfoB.ToString());
return Utils.AssemblyRefEqualsDef(nameRefB, nameA);
}
private static AssemblyInfo ReadAssemblyRef(PEFileReader peFile, MetadataToken assemblyRef)
{
System.Diagnostics.Contracts.Contract.Requires(peFile != null);
System.Diagnostics.Contracts.Contract.Requires(assemblyRef.Table == MDTables.Tables.AssemblyRef);
MDTables metaData = peFile.MetaData;
BinaryReader B = metaData.B;
metaData.SeekToMDToken(assemblyRef);
UInt16 major = B.ReadUInt16();
UInt16 minor = B.ReadUInt16();
UInt16 build = B.ReadUInt16();
UInt16 revision = B.ReadUInt16();
Version v = new Version(major, minor, build, revision);
UInt32 assemblyFlags = B.ReadUInt32();
byte[] publicKey = metaData.ReadBlob();
String simpleName = metaData.ReadString();
String culture = metaData.ReadString();
if ((culture != null) && (culture.Length == 0)) culture = null;
return new AssemblyInfo(v, assemblyFlags, publicKey, simpleName, culture);
}
public override int GetHashCode()
{
return FullName.GetHashCode();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
namespace FizzWare.NBuilder
{
public class SequentialGenerator<T> : IGenerator<T> where T : struct, IConvertible
{
private const IncrementDate DefaultIncrementDate = IncrementDate.Day;
private const double DefaultIncrementDateValue = 1;
private const int DefaultIncrementValue = 1;
private readonly IDictionary<Type, Action> typeAdvancers = new Dictionary<Type, Action>();
private readonly IDictionary<IncrementDate, Func<DateTime, DateTime>> dateTimeAdvancerIncrementers = new Dictionary<IncrementDate, Func<DateTime, DateTime>>();
private readonly IDictionary<IncrementDate, Func<DateTime, DateTime>> dateTimeAdvancerDecrementers = new Dictionary<IncrementDate, Func<DateTime, DateTime>>();
public SequentialGenerator()
{
typeAdvancers = InitializeTypeAdvancers();
dateTimeAdvancerIncrementers = InitializeDateTimeAdvancerIncrementers();
dateTimeAdvancerDecrementers = InitializeDateTimeAdvancerDecrementers();
if (!typeAdvancers.ContainsKey(typeof(T)))
throw new InvalidOperationException("Sequential generator does not support " + typeof(T).Name);
if (typeof(T) == typeof(DateTime))
{
Increment = (T)Convert.ChangeType(DateTime.MinValue, typeof(T), CultureInfo.InvariantCulture);
IncrementDateBy = DefaultIncrementDate;
IncrementDateValueBy = DefaultIncrementDateValue;
}
else
{
Increment = (T)Convert.ChangeType(DefaultIncrementValue, typeof(T), CultureInfo.InvariantCulture);
}
StartingWith(default(T));
}
private IDictionary<Type, Action> InitializeTypeAdvancers()
{
return new Dictionary<Type, Action>
{
{ typeof(short), ShortAdvancer },
{ typeof(int), IntAdvancer },
{ typeof(long), LongAdvancer },
{ typeof(decimal), DecimalAdvancer },
{ typeof(float), FloatAdvancer },
{ typeof(double), DoubleAdvancer },
{ typeof(ushort), UShortAdvancer },
{ typeof(uint), UIntAdvancer },
{ typeof(ulong), ULongAdvancer },
{ typeof(byte), ByteAdvancer },
{ typeof(char), CharAdvancer },
{ typeof(bool), BooleanAdvancer },
{ typeof(DateTime), DateTimeAdvancer },
};
}
private IDictionary<IncrementDate, Func<DateTime, DateTime>> InitializeDateTimeAdvancerIncrementers()
{
return new Dictionary<IncrementDate, Func<DateTime, DateTime>>
{
{IncrementDate.Tick, delegate(DateTime x) { return Convert.ToDateTime(x.AddTicks((long)IncrementDateValueBy)); } },
{IncrementDate.Millisecond, delegate(DateTime x) { return Convert.ToDateTime(x.AddMilliseconds(IncrementDateValueBy)); } },
{IncrementDate.Second, delegate(DateTime x) { return Convert.ToDateTime(x.AddSeconds(IncrementDateValueBy)); } },
{IncrementDate.Minute, delegate(DateTime x) { return Convert.ToDateTime(x.AddMinutes(IncrementDateValueBy)); } },
{IncrementDate.Hour, delegate(DateTime x) { return Convert.ToDateTime(x.AddHours(IncrementDateValueBy)); } },
{IncrementDate.Month, delegate(DateTime x) {return Convert.ToDateTime(x.AddMonths((int)IncrementDateValueBy)); } },
{IncrementDate.Year, delegate(DateTime x) {return Convert.ToDateTime(x.AddYears((int)IncrementDateValueBy)); } },
{IncrementDate.Day, delegate(DateTime x) { return Convert.ToDateTime(x.AddDays(IncrementDateValueBy)); } }
};
}
private IDictionary<IncrementDate, Func<DateTime, DateTime>> InitializeDateTimeAdvancerDecrementers()
{
return new Dictionary<IncrementDate, Func<DateTime, DateTime>>
{
{IncrementDate.Tick, delegate(DateTime x) { return Convert.ToDateTime(x.AddTicks(-(long)IncrementDateValueBy)); } },
{IncrementDate.Millisecond, delegate(DateTime x) { return Convert.ToDateTime(x.AddMilliseconds(-IncrementDateValueBy)); } },
{IncrementDate.Second, delegate(DateTime x) { return Convert.ToDateTime(x.AddSeconds(-IncrementDateValueBy)); } },
{IncrementDate.Minute, delegate(DateTime x) { return Convert.ToDateTime(x.AddMinutes(-IncrementDateValueBy)); } },
{IncrementDate.Hour, delegate(DateTime x) { return Convert.ToDateTime(x.AddHours(-IncrementDateValueBy)); } },
{IncrementDate.Month, delegate(DateTime x) {return Convert.ToDateTime(x.AddMonths(-(int)IncrementDateValueBy)); } },
{IncrementDate.Year, delegate(DateTime x) {return Convert.ToDateTime(x.AddYears(-(int)IncrementDateValueBy)); } },
{IncrementDate.Day, delegate(DateTime x) { return Convert.ToDateTime(x.AddDays(-IncrementDateValueBy)); } }
};
}
private T next;
private bool hasBeenReset;
public T Generate()
{
if (!hasBeenReset)
Advance();
hasBeenReset = false;
T val = (T)Convert.ChangeType(next, typeof (T), CultureInfo.InvariantCulture);
return val;
}
public virtual void StartingWith(T nextValueToGenerate)
{
next = nextValueToGenerate;
hasBeenReset = true;
}
protected virtual void Advance()
{
typeAdvancers[typeof(T)].Invoke();
}
private void DateTimeAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToDateTime(x), (x, y) => { return dateTimeAdvancerIncrementers[IncrementDateBy].Invoke(x); });
else
PerformAdvance(x => Convert.ToDateTime(x), (x, y) => { return dateTimeAdvancerDecrementers[IncrementDateBy].Invoke(x); });
}
private void BooleanAdvancer()
{
next = (T)Convert.ChangeType(Convert.ToBoolean(next) == false ? true : false, typeof(bool), CultureInfo.InvariantCulture);
}
private void CharAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToChar(x), (x, y) => Convert.ToChar(x + y));
else
PerformAdvance(x => Convert.ToChar(x), (x, y) => Convert.ToChar(x - y));
}
private void ByteAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
{
// TODO: Add this check in for all types
//if (Convert.ToByte(next) < byte.MaxValue)
PerformAdvance(x => Convert.ToByte(x), (x, y) => Convert.ToByte(x + y));
}
else
{
if (Convert.ToByte(next) > 0)
PerformAdvance(x => Convert.ToByte(x), (x, y) => Convert.ToByte(x - y));
}
}
private void ULongAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToUInt64(x), (x, y) => x + y);
else
{
if (Convert.ToUInt64(next) > 0)
PerformAdvance(x => Convert.ToUInt64(x), (x, y) => x - y);
}
}
private void UIntAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToUInt32(x), (x, y) => x + y);
else
{
if (Convert.ToUInt32(next) > 0)
PerformAdvance(x => Convert.ToUInt32(x), (x, y) => x - y);
}
}
private void UShortAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToUInt16(x), (x, y) => Convert.ToUInt16(x + y));
else
{
if (Convert.ToUInt16(next) > 0)
PerformAdvance(x => Convert.ToUInt16(x), (x, y) => Convert.ToUInt16(x - y));
}
}
private void DoubleAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToDouble(x), (x, y) => x + y);
else
PerformAdvance(x => Convert.ToDouble(x), (x, y) => x - y);
}
private void FloatAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToSingle(x), (x, y) => x + y);
else
PerformAdvance(x => Convert.ToSingle(x), (x, y) => x - y);
}
private void DecimalAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToDecimal(x), (x, y) => x + y);
else
PerformAdvance(x => Convert.ToDecimal(x), (x, y) => x - y);
}
private void LongAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToInt64(x), (x, y) => x + y);
else
PerformAdvance(x => Convert.ToInt64(x), (x, y) => x - y);
}
private void IntAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToInt32(x), (x, y) => x + y);
else
PerformAdvance(x => Convert.ToInt32(x), (x, y) => x - y);
}
private void ShortAdvancer()
{
if (Direction == GeneratorDirection.Ascending)
PerformAdvance(x => Convert.ToInt16(x), (x, y) => Convert.ToInt16(x + y));
else
PerformAdvance(x => Convert.ToInt16(x), (x, y) => Convert.ToInt16(x - y));
}
private void PerformAdvance<TTo>(Func<T, TTo> convert, Func<TTo, TTo, TTo> advance)
{
next = (T)Convert.ChangeType(advance(convert(next), convert(Increment)), typeof (T), CultureInfo.InvariantCulture);
}
public T Increment { get; set; }
public IncrementDate IncrementDateBy { get; set; }
public double IncrementDateValueBy { get; set; }
public GeneratorDirection Direction { get; set; }
}
public enum GeneratorDirection
{
Ascending,
Descending
}
public enum IncrementDate
{
Tick,
Millisecond,
Second,
Minute,
Hour,
Day,
Month,
Year
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Test.ModuleCore;
using System;
using System.Xml;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public enum EINTEGRITY
{
//DataReader
BEFORE_READ,
AFTER_READ_FALSE,
AFTER_RESETSTATE,
//DataWriter
BEFORE_WRITE,
AFTER_WRITE_FALSE,
AFTER_CLEAR,
AFTER_FLUSH,
// Both DataWriter and DataReader
AFTER_CLOSE,
CLOSE_IN_THE_MIDDLE,
}
//[TestCase(Name = "XMLIntegrityBase", Desc = "XMLIntegrityBase")]
public partial class TCXMLIntegrityBase : BridgeHelpers
{
private EINTEGRITY _eEIntegrity;
public EINTEGRITY IntegrityVer
{
get { return _eEIntegrity; }
set { _eEIntegrity = value; }
}
public static string pATTR = "Attr1";
public static string pNS = "Foo";
public static string pNAME = "PLAY0";
public XmlReader ReloadSource()
{
string strFile = GetTestFileName();
XmlReader DataReader = GetReader(strFile);
InitReaderPointer(DataReader);
return DataReader;
}
public void InitReaderPointer(XmlReader DataReader)
{
if (this.Desc == "BeforeRead")
{
IntegrityVer = EINTEGRITY.BEFORE_READ;
TestLog.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial");
TestLog.Compare(DataReader.EOF, false, "EOF==false");
}
else if (this.Desc == "AfterReadIsFalse")
{
IntegrityVer = EINTEGRITY.AFTER_READ_FALSE;
while (DataReader.Read()) ;
TestLog.Compare(DataReader.ReadState, ReadState.EndOfFile, "ReadState=EOF");
TestLog.Compare(DataReader.EOF, true, "EOF==true");
}
else if (this.Desc == "AfterClose")
{
IntegrityVer = EINTEGRITY.AFTER_CLOSE;
while (DataReader.Read()) ;
DataReader.Dispose();
TestLog.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed");
TestLog.Compare(DataReader.EOF, false, "EOF==true");
}
else if (this.Desc == "AfterCloseInTheMiddle")
{
IntegrityVer = EINTEGRITY.CLOSE_IN_THE_MIDDLE;
for (int i = 0; i < 1; i++)
{
if (false == DataReader.Read())
throw new TestFailedException("");
TestLog.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState=Interactive");
}
DataReader.Dispose();
TestLog.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed");
TestLog.Compare(DataReader.EOF, false, "EOF==true");
}
else if (this.Desc == "AfterResetState")
{
IntegrityVer = EINTEGRITY.AFTER_RESETSTATE;
// position the reader somewhere in the middle of the file
PositionOnElement(DataReader, "elem1");
TestLog.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial");
}
}
//[Variation("NodeType")]
public void GetXmlReaderNodeType()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.NodeType, XmlNodeType.None, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.None, Variation.Desc);
}
//[Variation("Name")]
public void GetXmlReaderName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.Name, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.Name, String.Empty, Variation.Desc);
}
//[Variation("LocalName")]
public void GetXmlReaderLocalName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.LocalName, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.LocalName, String.Empty, Variation.Desc);
}
//[Variation("NamespaceURI")]
public void Namespace()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.NamespaceURI, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.NamespaceURI, String.Empty, Variation.Desc);
}
//[Variation("Prefix")]
public void Prefix()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.Prefix, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.Prefix, String.Empty, Variation.Desc);
}
//[Variation("HasValue")]
public void HasValue()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.HasValue, false, Variation.Desc);
TestLog.Compare(DataReader.HasValue, false, Variation.Desc);
}
//[Variation("Value")]
public void GetXmlReaderValue()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.Value, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.Value, String.Empty, Variation.Desc);
}
//[Variation("Depth")]
public void GetDepth()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.Depth, 0, Variation.Desc);
TestLog.Compare(DataReader.Depth, 0, Variation.Desc);
}
//[Variation("BaseURI")]
public void GetBaseURI()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.BaseURI, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.BaseURI, String.Empty, Variation.Desc);
}
//[Variation("IsEmptyElement")]
public void IsEmptyElement()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsEmptyElement, false, Variation.Desc);
TestLog.Compare(DataReader.IsEmptyElement, false, Variation.Desc);
}
//[Variation("IsDefault")]
public void IsDefault()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsDefault, false, Variation.Desc);
TestLog.Compare(DataReader.IsDefault, false, Variation.Desc);
}
//[Variation("XmlSpace")]
public void GetXmlSpace()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, Variation.Desc);
TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, Variation.Desc);
}
//[Variation("XmlLang")]
public void GetXmlLang()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.XmlLang, String.Empty, Variation.Desc);
TestLog.Compare(DataReader.XmlLang, String.Empty, Variation.Desc);
}
//[Variation("AttributeCount")]
public void AttributeCount()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.AttributeCount, 0, Variation.Desc);
TestLog.Compare(DataReader.AttributeCount, 0, Variation.Desc);
}
//[Variation("HasAttributes")]
public void HasAttribute()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.HasAttributes, false, Variation.Desc);
TestLog.Compare(DataReader.HasAttributes, false, Variation.Desc);
}
//[Variation("GetAttributes(name)")]
public void GetAttributeName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.GetAttribute(pATTR), null, "Compare the GetAttribute");
}
//[Variation("GetAttribute(String.Empty)")]
public void GetAttributeEmptyName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.GetAttribute(String.Empty), null, "Compare the GetAttribute");
}
//[Variation("GetAttribute(name,ns)")]
public void GetAttributeNameNamespace()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.GetAttribute(pATTR, pNS), null, "Compare the GetAttribute");
}
//[Variation("GetAttribute(String.Empty, String.Empty)")]
public void GetAttributeEmptyNameNamespace()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.GetAttribute(String.Empty, String.Empty), null, "Compare the GetAttribute");
}
//[Variation("GetAttribute(i)")]
public void GetAttributeOrdinal()
{
XmlReader DataReader = ReloadSource();
DataReader.GetAttribute(0);
}
//[Variation("this[i]")]
public void HelperThisOrdinal()
{
XmlReader DataReader = ReloadSource();
string str = DataReader[0];
}
//[Variation("this[name]")]
public void HelperThisName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader[pATTR], null, "Compare the GetAttribute");
}
//[Variation("this[name,namespace]")]
public void HelperThisNameNamespace()
{
XmlReader DataReader = ReloadSource();
string str = DataReader[pATTR, pNS];
TestLog.Compare(DataReader[pATTR, pNS], null, "Compare the GetAttribute");
}
//[Variation("MoveToAttribute(name)")]
public void MoveToAttributeName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.MoveToAttribute(pATTR), false, Variation.Desc);
TestLog.Compare(DataReader.MoveToAttribute(pATTR), false, Variation.Desc);
}
//[Variation("MoveToAttributeNameNamespace(name,ns)")]
public void MoveToAttributeNameNamespace()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.MoveToAttribute(pATTR, pNS), false, Variation.Desc);
TestLog.Compare(DataReader.MoveToAttribute(pATTR, pNS), false, Variation.Desc);
}
//[Variation("MoveToAttribute(i)")]
public void MoveToAttributeOrdinal()
{
XmlReader DataReader = ReloadSource();
DataReader.MoveToAttribute(0);
}
//[Variation("MoveToFirstAttribute()")]
public void MoveToFirstAttribute()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc);
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc);
}
//[Variation("MoveToNextAttribute()")]
public void MoveToNextAttribute()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc);
TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc);
}
//[Variation("MoveToElement()")]
public void MoveToElement()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.MoveToElement(), false, Variation.Desc);
TestLog.Compare(DataReader.MoveToElement(), false, Variation.Desc);
}
//[Variation("Read")]
public void ReadTestAfterClose()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.Read(), true, Variation.Desc);
TestLog.Compare(DataReader.Read(), true, Variation.Desc);
}
//[Variation("GetEOF")]
public void GetEOF()
{
XmlReader DataReader = ReloadSource();
if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE))
{
TestLog.Compare(DataReader.EOF, true, Variation.Desc);
TestLog.Compare(DataReader.EOF, true, Variation.Desc);
}
else
{
TestLog.Compare(DataReader.EOF, false, Variation.Desc);
TestLog.Compare(DataReader.EOF, false, Variation.Desc);
}
}
//[Variation("GetReadState")]
public void GetReadState()
{
XmlReader DataReader = ReloadSource();
ReadState iState = ReadState.Initial;
// EndOfFile State
if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE))
{
iState = ReadState.EndOfFile;
}
// Closed State
if ((IntegrityVer == EINTEGRITY.AFTER_CLOSE) || (IntegrityVer == EINTEGRITY.CLOSE_IN_THE_MIDDLE))
{
iState = ReadState.Closed;
}
TestLog.Compare(DataReader.ReadState, iState, Variation.Desc);
TestLog.Compare(DataReader.ReadState, iState, Variation.Desc);
}
//[Variation("Skip")]
public void XMLSkip()
{
XmlReader DataReader = ReloadSource();
DataReader.Skip();
DataReader.Skip();
}
//[Variation("NameTable")]
public void TestNameTable()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.NameTable != null, "nt");
}
//[Variation("ReadInnerXml")]
public void ReadInnerXmlTestAfterClose()
{
XmlReader DataReader = ReloadSource();
XmlNodeType nt = DataReader.NodeType;
string name = DataReader.Name;
string value = DataReader.Value;
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn");
}
//[Variation("ReadOuterXml")]
public void TestReadOuterXml()
{
XmlReader DataReader = ReloadSource();
XmlNodeType nt = DataReader.NodeType;
string name = DataReader.Name;
string value = DataReader.Value;
TestLog.Compare(DataReader.ReadOuterXml(), String.Empty, Variation.Desc);
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn");
}
//[Variation("MoveToContent")]
public void TestMoveToContent()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
}
//[Variation("IsStartElement")]
public void TestIsStartElement()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
}
//[Variation("IsStartElement(name)")]
public void TestIsStartElementName()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsStartElement(pNAME), false, Variation.Desc);
}
//[Variation("IsStartElement(String.Empty)")]
public void TestIsStartElementName2()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsStartElement(String.Empty), false, Variation.Desc);
}
//[Variation("IsStartElement(name, ns)")]
public void TestIsStartElementNameNs()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsStartElement(pNAME, pNS), false, Variation.Desc);
}
//[Variation("IsStartElement(String.Empty,String.Empty)")]
public void TestIsStartElementNameNs2()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, Variation.Desc);
}
//[Variation("ReadStartElement")]
public void TestReadStartElement()
{
XmlReader DataReader = ReloadSource();
DataReader.ReadStartElement();
}
//[Variation("ReadStartElement(name)")]
public void TestReadStartElementName()
{
XmlReader DataReader = ReloadSource();
try
{
DataReader.ReadStartElement(pNAME);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(String.Empty)")]
public void TestReadStartElementName2()
{
XmlReader DataReader = ReloadSource();
try
{
DataReader.ReadStartElement(String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(name, ns)")]
public void TestReadStartElementNameNs()
{
XmlReader DataReader = ReloadSource();
try
{
DataReader.ReadStartElement(pNAME, pNS);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(String.Empty,String.Empty)")]
public void TestReadStartElementNameNs2()
{
XmlReader DataReader = ReloadSource();
try
{
DataReader.ReadStartElement(String.Empty, String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement")]
public void TestReadEndElement()
{
XmlReader DataReader = ReloadSource();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("LookupNamespace")]
public void LookupNamespace()
{
XmlReader DataReader = ReloadSource();
string[] astr = { "a", "Foo", String.Empty, "Foo1", "Foo_S" };
for (int i = 0; i < astr.Length; i++)
{
if (DataReader.LookupNamespace(astr[i]) != null)
{
}
TestLog.Compare(DataReader.LookupNamespace(astr[i]), null, Variation.Desc);
}
}
//[Variation("ReadAttributeValue")]
public void ReadAttributeValue()
{
XmlReader DataReader = ReloadSource();
TestLog.Compare(DataReader.ReadAttributeValue(), false, Variation.Desc);
TestLog.Compare(DataReader.ReadAttributeValue(), false, Variation.Desc);
}
//[Variation("Close")]
public void CloseTest()
{
XmlReader DataReader = ReloadSource();
DataReader.Dispose();
DataReader.Dispose();
DataReader.Dispose();
}
}
}
}
}
| |
namespace LuaInterface
{
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
/*
* Cached method
*/
struct MethodCache
{
private MethodBase _cachedMethod;
public MethodBase cachedMethod
{
get
{
return _cachedMethod;
}
set
{
_cachedMethod = value;
MethodInfo mi = value as MethodInfo;
if (mi != null)
{
//SJD this is guaranteed to be correct irrespective of actual name used for type..
IsReturnVoid = mi.ReturnType == typeof(void);
}
}
}
public bool IsReturnVoid;
// List or arguments
public object[] args;
// Positions of out parameters
public int[] outList;
// Types of parameters
public MethodArgs[] argTypes;
}
/*
* Parameter information
*/
struct MethodArgs
{
// Position of parameter
public int index;
// Type-conversion function
public ExtractValue extractValue;
public bool isParamsArray;
public Type paramsArrayType;
}
/*
* Argument extraction with type-conversion function
*/
delegate object ExtractValue(IntPtr luaState, int stackPos);
/*
* Wrapper class for methods/constructors accessed from Lua.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
class LuaMethodWrapper
{
private ObjectTranslator _Translator;
private MethodBase _Method;
private MethodCache _LastCalledMethod = new MethodCache();
private string _MethodName;
private MemberInfo[] _Members;
public IReflect _TargetType;
private ExtractValue _ExtractTarget;
private object _Target;
private BindingFlags _BindingType;
/*
* Constructs the wrapper for a known MethodBase instance
*/
public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method)
{
_Translator = translator;
_Target = target;
_TargetType = targetType;
if (targetType != null)
_ExtractTarget = translator.typeChecker.getExtractor(targetType);
_Method = method;
_MethodName = method.Name;
if (method.IsStatic)
{ _BindingType = BindingFlags.Static; }
else
{ _BindingType = BindingFlags.Instance; }
}
/*
* Constructs the wrapper for a known method name
*/
public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
{
_Translator = translator;
_MethodName = methodName;
_TargetType = targetType;
if (targetType != null)
_ExtractTarget = translator.typeChecker.getExtractor(targetType);
_BindingType = bindingType;
//CP: Removed NonPublic binding search and added IgnoreCase
_Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
}
/// <summary>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param>
int SetPendingException(Exception e)
{
return _Translator.interpreter.SetPendingException(e);
}
private static bool IsInteger(double x) {
return Math.Ceiling(x) == x;
}
private void ClearCachedArgs()
{
if(_LastCalledMethod.args == null) { return; }
for(int i = 0; i < _LastCalledMethod.args.Length; i++)
{
_LastCalledMethod.args[i] = null;
}
}
/*
* Calls the method. Receives the arguments from the Lua stack
* and returns values in it.
*/
public int call(IntPtr luaState)
{
MethodBase methodToCall = _Method;
object targetObject = _Target;
bool failedCall = true;
int nReturnValues = 0;
if (!LuaDLL.lua_checkstack(luaState, 5))
throw new LuaException("Lua stack overflow");
bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static;
SetPendingException(null);
if (methodToCall == null) // Method from name
{
if (isStatic)
targetObject = null;
else
targetObject = _ExtractTarget(luaState, 1);
//LuaDLL.lua_remove(luaState,1); // Pops the receiver
if (_LastCalledMethod.cachedMethod != null) // Cached?
{
int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject
int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip;
MethodBase method = _LastCalledMethod.cachedMethod;
if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match?
{
if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow");
object[] args = _LastCalledMethod.args;
try
{
for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++)
{
MethodArgs type = _LastCalledMethod.argTypes[i];
object luaParamValue = type.extractValue(luaState, i + 1 + numStackToSkip);
if (_LastCalledMethod.argTypes[i].isParamsArray)
{
args[type.index] = _Translator.tableToArray(luaParamValue,type.paramsArrayType);
}
else
{
args[type.index] = luaParamValue;
}
if (args[type.index] == null &&
!LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip))
{
throw new LuaException("argument number " + (i + 1) + " is invalid");
}
}
if ((_BindingType & BindingFlags.Static) == BindingFlags.Static)
{
_Translator.push(luaState, method.Invoke(null, args));
}
else
{
if (_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push(luaState, ((ConstructorInfo)method).Invoke(args));
else
_Translator.push(luaState, method.Invoke(targetObject,args));
}
failedCall = false;
}
catch (TargetInvocationException e)
{
// Failure of method invocation
return SetPendingException(e.GetBaseException());
}
catch (Exception e)
{
if (_Members.Length == 1) // Is the method overloaded?
// No, throw error
return SetPendingException(e);
}
}
}
// Cache miss
if (failedCall)
{
// System.Diagnostics.Debug.WriteLine("cache miss on " + methodName);
// If we are running an instance variable, we can now pop the targetObject from the stack
if (!isStatic)
{
if (targetObject == null)
{
_Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
LuaDLL.lua_pushnil(luaState);
return 1;
}
LuaDLL.lua_remove(luaState, 1); // Pops the receiver
}
bool hasMatch = false;
string candidateName = null;
foreach (MemberInfo member in _Members)
{
candidateName = member.ReflectedType.Name + "." + member.Name;
MethodBase m = (MethodInfo)member;
bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod);
if (isMethod)
{
hasMatch = true;
break;
}
}
if (!hasMatch)
{
string msg = (candidateName == null)
? "invalid arguments to method call"
: ("invalid arguments to method: " + candidateName);
_Translator.throwError(luaState, msg);
LuaDLL.lua_pushnil(luaState);
ClearCachedArgs();
return 1;
}
}
}
else // Method from MethodBase instance
{
if (methodToCall.ContainsGenericParameters)
{
// bool isMethod = //* not used
_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod);
if (methodToCall.IsGenericMethodDefinition)
{
//need to make a concrete type of the generic method definition
List<Type> typeArgs = new List<Type>();
foreach (object arg in _LastCalledMethod.args)
typeArgs.Add(arg.GetType());
MethodInfo concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray());
_Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args));
failedCall = false;
}
else if (methodToCall.ContainsGenericParameters)
{
_Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method");
LuaDLL.lua_pushnil(luaState);
ClearCachedArgs();
return 1;
}
}
else
{
if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
{
targetObject = _ExtractTarget(luaState, 1);
LuaDLL.lua_remove(luaState, 1); // Pops the receiver
}
if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod))
{
_Translator.throwError(luaState, "invalid arguments to method call");
LuaDLL.lua_pushnil(luaState);
ClearCachedArgs();
return 1;
}
}
}
if (failedCall)
{
if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
{
ClearCachedArgs();
throw new LuaException("Lua stack overflow");
}
try
{
if (isStatic)
{
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
}
else
{
if (_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
else
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
}
}
catch (TargetInvocationException e)
{
ClearCachedArgs();
return SetPendingException(e.GetBaseException());
}
catch (Exception e)
{
ClearCachedArgs();
return SetPendingException(e);
}
}
// Pushes out and ref return values
for (int index = 0; index < _LastCalledMethod.outList.Length; index++)
{
nReturnValues++;
_Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]);
}
//by isSingle 2010-09-10 11:26:31
//Desc:
// if not return void,we need add 1,
// or we will lost the function's return value
// when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code
if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0)
{
nReturnValues++;
}
ClearCachedArgs();
return nReturnValues < 1 ? 1 : nReturnValues;
}
}
/// <summary>
/// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session
/// </summary>
class EventHandlerContainer : IDisposable
{
Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>();
public void Add(Delegate handler, RegisterEventHandler eventInfo)
{
dict.Add(handler, eventInfo);
}
public void Remove(Delegate handler)
{
bool found = dict.Remove(handler);
Debug.Assert(found);
}
/// <summary>
/// Remove any still registered handlers
/// </summary>
public void Dispose()
{
foreach (KeyValuePair<Delegate, RegisterEventHandler> pair in dict)
{
pair.Value.RemovePending(pair.Key);
}
dict.Clear();
}
}
/*
* Wrapper class for events that does registration/deregistration
* of event handlers.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
class RegisterEventHandler
{
object target;
EventInfo eventInfo;
EventHandlerContainer pendingEvents;
public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo)
{
this.target = target;
this.eventInfo = eventInfo;
this.pendingEvents = pendingEvents;
}
/*
* Adds a new event handler
*/
public Delegate Add(LuaFunction function)
{
#if __NOGEN__
//translator.throwError(luaState,"Delegates not implemnented");
return null;
#else
//CP: Fix by Ben Bryant for event handling with one parameter
//link: http://luaforge.net/forum/message.php?msg_id=9266
Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function);
eventInfo.AddEventHandler(target, handlerDelegate);
pendingEvents.Add(handlerDelegate, this);
return handlerDelegate;
#endif
//MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke");
//ParameterInfo[] pi = mi.GetParameters();
//LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function);
//Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent");
//eventInfo.AddEventHandler(target,handlerDelegate);
//pendingEvents.Add(handlerDelegate, this);
//return handlerDelegate;
}
/*
* Removes an existing event handler
*/
public void Remove(Delegate handlerDelegate)
{
RemovePending(handlerDelegate);
pendingEvents.Remove(handlerDelegate);
}
/*
* Removes an existing event handler (without updating the pending handlers list)
*/
internal void RemovePending(Delegate handlerDelegate)
{
eventInfo.RemoveEventHandler(target, handlerDelegate);
}
}
/*
* Base wrapper class for Lua function event handlers.
* Subclasses that do actual event handling are created
* at runtime.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaEventHandler
{
public LuaFunction handler = null;
// CP: Fix provided by Ben Bryant for delegates with one param
// link: http://luaforge.net/forum/message.php?msg_id=9318
public void handleEvent(object[] args)
{
handler.Call(args);
}
//public void handleEvent(object sender,object data)
//{
// handler.call(new object[] { sender,data },new Type[0]);
//}
}
/*
* Wrapper class for Lua functions as delegates
* Subclasses with correct signatures are created
* at runtime.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaDelegate
{
public Type[] returnTypes;
public LuaFunction function;
public LuaDelegate()
{
function = null;
returnTypes = null;
}
public object callFunction(object[] args, object[] inArgs, int[] outArgs)
{
// args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
if (returnTypes[0] == typeof(void))
{
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
iRefArgs = 1;
}
// Sets the value of out and ref parameters (from
// the values returned by the Lua function).
for (int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++;
}
return returnValue;
}
}
/*
* Static helper methods for Lua tables acting as CLR objects.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaClassHelper
{
/*
* Gets the function called name from the provided table,
* returning null if it does not exist
*/
public static LuaFunction getTableFunction(LuaTable luaTable, string name)
{
object funcObj = luaTable.rawget(name);
if (funcObj is LuaFunction)
return (LuaFunction)funcObj;
else
return null;
}
/*
* Calls the provided function with the provided parameters
*/
public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs)
{
// args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
if (returnTypes[0] == typeof(void))
{
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
iRefArgs = 1;
}
for (int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++;
}
return returnValue;
}
}
}
| |
#region Copyright (c) 2017 Atif Aziz. 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.
//
#endregion
namespace WebLinq
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive;
public interface ISubmissionData<out T>
{
T Run(NameValueCollection data);
}
public interface ISubmissionDataAction<out T> : ISubmissionData<Unit>
{
ISubmissionData<T> Return();
}
static class FormSubmissionAction
{
public static SubmissionDataAction<T> Create<T>(ISubmissionData<T> submission) =>
new SubmissionDataAction<T>(submission);
}
public sealed class SubmissionDataAction<T> : ISubmissionDataAction<T>
{
readonly ISubmissionData<T> _submission;
public SubmissionDataAction(ISubmissionData<T> submission) =>
_submission = submission ?? throw new ArgumentNullException(nameof(submission));
public Unit Run(NameValueCollection data)
{
_submission.Run(data);
return Unit.Default;
}
public ISubmissionData<T> Return() => _submission;
}
public static partial class SubmissionData
{
public static ISubmissionData<T> Create<T>(Func<NameValueCollection, T> runner) =>
new DelegatingSubmission<T>(runner);
sealed class DelegatingSubmission<T> : ISubmissionData<T>
{
readonly Func<NameValueCollection, T> _runner;
public DelegatingSubmission(Func<NameValueCollection, T> runner) =>
_runner = runner ?? throw new ArgumentNullException(nameof(runner));
public T Run(NameValueCollection data) =>
_runner(data ?? throw new ArgumentNullException(nameof(data)));
}
public static ISubmissionData<T> Return<T>(T value) => Create(_ => value);
public static ISubmissionData<TResult> Bind<T, TResult>(this ISubmissionData<T> submission, Func<T, ISubmissionData<TResult>> selector) =>
Create(env => selector(submission.Run(env)).Run(env));
public static ISubmissionData<TResult> Select<T, TResult>(this ISubmissionData<T> submission, Func<T, TResult> selector) =>
Create(env => selector(submission.Run(env)));
public static ISubmissionData<TResult> SelectMany<TFirst, TSecond, TResult>(
this ISubmissionData<TFirst> submission,
Func<TFirst, ISubmissionData<TSecond>> secondSelector,
Func<TFirst, TSecond, TResult> resultSelector) =>
Create(env =>
{
var t = submission.Run(env);
return resultSelector(t, secondSelector(t).Run(env));
});
public static ISubmissionData<TResult> SelectMany<T, TResult>(
this ISubmissionData<T> submission,
Func<T, ISubmissionData<TResult>> resultSelector) =>
submission.SelectMany(resultSelector, (_, r) => r);
public static ISubmissionData<IEnumerable<TResult>> For<T, TResult>(IEnumerable<T> source,
Func<T, ISubmissionData<TResult>> f) =>
Create(data => source.Select(f).Select(e => e.Run(data)).ToList());
internal static ISubmissionData<T> Do<T>(this ISubmissionData<T> submission, Action<NameValueCollection> action) =>
submission.Bind(x => Create(env => { action(env); return x; }));
internal static ISubmissionData<Unit> Do(Action<NameValueCollection> action) =>
Create(env => { action(env); return Unit.Default; });
}
}
namespace WebLinq
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
using Collections;
using Mannex.Collections.Generic;
using Mannex.Collections.Specialized;
using Unit = System.Reactive.Unit;
public static partial class SubmissionData
{
/// <summary>
/// Represents nothing.
/// </summary>
public static readonly ISubmissionData<Unit> None = Do(delegate { });
/// <summary>
/// Get the names of all the fields.
/// </summary>
public static ISubmissionData<IReadOnlyCollection<string>> Names() =>
Create(data => data.AllKeys);
/// <summary>
/// Gets the value of a field identified by its name.
/// </summary>
public static ISubmissionData<string> Get(string name) =>
Create(data => data[name]);
/// <summary>
/// Gets all the values of a field identified by its name.
/// </summary>
public static ISubmissionData<Strings> GetValues(string name) =>
Create(data => Strings.Array(data.GetValues(name)));
/// <summary>
/// Removes a field from submission.
/// </summary>
public static ISubmissionData<Unit> Remove(string name) =>
Do(data => data.Remove(name));
/// <summary>
/// Sets the value of a field identified by its name.
/// </summary>
public static ISubmissionData<Unit> Set(string name, Strings value)
=> value.Count == 0 ? Remove(name)
: value.Count == 1 ? Do(data => data[name] = value[0])
: Remove(name).Then(For(value, v => Do(data => data.Add(name, v))).Ignore());
/// <summary>
/// Sets the values of all fields identified by a collection of
/// names to the same value.
/// </summary>
public static ISubmissionData<Unit> Set(IEnumerable<string> names, Strings value) =>
from _ in For(names, n => Set(n, value))
select Unit.Default;
static ISubmissionDataAction<string> TrySet(Func<IEnumerable<string>, string> matcher, Strings value) =>
FormSubmissionAction.Create(
from ns in Names()
select matcher(ns) into n
from r in n != null
? from _ in Set(n, value) select n
: Return((string) null)
select r);
/// <summary>
/// Sets the value of a single field identified by a predicate function
/// otherwise throws an error.
/// </summary>
/// <returns>
/// The name of the field whose value was set.
/// </returns>
public static ISubmissionDataAction<string> SetSingleWhere(Func<string, bool> matcher, Strings value) =>
TrySet(ns => ns.Single(matcher), value);
/// <summary>
/// Sets the value of a single field identified by a regular expression
/// pattern otherwise throws an error.
/// </summary>
/// <returns>
/// The name of the field whose value was set.
/// </returns>
public static ISubmissionDataAction<string> SetSingleMatching(string pattern, Strings value) =>
SetSingleWhere(n => Regex.IsMatch(n, pattern), value);
/// <summary>
/// Attempts to set the value of a single field identified by a
/// predicate function otherwise has no effect.
/// </summary>
/// <returns>
/// The name of the field whose value was set or <c>null</c> if zero
/// or multiple fields were identified.
/// </returns>
public static ISubmissionDataAction<string> TrySetSingleWhere(Func<string, bool> matcher, Strings value) =>
TrySet(ns => ns.SingleOrDefault(matcher), value);
/// <summary>
/// Attempts to Set the value of a single field identified by a
/// regular expression pattern otherwise has no effect.
/// </summary>
/// <returns>
/// The name of the field whose value was set or <c>null</c> if zero
/// or multiple fields were identified.
/// </returns>
public static ISubmissionDataAction<string> TrySetSingleMatching(string pattern, Strings value) =>
TrySetSingleWhere(n => Regex.IsMatch(n, pattern), value);
/// <summary>
/// Sets the value of the first field identified by a predicate
/// function otherwise throws an error if no field was identified.
/// </summary>
/// <returns>
/// The name of the first field identified by the predicate function.
/// </returns>
public static ISubmissionDataAction<string> SetFirstWhere(Func<string, bool> matcher, Strings value) =>
TrySet(ns => ns.First(matcher), value);
/// <summary>
/// Attempts to set the value of the first field identified by a
/// predicate function otherwise has no effect if no field was
/// identified.
/// </summary>
/// <returns>
/// The name of the first field identified by the predicate function.
/// </returns>
public static ISubmissionDataAction<string> TrySetFirstWhere(Func<string, bool> matcher, Strings value) =>
TrySet(ns => ns.FirstOrDefault(matcher), value);
/// <summary>
/// Attempts to set the value of the first field identified by a
/// regular expression pattern otherwise has no effect if no field was
/// identified.
/// </summary>
/// <returns>
/// The name of the first field identified by the predicate function.
/// </returns>
public static ISubmissionDataAction<string> TrySetFirstMatching(string pattern, Strings value) =>
TrySetFirstWhere(n => Regex.IsMatch(n, pattern), value);
/// <summary>
/// Sets the values of all fields identified by a predicate function
/// to the same value.
/// </summary>
/// <returns>
/// A sequence of field names that were identified by the predicate
/// function and affected.
/// </returns>
public static ISubmissionDataAction<IEnumerable<string>> SetWhere(Func<string, bool> matcher, Strings value) =>
FormSubmissionAction.Create(
from ns in Names()
select ns.Where(matcher).ToArray() into ns
from _ in Set(ns, value)
select ns);
/// <summary>
/// Sets the values of all fields identified by a regular expression
/// pattern to the same value.
/// </summary>
/// <returns>
/// A sequence of field names that matched and were affected.
/// </returns>
public static ISubmissionDataAction<IEnumerable<string>> SetMatching(string pattern, Strings value) =>
SetWhere(n => Regex.IsMatch(n, pattern), value);
public static ISubmissionData<Unit> Merge(NameValueCollection other) =>
Do(data =>
{
var entries = from e in other.AsEnumerable()
from v in e.Value select e.Key.AsKeyTo(v);
foreach (var e in entries)
data.Add(e.Key, e.Value);
});
/// <summary>
/// Returns a copy of the form data as a
/// <see cref="NameValueCollection"/>.
/// </summary>
public static ISubmissionData<NameValueCollection> Data() =>
Create(data => new NameValueCollection(data));
/// <summary>
/// Clears all form data.
/// </summary>
public static ISubmissionData<Unit> Clear() =>
Do(data => data.Clear());
/// <summary>
/// Changes the type of the submission to <seealso cref="Unit"/>.
/// </summary>
public static ISubmissionData<Unit> Ignore<T>(this ISubmissionData<T> submission) =>
from _ in submission
select Unit.Default;
/// <summary>
/// Continues one submission after another.
/// </summary>
public static ISubmissionData<T> Then<T>(this ISubmissionData<Unit> first, ISubmissionData<T> second) =>
from _ in first
from b in second
select b;
/// <summary>
/// Combines the result of one submission with another.
/// </summary>
public static ISubmissionData<TResult>
Zip<TFirst, TSecond, TResult>(
this ISubmissionData<TFirst> first,
ISubmissionData<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector) =>
from a in first
from b in second
select resultSelector(a, b);
public static ISubmissionData<Unit> Collect(params ISubmissionData<Unit>[] submissions) =>
submissions.AsEnumerable().Collect();
public static ISubmissionData<Unit> Collect(this IEnumerable<ISubmissionData<Unit>> submissions) =>
For(submissions, s => s).Ignore();
}
}
namespace WebLinq.Html
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Collections;
using static SubmissionData;
public static class FormSubmissionData
{
static ISubmissionDataAction<string> TrySet(this HtmlForm form, Func<IEnumerable<string>, string> matcher, Strings value) =>
FormSubmissionAction.Create(
from ns in Return(from c in form.Controls select c.Name)
select matcher(ns) into n
from r in n != null
? from _ in Set(n, value) select n
: Return((string) null)
select r);
/// <summary>
/// Sets the value of a single field identified by a predicate function
/// otherwise throws an error.
/// </summary>
/// <returns>
/// The name of the field whose value was set.
/// </returns>
public static ISubmissionDataAction<string> SetSingleWhere(this HtmlForm form, Func<string, bool> matcher, Strings value) =>
form.TrySet(ns => ns.Single(matcher), value);
/// <summary>
/// Sets the value of a single field identified by a regular expression
/// pattern otherwise throws an error.
/// </summary>
/// <returns>
/// The name of the field whose value was set.
/// </returns>
public static ISubmissionDataAction<string> SetSingleMatching(this HtmlForm form, string pattern, Strings value) =>
form.SetSingleWhere(n => Regex.IsMatch(n, pattern), value);
/// <summary>
/// Attempts to set the value of a single field identified by a
/// predicate function otherwise has no effect.
/// </summary>
/// <returns>
/// The name of the field whose value was set or <c>null</c> if zero
/// or multiple fields were identified.
/// </returns>
public static ISubmissionDataAction<string> TrySetSingleWhere(this HtmlForm form, Func<string, bool> matcher, Strings value) =>
form.TrySet(ns => ns.SingleOrDefault(matcher), value);
/// <summary>
/// Attempts to Set the value of a single field identified by a
/// regular expression pattern otherwise has no effect.
/// </summary>
/// <returns>
/// The name of the field whose value was set or <c>null</c> if zero
/// or multiple fields were identified.
/// </returns>
public static ISubmissionDataAction<string> TrySetSingleMatching(this HtmlForm form, string pattern, Strings value) =>
form.TrySetSingleWhere(n => Regex.IsMatch(n, pattern), value);
/// <summary>
/// Sets the value of the first field identified by a predicate
/// function otherwise throws an error if no field was identified.
/// </summary>
/// <returns>
/// The name of the first field identified by the predicate function.
/// </returns>
public static ISubmissionDataAction<string> SetFirstWhere(this HtmlForm form, Func<string, bool> matcher, Strings value) =>
form.TrySet(ns => ns.First(matcher), value);
/// <summary>
/// Attempts to set the value of the first field identified by a
/// predicate function otherwise has no effect if no field was
/// identified.
/// </summary>
/// <returns>
/// The name of the first field identified by the predicate function.
/// </returns>
public static ISubmissionDataAction<string> TrySetFirstWhere(this HtmlForm form, Func<string, bool> matcher, Strings value) =>
form.TrySet(ns => ns.FirstOrDefault(matcher), value);
/// <summary>
/// Attempts to set the value of the first field identified by a
/// regular expression pattern otherwise has no effect if no field was
/// identified.
/// </summary>
/// <returns>
/// The name of the first field identified by the predicate function.
/// </returns>
public static ISubmissionDataAction<string> TrySetFirstMatching(this HtmlForm form, string pattern, Strings value) =>
form.TrySetFirstWhere(n => Regex.IsMatch(n, pattern), value);
/// <summary>
/// Sets the values of all fields identified by a predicate function
/// to the same value.
/// </summary>
/// <returns>
/// A sequence of field names that were identified by the predicate
/// function and affected.
/// </returns>
public static ISubmissionDataAction<IEnumerable<string>> SetWhere(this HtmlForm form, Func<string, bool> matcher, Strings value) =>
FormSubmissionAction.Create(
from ns in Return(from c in form.Controls select c.Name)
select ns.Where(matcher).ToArray() into ns
from _ in Set(ns, value)
select ns);
/// <summary>
/// Sets the values of all fields identified by a regular expression
/// pattern to the same value.
/// </summary>
/// <returns>
/// A sequence of field names that matched and were affected.
/// </returns>
public static ISubmissionDataAction<IEnumerable<string>> SetMatching(this HtmlForm form, string pattern, Strings value) =>
form.SetWhere(n => Regex.IsMatch(n, pattern), value);
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Aurora.Simulation.Base;
using CSJ2K;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using Aurora.Framework;
namespace Aurora.Modules.Agent.J2KDecoder
{
public delegate void J2KDecodeDelegate(UUID assetID);
public class J2KDecoderModule : IService, IJ2KDecoder
{
/// <summary>
/// Temporarily holds deserialized layer data information in memory
/// </summary>
private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache =
new ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]>();
/// <summary>
/// List of client methods to notify of results of decode
/// </summary>
private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList =
new Dictionary<UUID, List<DecodedCallback>>();
/// <summary>
/// Cache that will store decoded JPEG2000 layer boundary data
/// </summary>
private IImprovedAssetCache m_cache;
private bool m_useCache = true;
private bool m_useCSJ2K = true;
#region IJ2KDecoder
public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback)
{
OpenJPEG.J2KLayerInfo[] result;
// If it's cached, return the cached results
if (m_decodedCache.TryGetValue(assetID, out result))
{
callback(assetID, result);
}
else
{
// Not cached, we need to decode it.
// Add to notify list and start decoding.
// Next request for this asset while it's decoding will only be added to the notify list
// once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated
bool decode = false;
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
m_notifyList[assetID].Add(callback);
}
else
{
List<DecodedCallback> notifylist = new List<DecodedCallback> {callback};
m_notifyList.Add(assetID, notifylist);
decode = true;
}
}
// Do Decode!
if (decode)
DoJ2KDecode(assetID, j2kData);
}
}
/// <summary>
/// Provides a synchronous decode so that caller can be assured that this executes before the next line
/// </summary>
/// <param name = "assetID"></param>
/// <param name = "j2kData"></param>
public bool Decode(UUID assetID, byte[] j2kData)
{
return DoJ2KDecode(assetID, j2kData);
}
#endregion IJ2KDecoder
#region IJ2KDecoder Members
public Image DecodeToImage(byte[] j2kData)
{
if (m_useCSJ2K)
return J2kImage.FromBytes(j2kData);
else
{
ManagedImage mimage;
Image image;
if (OpenJPEG.DecodeToImage(j2kData, out mimage, out image))
{
mimage = null;
return image;
}
else
return null;
}
}
#endregion
/// <summary>
/// Decode Jpeg2000 Asset Data
/// </summary>
/// <param name = "assetID">UUID of Asset</param>
/// <param name = "j2kData">JPEG2000 data</param>
private bool DoJ2KDecode(UUID assetID, byte[] j2kData)
{
return DoJ2KDecode(assetID, j2kData, m_useCSJ2K);
}
private bool DoJ2KDecode(UUID assetID, byte[] j2kData, bool m_useCSJ2K)
{
//int DecodeTime = 0;
//DecodeTime = Environment.TickCount;
OpenJPEG.J2KLayerInfo[] layers;
if (!TryLoadCacheForAsset(assetID, out layers))
{
if (m_useCSJ2K)
{
try
{
List<int> layerStarts = J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));
if (layerStarts != null && layerStarts.Count > 0)
{
layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
for (int i = 0; i < layerStarts.Count; i++)
{
OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo
{Start = i == 0 ? 0 : layerStarts[i]};
if (i == layerStarts.Count - 1)
layer.End = j2kData.Length;
else
layer.End = layerStarts[i + 1] - 1;
layers[i] = layer;
}
}
}
catch (Exception ex)
{
MainConsole.Instance.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " +
ex.Message);
}
}
else
{
int components;
if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components))
{
MainConsole.Instance.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID);
}
}
if (layers == null || layers.Length == 0)
{
if (m_useCSJ2K == this.m_useCSJ2K)
{
MainConsole.Instance.Warn("[J2KDecoderModule]: Failed to decode layer data with (" +
(m_useCSJ2K ? "CSJ2K" : "OpenJPEG") + ") for texture " + assetID + ", length " +
j2kData.Length + " trying " + (!m_useCSJ2K ? "CSJ2K" : "OpenJPEG"));
DoJ2KDecode(assetID, j2kData, !m_useCSJ2K);
}
else
{
//Second attempt at decode with the other j2k decoder, give up
MainConsole.Instance.Warn("[J2KDecoderModule]: Failed to decode layer data (" +
(m_useCSJ2K ? "CSJ2K" : "OpenJPEG") + ") for texture " + assetID + ", length " +
j2kData.Length + " guessing sane defaults");
// Layer decoding completely failed. Guess at sane defaults for the layer boundaries
layers = CreateDefaultLayers(j2kData.Length);
// Notify Interested Parties
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
#if (!ISWIN)
foreach (DecodedCallback d in m_notifyList[assetID])
{
if (d != null)
{
d.DynamicInvoke(assetID, layers);
}
}
#else
foreach (DecodedCallback d in m_notifyList[assetID].Where(d => d != null))
{
d.DynamicInvoke(assetID, layers);
}
#endif
m_notifyList.Remove(assetID);
}
}
return false;
}
}
else //Don't save the corrupt texture!
{
// Cache Decoded layers
SaveFileCacheForAsset(assetID, layers);
}
}
// Notify Interested Parties
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
#if (!ISWIN)
foreach (DecodedCallback d in m_notifyList[assetID])
{
if (d != null)
{
d.DynamicInvoke(assetID, layers);
}
}
#else
foreach (DecodedCallback d in m_notifyList[assetID].Where(d => d != null))
{
d.DynamicInvoke(assetID, layers);
}
#endif
m_notifyList.Remove(assetID);
}
}
return true;
}
private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
{
OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
for (int i = 0; i < layers.Length; i++)
layers[i] = new OpenJPEG.J2KLayerInfo();
// These default layer sizes are based on a small sampling of real-world texture data
// with extra padding thrown in for good measure. This is a worst case fallback plan
// and may not gracefully handle all real world data
layers[0].Start = 0;
layers[1].Start = (int) (j2kLength*0.02f);
layers[2].Start = (int) (j2kLength*0.05f);
layers[3].Start = (int) (j2kLength*0.20f);
layers[4].Start = (int) (j2kLength*0.50f);
layers[0].End = layers[1].Start - 1;
layers[1].End = layers[2].Start - 1;
layers[2].End = layers[3].Start - 1;
layers[3].End = layers[4].Start - 1;
layers[4].End = j2kLength;
return layers;
}
private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers)
{
if (m_useCache)
m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10));
if (m_cache != null)
{
string assetID = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, AssetType.Notecard,
UUID.Zero)
{Flags = AssetFlags.Local | AssetFlags.Temporary};
#region Serialize Layer Data
StringBuilder stringResult = new StringBuilder();
string strEnd = "\n";
for (int i = 0; i < Layers.Length; i++)
{
if (i == Layers.Length - 1)
strEnd = String.Empty;
stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End,
Layers[i].End - Layers[i].Start, strEnd);
}
layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
#endregion Serialize Layer Data
m_cache.Cache(assetID, layerDecodeAsset);
}
}
private bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers)
{
if (m_decodedCache.TryGetValue(AssetId, out Layers))
{
return true;
}
else if (m_cache != null)
{
string assetName = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset = m_cache.Get(assetName);
if (layerDecodeAsset != null)
{
#region Deserialize Layer Data
string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
string[] lines = readResult.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0)
{
MainConsole.Instance.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName);
m_cache.Expire(assetName);
return false;
}
Layers = new OpenJPEG.J2KLayerInfo[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
string[] elements = lines[i].Split('|');
if (elements.Length == 3)
{
int element1, element2;
try
{
element1 = Convert.ToInt32(elements[0]);
element2 = Convert.ToInt32(elements[1]);
}
catch (FormatException)
{
MainConsole.Instance.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName);
m_cache.Expire(assetName);
return false;
}
Layers[i] = new OpenJPEG.J2KLayerInfo {Start = element1, End = element2};
}
else
{
MainConsole.Instance.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName);
m_cache.Expire(assetName);
return false;
}
}
#endregion Deserialize Layer Data
return true;
}
}
return false;
}
#region IService Members
public void Initialize(IConfigSource config, IRegistryCore registry)
{
IConfig imageConfig = config.Configs["ImageDecoding"];
if (imageConfig != null)
{
m_useCSJ2K = imageConfig.GetBoolean("UseCSJ2K", m_useCSJ2K);
m_useCache = imageConfig.GetBoolean("UseJ2KCache", m_useCache);
}
registry.RegisterModuleInterface<IJ2KDecoder>(this);
}
public void Start(IConfigSource config, IRegistryCore registry)
{
m_cache = registry.RequestModuleInterface<IImprovedAssetCache>();
}
public void FinishedStartup()
{
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using WebsitePanel.Providers.SharePoint;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
using Microsoft.Win32;
namespace WebsitePanel.Providers.HostedSolution
{
/// <summary>
/// Provides hosted SharePoint server functionality implementation.
/// </summary>
public class HostedSharePointServer : HostingServiceProviderBase, IHostedSharePointServer
{
private delegate TReturn SharePointAction<TReturn>(HostedSharePointServerImpl impl);
protected string Wss3RegistryKey;
protected string Wss3Registry32Key;
protected string LanguagePacksPath;
public HostedSharePointServer()
{
this.Wss3RegistryKey = @"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0";
this.Wss3Registry32Key = @"SOFTWARE\Wow6432Node\Microsoft\Shared Tools\Web Server Extensions\12.0";
this.LanguagePacksPath = @"%commonprogramfiles%\microsoft shared\Web Server Extensions\12\HCCab\";
}
/// <summary>
/// Gets root web application uri.
/// </summary>
public Uri RootWebApplicationUri
{
get
{
return new Uri(ProviderSettings["RootWebApplicationUri"]);
}
}
public string BackupTemporaryFolder
{
get
{
return ProviderSettings["BackupTemporaryFolder"];
}
}
/// <summary>
/// Gets list of supported languages by this installation of SharePoint.
/// </summary>
/// <returns>List of supported languages</returns>
public int[] GetSupportedLanguages()
{
HostedSharePointServerImpl impl = new HostedSharePointServerImpl();
return impl.GetSupportedLanguages(LanguagePacksPath);
}
/// <summary>
/// Gets list of SharePoint collections within root web application.
/// </summary>
/// <returns>List of SharePoint collections within root web application.</returns>
public SharePointSiteCollection[] GetSiteCollections()
{
return
ExecuteSharePointAction<SharePointSiteCollection[]>(delegate(HostedSharePointServerImpl impl)
{
return impl.GetSiteCollections(RootWebApplicationUri);
});
}
/// <summary>
/// Gets SharePoint collection within root web application with given name.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</param>
/// <returns>SharePoint collection within root web application with given name.</returns>
public SharePointSiteCollection GetSiteCollection(string url)
{
return
ExecuteSharePointAction<SharePointSiteCollection>(delegate(HostedSharePointServerImpl impl)
{
return impl.GetSiteCollection(RootWebApplicationUri, url);
});
}
/// <summary>
/// Creates site collection within predefined root web application.
/// </summary>
/// <param name="siteCollection">Information about site coolection to be created.</param>
public void CreateSiteCollection(SharePointSiteCollection siteCollection)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.CreateSiteCollection(RootWebApplicationUri, siteCollection);
return null;
});
}
/// <summary>
/// Deletes site collection under given url.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
public void DeleteSiteCollection(SharePointSiteCollection siteCollection)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.DeleteSiteCollection(RootWebApplicationUri, siteCollection);
return null;
});
}
/// <summary>
/// Backups site collection under give url.
/// </summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Resulting backup file name.</param>
/// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <returns>Created backup full path.</returns>
public string BackupSiteCollection(string url, string filename, bool zip)
{
return ExecuteSharePointAction<string>(delegate(HostedSharePointServerImpl impl)
{
return impl.BackupSiteCollection(RootWebApplicationUri, url, filename, zip, BackupTemporaryFolder);
});
}
/// <summary>
/// Restores site collection under given url from backup.
/// </summary>
/// <param name="siteCollection">Site collection to be restored.</param>
/// <param name="filename">Backup file name to restore from.</param>
public void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.RestoreSiteCollection(RootWebApplicationUri, siteCollection, filename);
return null;
});
}
/// <summary>
/// Gets binary data chunk of specified size from specified offset.
/// </summary>
/// <param name="path">Path to file to get bunary data chunk from.</param>
/// <param name="offset">Offset from which to start data reading.</param>
/// <param name="length">Binary data chunk length.</param>
/// <returns>Binary data chunk read from file.</returns>
public virtual byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
byte[] buffer = FileUtils.GetFileBinaryChunk(path, offset, length);
// Delete temp file
if (buffer.Length < length)
{
FileUtils.DeleteFile(path);
}
return buffer;
}
/// <summary>
/// Appends supplied binary data chunk to file.
/// </summary>
/// <param name="fileName">Non existent file name to append to.</param>
/// <param name="path">Full path to existent file to append to.</param>
/// <param name="chunk">Binary data chunk to append to.</param>
/// <returns>Path to file that was appended with chunk.</returns>
public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
if (path == null)
{
path = Path.Combine(Path.GetTempPath(), fileName);
if (FileUtils.FileExists(path))
{
FileUtils.DeleteFile(path);
}
}
FileUtils.AppendFileBinaryContent(path, chunk);
return path;
}
public override bool IsInstalled()
{
return IsSharePointInstalled();
}
/// <summary>
/// Deletes service items that represent SharePoint site collection.
/// </summary>
/// <param name="items">Items to be deleted.</param>
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is SharePointSiteCollection)
{
try
{
DeleteSiteCollection((SharePointSiteCollection)item);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
/// <summary>
/// Calculates diskspace used by supplied service items.
/// </summary>
/// <param name="items">Service items to get diskspace usage for.</param>
/// <returns>Calculated disk space usage statistics.</returns>
public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
{
List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
// update items with diskspace
foreach (ServiceProviderItem item in items)
{
if (item is SharePointSiteCollection)
{
try
{
Log.WriteStart(String.Format("Calculating '{0}' site logs size", item.Name));
SharePointSiteCollection site = GetSiteCollection(item.Name);
ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace();
diskspace.ItemId = item.Id;
diskspace.DiskSpace = site.Diskspace;
itemsDiskspace.Add(diskspace);
Log.WriteEnd(String.Format("Calculating '{0}' site logs size", item.Name));
}
catch (Exception ex)
{
Log.WriteError(ex);
}
}
}
return itemsDiskspace.ToArray();
}
/// <summary>
/// Checks whether Wss 3.0 is installed.
/// </summary>
/// <returns>true - if it is installed; false - otherwise.</returns>
private bool IsSharePointInstalled()
{
RegistryKey spKey = Registry.LocalMachine.OpenSubKey(Wss3RegistryKey);
RegistryKey spKey32 = Registry.LocalMachine.OpenSubKey(Wss3Registry32Key);
if (spKey == null && spKey32 == null)
{
return false;
}
string spVal = (string)spKey.GetValue("SharePoint");
return (String.Compare(spVal, "installed", true) == 0);
}
/// <summary>
/// Executes supplied action within separate application domain.
/// </summary>
/// <param name="action">Action to be executed.</param>
/// <returns>Any object that results from action execution or null if nothing is supposed to be returned.</returns>
/// <exception cref="ArgumentNullException">Is thrown in case supplied action is null.</exception>
private static TReturn ExecuteSharePointAction<TReturn>(SharePointAction<TReturn> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
AppDomain domain = null;
try
{
// Create instance of server implementation in a separate application domain for
// security and isolation purposes.
Type type = typeof(HostedSharePointServerImpl);
AppDomainSetup info = new AppDomainSetup();
info.ApplicationBase = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
info.PrivateBinPath = "bin; bin/debug";
domain = AppDomain.CreateDomain("WSS30", null, info);
HostedSharePointServerImpl impl =
(HostedSharePointServerImpl)
domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
// Execute requested action within created application domain.
return action(impl);
}
finally
{
if (domain != null)
{
AppDomain.Unload(domain);
}
}
}
public void UpdateQuotas(string url, long maxStorage, long warningStorage)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServerImpl impl)
{
impl.UpdateQuotas(RootWebApplicationUri, url, maxStorage, warningStorage);
return null;
});
}
public SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls)
{
SharePointSiteDiskSpace[] sd = null;
sd = ExecuteSharePointAction<SharePointSiteDiskSpace[]>(delegate(HostedSharePointServerImpl impl)
{
return impl.CalculateSiteCollectionDiskSpace(RootWebApplicationUri, urls);
});
return sd;
}
public long GetSiteCollectionSize(string url)
{
long ret;
ret = ExecuteSharePointAction<long>(delegate(HostedSharePointServerImpl impl)
{
return impl.GetSiteCollectionSize(RootWebApplicationUri, url);
});
return ret;
}
public virtual void SetPeoplePickerOu(string site, string ou)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using AppLimit.CloudComputing.SharpBox.Common.Net.oAuth20;
using AppLimit.CloudComputing.SharpBox.Common.Net.Web;
using AppLimit.CloudComputing.SharpBox.Exceptions;
using AppLimit.CloudComputing.SharpBox.StorageProvider.API;
using AppLimit.CloudComputing.SharpBox.StorageProvider.BaseObjects;
using AppLimit.CloudComputing.SharpBox.StorageProvider.SkyDrive.Authorization;
namespace AppLimit.CloudComputing.SharpBox.StorageProvider.SkyDrive.Logic
{
internal class SkyDriveStorageProviderService : GenericStorageProviderService
{
public void RefreshDirectoryContent(IStorageProviderSession session, ICloudDirectoryEntry directory)
{
if (!(directory is BaseDirectoryEntry)) return;
var uri = String.Format(SkyDriveConstants.FilesAccessUrlFormat, directory.GetPropertyValue(SkyDriveConstants.InnerIDKey));
(directory as BaseDirectoryEntry).AddChilds(RequestContentByUrl(session, uri).Cast<BaseFileEntry>());
}
private static IEnumerable<ICloudFileSystemEntry> RequestContentByUrl(IStorageProviderSession session, String url)
{
var json = SkyDriveRequestHelper.PerformRequest(session, url);
return SkyDriveJsonParser.ParseListOfEntries(session, json) ?? new List<ICloudFileSystemEntry>();
}
private static ICloudFileSystemEntry RequestResourseByUrl(IStorageProviderSession session, String url)
{
var json = SkyDriveRequestHelper.PerformRequest(session, url);
return SkyDriveJsonParser.ParseSingleEntry(session, json);
}
public override bool VerifyAccessTokenType(ICloudStorageAccessToken token)
{
return token is OAuth20Token;
}
public override IStorageProviderSession CreateSession(ICloudStorageAccessToken token, ICloudStorageConfiguration configuration)
{
var skydriveToken = token as OAuth20Token;
if (skydriveToken == null) throw new ArgumentException("Cannot create skydrive session with given token", "token");
if (skydriveToken.IsExpired) token = SkyDriveAuthorizationHelper.RefreshToken(skydriveToken);
return new SkyDriveStorageProviderSession(token, this, configuration);
}
public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, String name, ICloudDirectoryEntry parent)
{
/* In this method name could be either requested resource name or it's ID.
* In first case just refresh the parent and then search child with an appropriate.
* In second case it does not matter if parent is null or not a parent because we use only resource ID. */
if (SkyDriveHelpers.HasResourceID(name) || name.Equals("/") && parent == null)
//If request by ID or root folder requested
{
var id = SkyDriveHelpers.GetResourceID(name);
var uri = id != String.Empty
? String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, id)
: SkyDriveConstants.RootAccessUrl;
if (SkyDriveHelpers.IsFolderID(id))
{
var contents = new List<ICloudFileSystemEntry>();
/*var completeContent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(state =>
{
contents.AddRange(RequestContentByUrl(session, uri + "/files"));
((AutoResetEvent) state).Set();
}, completeContent);
var completeEntry = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(state =>
{
entry = RequestResourseByUrl(session, uri) as BaseDirectoryEntry;
((AutoResetEvent) state).Set();
}, completeEntry);
WaitHandle.WaitAll(new WaitHandle[] {completeContent, completeEntry});*/
var entry = RequestResourseByUrl(session, uri) as BaseDirectoryEntry;
contents.AddRange(RequestContentByUrl(session, uri + "/files"));
if (entry != null && contents.Any())
entry.AddChilds(contents.Cast<BaseFileEntry>());
return entry;
}
return RequestResourseByUrl(session, uri);
}
else
{
String uri;
if (SkyDriveHelpers.HasParentID(name))
uri = String.Format(SkyDriveConstants.FilesAccessUrlFormat, SkyDriveHelpers.GetParentID(name));
else if (parent != null)
uri = String.Format(SkyDriveConstants.FilesAccessUrlFormat, parent.GetPropertyValue(SkyDriveConstants.InnerIDKey));
else
uri = SkyDriveConstants.RootAccessUrl + "/files";
name = Path.GetFileName(name);
var entry = RequestContentByUrl(session, uri).FirstOrDefault(x => x.Name.Equals(name));
return entry;
}
}
public override void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource)
{
//not refresh if resource was requested recently
var timestamp = resource.GetPropertyValue(SkyDriveConstants.TimestampKey);
var refreshNeeded = DateTime.Parse(timestamp, CultureInfo.InvariantCulture) + TimeSpan.FromSeconds(5) < DateTime.UtcNow;
if (refreshNeeded)
{
//Request resource by ID and then update properties from requested
var current = RequestResource(session, resource.GetPropertyValue(SkyDriveConstants.InnerIDKey), null);
SkyDriveHelpers.CopyProperties(current, resource);
}
var directory = resource as ICloudDirectoryEntry;
if (directory != null && !refreshNeeded && directory.HasChildrens == nChildState.HasNotEvaluated)
RefreshDirectoryContent(session, directory);
}
public override bool DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry)
{
var uri = String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var json = SkyDriveRequestHelper.PerformRequest(session, uri, "DELETE", null, true);
if (!SkyDriveJsonParser.ContainsError(json, false))
{
var parent = entry.Parent as BaseDirectoryEntry;
if (parent != null)
parent.RemoveChildById(entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
return true;
}
return false;
}
public override ICloudFileSystemEntry CreateResource(IStorageProviderSession session, String name, ICloudDirectoryEntry parent)
{
if (name.Contains("/"))
throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidFileOrDirectoryName);
var uri =
parent != null
? String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, parent.GetPropertyValue(SkyDriveConstants.InnerIDKey))
: SkyDriveConstants.RootAccessUrl;
var data = String.Format("{{name: \"{0}\"}}", name);
var json = SkyDriveRequestHelper.PerformRequest(session, uri, "POST", data, false);
var entry = SkyDriveJsonParser.ParseSingleEntry(session, json);
var parentBase = parent as BaseDirectoryEntry;
if (parentBase != null && entry != null)
parentBase.AddChild(entry as BaseFileEntry);
return entry;
}
public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry entry, String newName)
{
if (entry.Name.Equals("/") || newName.Contains("/"))
return false;
var uri = String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var data = String.Format("{{name: \"{0}\"}}", newName);
var json = SkyDriveRequestHelper.PerformRequest(session, uri, "PUT", data, false);
if (!SkyDriveJsonParser.ContainsError(json, false))
{
var entryBase = entry as BaseFileEntry;
if (entryBase != null)
entryBase.Name = newName;
return true;
}
return false;
}
public override bool MoveResource(IStorageProviderSession session, ICloudFileSystemEntry entry, ICloudDirectoryEntry moveTo)
{
if (entry.Name.Equals("/"))
return false;
var uri = String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var data = String.Format("{{destination: \"{0}\"}}", moveTo.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var json = SkyDriveRequestHelper.PerformRequest(session, uri, "MOVE", data, false);
if (!SkyDriveJsonParser.ContainsError(json, false))
{
var parent = entry.Parent as BaseDirectoryEntry;
if (parent != null)
parent.RemoveChildById(entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var moveToBase = moveTo as BaseDirectoryEntry;
if (moveToBase != null)
moveToBase.AddChild(entry as BaseFileEntry);
return true;
}
return false;
}
public override bool CopyResource(IStorageProviderSession session, ICloudFileSystemEntry entry, ICloudDirectoryEntry copyTo)
{
if (entry.Name.Equals("/"))
return false;
if (entry is ICloudDirectoryEntry)
{
// skydrive allowes to copy only files so we will recursively create/copy entries
var newEntry = CreateResource(session, entry.Name, copyTo) as ICloudDirectoryEntry;
return newEntry != null && (entry as ICloudDirectoryEntry).Aggregate(true, (current, subEntry) => current && CopyResource(session, subEntry, newEntry));
}
var uri = String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var data = String.Format("{{destination: \"{0}\"}}", copyTo.GetPropertyValue(SkyDriveConstants.InnerIDKey));
var json = SkyDriveRequestHelper.PerformRequest(session, uri, "COPY", data, false);
if (json != null && !SkyDriveJsonParser.ContainsError(json, false))
{
var copyToBase = copyTo as BaseDirectoryEntry;
if (copyToBase != null)
copyToBase.AddChild(entry as BaseFileEntry);
return true;
}
return false;
}
public override Stream CreateDownloadStream(IStorageProviderSession session, ICloudFileSystemEntry entry)
{
if (entry is ICloudDirectoryEntry)
throw new ArgumentException("Download operation can be perform for files only");
var uri = String.Format("{0}/{1}/content", SkyDriveConstants.BaseAccessUrl, entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
uri = SkyDriveRequestHelper.SignUri(session, uri);
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
{
((BaseFileEntry)entry).Length = response.ContentLength;
return new BaseFileEntryDownloadStream(response.GetResponseStream(), entry);
}
}
public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry entry, long uploadSize)
{
if (entry is ICloudDirectoryEntry)
throw new ArgumentException("Upload operation can be perform for files only");
var tempStream = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose);
var uploadStream = new WebRequestStream(tempStream, null, null);
uploadStream.PushPreDisposeOperation(CommitUploadOperation, tempStream, uploadSize, session, entry);
return uploadStream;
}
public override void CommitStreamOperation(IStorageProviderSession session, ICloudFileSystemEntry entry, nTransferDirection direction, Stream notDisposedStream)
{
}
public override bool SupportsDirectRetrieve
{
get { return true; }
}
public override void StoreToken(IStorageProviderSession session, Dictionary<String, String> tokendata, ICloudStorageAccessToken token)
{
if (token is OAuth20Token)
{
tokendata.Add(SkyDriveConstants.SerializedDataKey, (token as OAuth20Token).ToJson());
}
}
public override ICloudStorageAccessToken LoadToken(Dictionary<String, String> tokendata)
{
var type = tokendata[CloudStorage.TokenCredentialType];
if (type.Equals(typeof (OAuth20Token).ToString()))
{
var json = tokendata[SkyDriveConstants.SerializedDataKey];
return OAuth20Token.FromJson(json);
}
return null;
}
private static void CommitUploadOperation(object[] args)
{
var tempStream = (Stream)args[0];
var contentLength = (long)args[1];
var session = (IStorageProviderSession)args[2];
var file = (BaseFileEntry)args[3];
var request = (HttpWebRequest)WebRequest.Create(GetSignedUploadUrl(session, file));
request.Method = "PUT";
request.ContentLength = contentLength;
request.Timeout = Timeout.Infinite;
tempStream.Flush();
tempStream.Seek(0, SeekOrigin.Begin);
using (var requestSteam = request.GetRequestStream())
{
tempStream.CopyTo(requestSteam);
}
tempStream.Close();
using (var response = request.GetResponse())
using (var rs = response.GetResponseStream())
{
if (rs == null) return;
string json;
using (var streamReader = new StreamReader(rs))
{
json = streamReader.ReadToEnd();
}
var id = SkyDriveJsonParser.ParseEntryID(json);
file.Id = id;
file[SkyDriveConstants.InnerIDKey] = id;
file.Modified = DateTime.UtcNow;
var parent = file.Parent as BaseDirectoryEntry;
if (parent != null)
{
parent.RemoveChildById(file.Name);
parent.AddChild(file);
}
}
}
public override string GetResourceUrl(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, string additionalPath)
{
var id = SkyDriveHelpers.GetResourceID(additionalPath);
if (!String.IsNullOrEmpty(id) || additionalPath != null && additionalPath.Equals("/"))
return "/" + id;
if (String.IsNullOrEmpty(additionalPath) && fileSystemEntry != null)
return "/" + (!fileSystemEntry.Id.Equals("/") ? fileSystemEntry.Id : "");
return base.GetResourceUrl(session, fileSystemEntry, additionalPath);
}
private static string GetSignedUploadUrl(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry)
{
var uri = String.Format("{0}/{1}/files/{2}",
SkyDriveConstants.BaseAccessUrl,
fileSystemEntry.Parent.GetPropertyValue(SkyDriveConstants.InnerIDKey),
fileSystemEntry.Name);
return SkyDriveRequestHelper.SignUri(session, uri);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using com.google.zxing.common;
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace com.google.zxing.datamatrix.decoder
{
using FormatException = com.google.zxing.FormatException;
using BitSource = com.google.zxing.common.BitSource;
using DecoderResult = com.google.zxing.common.DecoderResult;
/// <summary>
/// <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes
/// in one Data Matrix Code. This class decodes the bits back into text.</p>
///
/// <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p>
///
/// @author bbrown@google.com (Brian Brown)
/// @author Sean Owen
/// </summary>
internal sealed class DecodedBitStreamParser
{
private enum Mode
{
PAD_ENCODE, // Not really a mode
ASCII_ENCODE,
C40_ENCODE,
TEXT_ENCODE,
ANSIX12_ENCODE,
EDIFACT_ENCODE,
BASE256_ENCODE
}
/// <summary>
/// See ISO 16022:2006, Annex C Table C.1
/// The C40 Basic Character Set (*'s used for placeholders for the shift values)
/// </summary>
private static readonly char[] C40_BASIC_SET_CHARS = {'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private static readonly char[] C40_SHIFT2_SET_CHARS = {'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_'};
/// <summary>
/// See ISO 16022:2006, Annex C Table C.2
/// The Text Basic Character Set (*'s used for placeholders for the shift values)
/// </summary>
private static readonly char[] TEXT_BASIC_SET_CHARS = {'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
private static readonly char[] TEXT_SHIFT3_SET_CHARS = {'\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127};
private DecodedBitStreamParser()
{
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static com.google.zxing.common.DecoderResult decode(byte[] bytes) throws com.google.zxing.FormatException
internal static DecoderResult decode(sbyte[] bytes)
{
BitSource bits = new BitSource(bytes);
StringBuilder result = new StringBuilder(100);
StringBuilder resultTrailer = new StringBuilder(0);
IList<sbyte[]> byteSegments = new List<sbyte[]>(1);
Mode mode = Mode.ASCII_ENCODE;
do
{
if (mode == Mode.ASCII_ENCODE)
{
mode = decodeAsciiSegment(bits, result, resultTrailer);
}
else
{
switch (mode)
{
case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.C40_ENCODE:
decodeC40Segment(bits, result);
break;
case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.TEXT_ENCODE:
decodeTextSegment(bits, result);
break;
case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.ANSIX12_ENCODE:
decodeAnsiX12Segment(bits, result);
break;
case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.EDIFACT_ENCODE:
decodeEdifactSegment(bits, result);
break;
case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.BASE256_ENCODE:
decodeBase256Segment(bits, result, byteSegments);
break;
default:
throw FormatException.FormatInstance;
}
mode = Mode.ASCII_ENCODE;
}
} while (mode != Mode.PAD_ENCODE && bits.available() > 0);
if (resultTrailer.Length > 0)
{
result.Append(resultTrailer.ToString());
}
return new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, null);
}
/// <summary>
/// See ISO 16022:2006, 5.2.3 and Annex C, Table C.2
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static Mode decodeAsciiSegment(com.google.zxing.common.BitSource bits, StringBuilder result, StringBuilder resultTrailer) throws com.google.zxing.FormatException
private static Mode decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer)
{
bool upperShift = false;
do
{
int oneByte = bits.readBits(8);
if (oneByte == 0)
{
throw FormatException.FormatInstance;
} // ASCII data (ASCII value + 1)
else if (oneByte <= 128)
{
if (upperShift)
{
oneByte += 128;
//upperShift = false;
}
result.Append((char)(oneByte - 1));
return Mode.ASCII_ENCODE;
} // Pad
else if (oneByte == 129)
{
return Mode.PAD_ENCODE;
} // 2-digit data 00-99 (Numeric Value + 130)
else if (oneByte <= 229)
{
int value = oneByte - 130;
if (value < 10) // padd with '0' for single digit values
{
result.Append('0');
}
result.Append(value);
} // Latch to C40 encodation
else if (oneByte == 230)
{
return Mode.C40_ENCODE;
} // Latch to Base 256 encodation
else if (oneByte == 231)
{
return Mode.BASE256_ENCODE;
}
else if (oneByte == 232)
{
// FNC1
result.Append((char) 29); // translate as ASCII 29
}
else if (oneByte == 233 || oneByte == 234)
{
// Structured Append, Reader Programming
// Ignore these symbols for now
//throw ReaderException.getInstance();
} // Upper Shift (shift to Extended ASCII)
else if (oneByte == 235)
{
upperShift = true;
} // 05 Macro
else if (oneByte == 236)
{
result.Append("[)>\u001E05\u001D");
resultTrailer.Insert(0, "\u001E\u0004");
} // 06 Macro
else if (oneByte == 237)
{
result.Append("[)>\u001E06\u001D");
resultTrailer.Insert(0, "\u001E\u0004");
} // Latch to ANSI X12 encodation
else if (oneByte == 238)
{
return Mode.ANSIX12_ENCODE;
} // Latch to Text encodation
else if (oneByte == 239)
{
return Mode.TEXT_ENCODE;
} // Latch to EDIFACT encodation
else if (oneByte == 240)
{
return Mode.EDIFACT_ENCODE;
} // ECI Character
else if (oneByte == 241)
{
// TODO(bbrown): I think we need to support ECI
//throw ReaderException.getInstance();
// Ignore this symbol for now
} // Not to be used in ASCII encodation
else if (oneByte >= 242)
{
// ... but work around encoders that end with 254, latch back to ASCII
if (oneByte != 254 || bits.available() != 0)
{
throw FormatException.FormatInstance;
}
}
} while (bits.available() > 0);
return Mode.ASCII_ENCODE;
}
/// <summary>
/// See ISO 16022:2006, 5.2.5 and Annex C, Table C.1
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeC40Segment(com.google.zxing.common.BitSource bits, StringBuilder result) throws com.google.zxing.FormatException
private static void decodeC40Segment(BitSource bits, StringBuilder result)
{
// Three C40 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time
bool upperShift = false;
int[] cValues = new int[3];
int shift = 0;
do
{
// If there is only one byte left then it will be encoded as ASCII
if (bits.available() == 8)
{
return;
}
int firstByte = bits.readBits(8);
if (firstByte == 254) // Unlatch codeword
{
return;
}
parseTwoBytes(firstByte, bits.readBits(8), cValues);
for (int i = 0; i < 3; i++)
{
int cValue = cValues[i];
switch (shift)
{
case 0:
if (cValue < 3)
{
shift = cValue + 1;
}
else if (cValue < C40_BASIC_SET_CHARS.Length)
{
char c40char = C40_BASIC_SET_CHARS[cValue];
if (upperShift)
{
result.Append((char)(c40char + 128));
upperShift = false;
}
else
{
result.Append(c40char);
}
}
else
{
throw FormatException.FormatInstance;
}
break;
case 1:
if (upperShift)
{
result.Append((char)(cValue + 128));
upperShift = false;
}
else
{
result.Append((char) cValue);
}
shift = 0;
break;
case 2:
if (cValue < C40_SHIFT2_SET_CHARS.Length)
{
char c40char = C40_SHIFT2_SET_CHARS[cValue];
if (upperShift)
{
result.Append((char)(c40char + 128));
upperShift = false;
}
else
{
result.Append(c40char);
}
} // FNC1
else if (cValue == 27)
{
result.Append((char) 29); // translate as ASCII 29
} // Upper Shift
else if (cValue == 30)
{
upperShift = true;
}
else
{
throw FormatException.FormatInstance;
}
shift = 0;
break;
case 3:
if (upperShift)
{
result.Append((char)(cValue + 224));
upperShift = false;
}
else
{
result.Append((char)(cValue + 96));
}
shift = 0;
break;
default:
throw FormatException.FormatInstance;
}
}
} while (bits.available() > 0);
}
/// <summary>
/// See ISO 16022:2006, 5.2.6 and Annex C, Table C.2
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeTextSegment(com.google.zxing.common.BitSource bits, StringBuilder result) throws com.google.zxing.FormatException
private static void decodeTextSegment(BitSource bits, StringBuilder result)
{
// Three Text values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
bool upperShift = false;
int[] cValues = new int[3];
int shift = 0;
do
{
// If there is only one byte left then it will be encoded as ASCII
if (bits.available() == 8)
{
return;
}
int firstByte = bits.readBits(8);
if (firstByte == 254) // Unlatch codeword
{
return;
}
parseTwoBytes(firstByte, bits.readBits(8), cValues);
for (int i = 0; i < 3; i++)
{
int cValue = cValues[i];
switch (shift)
{
case 0:
if (cValue < 3)
{
shift = cValue + 1;
}
else if (cValue < TEXT_BASIC_SET_CHARS.Length)
{
char textChar = TEXT_BASIC_SET_CHARS[cValue];
if (upperShift)
{
result.Append((char)(textChar + 128));
upperShift = false;
}
else
{
result.Append(textChar);
}
}
else
{
throw FormatException.FormatInstance;
}
break;
case 1:
if (upperShift)
{
result.Append((char)(cValue + 128));
upperShift = false;
}
else
{
result.Append((char) cValue);
}
shift = 0;
break;
case 2:
// Shift 2 for Text is the same encoding as C40
if (cValue < C40_SHIFT2_SET_CHARS.Length)
{
char c40char = C40_SHIFT2_SET_CHARS[cValue];
if (upperShift)
{
result.Append((char)(c40char + 128));
upperShift = false;
}
else
{
result.Append(c40char);
}
} // FNC1
else if (cValue == 27)
{
result.Append((char) 29); // translate as ASCII 29
} // Upper Shift
else if (cValue == 30)
{
upperShift = true;
}
else
{
throw FormatException.FormatInstance;
}
shift = 0;
break;
case 3:
if (cValue < TEXT_SHIFT3_SET_CHARS.Length)
{
char textChar = TEXT_SHIFT3_SET_CHARS[cValue];
if (upperShift)
{
result.Append((char)(textChar + 128));
upperShift = false;
}
else
{
result.Append(textChar);
}
shift = 0;
}
else
{
throw FormatException.FormatInstance;
}
break;
default:
throw FormatException.FormatInstance;
}
}
} while (bits.available() > 0);
}
/// <summary>
/// See ISO 16022:2006, 5.2.7
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeAnsiX12Segment(com.google.zxing.common.BitSource bits, StringBuilder result) throws com.google.zxing.FormatException
private static void decodeAnsiX12Segment(BitSource bits, StringBuilder result)
{
// Three ANSI X12 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
int[] cValues = new int[3];
do
{
// If there is only one byte left then it will be encoded as ASCII
if (bits.available() == 8)
{
return;
}
int firstByte = bits.readBits(8);
if (firstByte == 254) // Unlatch codeword
{
return;
}
parseTwoBytes(firstByte, bits.readBits(8), cValues);
for (int i = 0; i < 3; i++)
{
int cValue = cValues[i];
if (cValue == 0) // X12 segment terminator <CR>
{
result.Append('\r');
} // X12 segment separator *
else if (cValue == 1)
{
result.Append('*');
} // X12 sub-element separator >
else if (cValue == 2)
{
result.Append('>');
} // space
else if (cValue == 3)
{
result.Append(' ');
} // 0 - 9
else if (cValue < 14)
{
result.Append((char)(cValue + 44));
} // A - Z
else if (cValue < 40)
{
result.Append((char)(cValue + 51));
}
else
{
throw FormatException.FormatInstance;
}
}
} while (bits.available() > 0);
}
private static void parseTwoBytes(int firstByte, int secondByte, int[] result)
{
int fullBitValue = (firstByte << 8) + secondByte - 1;
int temp = fullBitValue / 1600;
result[0] = temp;
fullBitValue -= temp * 1600;
temp = fullBitValue / 40;
result[1] = temp;
result[2] = fullBitValue - temp * 40;
}
/// <summary>
/// See ISO 16022:2006, 5.2.8 and Annex C Table C.3
/// </summary>
private static void decodeEdifactSegment(BitSource bits, StringBuilder result)
{
do
{
// If there is only two or less bytes left then it will be encoded as ASCII
if (bits.available() <= 16)
{
return;
}
for (int i = 0; i < 4; i++)
{
int edifactValue = bits.readBits(6);
// Check for the unlatch character
if (edifactValue == 0x1F) // 011111
{
// Read rest of byte, which should be 0, and stop
int bitsLeft = 8 - bits.BitOffset;
if (bitsLeft != 8)
{
bits.readBits(bitsLeft);
}
return;
}
if ((edifactValue & 0x20) == 0) // no 1 in the leading (6th) bit
{
edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value
}
result.Append((char) edifactValue);
}
} while (bits.available() > 0);
}
/// <summary>
/// See ISO 16022:2006, 5.2.9 and Annex B, B.2
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeBase256Segment(com.google.zxing.common.BitSource bits, StringBuilder result, java.util.Collection<byte[]> byteSegments) throws com.google.zxing.FormatException
private static void decodeBase256Segment(BitSource bits, StringBuilder result, ICollection<sbyte[]> byteSegments)
{
// Figure out how long the Base 256 Segment is.
int codewordPosition = 1 + bits.ByteOffset; // position is 1-indexed
int d1 = unrandomize255State(bits.readBits(8), codewordPosition++);
int count;
if (d1 == 0) // Read the remainder of the symbol
{
count = bits.available() / 8;
}
else if (d1 < 250)
{
count = d1;
}
else
{
count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++);
}
// We're seeing NegativeArraySizeException errors from users.
if (count < 0)
{
throw FormatException.FormatInstance;
}
sbyte[] bytes = new sbyte[count];
for (int i = 0; i < count; i++)
{
// Have seen this particular error in the wild, such as at
// http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
if (bits.available() < 8)
{
throw FormatException.FormatInstance;
}
bytes[i] = (sbyte) unrandomize255State(bits.readBits(8), codewordPosition++);
}
byteSegments.Add(bytes);
try
{
//result.Append(new string(bytes, "ISO8859_1"));
result.Append(GetEncodedStringFromBuffer(bytes, "ISO-8859-1"));
}
catch (System.IO.IOException uee)
{
throw new InvalidOperationException("Platform does not support required encoding: " + uee);
}
}
private static string GetEncodedStringFromBuffer(sbyte[] buffer, string encoding)
{
byte[] bytes = buffer.ToBytes();
Encoding en = Encoding.GetEncoding(encoding);
return en.GetString(bytes);
}
/// <summary>
/// See ISO 16022:2006, Annex B, B.2
/// </summary>
private static int unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition)
{
int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1;
int tempVariable = randomizedBase256Codeword - pseudoRandomNumber;
return tempVariable >= 0 ? tempVariable : tempVariable + 256;
}
}
}
| |
using Sandbox.Common;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Common.Components;
using Sandbox.Definitions;
using Sandbox.ModAPI.Interfaces;
using Sandbox.ModAPI.Ingame;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VRageMath;
namespace AirlockRKR
{
public static class Utils
{
public static Vector3 ToHsvColor(this VRageMath.Color color)
{
var hsvColor = color.ColorToHSV();
return new Vector3(hsvColor.X, hsvColor.Y * 2f - 1f, hsvColor.Z * 2f - 1f);
}
public static VRageMath.Color ToColor(this Vector3 hsv)
{
return new Vector3(hsv.X, (hsv.Y + 1f) / 2f, (hsv.Z + 1f) / 2f).HSVtoColor();
}
public static void setPressureColor(List<IMyInteriorLight> lights, List<IMyAirVent> vans, Boolean ignoreIfYellow = false)
{
if (ignoreIfYellow && lights.Count > 0 && Color.Yellow.Equals(lights[0].GetValue<Color>("Color")))
{
return;
}
if (!isPressurized(vans[0]))
{
setColor(lights, Color.Red);
}
else
{
setColor(lights, Color.Green);
}
}
public static void setColor(List<IMyInteriorLight> lights, Color color)
{
for (int i = 0; i < lights.Count; i++)
{
IMyInteriorLight light = lights[i];
light.SetValue<Color>("Color", color);
}
}
public static float getPressure(IMyAirVent vanToCheck)
{
return vanToCheck.GetOxygenLevel() * 100;
}
public static float getCurrentOxygenFill(Sandbox.ModAPI.Ingame.IMyGridTerminalSystem gridTerminalSystem)
{
List<IMyOxygenTank> oxygenTanks = new List<IMyOxygenTank>();
List<IMyTerminalBlock> gridBlocks = new List<IMyTerminalBlock>();
gridTerminalSystem.GetBlocksOfType<IMyOxygenTank>(gridBlocks);
foreach (IMyTerminalBlock gridBlock in gridBlocks)
{
if (gridBlock as IMyOxygenTank != null)
{
oxygenTanks.Add(gridBlock as IMyOxygenTank);
}
}
return getCurrentOxygenFill(oxygenTanks[0]);
}
public static float getCurrentOxygenFill(IMyOxygenTank tankToCheck)
{
return tankToCheck.GetOxygenLevel() * 100;
}
public static bool isPressurized(IMyAirVent vanToCheck)
{
return Utils.getPressure(vanToCheck) > 95;
}
public static bool isOneDoorOpen(List<IMyDoor> doors)
{
bool isOpen = false;
foreach (IMyDoor door in doors)
{
isOpen |= door.Open;
}
return isOpen;
}
public static bool isOneDoorClosed(List<IMyDoor> doors)
{
bool isClosed = false;
foreach (IMyDoor door in doors)
{
isClosed |= !door.Open;
}
return isClosed;
}
public static void closeDoors(List<IMyDoor> doors)
{
foreach (IMyDoor door in doors)
{
door.GetActionWithName("Open_Off").Apply(door);
}
}
public static void openDoors(List<IMyDoor> doors)
{
foreach (IMyDoor door in doors)
{
door.GetActionWithName("Open_On").Apply(door);
}
}
public static void pressurizeRoom(List<IMyAirVent> vents)
{
foreach (IMyAirVent vent in vents) {
vent.GetActionWithName("Depressurize_Off").Apply(vent);
}
}
public static void depressurizeRoom(List<IMyAirVent> vents)
{
foreach (IMyAirVent vent in vents)
{
vent.GetActionWithName("Depressurize_On").Apply(vent);
}
}
internal static List<Control.Event> getSensorStatusChanges(Dictionary<IMySensorBlock, bool> sensorStatus, Config config)
{
List<Control.Event> currentEvents = new List<Control.Event>();
foreach (IMySensorBlock sensor in config.sensors1)
{
bool oldStatus = sensorStatus.GetValueOrDefault(sensor, false);
if (!oldStatus.Equals(sensor.IsActive) || sensor.IsActive)
{
currentEvents.Add(sensor.IsActive ? Control.Event.InEnter : Control.Event.InLeave);
}
if (sensorStatus.ContainsKey(sensor))
{
sensorStatus.Remove(sensor);
}
sensorStatus.Add(sensor, sensor.IsActive);
}
foreach (IMySensorBlock sensor in config.sluiceSensors)
{
bool oldStatus = sensorStatus.GetValueOrDefault(sensor, false);
if (!oldStatus.Equals(sensor.IsActive) || sensor.IsActive)
{
currentEvents.Add(sensor.IsActive ? Control.Event.SEnter : Control.Event.SLeave);
}
if (sensorStatus.ContainsKey(sensor))
{
sensorStatus.Remove(sensor);
}
sensorStatus.Add(sensor, sensor.IsActive);
}
foreach (IMySensorBlock sensor in config.sensors2)
{
bool oldStatus = sensorStatus.GetValueOrDefault(sensor, false);
if (!oldStatus.Equals(sensor.IsActive) || sensor.IsActive)
{
currentEvents.Add(sensor.IsActive ? Control.Event.OutEnter : Control.Event.OutLeave);
}
if (sensorStatus.ContainsKey(sensor))
{
sensorStatus.Remove(sensor);
}
sensorStatus.Add(sensor, sensor.IsActive);
}
List<IMySensorBlock> sensorsToDelete = new List<IMySensorBlock>();
foreach (IMySensorBlock sensor in sensorStatus.Keys)
{
if (!config.sensors1.Contains(sensor) && !config.sluiceSensors.Contains(sensor) && !config.sensors2.Contains(sensor))
{
sensorsToDelete.Add(sensor);
}
}
foreach (IMySensorBlock sensor in sensorsToDelete)
{
sensorStatus.Remove(sensor);
}
return currentEvents;
}
public static IMyTextPanel searchLcdWithName(Sandbox.ModAPI.Ingame.IMyGridTerminalSystem gridTerminal, String name)
{
IMyTextPanel lcd = null;
IMyTerminalBlock lcdTerminalBlock = gridTerminal.GetBlockWithName(name);
if (lcdTerminalBlock as IMyTextPanel != null)
{
lcd = lcdTerminalBlock as IMyTextPanel;
}
return lcd;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
using System;
using System.Security;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
using WFD = Windows.Foundation.Diagnostics;
#endif
namespace System.Threading.Tasks
{
[FriendAccessAllowed]
internal enum CausalityTraceLevel
{
#if FEATURE_COMINTEROP
Required = WFD.CausalityTraceLevel.Required,
Important = WFD.CausalityTraceLevel.Important,
Verbose = WFD.CausalityTraceLevel.Verbose
#else
Required,
Important,
Verbose
#endif
}
[FriendAccessAllowed]
internal enum AsyncCausalityStatus
{
#if FEATURE_COMINTEROP
Canceled = WFD.AsyncCausalityStatus.Canceled,
Completed = WFD.AsyncCausalityStatus.Completed,
Error = WFD.AsyncCausalityStatus.Error,
Started = WFD.AsyncCausalityStatus.Started
#else
Started,
Completed,
Canceled,
Error
#endif
}
internal enum CausalityRelation
{
#if FEATURE_COMINTEROP
AssignDelegate = WFD.CausalityRelation.AssignDelegate,
Join = WFD.CausalityRelation.Join,
Choice = WFD.CausalityRelation.Choice,
Cancel = WFD.CausalityRelation.Cancel,
Error = WFD.CausalityRelation.Error
#else
AssignDelegate,
Join,
Choice,
Cancel,
Error
#endif
}
internal enum CausalitySynchronousWork
{
#if FEATURE_COMINTEROP
CompletionNotification = WFD.CausalitySynchronousWork.CompletionNotification,
ProgressNotification = WFD.CausalitySynchronousWork.ProgressNotification,
Execution = WFD.CausalitySynchronousWork.Execution
#else
CompletionNotification,
ProgressNotification,
Execution
#endif
}
[FriendAccessAllowed]
internal static class AsyncCausalityTracer
{
static internal void EnableToETW(bool enabled)
{
#if FEATURE_COMINTEROP
if (enabled)
f_LoggingOn |= Loggers.ETW;
else
f_LoggingOn &= ~Loggers.ETW;
#endif
}
[FriendAccessAllowed]
internal static bool LoggingOn
{
[FriendAccessAllowed]
get
{
#if FEATURE_COMINTEROP
return f_LoggingOn != 0;
#else
return false;
#endif
}
}
#if FEATURE_COMINTEROP
//s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995}
private static readonly Guid s_PlatformId = new Guid(0x4B0171A6, 0xF3D0, 0x41A0, 0x9B, 0x33, 0x02, 0x55, 0x06, 0x52, 0xB9, 0x95);
//Indicates this information comes from the BCL Library
private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library;
//Lazy initialize the actual factory
private static WFD.IAsyncCausalityTracerStatics s_TracerFactory;
// The loggers that this Tracer knows about.
[Flags]
private enum Loggers : byte {
CausalityTracer = 1,
ETW = 2
}
//We receive the actual value for these as a callback
private static Loggers f_LoggingOn; //assumes false by default
// The precise static constructor will run first time somebody attempts to access this class
[SecuritySafeCritical]
static AsyncCausalityTracer()
{
if (!Environment.IsWinRTSupported) return;
//COM Class Id
string ClassId = "Windows.Foundation.Diagnostics.AsyncCausalityTracer";
//COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE}
Guid guid = new Guid(0x50850B26, 0x267E, 0x451B, 0xA8, 0x90, 0XAB, 0x6A, 0x37, 0x02, 0x45, 0xEE);
Object factory = null;
try
{
int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory);
if (hresult < 0 || factory == null) return; //This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered.
s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler));
Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
}
catch (Exception ex)
{
// Although catching generic Exception is not recommended, this file is one exception
// since we don't want to propagate any kind of exception to the user since all we are
// doing here depends on internal state.
LogAndDisable(ex);
}
}
[SecuritySafeCritical]
private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args)
{
if (args.Enabled)
f_LoggingOn |= Loggers.CausalityTracer;
else
f_LoggingOn &= ~Loggers.CausalityTracer;
}
#endif
//
// The TraceXXX methods should be called only if LoggingOn property returned true
//
[FriendAccessAllowed]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Tracking is slow path. Disable inlining for it.
internal static void TraceOperationCreation(CausalityTraceLevel traceLevel, int taskId, string operationName, ulong relatedContext)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceOperationBegin(taskId, operationName, (long) relatedContext);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationCreation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[FriendAccessAllowed]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceOperationCompletion(CausalityTraceLevel traceLevel, int taskId, AsyncCausalityStatus status)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceOperationEnd(taskId, status);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceOperationRelation(CausalityTraceLevel traceLevel, int taskId, CausalityRelation relation)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceOperationRelation(taskId, relation);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationRelation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, int taskId, CausalitySynchronousWork work)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceSynchronousWorkBegin(taskId, work);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceSynchronousWorkStart((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySynchronousWork work)
{
#if FEATURE_COMINTEROP
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
TplEtwProvider.Log.TraceSynchronousWorkEnd(work);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceSynchronousWorkCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, (WFD.CausalitySynchronousWork)work);
}
catch(Exception ex)
{
//view function comment
LogAndDisable(ex);
}
#endif
}
#if FEATURE_COMINTEROP
//fix for 796185: leaking internal exceptions to customers,
//we should catch and log exceptions but never propagate them.
private static void LogAndDisable(Exception ex)
{
f_LoggingOn = 0;
Debugger.Log(0, "AsyncCausalityTracer", ex.ToString());
}
#endif
private static ulong GetOperationId(uint taskId)
{
return (((ulong)AppDomain.CurrentDomain.Id) << 32) + taskId;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Neural.PNN;
using Encog.Persist;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.Neural.Pnn
{
/// <summary>
/// Persist a PNN.
/// </summary>
///
public class PersistBasicPNN : IEncogPersistor
{
/// <summary>
/// The output mode property.
/// </summary>
///
public const String PropertyOutputMode = "outputMode";
/// <summary>
/// File version.
/// </summary>
public virtual int FileVersion
{
get { return 1; }
}
/// <summary>
/// File version.
/// </summary>
public virtual String PersistClassString
{
get { return "BasicPNN"; }
}
/// <summary>
/// Read an object.
/// </summary>
public Object Read(Stream mask0)
{
var ins0 = new EncogReadHelper(mask0);
EncogFileSection section;
var samples = new BasicMLDataSet();
IDictionary<String, String> networkParams = null;
PNNKernelType kernel = default(PNNKernelType) /* was: null */;
PNNOutputMode outmodel = default(PNNOutputMode) /* was: null */;
int inputCount = 0;
int outputCount = 0;
double error = 0;
double[] sigma = null;
while ((section = ins0.ReadNextSection()) != null)
{
if (section.SectionName.Equals("PNN")
&& section.SubSectionName.Equals("PARAMS"))
{
networkParams = section.ParseParams();
}
if (section.SectionName.Equals("PNN")
&& section.SubSectionName.Equals("NETWORK"))
{
IDictionary<String, String> paras = section.ParseParams();
inputCount = EncogFileSection.ParseInt(paras,
PersistConst.InputCount);
outputCount = EncogFileSection.ParseInt(paras,
PersistConst.OutputCount);
kernel = StringToKernel(paras[PersistConst.Kernel]);
outmodel = StringToOutputMode(paras[PropertyOutputMode]);
error = EncogFileSection
.ParseDouble(paras, PersistConst.Error);
sigma = section.ParseDoubleArray(paras, PersistConst.Sigma);
}
if (section.SectionName.Equals("PNN")
&& section.SubSectionName.Equals("SAMPLES"))
{
foreach (String line in section.Lines)
{
IList<String> cols = EncogFileSection
.SplitColumns(line);
int index = 0;
var inputData = new BasicMLData(inputCount);
for (int i = 0; i < inputCount; i++)
{
inputData[i] =
CSVFormat.EgFormat.Parse(cols[index++]);
}
var idealData = new BasicMLData(inputCount);
idealData[0] = CSVFormat.EgFormat.Parse(cols[index++]);
IMLDataPair pair = new BasicMLDataPair(inputData,
idealData);
samples.Add(pair);
}
}
}
var result = new BasicPNN(kernel, outmodel, inputCount,
outputCount);
if (networkParams != null)
{
EngineArray.PutAll(networkParams, result.Properties);
}
result.Samples = samples;
result.Error = error;
if (sigma != null)
{
EngineArray.ArrayCopy(sigma, result.Sigma);
}
return result;
}
/// <summary>
///
/// </summary>
///
public void Save(Stream os, Object obj)
{
var xout = new EncogWriteHelper(os);
var pnn = (BasicPNN) obj;
xout.AddSection("PNN");
xout.AddSubSection("PARAMS");
xout.AddProperties(pnn.Properties);
xout.AddSubSection("NETWORK");
xout.WriteProperty(PersistConst.Error, pnn.Error);
xout.WriteProperty(PersistConst.InputCount, pnn.InputCount);
xout.WriteProperty(PersistConst.Kernel,
KernelToString(pnn.Kernel));
xout.WriteProperty(PersistConst.OutputCount, pnn.OutputCount);
xout.WriteProperty(PropertyOutputMode,
OutputModeToString(pnn.OutputMode));
xout.WriteProperty(PersistConst.Sigma, pnn.Sigma);
xout.AddSubSection("SAMPLES");
if (pnn.Samples != null)
{
foreach (IMLDataPair pair in pnn.Samples)
{
for (int i = 0; i < pair.Input.Count; i++)
{
xout.AddColumn(pair.Input[i]);
}
for (int i = 0; i < pair.Ideal.Count; i++)
{
xout.AddColumn(pair.Ideal[i]);
}
xout.WriteLine();
}
}
xout.Flush();
}
/// <summary>
/// Convert a kernel type to a string.
/// </summary>
///
/// <param name="k">The kernel type.</param>
/// <returns>The string.</returns>
public static String KernelToString(PNNKernelType k)
{
switch (k)
{
case PNNKernelType.Gaussian:
return "gaussian";
case PNNKernelType.Reciprocal:
return "reciprocal";
default:
return null;
}
}
/// <summary>
/// Convert output mode to string.
/// </summary>
///
/// <param name="mode">The output mode.</param>
/// <returns>The string.</returns>
public static String OutputModeToString(PNNOutputMode mode)
{
switch (mode)
{
case PNNOutputMode.Regression:
return "regression";
case PNNOutputMode.Unsupervised:
return "unsupervised";
case PNNOutputMode.Classification:
return "classification";
default:
return null;
}
}
/// <summary>
/// Convert a string to a PNN kernel.
/// </summary>
///
/// <param name="k">The string.</param>
/// <returns>The kernel.</returns>
public static PNNKernelType StringToKernel(String k)
{
if (k.Equals("gaussian", StringComparison.InvariantCultureIgnoreCase))
{
return PNNKernelType.Gaussian;
}
if (k.Equals("reciprocal", StringComparison.InvariantCultureIgnoreCase))
{
return PNNKernelType.Reciprocal;
}
return default(PNNKernelType) /* was: null */;
}
/// <summary>
/// Convert a string to a PNN output mode.
/// </summary>
///
/// <param name="mode">The string.</param>
/// <returns>The output ndoe.</returns>
public static PNNOutputMode StringToOutputMode(String mode)
{
if (mode.Equals("regression", StringComparison.InvariantCultureIgnoreCase))
{
return PNNOutputMode.Regression;
}
if (mode.Equals("unsupervised", StringComparison.InvariantCultureIgnoreCase))
{
return PNNOutputMode.Unsupervised;
}
if (mode.Equals("classification", StringComparison.InvariantCultureIgnoreCase))
{
return PNNOutputMode.Classification;
}
return default(PNNOutputMode) /* was: null */;
}
/// <inheritdoc/>
public Type NativeType
{
get { return typeof(BasicPNN); }
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.Serialization;
namespace XenAPI
{
public partial class HTTP
{
[Serializable]
public class TooManyRedirectsException : Exception
{
private readonly int redirect;
private readonly Uri uri;
public TooManyRedirectsException(int redirect, Uri uri)
{
this.redirect = redirect;
this.uri = uri;
}
public TooManyRedirectsException() : base() { }
public TooManyRedirectsException(string message) : base(message) { }
public TooManyRedirectsException(string message, Exception exception) : base(message, exception) { }
protected TooManyRedirectsException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
redirect = info.GetInt32("redirect");
uri = (Uri)info.GetValue("uri", typeof(Uri));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("redirect", redirect);
info.AddValue("uri", uri, typeof(Uri));
base.GetObjectData(info, context);
}
}
[Serializable]
public class BadServerResponseException : Exception
{
public BadServerResponseException() : base() { }
public BadServerResponseException(string message) : base(message) { }
public BadServerResponseException(string message, Exception exception) : base(message, exception) { }
protected BadServerResponseException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class CancelledException : Exception
{
public CancelledException() : base() { }
public CancelledException(string message) : base(message) { }
public CancelledException(string message, Exception exception) : base(message, exception) { }
protected CancelledException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
public delegate bool FuncBool();
public delegate void UpdateProgressDelegate(int percent);
public delegate void DataCopiedDelegate(long bytes);
// Size of byte buffer used for GETs and PUTs
// (not the socket rx buffer)
public const int BUFFER_SIZE = 32 * 1024;
public const int MAX_REDIRECTS = 10;
public const int DEFAULT_HTTPS_PORT = 443;
#region Helper functions
private static void WriteLine(String txt, Stream stream)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", txt));
stream.Write(bytes, 0, bytes.Length);
}
private static void WriteLine(Stream stream)
{
WriteLine("", stream);
}
private static string ReadLine(Stream stream)
{
System.Text.StringBuilder result = new StringBuilder();
while (true)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
char c = Convert.ToChar(b);
result.Append(c);
if (c == '\n')
return result.ToString();
}
}
/// <summary>
/// Read HTTP headers, doing any redirects as necessary
/// </summary>
/// <param name="stream"></param>
/// <returns>True if a redirect has occurred - headers will need to be resent.</returns>
private static bool ReadHttpHeaders(ref Stream stream, IWebProxy proxy, bool nodelay, int timeout_ms)
{
string response = ReadLine(stream);
int code = getResultCode(response);
switch (code)
{
case 200:
break;
case 302:
string url = "";
while (true)
{
response = ReadLine(stream);
if (response.StartsWith("Location: "))
url = response.Substring(10);
if (response.Equals("\r\n") || response.Equals("\n") || response.Equals(""))
break;
}
Uri redirect = new Uri(url.Trim());
stream.Close();
stream = ConnectStream(redirect, proxy, nodelay, timeout_ms);
return true; // headers need to be sent again
default:
if (response.EndsWith("\r\n"))
response = response.Substring(0, response.Length - 2);
else if (response.EndsWith("\n"))
response = response.Substring(0, response.Length - 1);
stream.Close();
throw new BadServerResponseException(string.Format("Received error code {0} from the server", response));
}
while (true)
{
string line = ReadLine(stream);
if (System.Text.RegularExpressions.Regex.Match(line, "^\\s*$").Success)
break;
}
return false;
}
public static int getResultCode(string line)
{
string[] bits = line.Split(new char[] { ' ' });
return (bits.Length < 2 ? 0 : Int32.Parse(bits[1]));
}
public static bool UseSSL(Uri uri)
{
return uri.Scheme == "https" || uri.Port == DEFAULT_HTTPS_PORT;
}
private static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static long CopyStream(Stream inStream, Stream outStream,
DataCopiedDelegate progressDelegate, FuncBool cancellingDelegate)
{
long bytesWritten = 0;
byte[] buffer = new byte[BUFFER_SIZE];
DateTime lastUpdate = DateTime.Now;
while (cancellingDelegate == null || !cancellingDelegate())
{
int bytesRead = inStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
outStream.Write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
if (progressDelegate != null &&
DateTime.Now - lastUpdate > TimeSpan.FromMilliseconds(500))
{
progressDelegate(bytesWritten);
lastUpdate = DateTime.Now;
}
}
if (cancellingDelegate != null && cancellingDelegate())
throw new CancelledException();
if (progressDelegate != null)
progressDelegate(bytesWritten);
return bytesWritten;
}
/// <summary>
/// Build a URI from a hostname, a path, and some query arguments
/// </summary>
/// <param name="args">An even-length array, alternating argument names and values</param>
/// <returns></returns>
public static Uri BuildUri(string hostname, string path, params object[] args)
{
// The last argument may be an object[] in its own right, in which case we need
// to flatten the array.
List<object> flatargs = new List<object>();
foreach (object arg in args)
{
if (arg is IEnumerable<object>)
flatargs.AddRange((IEnumerable<object>)arg);
else
flatargs.Add(arg);
}
UriBuilder uri = new UriBuilder();
uri.Scheme = "https";
uri.Port = DEFAULT_HTTPS_PORT;
uri.Host = hostname;
uri.Path = path;
StringBuilder query = new StringBuilder();
for (int i = 0; i < flatargs.Count - 1; i += 2)
{
string kv;
// If the argument is null, don't include it in the URL
if (flatargs[i + 1] == null)
continue;
// bools are special because some xapi calls use presence/absence and some
// use "b=true" (not "True") and "b=false". But all accept "b=true" or absent.
if (flatargs[i + 1] is bool)
{
if (!((bool)flatargs[i + 1]))
continue;
kv = flatargs[i] + "=true";
}
else
kv = flatargs[i] + "=" + Uri.EscapeDataString(flatargs[i + 1].ToString());
if (query.Length != 0)
query.Append('&');
query.Append(kv);
}
uri.Query = query.ToString();
return uri.Uri;
}
#endregion
private static NetworkStream ConnectSocket(Uri uri, bool nodelay, int timeout_ms)
{
AddressFamily addressFamily = uri.HostNameType == UriHostNameType.IPv6
? AddressFamily.InterNetworkV6
: AddressFamily.InterNetwork;
Socket socket =
new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = nodelay;
//socket.ReceiveBufferSize = 64 * 1024;
socket.ReceiveTimeout = timeout_ms;
socket.SendTimeout = timeout_ms;
socket.Connect(uri.Host, uri.Port);
return new NetworkStream(socket, true);
}
/// <summary>
/// This function will connect a stream to a uri (host and port),
/// negotiating proxies and SSL
/// </summary>
/// <param name="uri"></param>
/// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param>
/// <returns></returns>
public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms)
{
IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null;
if (mockProxy != null)
return mockProxy.GetStream(uri);
Stream stream;
bool useProxy = proxy != null && !proxy.IsBypassed(uri);
if (useProxy)
{
Uri proxyURI = proxy.GetProxy(uri);
stream = ConnectSocket(proxyURI, nodelay, timeout_ms);
}
else
{
stream = ConnectSocket(uri, nodelay, timeout_ms);
}
try
{
if (useProxy)
{
string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port);
WriteLine(line, stream);
WriteLine(stream);
ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms);
}
if (UseSSL(uri))
{
SslStream sslStream = new SslStream(stream, false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient("", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true);
stream = sslStream;
}
return stream;
}
catch
{
stream.Close();
throw;
}
}
private static Stream DO_HTTP(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms, params string[] headers)
{
Stream stream = ConnectStream(uri, proxy, nodelay, timeout_ms);
int redirects = 0;
do
{
if (redirects > MAX_REDIRECTS)
throw new TooManyRedirectsException(redirects, uri);
redirects++;
foreach (string header in headers)
WriteLine(header, stream);
WriteLine(stream);
stream.Flush();
}
while (ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms));
return stream;
}
//
// The following functions do all the HTTP headers related stuff
// returning the stream ready for use
//
public static Stream CONNECT(Uri uri, IWebProxy proxy, String session, int timeout_ms)
{
return DO_HTTP(uri, proxy, true, timeout_ms,
string.Format("CONNECT {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host),
string.Format("Cookie: session_id={0}", session));
}
public static Stream PUT(Uri uri, IWebProxy proxy, long ContentLength, int timeout_ms)
{
return DO_HTTP(uri, proxy, false, timeout_ms,
string.Format("PUT {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Content-Length: {0}", ContentLength));
}
public static Stream GET(Uri uri, IWebProxy proxy, int timeout_ms)
{
return DO_HTTP(uri, proxy, false, timeout_ms,
string.Format("GET {0} HTTP/1.0", uri.PathAndQuery));
}
/// <summary>
/// A general HTTP PUT method, with delegates for progress and cancelling. May throw various exceptions.
/// </summary>
/// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param>
/// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
/// <param name="uri">URI to PUT to</param>
/// <param name="proxy">A proxy to handle the HTTP connection</param>
/// <param name="path">Path to file to put</param>
/// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param>
public static void Put(UpdateProgressDelegate progressDelegate, FuncBool cancellingDelegate,
Uri uri, IWebProxy proxy, string path, int timeout_ms)
{
using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read),
requestStream = PUT(uri, proxy, fileStream.Length, timeout_ms))
{
long len = fileStream.Length;
DataCopiedDelegate dataCopiedDelegate = delegate(long bytes)
{
if (progressDelegate != null && len > 0)
progressDelegate((int)((bytes * 100) / len));
};
CopyStream(fileStream, requestStream, dataCopiedDelegate, cancellingDelegate);
}
}
/// <summary>
/// A general HTTP GET method, with delegates for progress and cancelling. May throw various exceptions.
/// </summary>
/// <param name="dataRxDelegate">Delegate called periodically (500 ms) with the number of bytes transferred</param>
/// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
/// <param name="uri">URI to GET from</param>
/// <param name="proxy">A proxy to handle the HTTP connection</param>
/// <param name="path">Path to file to receive the data</param>
/// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param>
public static void Get(DataCopiedDelegate dataCopiedDelegate, FuncBool cancellingDelegate,
Uri uri, IWebProxy proxy, string path, int timeout_ms)
{
string tmpFile = Path.GetTempFileName();
try
{
using (Stream fileStream = new FileStream(tmpFile, FileMode.Create, FileAccess.Write, FileShare.None),
downloadStream = GET(uri, proxy, timeout_ms))
{
CopyStream(downloadStream, fileStream, dataCopiedDelegate, cancellingDelegate);
fileStream.Flush();
}
File.Delete(path);
File.Move(tmpFile, path);
}
finally
{
File.Delete(tmpFile);
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Auto body shop.
/// </summary>
public class AutoBodyShop_Core : TypeCore, IAutomotiveBusiness
{
public AutoBodyShop_Core()
{
this._TypeId = 23;
this._Id = "AutoBodyShop";
this._Schema_Org_Url = "http://schema.org/AutoBodyShop";
string label = "";
GetLabel(out label, "AutoBodyShop", typeof(AutoBodyShop_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,30};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{30};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.EnterpriseServer.Base.Scheduling;
using WebsitePanel.Portal.Code.Framework;
namespace WebsitePanel.Portal
{
public partial class SchedulesEditSchedule : WebsitePanelModuleBase
{
private static readonly string ScheduleViewEnvironment = "ASP.NET";
private ISchedulerTaskView configurationView;
private string cachedTaskIdsToLoad = String.Empty;
public int PackageId
{
get { return (int)ViewState["PackageId"]; }
set { ViewState["PackageId"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Visible = (PanelRequest.ScheduleID > 0);
this.ControlToLoad.Value = this.cachedTaskIdsToLoad;
if (!IsPostBack)
{
try
{
// bind controls
BindTasks();
// bind schedule
BindSchedule();
}
catch (Exception ex)
{
ShowErrorMessage("SCHEDULE_INIT_FORM", ex);
return;
}
}
}
/// <summary>
/// Overridden. Dynamically loads configuration view.
/// </summary>
/// <param name="e">Event arguments.</param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// Make sure control is loaded before view state and post back data are loaded.
string taskIdsToLoad = HttpContext.Current.Request.Params[this.ControlToLoad.Name];
if (taskIdsToLoad == null)
{
taskIdsToLoad = String.Empty;
}
string selectedTaskId = HttpContext.Current.Request.Params[this.ddlTaskType.UniqueID];
if (!IsPostBack)
{
if (PanelRequest.ScheduleID != 0)
{
ScheduleInfo sc = ES.Services.Scheduler.GetSchedule(PanelRequest.ScheduleID);
if (sc != null)
{
selectedTaskId = sc.TaskId;
}
}
}
List<string> tasksListToLoad = new List<string>(taskIdsToLoad.Split(new char[] { ';' }));
if (!String.IsNullOrEmpty(selectedTaskId))
{
if (!tasksListToLoad.Contains(selectedTaskId))
{
tasksListToLoad.Add(selectedTaskId);
}
}
foreach (string taskId in tasksListToLoad)
{
ISchedulerTaskView view = LoadScheduleTaskConfigurationView(taskId, taskId == selectedTaskId);
if (taskId == selectedTaskId)
{
this.configurationView = view;
}
}
cachedTaskIdsToLoad = String.Join(";", tasksListToLoad.ToArray());
}
/// <summary>
/// Loads control that is intended to provide user ability to configure schedule task.
/// </summary>
/// <remarks>
/// Returns loaded configuration view.
/// </remarks>
private ISchedulerTaskView LoadScheduleTaskConfigurationView(string taskId, bool visible)
{
//this.TaskParametersPlaceHolder.Controls.Clear();
string selectedTaskId = taskId;
if (!String.IsNullOrEmpty(selectedTaskId))
{
// Try to find view configuration
ScheduleTaskViewConfiguration aspNetEnvironmentViewConfiguration = ES.Services.Scheduler.GetScheduleTaskViewConfiguration(selectedTaskId, ScheduleViewEnvironment);
// If no configuration found ignore view
if (aspNetEnvironmentViewConfiguration == null)
{
return null;
}
// Description contains relative path to control to be loaded.
Control view = this.LoadControl(aspNetEnvironmentViewConfiguration.Description);
if (!(view is ISchedulerTaskView))
{
// The view does not provide ability to set and get parameters.
return null;
}
view.ID = taskId;
view.Visible = visible;
view.EnableTheming = true;
this.TaskParametersPlaceHolder.Controls.Add(view);
return (ISchedulerTaskView) view;
}
return null;
}
private void BindTasks()
{
ScheduleTaskInfo[] tasks = ES.Services.Scheduler.GetScheduleTasks();
ddlTaskType.Items.Add(new ListItem("<Select Task>", ""));
foreach (ScheduleTaskInfo task in tasks)
{
string localizedTaskName = GetSharedLocalizedString(Utils.ModuleName, "SchedulerTask." + task.TaskId);
if (localizedTaskName == null)
localizedTaskName = task.TaskId;
ddlTaskType.Items.Add(new ListItem(localizedTaskName, task.TaskId));
}
}
private void BindSchedule()
{
txtStartDate.Text = DateTime.Now.ToString("d");
timeFromTime.SelectedValue = new DateTime(2000, 1, 1, 0, 0, 0);
timeToTime.SelectedValue = new DateTime(2000, 1, 1, 23, 59, 59);
intMaxExecutionTime.Interval = 3600;
if (PanelRequest.ScheduleID == 0)
{
ApplyPackageContextRestrictions(PanelSecurity.PackageId);
PackageId = PanelSecurity.PackageId;
}
else
{
ScheduleInfo sc = ES.Services.Scheduler.GetSchedule(PanelRequest.ScheduleID);
if (sc == null)
return;
ApplyPackageContextRestrictions(sc.PackageId);
PackageId = sc.PackageId;
txtTaskName.Text = sc.ScheduleName;
Utils.SelectListItem(ddlTaskType, sc.TaskId);
Utils.SelectListItem(ddlSchedule, sc.ScheduleTypeId);
timeFromTime.SelectedValue = sc.FromTime;
timeToTime.SelectedValue = sc.ToTime;
timeStartTime.SelectedValue = sc.StartTime;
intInterval.Interval = sc.Interval;
// run once
if (ddlSchedule.SelectedIndex == 3)
{
txtStartDate.Text = sc.StartTime.ToString("d");
}
txtWeekDay.Text = sc.WeekMonthDay.ToString();
txtMonthDay.Text = sc.WeekMonthDay.ToString();
chkEnabled.Checked = sc.Enabled;
Utils.SelectListItem(ddlPriority, sc.PriorityId);
intMaxExecutionTime.Interval = sc.MaxExecutionTime;
}
// bind schedule parameters
BindScheduleParameters();
// toggle
ToggleControls();
}
private void ApplyPackageContextRestrictions(int packageId)
{
// load context
PackageContext cntx = PackagesHelper.GetCachedPackageContext(packageId);
bool intervalTasksAllowed = (cntx.Quotas.ContainsKey(Quotas.OS_SCHEDULEDINTERVALTASKS)
&& cntx.Quotas[Quotas.OS_SCHEDULEDINTERVALTASKS].QuotaAllocatedValue != 0);
if (!intervalTasksAllowed)
ddlSchedule.Items.Remove(ddlSchedule.Items.FindByValue("Interval"));
// check if this an admin
if (PanelSecurity.LoggedUser.Role != UserRole.Administrator)
{
// remove "high" priorities
ddlPriority.Items.Remove(ddlPriority.Items.FindByValue("Highest"));
ddlPriority.Items.Remove(ddlPriority.Items.FindByValue("AboveNormal"));
ddlPriority.Items.Remove(ddlPriority.Items.FindByValue("Normal"));
}
}
/// <summary>
/// Binds schedule task parameters to configuration view.
/// </summary>
private void BindScheduleParameters()
{
ScheduleTaskParameterInfo[] parameters = ES.Services.Scheduler.GetScheduleParameters(ddlTaskType.SelectedValue,
PanelRequest.ScheduleID);
gvTaskParameters.DataSource = parameters;
gvTaskParameters.DataBind();
if (this.configurationView != null)
{
this.configurationView.SetParameters(parameters);
}
}
protected void gvTaskParameters_RowDataBound(object sender, GridViewRowEventArgs e)
{
ParameterEditor txtValue = (ParameterEditor)e.Row.FindControl("txtValue");
if (txtValue == null)
return;
ScheduleTaskParameterInfo prm = (ScheduleTaskParameterInfo)e.Row.DataItem;
txtValue.DataType = prm.DataTypeId;
txtValue.DefaultValue = prm.DefaultValue;
txtValue.Value = prm.ParameterValue;
}
public string GetHistoryFinishTime(DateTime dt)
{
return (dt == DateTime.MinValue) ? "" : dt.ToString();
}
private void ToggleControls()
{
tblWeekly.Visible = (ddlSchedule.SelectedIndex == 1);
tblMonthly.Visible = (ddlSchedule.SelectedIndex == 2);
tblOneTime.Visible = (ddlSchedule.SelectedIndex == 3);
tblInterval.Visible = (ddlSchedule.SelectedIndex == 4);
timeStartTime.Enabled = (ddlSchedule.SelectedIndex != 4);
}
protected void ddlSchedule_SelectedIndexChanged(object sender, EventArgs e)
{
ToggleControls();
}
protected void ddlTaskType_SelectedIndexChanged(object sender, EventArgs e)
{
//this.configurationView = this.LoadScheduleTaskConfigurationView(this.ddlTaskType.SelectedValue);
BindScheduleParameters();
}
private void SaveTask()
{
// gather form parameters
ScheduleInfo sc = new ScheduleInfo();
sc.ScheduleId = PanelRequest.ScheduleID;
sc.ScheduleName = txtTaskName.Text.Trim();
sc.TaskId = ddlTaskType.SelectedValue;
sc.PackageId = PanelSecurity.PackageId;
sc.ScheduleTypeId = ddlSchedule.SelectedValue;
sc.FromTime = timeFromTime.SelectedValue;
sc.ToTime = timeToTime.SelectedValue;
sc.StartTime = timeStartTime.SelectedValue;
sc.Interval = intInterval.Interval;
// check maximum interval
// load context
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PackageId);
if(cntx.Quotas.ContainsKey(Quotas.OS_MINIMUMTASKINTERVAL))
{
int minInterval = cntx.Quotas[Quotas.OS_MINIMUMTASKINTERVAL].QuotaAllocatedValue;
if (minInterval != -1 && sc.Interval < (minInterval * 60))
sc.Interval = (minInterval * 60);
}
// run once
if (ddlSchedule.SelectedIndex == 3)
{
DateTime tm = timeStartTime.SelectedValue;
DateTime dt = DateTime.Parse(txtStartDate.Text);
DateTime startTime = new DateTime(dt.Year, dt.Month, dt.Day, tm.Hour, tm.Minute, tm.Second);
sc.StartTime = startTime;
}
sc.WeekMonthDay = Utils.ParseInt(txtWeekDay.Text, 0);
if (ddlSchedule.SelectedIndex == 2)
sc.WeekMonthDay = Utils.ParseInt(txtMonthDay.Text, 0);
sc.Enabled = chkEnabled.Checked;
sc.PriorityId = ddlPriority.SelectedValue;
sc.HistoriesNumber = 0;
sc.MaxExecutionTime = intMaxExecutionTime.Interval;
// gather parameters
List<ScheduleTaskParameterInfo> parameters = new List<ScheduleTaskParameterInfo>();
foreach (GridViewRow row in gvTaskParameters.Rows)
{
ParameterEditor txtValue = (ParameterEditor)row.FindControl("txtValue");
if (txtValue == null)
continue;
string prmId = (string)gvTaskParameters.DataKeys[row.RowIndex][0];
ScheduleTaskParameterInfo parameter = new ScheduleTaskParameterInfo();
parameter.ParameterId = prmId;
parameter.ParameterValue = txtValue.Value;
parameters.Add(parameter);
}
sc.Parameters = parameters.ToArray();
// Gather parameters from view.
if (this.configurationView != null)
{
sc.Parameters = this.configurationView.GetParameters();
}
// save
if (PanelRequest.ScheduleID == 0)
{
// add new schedule
try
{
int result = ES.Services.Scheduler.AddSchedule(sc);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("SCHEDULE_ADD_TASK", ex);
return;
}
}
else
{
// update existing
try
{
int result = ES.Services.Scheduler.UpdateSchedule(sc);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("SCHEDULE_UPDATE_TASK", ex);
return;
}
}
// redirect
RedirectSpaceHomePage();
}
private void DeleteTask()
{
try
{
// delete
if (PanelRequest.ScheduleID == 0)
return;
// delete schedule
int result = ES.Services.Scheduler.DeleteSchedule(PanelRequest.ScheduleID);
if (result < 0)
{
ShowResultMessage(result);
return;
}
// redirect
RedirectSpaceHomePage();
}
catch (Exception ex)
{
ShowErrorMessage("SCHEDULE_DELETE_TASK", ex);
return;
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
SaveTask();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
RedirectSpaceHomePage();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
DeleteTask();
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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 UnityEngine;
using UnityEditor;
using Spine;
namespace Spine.Unity.Editor {
[InitializeOnLoad]
[CustomEditor(typeof(SkeletonGraphic))]
[CanEditMultipleObjects]
public class SkeletonGraphicInspector : UnityEditor.Editor {
SerializedProperty material, color;
SerializedProperty skeletonDataAsset, initialSkinName;
SerializedProperty startingAnimation, startingLoop, timeScale, freeze, unscaledTime, tintBlack;
SerializedProperty initialFlipX, initialFlipY;
SerializedProperty meshGeneratorSettings;
SerializedProperty raycastTarget;
SkeletonGraphic thisSkeletonGraphic;
void OnEnable () {
var so = this.serializedObject;
thisSkeletonGraphic = target as SkeletonGraphic;
// MaskableGraphic
material = so.FindProperty("m_Material");
color = so.FindProperty("m_Color");
raycastTarget = so.FindProperty("m_RaycastTarget");
// SkeletonRenderer
skeletonDataAsset = so.FindProperty("skeletonDataAsset");
initialSkinName = so.FindProperty("initialSkinName");
initialFlipX = so.FindProperty("initialFlipX");
initialFlipY = so.FindProperty("initialFlipY");
// SkeletonAnimation
startingAnimation = so.FindProperty("startingAnimation");
startingLoop = so.FindProperty("startingLoop");
timeScale = so.FindProperty("timeScale");
unscaledTime = so.FindProperty("unscaledTime");
freeze = so.FindProperty("freeze");
meshGeneratorSettings = so.FindProperty("meshGenerator").FindPropertyRelative("settings");
meshGeneratorSettings.isExpanded = SkeletonRendererInspector.advancedFoldout;
}
public override void OnInspectorGUI () {
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(skeletonDataAsset);
EditorGUILayout.PropertyField(material);
EditorGUILayout.PropertyField(color);
if (thisSkeletonGraphic.skeletonDataAsset == null) {
EditorGUILayout.HelpBox("You need to assign a SkeletonDataAsset first.", MessageType.Info);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
return;
}
using (new SpineInspectorUtility.BoxScope()) {
EditorGUILayout.PropertyField(meshGeneratorSettings, SpineInspectorUtility.TempContent("Advanced..."), includeChildren: true);
SkeletonRendererInspector.advancedFoldout = meshGeneratorSettings.isExpanded;
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(initialSkinName);
{
var rect = GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, EditorGUIUtility.singleLineHeight);
EditorGUI.PrefixLabel(rect, SpineInspectorUtility.TempContent("Initial Flip"));
rect.x += EditorGUIUtility.labelWidth;
rect.width = 30f;
initialFlipX.boolValue = EditorGUI.ToggleLeft(rect, SpineInspectorUtility.TempContent("X", tooltip:"initialFlipX"), initialFlipX.boolValue);
rect.x += 35f;
initialFlipY.boolValue = EditorGUI.ToggleLeft(rect, SpineInspectorUtility.TempContent("Y", tooltip:"initialFlipY"), initialFlipY.boolValue);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Animation", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(startingAnimation);
EditorGUILayout.PropertyField(startingLoop);
EditorGUILayout.PropertyField(timeScale);
EditorGUILayout.PropertyField(unscaledTime, SpineInspectorUtility.TempContent(unscaledTime.displayName, tooltip: "If checked, this will use Time.unscaledDeltaTime to make this update independent of game Time.timeScale. Instance SkeletonGraphic.timeScale will still be applied."));
EditorGUILayout.Space();
EditorGUILayout.PropertyField(freeze);
EditorGUILayout.Space();
EditorGUILayout.LabelField("UI", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(raycastTarget);
bool wasChanged = EditorGUI.EndChangeCheck();
if (wasChanged)
serializedObject.ApplyModifiedProperties();
}
#region Menus
[MenuItem("CONTEXT/SkeletonGraphic/Match RectTransform with Mesh Bounds")]
static void MatchRectTransformWithBounds (MenuCommand command) {
var skeletonGraphic = (SkeletonGraphic)command.context;
Mesh mesh = skeletonGraphic.GetLastMesh();
if (mesh == null) {
Debug.Log("Mesh was not previously generated.");
return;
}
if (mesh.vertexCount == 0) {
skeletonGraphic.rectTransform.sizeDelta = new Vector2(50f, 50f);
skeletonGraphic.rectTransform.pivot = new Vector2(0.5f, 0.5f);
return;
}
mesh.RecalculateBounds();
var bounds = mesh.bounds;
var size = bounds.size;
var center = bounds.center;
var p = new Vector2(
0.5f - (center.x / size.x),
0.5f - (center.y / size.y)
);
skeletonGraphic.rectTransform.sizeDelta = size;
skeletonGraphic.rectTransform.pivot = p;
}
[MenuItem("GameObject/Spine/SkeletonGraphic (UnityUI)", false, 15)]
static public void SkeletonGraphicCreateMenuItem () {
var parentGameObject = Selection.activeObject as GameObject;
var parentTransform = parentGameObject == null ? null : parentGameObject.GetComponent<RectTransform>();
if (parentTransform == null)
Debug.LogWarning("Your new SkeletonGraphic will not be visible until it is placed under a Canvas");
var gameObject = NewSkeletonGraphicGameObject("New SkeletonGraphic");
gameObject.transform.SetParent(parentTransform, false);
EditorUtility.FocusProjectWindow();
Selection.activeObject = gameObject;
EditorGUIUtility.PingObject(Selection.activeObject);
}
// SpineEditorUtilities.InstantiateDelegate. Used by drag and drop.
public static Component SpawnSkeletonGraphicFromDrop (SkeletonDataAsset data) {
return InstantiateSkeletonGraphic(data);
}
public static SkeletonGraphic InstantiateSkeletonGraphic (SkeletonDataAsset skeletonDataAsset, string skinName) {
return InstantiateSkeletonGraphic(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName));
}
public static SkeletonGraphic InstantiateSkeletonGraphic (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
string spineGameObjectName = string.Format("SkeletonGraphic ({0})", skeletonDataAsset.name.Replace("_SkeletonData", ""));
var go = NewSkeletonGraphicGameObject(spineGameObjectName);
var graphic = go.GetComponent<SkeletonGraphic>();
graphic.skeletonDataAsset = skeletonDataAsset;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
}
data = skeletonDataAsset.GetSkeletonData(true);
}
skin = skin ?? data.DefaultSkin ?? data.Skins.Items[0];
graphic.MeshGenerator.settings.zSpacing = SpineEditorUtilities.defaultZSpacing;
graphic.Initialize(false);
if (skin != null) graphic.Skeleton.SetSkin(skin);
graphic.initialSkinName = skin.Name;
graphic.Skeleton.UpdateWorldTransform();
graphic.UpdateMesh();
return graphic;
}
static GameObject NewSkeletonGraphicGameObject (string gameObjectName) {
var go = new GameObject(gameObjectName, typeof(RectTransform), typeof(CanvasRenderer), typeof(SkeletonGraphic));
var graphic = go.GetComponent<SkeletonGraphic>();
graphic.material = SkeletonGraphicInspector.DefaultSkeletonGraphicMaterial;
return go;
}
public static Material DefaultSkeletonGraphicMaterial {
get {
var guids = AssetDatabase.FindAssets("SkeletonGraphicDefault t:material");
if (guids.Length <= 0) return null;
var firstAssetPath = AssetDatabase.GUIDToAssetPath(guids[0]);
if (string.IsNullOrEmpty(firstAssetPath)) return null;
var firstMaterial = AssetDatabase.LoadAssetAtPath<Material>(firstAssetPath);
return firstMaterial;
}
}
#endregion
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using MLifter.DAL;
using System.ComponentModel;
using System.Drawing;
using System.Net;
namespace MLifter.Components
{
/// <summary>
/// This is the Textbox to use for entering the answer including the OnTheFly-Correction.
/// </summary>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
public class MLifterTextBox : RichTextBox
{
private int selectionStart = 0;
private int selectionLength = 0;
private bool lastCharIsWrong = false;
private Regex validChar;
private List<int> wrongChars = new List<int>();
private string oldText = string.Empty;
private List<char> allowedControlChars = new List<char>();
private bool selectionEventEnabled = true;
private bool showTipp = false;
public int Errors = 0;
public int CorrectSynonyms;
public bool CorrectFirstSynonym;
#region properties and events
private List<string> stripChars = new List<string>();
[Browsable(false), ReadOnly(true)]
public List<string> StripChars
{
get { return stripChars; }
set { stripChars = value; }
}
private string ignoreChars;
[Browsable(false), ReadOnly(true)]
public string IgnoreChars
{
get { return ignoreChars; }
set
{
//[ML-558] Adding a '-' to the ingnore chars throws an unhandled exception - Escape each character
ignoreChars = Regex.Escape(value).Replace("-", "\\-");
validChar = new Regex("[" + ignoreChars + "\\b" + "]");
}
}
private List<char> newLineChars = new List<char>();
[Browsable(false), ReadOnly(true)]
public List<char> NewLineChars
{
get { return newLineChars; }
set { newLineChars = value; }
}
private bool caseSensitive;
[Browsable(false), ReadOnly(true)]
public bool CaseSensitive
{
get { return caseSensitive; }
set { caseSensitive = value; }
}
private bool correctOnTheFly;
[Browsable(false), ReadOnly(true)]
public bool CorrectOnTheFly
{
get { return correctOnTheFly; }
set { correctOnTheFly = value; }
}
private Color tippForeColor = Color.Empty, orgForeColor = Color.Empty;
public Color TippForeColor
{
get { return tippForeColor; }
set { tippForeColor = value; orgForeColor = ForeColor; }
}
private Color tippBackColor = Color.Empty, orgBackColor = Color.Empty;
public Color TippBackColor
{
get { return tippBackColor; }
set { tippBackColor = value; orgBackColor = BackColor; }
}
private List<string> synonyms = new List<string>();
[Browsable(false), ReadOnly(true)]
public IList<string> Synonyms
{
get
{
return synonyms;
}
set
{
Text = String.Empty;
Errors = 0;
wrongChars.Clear();
synonyms.Clear();
foreach (string word in value)
synonyms.Add(WebUtility.HtmlDecode(word)); //[ML-1474] Convert Html entities to their character representations for the answer input window
CalulateSize();
ShowTipp();
}
}
private string welcomeTipp = String.Empty;
[Browsable(false), ReadOnly(true)]
public string WelcomeTipp
{
get { return welcomeTipp; }
set
{
welcomeTipp = value;
if (showTipp)
ShowTipp(); //refresh tip [ML-1955]
}
}
[Browsable(false), DefaultValue(true)]
public bool AllowAnswerSubmit { get; set; }
public event EventHandler Correct;
protected void OnCorrect(EventArgs e)
{
if (!AllowAnswerSubmit)
return;
if (Correct != null)
Correct(this, e);
}
public event EventHandler Wrong;
protected void OnWrong(EventArgs e)
{
if (!AllowAnswerSubmit)
return;
if (Wrong != null)
Wrong(this, e);
}
# endregion
/// <summary>
/// Initializes a new instance of the <see cref="MLifterTextBox"/> class.
/// </summary>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
public MLifterTextBox()
{
AllowAnswerSubmit = true;
BorderStyle = BorderStyle.None;
Font = new System.Drawing.Font("MS Sans Serif", 14, System.Drawing.FontStyle.Bold);
SelectionAlignment = HorizontalAlignment.Center;
//ScrollBars = RichTextBoxScrollBars.ForcedVertical;
AllowDrop = true;
DragEnter += new DragEventHandler(MLifterTextBox_DragEnter);
DragDrop += new DragEventHandler(MLifterTextBox_DragDrop);
MouseDown += new MouseEventHandler(MLifterTextBox_MouseDown);
Leave += new EventHandler(MLifterTextBox_Leave);
ContentsResized += new ContentsResizedEventHandler(MLifterTextBox_ContentsResized);
caseSensitive = false;
correctOnTheFly = false;
StripChars.Add("\n\r");
StripChars.Add("\r\n");
StripChars.Add("\n");
//StripChars.Add(",");
allowedControlChars.Clear();
allowedControlChars.Add((char)Keys.Enter);
allowedControlChars.Add((char)Keys.Back);
allowedControlChars.Add((char)Keys.Space);
allowedControlChars.Add((char)Keys.LineFeed);
IgnoreChars = ".!?;,";
}
/// <summary>
/// Handles the Leave event of the MLifterTextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2009-04-16</remarks>
void MLifterTextBox_Leave(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(this.Text))
ShowTipp();
}
/// <summary>
/// Gets or sets a value indicating whether control's elements are aligned to support locales using right-to-left fonts.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Windows.Forms.RightToLeft"/> values. The default is <see cref="F:System.Windows.Forms.RightToLeft.Inherit"/>.</returns>
/// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:System.Windows.Forms.RightToLeft"/> values. </exception>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/>
/// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
/// </PermissionSet>
/// <remarks>Documented by Dev02, 2008-07-16</remarks>
public override RightToLeft RightToLeft
{
get
{
return base.RightToLeft;
}
set
{
base.RightToLeft = value;
//restore the horizontal text alignment (gets destroyed through RightToLeft)
this.SelectAll();
this.SelectionAlignment = HorizontalAlignment.Center;
}
}
/// <summary>
/// Handles the MouseDown event of the MLifterTextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-10-02</remarks>
void MLifterTextBox_MouseDown(object sender, MouseEventArgs e)
{
ClearTipp();
if (SelectionLength > 0 && !CorrectOnTheFly)
{
selectionEventEnabled = false;
selectionStart = SelectionStart;
selectionLength = SelectionLength;
selectionEventEnabled = true;
DoDragDrop(SelectedText, DragDropEffects.Move);
if (selectionStart <= Text.Length)
SelectionStart = selectionStart; //[ML-877] Restore selection as it was before drag and drop operation
if (SelectionStart + selectionLength <= Text.Length)
SelectionLength = selectionLength;
}
}
/// <summary>
/// Handles the DragEnter event of the MLifterTextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-10-02</remarks>
void MLifterTextBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text) && !CorrectOnTheFly)
e.Effect = DragDropEffects.Move;
else if (e.Data.GetDataPresent(DataFormats.FileDrop) && FileDropped != null)
e.Effect = DragDropEffects.Link;
else
e.Effect = DragDropEffects.None;
}
/// <summary>
/// Handles the DragDrop event of the MLifterTextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-10-02</remarks>
void MLifterTextBox_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text) &&
(SelectionStart <= selectionStart || SelectionStart >= selectionStart + selectionLength)) //[ML-877] Do not allow text to be inserted inside itself
{
ClearTipp();
selectionEventEnabled = false;
int selStart = SelectionStart;
string text = e.Data.GetData(DataFormats.Text) as string;
Text = Text.Remove(selectionStart, selectionLength).Insert(SelectionStart - (SelectionStart > selectionStart ? selectionLength : 0), text);
SelectionStart = selStart + text.Length;
selectionStart = 0;
selectionLength = 0;
selectionEventEnabled = true;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
if (FileDropped != null)
FileDropped(this, e);
}
}
public delegate void FileDroppedEventHandler(object sender, DragEventArgs e);
public event FileDroppedEventHandler FileDropped;
/// <summary>
/// Sends the char.
/// </summary>
/// <param name="character">The character.</param>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
public void SendChar(char character)
{
OnKeyPress(new KeyPressEventArgs(character));
}
public void ManualOnKeyPress(KeyPressEventArgs e)
{
OnKeyPress(e);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.KeyPress"></see> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.KeyPressEventArgs"></see> that contains the event data.</param>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
protected override void OnKeyPress(KeyPressEventArgs e)
{
ClearTipp();
if (!allowedControlChars.Contains(e.KeyChar) && char.IsControl(e.KeyChar))
return;
if (e.KeyChar == (char)Keys.Back && CorrectOnTheFly)
{
for (int i = 0; i < wrongChars.Count; i++)
if (wrongChars[i] > Text.Length - 1)
{
wrongChars.Remove(wrongChars[i]);
i++;
}
lastCharIsWrong = false;
OnSelectionChanged(new EventArgs());
return;
}
//fix for [ML-799] MLifterTextbox: Cannot go back and insert additional characters - delete the newline at the current cursor position
if (!CorrectOnTheFly && e.KeyChar == (char)Keys.Enter && SelectionLength == 0)
{
if (SelectionStart > 0 && Text[SelectionStart - 1] == Convert.ToChar("\n"))
{
int cursorposition = SelectionStart; //preserve the cursor position
Text = Text.Remove(cursorposition - 1, 1);
this.SelectionStart = cursorposition - 1;
}
}
# region generate lists with all and entered synonyms
List<string> openSynonyms = new List<string>();
List<string> gottenSynonyms = new List<string>();
foreach (string str in synonyms)
{
string strg;
if (!CaseSensitive)
strg = str.ToLower();
else
strg = str;
strg = validChar.Replace(strg, string.Empty);
strg = RemoveUnicodeFormatChars(strg); //fix for [ML-588] MLifterTextbox: Unicode control characters in answer cause comparison to fail
openSynonyms.Add(RemoveIgnoreChars(strg));
}
if (CorrectOnTheFly && SelectionLength > 0)
Text = Text.Substring(0, Text.Length - 1);
if (CorrectOnTheFly)
Text += e.KeyChar.ToString();
//corrected because of [ML-486] - deletion with backspace still causes the answer to be true
//if (e.KeyChar == (char)Keys.Enter)
// Undo();
List<string> currentSynonyms = new List<string>();
currentSynonyms.AddRange(Text.Split(StripChars.ToArray(), StringSplitOptions.RemoveEmptyEntries));
# endregion
# region remove entered synonyms from open-list
CorrectFirstSynonym = false;
CorrectSynonyms = 0;
foreach (string str in currentSynonyms.ToArray())
{
string strg = CaseSensitive ? str.Trim() : str.ToLower().Trim();
strg = RemoveIgnoreChars(strg);
if (openSynonyms.Contains(strg))
{
CorrectSynonyms++;
if (RemoveIgnoreChars(synonyms[0].ToLower()) == strg.ToLower())
CorrectFirstSynonym = true;
openSynonyms.Remove(strg);
//currentSynonyms.Remove(strg); //[ML-522] currentsynonyms contains the not-lowered version (str) instead of the lowered version (strg)
currentSynonyms.Remove(str);
gottenSynonyms.Add(str);
}
else
continue;
}
# endregion
# region check input
if (e.KeyChar == (char)Keys.Back)
return;
else if (CorrectOnTheFly)
{
Text = string.Join("\n", gottenSynonyms.ToArray()) + (CorrectSynonyms > 0 ? "\n" : "");
e.Handled = true;
string currentSynonym = (currentSynonyms.Count > 0 ? currentSynonyms[0] : "");
Text += currentSynonym;
selectionEventEnabled = false;
SelectionLength = 0;
SelectionStart = Text.Length;
selectionEventEnabled = true;
MarkWrongChars();
if (e.KeyChar == (int)Keys.Enter || openSynonyms.Count == 0)
{
if (e.KeyChar == (int)Keys.Enter && lastCharIsWrong) //[ML-525] Correct-on-the-fly does not show last (wrong) char
{
Text = oldText;
oldText = string.Empty; //[ML-540] when only pressing enter, the last entered text gets shown
}
if (openSynonyms.Count == 0)
OnCorrect(EventArgs.Empty);
else
OnWrong(EventArgs.Empty);
}
else if (currentSynonyms.Count != 0)
{
foreach (string str in openSynonyms.ToArray())
if (!str.StartsWith(CaseSensitive ? currentSynonym : currentSynonym.ToLower())) //[ML-522] currentsynonym must be converted to lower for the comparison to work
openSynonyms.Remove(str);
if (openSynonyms.Count == 0)
{
if (!lastCharIsWrong)
Errors++;
wrongChars.Add(Text.Length - 1);
lastCharIsWrong = true;
SelectionStart = Text.Length - 1;
SelectionLength = 1;
}
else
lastCharIsWrong = false;
oldText = Text;
}
}
else
{
if (e.KeyChar == (int)Keys.Enter)
{
if (Lines.Length < synonyms.Count && (Lines.Length > 0 && Lines[Lines.Length - 1].Length > 0))
{
int selectionStart = SelectionStart;
Text = Text.Insert(SelectionStart, e.KeyChar.ToString());
SelectionStart = selectionStart + 1;
return;
}
//corrected because of [ML-530] - MLifterTextbox: Chinese Input (IME) does not appear correctly
//Undo();
if (openSynonyms.Count == 0)
OnCorrect(EventArgs.Empty);
else
OnWrong(EventArgs.Empty);
return;
}
else if (StripChars.Contains(e.KeyChar.ToString()))
{
int selectionStart = SelectionStart;
Text = Text.Insert(SelectionStart, "\n");
SelectionStart = selectionStart + 1;
e.Handled = true;
}
else
{
int selectionStart = SelectionStart;
if (SelectionLength > 0)
Text = Text.Substring(0, selectionStart) + e.KeyChar.ToString() + Text.Substring(selectionStart + SelectionLength, Text.Length - selectionStart - SelectionLength);
else
Text = Text.Insert(selectionStart, e.KeyChar.ToString());
SelectionStart = selectionStart + 1;
e.Handled = true;
}
}
# endregion
}
/// <summary>
/// Removes the ignor chars.
/// </summary>
/// <param name="strg">The STRG.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2007-11-19</remarks>
private string RemoveIgnoreChars(string strg)
{
return validChar.Replace(strg, "");
}
/// <summary>
/// Marks the wrong chars.
/// </summary>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
private void MarkWrongChars()
{
selectionEventEnabled = false;
int oldLength = SelectionLength;
int oldPos = SelectionStart;
//Bugfix for [ML-533] MLifterTextbox: Whole word gets marked as red in correct-on-the-fly
SelectionStart = 0;
SelectionLength = Text.Length;
SelectionColor = System.Drawing.Color.Black;
foreach (int index in wrongChars)
{
SelectionStart = index;
SelectionLength = 1;
SelectionColor = System.Drawing.Color.Red;
}
SelectionStart = oldPos;
SelectionLength = oldLength;
selectionEventEnabled = true;
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.KeyDown"></see> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.KeyEventArgs"></see> that contains the event data.</param>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Enter)
e.Handled = true;
else if (e.Control && (e.KeyCode == Keys.V || e.KeyCode == Keys.X) && CorrectOnTheFly) //prevent paste and cut (from/to clipboard)
e.Handled = true;
else if (e.KeyCode == Keys.Delete && CorrectOnTheFly) //prevent delete key
e.Handled = true;
else
base.OnKeyDown(e);
}
/// <summary>
/// Raises the <see cref="E:MouseUp"/> event.
/// </summary>
/// <param name="mevent">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-09-19</remarks>
protected override void OnMouseUp(MouseEventArgs mevent)
{
if (CorrectOnTheFly && Text.Length > 0 && selectionEventEnabled)
{
selectionEventEnabled = false;
if (lastCharIsWrong)
{
SelectionStart = Text.Length - 1;
SelectionLength = 1;
}
else
{
SelectionLength = 0;
SelectionStart = Text.Length;
}
selectionEventEnabled = true;
}
base.OnMouseUp(mevent);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.RichTextBox.SelectionChanged"></see> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
/// <remarks>Documented by Dev02, 2008-01-25</remarks>
protected override void OnSelectionChanged(EventArgs e)
{
if (selectionEventEnabled)
{
selectionEventEnabled = false;
if (CorrectOnTheFly && Text.Length > 0 &&
(lastCharIsWrong && (SelectionStart != Text.Length - 1 || SelectionLength != 1) || !lastCharIsWrong && SelectionStart != Text.Length))
{
if (lastCharIsWrong)
{
SelectionStart = Text.Length - 1;
SelectionLength = 1; // [ML-538] MLifterTextbox: Right arrow confuses the 'On-The-Fly' Mode - the selectionlength must be set after the selectionstart
}
else
{
SelectionLength = 0;
SelectionStart = Text.Length;
}
}
selectionEventEnabled = true;
}
base.OnSelectionChanged(e);
}
/// <summary>
/// Replaces the control chars.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
/// <remarks>Documented by Dev02, 2008-02-20</remarks>
private string RemoveUnicodeFormatChars(string text)
{
List<char> formatChars = new List<char>();
foreach (char character in text.ToCharArray())
{
if (Char.IsControl(character) || Char.GetUnicodeCategory(character) == System.Globalization.UnicodeCategory.Format)
formatChars.Add(character);
}
foreach (char formatChar in formatChars)
{
text = text.Replace(formatChar.ToString(), string.Empty);
}
return text;
}
/// <summary>
/// Handles the ContentsResized event of the MLifterTextBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.ContentsResizedEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev03, 2009-04-30</remarks>
void MLifterTextBox_ContentsResized(object sender, ContentsResizedEventArgs e)
{
if (!Visible) return;
if (Height < e.NewRectangle.Height)
{
Height = e.NewRectangle.Height + 10;
}
if (Height > minHeigth)
{
Height = e.NewRectangle.Height + 10;
}
}
/// <summary>
/// Gets or sets the size that is the lower limit that <see cref="M:System.Windows.Forms.Control.GetPreferredSize(System.Drawing.Size)"/> can specify.
/// </summary>
/// <value></value>
/// <returns>
/// An ordered pair of type <see cref="T:System.Drawing.Size"/> representing the width and height of a rectangle.
/// </returns>
/// <remarks>Documented by Dev03, 2009-04-30</remarks>
public override Size MinimumSize
{
get
{
if (this.DesignMode)
return base.MinimumSize;
int width = Parent.Width - 10;
return new Size(width, minHeigth);
}
set
{
base.MinimumSize = value;
}
}
/// <summary>
/// Gets or sets the size that is the upper limit that <see cref="M:System.Windows.Forms.Control.GetPreferredSize(System.Drawing.Size)"/> can specify.
/// </summary>
/// <value></value>
/// <returns>
/// An ordered pair of type <see cref="T:System.Drawing.Size"/> representing the width and height of a rectangle.
/// </returns>
/// <remarks>Documented by Dev03, 2009-04-30</remarks>
public override Size MaximumSize
{
get
{
if (this.DesignMode)
return base.MaximumSize;
int width = Parent.Width - 10;
int heigth = Parent.Height - 10;
foreach (Control c in Parent.Controls)
{
if (c.Visible && !(c is MLifterTextBox) && !(c is Panel))
heigth -= c.Height;
}
return new Size(width, heigth);
}
set
{
base.MaximumSize = value;
}
}
private int linecount = 0;
private int minHeigth = 0;
/// <summary>
/// Calulates the size.
/// </summary>
/// <remarks>Documented by Dev03, 2009-04-14</remarks>
private void CalulateSize()
{
using (Graphics g = this.CreateGraphics())
{
string lines = String.Empty;
linecount = (((synonyms.Count >= 3) ? synonyms.Count : 3) > 5) ? 5 : (synonyms.Count >= 3) ? synonyms.Count : 3;
for (int i = 0; i < linecount; i++)
lines += "line" + Environment.NewLine;
this.Height = minHeigth = Convert.ToInt32(g.MeasureString(lines.Trim(), Font).Height);
}
}
/// <summary>
/// Shows the tipp.
/// </summary>
/// <remarks>Documented by Dev03, 2009-04-14</remarks>
private void ShowTipp()
{
showTipp = true;
if (tippBackColor != Color.Empty)
BackColor = tippBackColor;
if (tippForeColor != Color.Empty)
ForeColor = tippForeColor;
Text = String.Empty;
for (int i = 0; i < Convert.ToInt32(Math.Ceiling(linecount / 2.0)) - 1; i++)
Text += Environment.NewLine;
Text += welcomeTipp;
SelectionStart = Text.Length;
}
/// <summary>
/// Clears the tipp.
/// </summary>
/// <remarks>Documented by Dev03, 2009-04-14</remarks>
private void ClearTipp()
{
if (showTipp)
{
showTipp = false;
Text = String.Empty;
BackColor = orgBackColor;
ForeColor = orgForeColor;
}
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using Internal.Runtime.CompilerServices;
namespace System.Globalization
{
public partial class CompareInfo
{
[NonSerialized]
private IntPtr _sortHandle;
[NonSerialized]
private bool _isAsciiEqualityOrdinal;
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
if (GlobalizationMode.Invariant)
{
_isAsciiEqualityOrdinal = true;
}
else
{
// Inline the following condition to avoid potential implementation cycles within globalization
//
// _isAsciiEqualityOrdinal = _sortName == "" || _sortName == "en" || _sortName.StartsWith("en-", StringComparison.Ordinal);
//
_isAsciiEqualityOrdinal = _sortName.Length == 0 ||
(_sortName.Length >= 2 && _sortName[0] == 'e' && _sortName[1] == 'n' && (_sortName.Length == 2 || _sortName[2] == '-'));
_sortHandle = SortHandleCache.GetCachedSortHandle(_sortName);
}
}
internal static unsafe int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.Globalization.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase, bool fromBeginning)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source.Length != 0);
Debug.Assert(value.Length != 0);
if (source.Length < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pValue = &MemoryMarshal.GetReference(value))
{
return Interop.Globalization.IndexOfOrdinalIgnoreCase(pValue, value.Length, pSource, source.Length, findLast: !fromBeginning);
}
}
int startIndex, endIndex, jump;
if (fromBeginning)
{
// Left to right, from zero to last possible index in the source string.
// Incrementing by one after each iteration. Stop condition is last possible index plus 1.
startIndex = 0;
endIndex = source.Length - value.Length + 1;
jump = 1;
}
else
{
// Right to left, from first possible index in the source string to zero.
// Decrementing by one after each iteration. Stop condition is last possible index minus 1.
startIndex = source.Length - value.Length;
endIndex = -1;
jump = -1;
}
for (int i = startIndex; i != endIndex; i += jump)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++)
;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
internal static unsafe int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.Globalization.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private static unsafe int CompareStringOrdinalIgnoreCase(ref char string1, int count1, ref char string2, int count2)
{
Debug.Assert(!GlobalizationMode.Invariant);
fixed (char* char1 = &string1)
fixed (char* char2 = &string2)
{
return Interop.Globalization.CompareStringOrdinalIgnoreCase(char1, count1, char2, count2);
}
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
private unsafe int CompareString(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(string2 != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = &MemoryMarshal.GetReference(string1))
fixed (char* pString2 = &string2.GetRawStringData())
{
return Interop.Globalization.CompareString(_sortHandle, pString1, string1.Length, pString2, string2.Length, options);
}
}
private unsafe int CompareString(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = &MemoryMarshal.GetReference(string1))
fixed (char* pString2 = &MemoryMarshal.GetReference(string2))
{
return Interop.Globalization.CompareString(_sortHandle, pString1, string1.Length, pString2, string2.Length, options);
}
}
internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
Debug.Assert((options & CompareOptions.Ordinal) == 0);
int index;
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options))
{
if ((options & CompareOptions.IgnoreCase) != 0)
index = IndexOfOrdinalIgnoreCaseHelper(source.AsSpan(startIndex, count), target.AsSpan(), options, matchLengthPtr, fromBeginning: true);
else
index = IndexOfOrdinalHelper(source.AsSpan(startIndex, count), target.AsSpan(), options, matchLengthPtr, fromBeginning: true);
}
else
{
fixed (char* pSource = source)
fixed (char* pTarget = target)
{
index = Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource + startIndex, count, options, matchLengthPtr);
}
}
return index != -1 ? index + startIndex : -1;
}
// For now, this method is only called from Span APIs with either options == CompareOptions.None or CompareOptions.IgnoreCase
internal unsafe int IndexOfCore(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source.Length != 0);
Debug.Assert(target.Length != 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options))
{
if ((options & CompareOptions.IgnoreCase) != 0)
return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr, fromBeginning);
else
return IndexOfOrdinalHelper(source, target, options, matchLengthPtr, fromBeginning);
}
else
{
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pTarget = &MemoryMarshal.GetReference(target))
{
if (fromBeginning)
return Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options, matchLengthPtr);
else
return Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options);
}
}
}
/// <summary>
/// Duplicate of IndexOfOrdinalHelper that also handles ignore case. Can't converge both methods
/// as the JIT wouldn't be able to optimize the ignoreCase path away.
/// </summary>
/// <returns></returns>
private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!target.IsEmpty);
Debug.Assert(_isAsciiEqualityOrdinal);
fixed (char* ap = &MemoryMarshal.GetReference(source))
fixed (char* bp = &MemoryMarshal.GetReference(target))
{
char* a = ap;
char* b = bp;
for (int j = 0; j < target.Length; j++)
{
char targetChar = *(b + j);
if (targetChar >= 0x80 || HighCharTable[targetChar])
goto InteropCall;
}
if (target.Length > source.Length)
{
for (int k = 0; k < source.Length; k++)
{
char targetChar = *(a + k);
if (targetChar >= 0x80 || HighCharTable[targetChar])
goto InteropCall;
}
return -1;
}
int startIndex, endIndex, jump;
if (fromBeginning)
{
// Left to right, from zero to last possible index in the source string.
// Incrementing by one after each iteration. Stop condition is last possible index plus 1.
startIndex = 0;
endIndex = source.Length - target.Length + 1;
jump = 1;
}
else
{
// Right to left, from first possible index in the source string to zero.
// Decrementing by one after each iteration. Stop condition is last possible index minus 1.
startIndex = source.Length - target.Length;
endIndex = -1;
jump = -1;
}
for (int i = startIndex; i != endIndex; i += jump)
{
int targetIndex = 0;
int sourceIndex = i;
for (; targetIndex < target.Length; targetIndex++, sourceIndex++)
{
char valueChar = *(a + sourceIndex);
char targetChar = *(b + targetIndex);
if (valueChar >= 0x80 || HighCharTable[valueChar])
goto InteropCall;
if (valueChar == targetChar)
{
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(valueChar - 'a') <= ('z' - 'a'))
valueChar = (char)(valueChar - 0x20);
if ((uint)(targetChar - 'a') <= ('z' - 'a'))
targetChar = (char)(targetChar - 0x20);
if (valueChar == targetChar)
{
continue;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (sourceIndex < source.Length - 1 && *(a + sourceIndex + 1) >= 0x80)
goto InteropCall;
goto Next;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (sourceIndex < source.Length && *(a + sourceIndex) >= 0x80)
goto InteropCall;
if (matchLengthPtr != null)
*matchLengthPtr = target.Length;
return i;
Next: ;
}
return -1;
InteropCall:
if (fromBeginning)
return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr);
else
return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options);
}
}
private unsafe int IndexOfOrdinalHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!target.IsEmpty);
Debug.Assert(_isAsciiEqualityOrdinal);
fixed (char* ap = &MemoryMarshal.GetReference(source))
fixed (char* bp = &MemoryMarshal.GetReference(target))
{
char* a = ap;
char* b = bp;
for (int j = 0; j < target.Length; j++)
{
char targetChar = *(b + j);
if (targetChar >= 0x80 || HighCharTable[targetChar])
goto InteropCall;
}
if (target.Length > source.Length)
{
for (int k = 0; k < source.Length; k++)
{
char targetChar = *(a + k);
if (targetChar >= 0x80 || HighCharTable[targetChar])
goto InteropCall;
}
return -1;
}
int startIndex, endIndex, jump;
if (fromBeginning)
{
// Left to right, from zero to last possible index in the source string.
// Incrementing by one after each iteration. Stop condition is last possible index plus 1.
startIndex = 0;
endIndex = source.Length - target.Length + 1;
jump = 1;
}
else
{
// Right to left, from first possible index in the source string to zero.
// Decrementing by one after each iteration. Stop condition is last possible index minus 1.
startIndex = source.Length - target.Length;
endIndex = -1;
jump = -1;
}
for (int i = startIndex; i != endIndex; i += jump)
{
int targetIndex = 0;
int sourceIndex = i;
for (; targetIndex < target.Length; targetIndex++, sourceIndex++)
{
char valueChar = *(a + sourceIndex);
char targetChar = *(b + targetIndex);
if (valueChar >= 0x80 || HighCharTable[valueChar])
goto InteropCall;
if (valueChar == targetChar)
{
continue;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (sourceIndex < source.Length - 1 && *(a + sourceIndex + 1) >= 0x80)
goto InteropCall;
goto Next;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (sourceIndex < source.Length && *(a + sourceIndex) >= 0x80)
goto InteropCall;
if (matchLengthPtr != null)
*matchLengthPtr = target.Length;
return i;
Next: ;
}
return -1;
InteropCall:
if (fromBeginning)
return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr);
else
return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options);
}
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinalCore(source, target, startIndex, count, ignoreCase: false);
}
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
int lastIndex;
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options))
{
if ((options & CompareOptions.IgnoreCase) != 0)
lastIndex = IndexOfOrdinalIgnoreCaseHelper(source.AsSpan(leftStartIndex, count), target.AsSpan(), options, matchLengthPtr: null, fromBeginning: false);
else
lastIndex = IndexOfOrdinalHelper(source.AsSpan(leftStartIndex, count), target.AsSpan(), options, matchLengthPtr: null, fromBeginning: false);
}
else
{
fixed (char* pSource = source)
fixed (char* pTarget = target)
{
lastIndex = Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource + (startIndex - count + 1), count, options);
}
}
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
private unsafe bool StartsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!prefix.IsEmpty);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options))
{
if ((options & CompareOptions.IgnoreCase) != 0)
return StartsWithOrdinalIgnoreCaseHelper(source, prefix, options);
else
return StartsWithOrdinalHelper(source, prefix, options);
}
else
{
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pPrefix = &MemoryMarshal.GetReference(prefix))
{
return Interop.Globalization.StartsWith(_sortHandle, pPrefix, prefix.Length, pSource, source.Length, options);
}
}
}
private unsafe bool StartsWithOrdinalIgnoreCaseHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!prefix.IsEmpty);
Debug.Assert(_isAsciiEqualityOrdinal);
int length = Math.Min(source.Length, prefix.Length);
fixed (char* ap = &MemoryMarshal.GetReference(source))
fixed (char* bp = &MemoryMarshal.GetReference(prefix))
{
char* a = ap;
char* b = bp;
while (length != 0)
{
int charA = *a;
int charB = *b;
if (charA >= 0x80 || charB >= 0x80 || HighCharTable[charA] || HighCharTable[charB])
goto InteropCall;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (a < ap + source.Length - 1 && *(a + 1) >= 0x80)
goto InteropCall;
if (b < bp + prefix.Length - 1 && *(b + 1) >= 0x80)
goto InteropCall;
return false;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (source.Length < prefix.Length)
{
if (*b >= 0x80)
goto InteropCall;
return false;
}
if (source.Length > prefix.Length)
{
if (*a >= 0x80)
goto InteropCall;
}
return true;
InteropCall:
return Interop.Globalization.StartsWith(_sortHandle, bp, prefix.Length, ap, source.Length, options);
}
}
private unsafe bool StartsWithOrdinalHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!prefix.IsEmpty);
Debug.Assert(_isAsciiEqualityOrdinal);
int length = Math.Min(source.Length, prefix.Length);
fixed (char* ap = &MemoryMarshal.GetReference(source))
fixed (char* bp = &MemoryMarshal.GetReference(prefix))
{
char* a = ap;
char* b = bp;
while (length != 0)
{
int charA = *a;
int charB = *b;
if (charA >= 0x80 || charB >= 0x80 || HighCharTable[charA] || HighCharTable[charB])
goto InteropCall;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (a < ap + source.Length - 1 && *(a + 1) >= 0x80)
goto InteropCall;
if (b < bp + prefix.Length - 1 && *(b + 1) >= 0x80)
goto InteropCall;
return false;
}
// The match may be affected by special character. Verify that the following character is regular ASCII.
if (source.Length < prefix.Length)
{
if (*b >= 0x80)
goto InteropCall;
return false;
}
if (source.Length > prefix.Length)
{
if (*a >= 0x80)
goto InteropCall;
}
return true;
InteropCall:
return Interop.Globalization.StartsWith(_sortHandle, bp, prefix.Length, ap, source.Length, options);
}
}
private unsafe bool EndsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!suffix.IsEmpty);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options))
{
if ((options & CompareOptions.IgnoreCase) != 0)
return EndsWithOrdinalIgnoreCaseHelper(source, suffix, options);
else
return EndsWithOrdinalHelper(source, suffix, options);
}
else
{
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pSuffix = &MemoryMarshal.GetReference(suffix))
{
return Interop.Globalization.EndsWith(_sortHandle, pSuffix, suffix.Length, pSource, source.Length, options);
}
}
}
private unsafe bool EndsWithOrdinalIgnoreCaseHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!suffix.IsEmpty);
Debug.Assert(_isAsciiEqualityOrdinal);
int length = Math.Min(source.Length, suffix.Length);
fixed (char* ap = &MemoryMarshal.GetReference(source))
fixed (char* bp = &MemoryMarshal.GetReference(suffix))
{
char* a = ap + source.Length - 1;
char* b = bp + suffix.Length - 1;
while (length != 0)
{
int charA = *a;
int charB = *b;
if (charA >= 0x80 || charB >= 0x80 || HighCharTable[charA] || HighCharTable[charB])
goto InteropCall;
if (charA == charB)
{
a--; b--;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
if (charA == charB)
{
a--; b--;
length--;
continue;
}
return false;
}
return (source.Length >= suffix.Length);
InteropCall:
return Interop.Globalization.EndsWith(_sortHandle, bp, suffix.Length, ap, source.Length, options);
}
}
private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!suffix.IsEmpty);
Debug.Assert(_isAsciiEqualityOrdinal);
int length = Math.Min(source.Length, suffix.Length);
fixed (char* ap = &MemoryMarshal.GetReference(source))
fixed (char* bp = &MemoryMarshal.GetReference(suffix))
{
char* a = ap + source.Length - 1;
char* b = bp + suffix.Length - 1;
while (length != 0)
{
int charA = *a;
int charB = *b;
if (charA >= 0x80 || charB >= 0x80 || HighCharTable[charA] || HighCharTable[charB])
goto InteropCall;
if (charA == charB)
{
a--; b--;
length--;
continue;
}
return false;
}
return (source.Length >= suffix.Length);
InteropCall:
return Interop.Globalization.EndsWith(_sortHandle, bp, suffix.Length, ap, source.Length, options);
}
}
private unsafe SortKey CreateSortKey(string source, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
if (source==null) { throw new ArgumentNullException(nameof(source)); }
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<byte>();
}
else
{
fixed (char* pSource = source)
{
int sortKeyLength = Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, null, 0, options);
keyData = new byte[sortKeyLength];
fixed (byte* pSortKey = keyData)
{
if (Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, pSortKey, sortKeyLength, options) != sortKeyLength)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
}
}
}
return new SortKey(Name, source, options, keyData);
}
private static unsafe bool IsSortable(char *text, int length)
{
Debug.Assert(!GlobalizationMode.Invariant);
int index = 0;
UnicodeCategory uc;
while (index < length)
{
if (char.IsHighSurrogate(text[index]))
{
if (index == length - 1 || !char.IsLowSurrogate(text[index+1]))
return false; // unpaired surrogate
uc = CharUnicodeInfo.GetUnicodeCategory(char.ConvertToUtf32(text[index], text[index+1]));
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
return false;
index += 2;
continue;
}
if (char.IsLowSurrogate(text[index]))
{
return false; // unpaired surrogate
}
uc = CharUnicodeInfo.GetUnicodeCategory(text[index]);
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
{
return false;
}
index++;
}
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
internal unsafe int GetHashCodeOfStringCore(ReadOnlySpan<char> source, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
// according to ICU User Guide the performance of ucol_getSortKey is worse when it is called with null output buffer
// the solution is to try to fill the sort key in a temporary buffer of size equal 4 x string length
// 1MB is the biggest array that can be rented from ArrayPool.Shared without memory allocation
int sortKeyLength = (source.Length > 1024 * 1024 / 4) ? 0 : 4 * source.Length;
byte[]? borrowedArray = null;
Span<byte> sortKey = sortKeyLength <= 1024
? stackalloc byte[1024]
: (borrowedArray = ArrayPool<byte>.Shared.Rent(sortKeyLength));
fixed (char* pSource = &MemoryMarshal.GetReference(source))
{
fixed (byte* pSortKey = &MemoryMarshal.GetReference(sortKey))
{
sortKeyLength = Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, pSortKey, sortKey.Length, options);
}
if (sortKeyLength > sortKey.Length) // slow path for big strings
{
if (borrowedArray != null)
{
ArrayPool<byte>.Shared.Return(borrowedArray);
}
sortKey = (borrowedArray = ArrayPool<byte>.Shared.Rent(sortKeyLength));
fixed (byte* pSortKey = &MemoryMarshal.GetReference(sortKey))
{
sortKeyLength = Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, pSortKey, sortKey.Length, options);
}
}
}
if (sortKeyLength == 0 || sortKeyLength > sortKey.Length) // internal error (0) or a bug (2nd call failed) in ucol_getSortKey
{
throw new ArgumentException(SR.Arg_ExternalException);
}
int hash = Marvin.ComputeHash32(sortKey.Slice(0, sortKeyLength), Marvin.DefaultSeed);
if (borrowedArray != null)
{
ArrayPool<byte>.Shared.Return(borrowedArray);
}
return hash;
}
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) != 0)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
private SortVersion GetSortVersion()
{
Debug.Assert(!GlobalizationMode.Invariant);
int sortVersion = Interop.Globalization.GetSortVersion(_sortHandle);
return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0,
(byte) (LCID >> 24),
(byte) ((LCID & 0x00FF0000) >> 16),
(byte) ((LCID & 0x0000FF00) >> 8),
(byte) (LCID & 0xFF)));
}
private static class SortHandleCache
{
// in most scenarios there is a limited number of cultures with limited number of sort options
// so caching the sort handles and not freeing them is OK, see https://github.com/dotnet/coreclr/pull/25117 for more
private static readonly Dictionary<string, IntPtr> s_sortNameToSortHandleCache = new Dictionary<string, IntPtr>();
internal static IntPtr GetCachedSortHandle(string sortName)
{
lock (s_sortNameToSortHandleCache)
{
if (!s_sortNameToSortHandleCache.TryGetValue(sortName, out IntPtr result))
{
Interop.Globalization.ResultCode resultCode = Interop.Globalization.GetSortHandle(sortName, out result);
if (resultCode == Interop.Globalization.ResultCode.OutOfMemory)
throw new OutOfMemoryException();
else if (resultCode != Interop.Globalization.ResultCode.Success)
throw new ExternalException(SR.Arg_ExternalException);
try
{
s_sortNameToSortHandleCache.Add(sortName, result);
}
catch
{
Interop.Globalization.CloseSortHandle(result);
throw;
}
}
return result;
}
}
}
private static ReadOnlySpan<bool> HighCharTable => new bool[0x80]
{
true, /* 0x0, 0x0 */
true, /* 0x1, .*/
true, /* 0x2, .*/
true, /* 0x3, .*/
true, /* 0x4, .*/
true, /* 0x5, .*/
true, /* 0x6, .*/
true, /* 0x7, .*/
true, /* 0x8, .*/
false, /* 0x9, */
true, /* 0xA, */
false, /* 0xB, .*/
false, /* 0xC, .*/
true, /* 0xD, */
true, /* 0xE, .*/
true, /* 0xF, .*/
true, /* 0x10, .*/
true, /* 0x11, .*/
true, /* 0x12, .*/
true, /* 0x13, .*/
true, /* 0x14, .*/
true, /* 0x15, .*/
true, /* 0x16, .*/
true, /* 0x17, .*/
true, /* 0x18, .*/
true, /* 0x19, .*/
true, /* 0x1A, */
true, /* 0x1B, .*/
true, /* 0x1C, .*/
true, /* 0x1D, .*/
true, /* 0x1E, .*/
true, /* 0x1F, .*/
false, /*0x20, */
false, /*0x21, !*/
false, /*0x22, "*/
false, /*0x23, #*/
false, /*0x24, $*/
false, /*0x25, %*/
false, /*0x26, &*/
true, /*0x27, '*/
false, /*0x28, (*/
false, /*0x29, )*/
false, /*0x2A **/
false, /*0x2B, +*/
false, /*0x2C, ,*/
true, /*0x2D, -*/
false, /*0x2E, .*/
false, /*0x2F, /*/
false, /*0x30, 0*/
false, /*0x31, 1*/
false, /*0x32, 2*/
false, /*0x33, 3*/
false, /*0x34, 4*/
false, /*0x35, 5*/
false, /*0x36, 6*/
false, /*0x37, 7*/
false, /*0x38, 8*/
false, /*0x39, 9*/
false, /*0x3A, :*/
false, /*0x3B, ;*/
false, /*0x3C, <*/
false, /*0x3D, =*/
false, /*0x3E, >*/
false, /*0x3F, ?*/
false, /*0x40, @*/
false, /*0x41, A*/
false, /*0x42, B*/
false, /*0x43, C*/
false, /*0x44, D*/
false, /*0x45, E*/
false, /*0x46, F*/
false, /*0x47, G*/
false, /*0x48, H*/
false, /*0x49, I*/
false, /*0x4A, J*/
false, /*0x4B, K*/
false, /*0x4C, L*/
false, /*0x4D, M*/
false, /*0x4E, N*/
false, /*0x4F, O*/
false, /*0x50, P*/
false, /*0x51, Q*/
false, /*0x52, R*/
false, /*0x53, S*/
false, /*0x54, T*/
false, /*0x55, U*/
false, /*0x56, V*/
false, /*0x57, W*/
false, /*0x58, X*/
false, /*0x59, Y*/
false, /*0x5A, Z*/
false, /*0x5B, [*/
false, /*0x5C, \*/
false, /*0x5D, ]*/
false, /*0x5E, ^*/
false, /*0x5F, _*/
false, /*0x60, `*/
false, /*0x61, a*/
false, /*0x62, b*/
false, /*0x63, c*/
false, /*0x64, d*/
false, /*0x65, e*/
false, /*0x66, f*/
false, /*0x67, g*/
false, /*0x68, h*/
false, /*0x69, i*/
false, /*0x6A, j*/
false, /*0x6B, k*/
false, /*0x6C, l*/
false, /*0x6D, m*/
false, /*0x6E, n*/
false, /*0x6F, o*/
false, /*0x70, p*/
false, /*0x71, q*/
false, /*0x72, r*/
false, /*0x73, s*/
false, /*0x74, t*/
false, /*0x75, u*/
false, /*0x76, v*/
false, /*0x77, w*/
false, /*0x78, x*/
false, /*0x79, y*/
false, /*0x7A, z*/
false, /*0x7B, {*/
false, /*0x7C, |*/
false, /*0x7D, }*/
false, /*0x7E, ~*/
true, /*0x7F, */
};
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Transports;
using SuperSocket.ClientEngine;
using WebSocket4Net;
using Microsoft.AspNet.SignalR.Client.Http;
using System.Net;
using SuperSocket.ClientEngine.Proxy;
using Microsoft.AspNet.SignalR.Client.Infrastructure;
using Microsoft.AspNet.SignalR.WebSockets;
using ClientR.WebSockets4Net;
namespace SignalR.Client.WebSocket4Net
{
public class WebSocket4NetTransport : WebSocketHandler, IClientTransport, IDisposable
{
private IHttpClient _client;
private readonly TransportAbortHandler _abortHandler;
private CancellationToken _disconnectToken;
private TransportInitializationHandler _initializeHandler;
private WebSocketConnectionInfo _connectionInfo;
private CancellationTokenSource _webSocketTokenSource;
private WebSocket _webSocket;
private TaskCompletionSource<object> _connectCompletionSource;
private bool _connected;
private int _disposed;
public WebSocket4NetTransport() : this(new DefaultHttpClient())
{
}
public WebSocket4NetTransport(IHttpClient httpClient) : base(null)
{
this._client = httpClient;
_disconnectToken = CancellationToken.None;
this._abortHandler = new TransportAbortHandler(httpClient, this.Name);
this.ReconnectDelay = TimeSpan.FromSeconds(2);
}
public TimeSpan ReconnectDelay { get; set; }
public void Dispose()
{
this.Disconnect();
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Interlocked.Exchange(ref this._disposed, 1) == 1)
{
return;
}
if (this._webSocketTokenSource != null)
{
this._webSocketTokenSource.Cancel();
}
this._abortHandler.Dispose();
if (this._webSocketTokenSource != null)
{
this._webSocketTokenSource.Dispose();
}
}
}
private async void DoReconnect()
{
while (TransportHelper.VerifyLastActive(this._connectionInfo.Connection) && this._connectionInfo.Connection.EnsureReconnecting())
{
try
{
await this.PerformConnect(true);
break;
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
if (ExceptionHelper.IsRequestAborted(ex))
{
break;
}
this._connectionInfo.Connection.OnError(ex);
}
await Task.Delay(this.ReconnectDelay);
}
}
public override void OnClose()
{
this._connectionInfo.Connection.Trace(TraceLevels.Events, "WS: OnClose()", new object[0]);
if (this._disconnectToken.IsCancellationRequested)
{
return;
}
if (this._abortHandler.TryCompleteAbort())
{
return;
}
this.DoReconnect();
}
public override void OnError()
{
this._connectionInfo.Connection.OnError(base.Error);
}
public Task<NegotiationResponse> Negotiate(IConnection connection, string connectionData)
{
return this._client.GetNegotiationResponse(connection, connectionData);
}
public Task Start(IConnection connection, string connectionData, CancellationToken disconnectToken)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
this._initializeHandler = new TransportInitializationHandler(connection.TotalTransportConnectTimeout, disconnectToken);
this._initializeHandler.OnFailure += delegate
{
this.Dispose();
};
_disconnectToken = disconnectToken;
_connectionInfo = new WebSocketConnectionInfo(connection, connectionData);
_connectCompletionSource = new TaskCompletionSource<object>();
this.PerformConnect().ContinueWith(t =>
{
if (t.IsFaulted)
{
this._initializeHandler.Fail(t.Exception);
_connectCompletionSource.SetException(t.Exception);
}
else if (t.IsCanceled)
{
this._initializeHandler.Fail();
_connectCompletionSource.SetCanceled();
}
}, TaskContinuationOptions.NotOnRanToCompletion);
return _connectCompletionSource.Task;
}
public Task Send(IConnection connection, string data, string connectionData)
{
if (connection == null)
throw new ArgumentNullException("connection");
return this.SendAsync(connection, data);
}
private Task SendAsync(IConnection connection, string data)
{
return Task.Run(() =>
{
if (_webSocket.State != WebSocketState.Open)
{
var ex = new InvalidOperationException("Data cannot be sent during web socket reconnect.");
connection.OnError(ex);
throw ex;
}
_webSocket.Send(data);
}, _disconnectToken);
}
public void Abort(IConnection connection, TimeSpan timeout, string connectionData)
{
this._abortHandler.Abort(connection, timeout, connectionData);
}
public void LostConnection(IConnection connection)
{
this._connectionInfo.Connection.Trace(TraceLevels.Events, "WS: LostConnection", new object[0]);
if (this._webSocketTokenSource != null)
{
this._webSocketTokenSource.Cancel();
}
}
public string Name
{
get { return "webSockets"; }
}
public bool SupportsKeepAlive
{
get { return true; }
}
public virtual Task PerformConnect()
{
return this.PerformConnect(false);
}
private Task PerformConnect(bool reconnecting = false)
{
return Task.Run(() =>
{
this.Disconnect(true);
var url = _connectionInfo.Connection.Url + (reconnecting ? "reconnect" : "connect");
url += TransportHelper.GetReceiveQueryString(_connectionInfo.Connection, _connectionInfo.Data, this.Name);
var builder = new UriBuilder(url);
builder.Scheme = builder.Scheme == "https" ? "wss" : "ws";
_connectionInfo.Connection.Trace(TraceLevels.Events, "WS connecting to: {0}", builder.Uri);
this._webSocketTokenSource = new CancellationTokenSource();
_webSocket = new WebSocket(builder.Uri.AbsoluteUri);
var proxy = System.Net.HttpWebRequest.GetSystemWebProxy();
if (proxy != null)
{
Uri destUri = new Uri(url);
Uri proxyUri = proxy.GetProxy(destUri);
if (proxyUri != null)
{
DnsEndPoint proxyEndPoint = new DnsEndPoint(proxyUri.Host, proxyUri.Port);
SuperSocket.ClientEngine.Proxy.HttpConnectProxy ssProxy = new SuperSocket.ClientEngine.Proxy.HttpConnectProxy(proxyEndPoint);
_webSocket.Proxy = ssProxy;
}
}
_webSocket.Error += OnWebSocketError;
_webSocket.Opened += OnWebSocketOpened;
_webSocket.Closed += OnWebSocketClosed;
_webSocket.DataReceived += OnWebSocketDataReceived;
_webSocket.MessageReceived += OnMessage;
_webSocket.Open();
}, _disconnectToken);
}
private void Disconnect(bool releaseOnly = false)
{
if (_webSocket == null)
return;
_webSocket.Closed -= OnWebSocketClosed;
if (!releaseOnly)
_webSocket.Close();
_webSocket.Error -= OnWebSocketError;
_webSocket.Opened -= OnWebSocketOpened;
_webSocket.DataReceived -= OnWebSocketDataReceived;
_webSocket.MessageReceived -= OnMessage;
}
private void OnWebSocketError(object sender, ErrorEventArgs errorEventArgs)
{
_connectionInfo.Connection.OnError(errorEventArgs.Exception);
if (!_connected)
_connectCompletionSource.SetException(errorEventArgs.Exception);
}
private void OnMessage(object sender, MessageReceivedEventArgs messageReceivedEventArgs)
{
string message = messageReceivedEventArgs.Message;
this._connectionInfo.Connection.Trace(TraceLevels.Messages, "WS: OnMessage({0})", new object[]
{
message
});
bool shouldReconnect;
bool disconnected;
IConnection connection = this._connectionInfo.Connection;
string response = message;
TransportHelper.ProcessResponse(this._connectionInfo.Connection, message, out shouldReconnect, out disconnected, new Action(this._initializeHandler.Success));
if (disconnected && !this._disconnectToken.IsCancellationRequested)
{
this._connectionInfo.Connection.Trace(TraceLevels.Messages, "Disconnect command received from server.", new object[0]);
this._connectionInfo.Connection.Disconnect();
}
}
public override void OnOpen()
{
if (this._connectionInfo.Connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
{
this._connectionInfo.Connection.OnReconnected();
}
}
private void OnWebSocketDataReceived(object sender, DataReceivedEventArgs dataReceivedEventArgs)
{
throw new NotImplementedException();
}
private void OnWebSocketClosed(object sender, EventArgs eventArgs)
{
throw new NotImplementedException();
}
private void OnWebSocketOpened(object sender, EventArgs eventArgs)
{
_connected = true;
_connectCompletionSource.SetResult(null);
}
private class WebSocketConnectionInfo
{
public readonly IConnection Connection;
public readonly string Data;
public WebSocketConnectionInfo(IConnection connection, string data)
{
this.Connection = connection;
this.Data = data;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using VotingInfo.Database.Contracts;
using VotingInfo.Database.Contracts.Data;
//////////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend. //
//Override methods in the logic front class. //
//////////////////////////////////////////////////////////////
namespace VotingInfo.Database.Logic.Data
{
[Serializable]
public abstract partial class ElectionLogicBase : LogicBase<ElectionLogicBase>
{
//Put your code in a separate file. This is auto generated.
[XmlArray] public List<ElectionContract> Results;
public ElectionLogicBase()
{
Results = new List<ElectionContract>();
}
/// <summary>
/// Run Election_Insert.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="fldLocationId">Value for LocationId</param>
/// <param name="fldVotingDate">Value for VotingDate</param>
/// <returns>The new ID</returns>
public virtual int? Insert(int fldContentInspectionId
, int fldElectionLevelId
, int fldLocationId
, DateTime fldVotingDate
)
{
int? result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
,
new SqlParameter("@ElectionLevelId", fldElectionLevelId)
,
new SqlParameter("@LocationId", fldLocationId)
,
new SqlParameter("@VotingDate", fldVotingDate)
});
result = (int?)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Run Election_Insert.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="fldLocationId">Value for LocationId</param>
/// <param name="fldVotingDate">Value for VotingDate</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The new ID</returns>
public virtual int? Insert(int fldContentInspectionId
, int fldElectionLevelId
, int fldLocationId
, DateTime fldVotingDate
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
,
new SqlParameter("@ElectionLevelId", fldElectionLevelId)
,
new SqlParameter("@LocationId", fldLocationId)
,
new SqlParameter("@VotingDate", fldVotingDate)
});
return (int?)cmd.ExecuteScalar();
}
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(ElectionContract row)
{
int? result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
,
new SqlParameter("@ElectionLevelId", row.ElectionLevelId)
,
new SqlParameter("@LocationId", row.LocationId)
,
new SqlParameter("@VotingDate", row.VotingDate)
});
result = (int?)cmd.ExecuteScalar();
row.ElectionId = result;
}
});
return result != null ? 1 : 0;
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(ElectionContract row, SqlConnection connection, SqlTransaction transaction)
{
int? result = null;
using (
var cmd = new SqlCommand("[Data].[Election_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
,
new SqlParameter("@ElectionLevelId", row.ElectionLevelId)
,
new SqlParameter("@LocationId", row.LocationId)
,
new SqlParameter("@VotingDate", row.VotingDate)
});
result = (int?)cmd.ExecuteScalar();
row.ElectionId = result;
}
return result != null ? 1 : 0;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<ElectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = InsertAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<ElectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Insert(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Election_Update.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="fldLocationId">Value for LocationId</param>
/// <param name="fldVotingDate">Value for VotingDate</param>
public virtual int Update(int fldElectionId
, int fldContentInspectionId
, int fldElectionLevelId
, int fldLocationId
, DateTime fldVotingDate
)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
,
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
,
new SqlParameter("@ElectionLevelId", fldElectionLevelId)
,
new SqlParameter("@LocationId", fldLocationId)
,
new SqlParameter("@VotingDate", fldVotingDate)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Election_Update.
/// </summary>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="fldLocationId">Value for LocationId</param>
/// <param name="fldVotingDate">Value for VotingDate</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(int fldElectionId
, int fldContentInspectionId
, int fldElectionLevelId
, int fldLocationId
, DateTime fldVotingDate
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Election_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
,
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
,
new SqlParameter("@ElectionLevelId", fldElectionLevelId)
,
new SqlParameter("@LocationId", fldLocationId)
,
new SqlParameter("@VotingDate", fldVotingDate)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(ElectionContract row)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", row.ElectionId)
,
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
,
new SqlParameter("@ElectionLevelId", row.ElectionLevelId)
,
new SqlParameter("@LocationId", row.LocationId)
,
new SqlParameter("@VotingDate", row.VotingDate)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(ElectionContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Election_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", row.ElectionId)
,
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
,
new SqlParameter("@ElectionLevelId", row.ElectionLevelId)
,
new SqlParameter("@LocationId", row.LocationId)
,
new SqlParameter("@VotingDate", row.VotingDate)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<ElectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = UpdateAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<ElectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Update(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Election_Delete.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldElectionId">Value for ElectionId</param>
public virtual int Delete(int fldElectionId
)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Election_Delete.
/// </summary>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(int fldElectionId
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Election_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(ElectionContract row)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", row.ElectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(ElectionContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Election_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", row.ElectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<ElectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = DeleteAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<ElectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Delete(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldElectionId
)
{
bool result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_Exists]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
});
result = (bool)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldElectionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_Exists]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
});
return (bool)cmd.ExecuteScalar();
}
}
/// <summary>
/// Run Election_SelectAll, and return results as a list of ElectionRow.
/// </summary>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectAll()
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectAll]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Election_SelectAll, and return results as a list of ElectionRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectAll]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Election_SelectBy_ElectionId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_ElectionId(int fldElectionId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_ElectionId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Election_SelectBy_ElectionId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldElectionId">Value for ElectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_ElectionId(int fldElectionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_ElectionId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionId", fldElectionId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Election_SelectBy_ContentInspectionId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_ContentInspectionId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Election_SelectBy_ContentInspectionId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_ContentInspectionId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Election_SelectBy_ElectionLevelId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_ElectionLevelId(int fldElectionLevelId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_ElectionLevelId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionLevelId", fldElectionLevelId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Election_SelectBy_ElectionLevelId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_ElectionLevelId(int fldElectionLevelId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_ElectionLevelId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ElectionLevelId", fldElectionLevelId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Election_SelectBy_LocationId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldLocationId">Value for LocationId</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_LocationId(int fldLocationId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_LocationId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LocationId", fldLocationId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Election_SelectBy_LocationId, and return results as a list of ElectionRow.
/// </summary>
/// <param name="fldLocationId">Value for LocationId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionRow.</returns>
public virtual bool SelectBy_LocationId(int fldLocationId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Election_SelectBy_LocationId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LocationId", fldLocationId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Read all items into this collection
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadAll(SqlDataReader reader)
{
var canRead = ReadOne(reader);
var result = canRead;
while (canRead) canRead = ReadOne(reader);
return result;
}
/// <summary>
/// Read one item into Results
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadOne(SqlDataReader reader)
{
if (reader.Read())
{
Results.Add(
new ElectionContract
{
ElectionId = reader.GetInt32(0),
ContentInspectionId = reader.GetInt32(1),
ElectionLevelId = reader.GetInt32(2),
LocationId = reader.GetInt32(3),
VotingDate = reader.GetDateTime(4),
});
return true;
}
return false;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(ElectionContract row)
{
if(row == null) return 0;
if(row.ElectionId != null) return Update(row);
return Insert(row);
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(ElectionContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row == null) return 0;
if(row.ElectionId != null) return Update(row, connection, transaction);
return Insert(row, connection, transaction);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<ElectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
foreach(var row in rows) rowCount += Save(row, x, null);
});
return rowCount;
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<ElectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Save(row, connection, transaction);
return rowCount;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
#endif
namespace Pathfinding
{
public class NodeLink3Node : PointNode {
public NodeLink3 link;
public Vector3 portalA;
public Vector3 portalB;
public NodeLink3Node ( AstarPath active ) : base ( active ) {}
public override bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards)
{
if ( this.connections.Length < 2 ) return false;
if ( this.connections.Length != 2 ) throw new System.Exception ("Invalid NodeLink3Node. Expected 2 connections, found " + this.connections.Length);
//if ( other != connections[0] || other != connections[1] ) return false;
if ( left != null ) {
//Debug.DrawLine ( portalA, portalB, Color.red);
left.Add ( portalA );
right.Add ( portalB );
/*
Vector3 normal = link.transform.forward;
Vector3 tangent = Vector3.Dot (normal, (Vector3)(other.Position - this.Position) ) > 0 ? link.transform.right*0.5f : -link.transform.right*0.5f;
Debug.DrawLine ( link.transform.position -tangent * link.portalWidth, link.transform.position +tangent * link.portalWidth, Color.red);
Debug.DrawRay ( link.transform.position -tangent * link.portalWidth, Vector3.up*5, Color.red);
Debug.Break ();
left.Add ( link.transform.position -tangent * link.portalWidth );
right.Add (link.transform.position +tangent * link.portalWidth );*/
}
return true;
}
public GraphNode GetOther ( GraphNode a ) {
if ( this.connections.Length < 2 ) return null;
if ( this.connections.Length != 2 ) throw new System.Exception ("Invalid NodeLink3Node. Expected 2 connections, found " + this.connections.Length);
return a == connections[0] ? (connections[1] as NodeLink3Node).GetOtherInternal(this) : (connections[0] as NodeLink3Node).GetOtherInternal(this);
}
GraphNode GetOtherInternal ( GraphNode a ) {
if ( this.connections.Length < 2 ) return null;
return a == connections[0] ? connections[1] : connections[0];
}
}
[AddComponentMenu("Pathfinding/Link3")]
public class NodeLink3 : GraphModifier {
protected static Dictionary<GraphNode,NodeLink3> reference = new Dictionary<GraphNode,NodeLink3>();
public static NodeLink3 GetNodeLink (GraphNode node) {
NodeLink3 v;
reference.TryGetValue (node, out v);
return v;
}
/** End position of the link */
public Transform end;
/** The connection will be this times harder/slower to traverse.
* Note that values lower than one will not always make the pathfinder choose this path instead of another path even though this one should
* lead to a lower total cost unless you also adjust the Heuristic Scale in A* Inspector -> Settings -> Pathfinding or disable the heuristic altogether.
*/
public float costFactor = 1.0f;
/** Make a one-way connection */
public bool oneWay = false;
/* Delete existing connection instead of adding one */
//public bool deleteConnection = false;
//private bool createHiddenNodes = true;
public Transform StartTransform {
get { return transform; }
}
public Transform EndTransform {
get { return end; }
}
NodeLink3Node startNode;
NodeLink3Node endNode;
MeshNode connectedNode1, connectedNode2;
Vector3 clamped1, clamped2;
bool postScanCalled = false;
public GraphNode StartNode {
get { return startNode; }
}
public GraphNode EndNode {
get { return endNode; }
}
public override void OnPostScan () {
if (AstarPath.active.isScanning) {
InternalOnPostScan ();
} else {
AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (delegate (bool force) {
InternalOnPostScan ();
return true;
}));
}
}
public void InternalOnPostScan () {
if ( AstarPath.active.astarData.pointGraph == null ) {
AstarPath.active.astarData.AddGraph ( new PointGraph () );
}
//Get nearest nodes from the first point graph, assuming both start and end transforms are nodes
startNode = AstarPath.active.astarData.pointGraph.AddNode ( new NodeLink3Node(AstarPath.active), (Int3)StartTransform.position );//AstarPath.active.astarData.pointGraph.GetNearest(StartTransform.position).node as PointNode;
startNode.link = this;
endNode = AstarPath.active.astarData.pointGraph.AddNode ( new NodeLink3Node(AstarPath.active), (Int3)EndTransform.position ); //AstarPath.active.astarData.pointGraph.GetNearest(EndTransform.position).node as PointNode;
endNode.link = this;
connectedNode1 = null;
connectedNode2 = null;
if (startNode == null || endNode == null) {
startNode = null;
endNode = null;
return;
}
postScanCalled = true;
reference[startNode] = this;
reference[endNode] = this;
Apply( true );
}
public override void OnGraphsPostUpdate () {
//if (connectedNode1 != null && connectedNode2 != null) {
if (!AstarPath.active.isScanning) {
if (connectedNode1 != null && connectedNode1.Destroyed) {
connectedNode1 = null;
}
if (connectedNode2 != null && connectedNode2.Destroyed) {
connectedNode2 = null;
}
if (!postScanCalled) {
OnPostScan();
} else {
//OnPostScan will also call this method
Apply( false );
}
}
}
protected override void OnEnable () {
base.OnEnable();
if (AstarPath.active != null && AstarPath.active.astarData != null && AstarPath.active.astarData.pointGraph != null) {
OnGraphsPostUpdate ();
}
}
protected override void OnDisable () {
base.OnDisable();
postScanCalled = false;
if (startNode != null) reference.Remove(startNode);
if (endNode != null) reference.Remove(endNode);
if (startNode != null && endNode != null) {
startNode.RemoveConnection (endNode);
endNode.RemoveConnection (startNode);
if (connectedNode1 != null && connectedNode2 != null) {
startNode.RemoveConnection (connectedNode1);
connectedNode1.RemoveConnection (startNode);
endNode.RemoveConnection (connectedNode2);
connectedNode2.RemoveConnection (endNode);
}
}
}
void RemoveConnections (GraphNode node) {
//TODO, might be better to replace connection
node.ClearConnections (true);
}
[ContextMenu ("Recalculate neighbours")]
void ContextApplyForce () {
if (Application.isPlaying) {
Apply ( true );
if ( AstarPath.active != null ) {
AstarPath.active.FloodFill ();
}
}
}
public void Apply ( bool forceNewCheck ) {
//TODO
//This function assumes that connections from the n1,n2 nodes never need to be removed in the future (e.g because the nodes move or something)
NNConstraint nn = NNConstraint.None;
nn.distanceXZ = true;
int graph = (int)startNode.GraphIndex;
//Search all graphs but the one which start and end nodes are on
nn.graphMask = ~(1 << graph);
bool same = true;
if (true) {
NNInfo n1 = AstarPath.active.GetNearest(StartTransform.position, nn);
same &= n1.node == connectedNode1 && n1.node != null;
connectedNode1 = n1.node as MeshNode;
clamped1 = n1.clampedPosition;
if ( connectedNode1 != null ) Debug.DrawRay ( (Vector3)connectedNode1.position, Vector3.up*5,Color.red);
}
if (true) {
NNInfo n2 = AstarPath.active.GetNearest(EndTransform.position, nn);
same &= n2.node == connectedNode2 && n2.node != null;
connectedNode2 = n2.node as MeshNode;
clamped2 = n2.clampedPosition;
if ( connectedNode2 != null ) Debug.DrawRay ( (Vector3)connectedNode2.position, Vector3.up*5,Color.cyan);
}
if (connectedNode2 == null || connectedNode1 == null) return;
startNode.SetPosition ( (Int3)StartTransform.position );
endNode.SetPosition ( (Int3)EndTransform.position );
if ( same && !forceNewCheck ) return;
RemoveConnections(startNode);
RemoveConnections(endNode);
uint cost = (uint)Mathf.RoundToInt(((Int3)(StartTransform.position-EndTransform.position)).costMagnitude*costFactor);
startNode.AddConnection (endNode, cost);
endNode.AddConnection(startNode, cost);
Int3 dir = connectedNode2.position - connectedNode1.position;
for ( int a=0;a<connectedNode1.GetVertexCount();a++) {
Int3 va1 = connectedNode1.GetVertex ( a );
Int3 va2 = connectedNode1.GetVertex ( (a+1) % connectedNode1.GetVertexCount() );
if ( Int3.DotLong ( (va2-va1).Normal2D (), dir ) > 0 ) continue;
for ( int b=0;b<connectedNode2.GetVertexCount();b++) {
Int3 vb1 = connectedNode2.GetVertex ( b );
Int3 vb2 = connectedNode2.GetVertex ( (b+1) % connectedNode2.GetVertexCount() );
if ( Int3.DotLong ( (vb2-vb1).Normal2D (), dir ) < 0 ) continue;
//Debug.DrawLine ((Vector3)va1, (Vector3)va2, Color.magenta);
//Debug.DrawLine ((Vector3)vb1, (Vector3)vb2, Color.cyan);
//Debug.Break ();
if ( Int3.Angle ( (vb2-vb1), (va2-va1) ) > (170.0/360.0f)*Mathf.PI*2 ) {
float t1 = 0;
float t2 = 1;
t2 = System.Math.Min ( t2, AstarMath.NearestPointFactor ( va1, va2, vb1 ) );
t1 = System.Math.Max ( t1, AstarMath.NearestPointFactor ( va1, va2, vb2 ) );
if ( t2 < t1 ) {
Debug.LogError ("Wait wut!? " + t1 + " " + t2 + " " + va1 + " " + va2 + " " + vb1 + " " + vb2+"\nTODO, fix this error" );
} else {
Vector3 pa = (Vector3)(va2-va1)*t1 + (Vector3)va1;
Vector3 pb = (Vector3)(va2-va1)*t2 + (Vector3)va1;
startNode.portalA = pa;
startNode.portalB = pb;
endNode.portalA = pb;
endNode.portalB = pa;
//Add connections between nodes, or replace old connections if existing
connectedNode1.AddConnection(startNode, (uint)Mathf.RoundToInt (((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
connectedNode2.AddConnection(endNode, (uint)Mathf.RoundToInt (((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
startNode.AddConnection(connectedNode1, (uint)Mathf.RoundToInt (((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
endNode.AddConnection(connectedNode2, (uint)Mathf.RoundToInt (((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
return;
}
}
}
}
}
void DrawCircle (Vector3 o, float r, int detail, Color col) {
Vector3 prev = new Vector3(Mathf.Cos(0)*r,0,Mathf.Sin(0)*r) + o;
Gizmos.color = col;
for (int i=0;i<=detail;i++) {
float t = (i*Mathf.PI*2f)/detail;
Vector3 c = new Vector3(Mathf.Cos(t)*r,0,Mathf.Sin(t)*r) + o;
Gizmos.DrawLine(prev,c);
prev = c;
}
}
private readonly static Color GizmosColor = new Color(206.0f/255.0f,136.0f/255.0f,48.0f/255.0f,0.5f);
private readonly static Color GizmosColorSelected = new Color(235.0f/255.0f,123.0f/255.0f,32.0f/255.0f,1.0f);
void DrawGizmoBezier (Vector3 p1, Vector3 p2) {
Vector3 dir = p2-p1;
if (dir == Vector3.zero) return;
Vector3 normal = Vector3.Cross (Vector3.up,dir);
Vector3 normalUp = Vector3.Cross (dir,normal);
normalUp = normalUp.normalized;
normalUp *= dir.magnitude*0.1f;
Vector3 p1c = p1+normalUp;
Vector3 p2c = p2+normalUp;
Vector3 prev = p1;
for (int i=1;i<=20;i++) {
float t = i/20.0f;
Vector3 p = AstarMath.CubicBezier (p1,p1c,p2c,p2,t);
Gizmos.DrawLine (prev,p);
prev = p;
}
}
public virtual void OnDrawGizmosSelected () {
OnDrawGizmos(true);
}
public void OnDrawGizmos () {
OnDrawGizmos (false);
}
public void OnDrawGizmos (bool selected) {
Color col = selected ? GizmosColorSelected : GizmosColor;
if (StartTransform != null) {
DrawCircle(StartTransform.position,0.4f,10,col);
}
if (EndTransform != null) {
DrawCircle(EndTransform.position,0.4f,10,col);
}
//Gizmos.DrawLine ( transform.position - transform.right*0.5f*portalWidth, transform.position + transform.right*0.5f*portalWidth );
if (StartTransform != null && EndTransform != null) {
Gizmos.color = col;
DrawGizmoBezier (StartTransform.position,EndTransform.position);
if (selected) {
Vector3 cross = Vector3.Cross (Vector3.up, (EndTransform.position-StartTransform.position)).normalized;
DrawGizmoBezier (StartTransform.position+cross*0.1f,EndTransform.position+cross*0.1f);
DrawGizmoBezier (StartTransform.position-cross*0.1f,EndTransform.position-cross*0.1f);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32 {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Diagnostics.Tracing;
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods {
[DllImport(Win32Native.KERNEL32, EntryPoint="GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetTimeZoneInformation(out Win32Native.TimeZoneInformation lpTimeZoneInformation);
[DllImport(Win32Native.KERNEL32, EntryPoint="GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation);
//
// BOOL GetFileMUIPath(
// DWORD dwFlags,
// PCWSTR pcwszFilePath,
// PWSTR pwszLanguage,
// PULONG pcchLanguage,
// PWSTR pwszFileMUIPath,
// PULONG pcchFileMUIPath,
// PULONGLONG pululEnumerator
// );
//
[DllImport(Win32Native.KERNEL32, EntryPoint="GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetFileMUIPath(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
String filePath,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder language,
ref int languageLength,
[Out, MarshalAs(UnmanagedType.LPWStr)]
StringBuilder fileMuiPath,
ref int fileMuiPathLength,
ref Int64 enumerator);
[DllImport(Win32Native.USER32, EntryPoint="LoadStringW", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
internal static extern int LoadString(SafeLibraryHandle handle, int id, [Out] StringBuilder buffer, int bufferLength);
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool FreeLibrary(IntPtr hModule);
[SuppressUnmanagedCodeSecurityAttribute()]
internal static unsafe class ManifestEtw
{
//
// Constants error coded returned by ETW APIs
//
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 534;
// Occurs when filled buffers are trying to flush to disk,
// but disk IOs are not happening fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NOT_SUPPORTED = 50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
//
// ETW Methods
//
internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0;
internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1;
internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2;
//
// Callback
//
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In][Out]ref long registrationHandle
);
//
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
//
// Writing (Publishing/Logging) APIs
//
//
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWrite(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keyword,
[In] string msg
);
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct EVENT_FILTER_DESCRIPTOR
{
public long Ptr;
public int Size;
public int Type;
};
/// <summary>
/// Call the ETW native API EventWriteTransfer and checks for invalid argument error.
/// The implementation of EventWriteTransfer on some older OSes (Windows 2008) does not accept null relatedActivityId.
/// So, for these cases we will retry the call with an empty Guid.
/// </summary>
internal static int EventWriteTransferWrapper(long registrationHandle,
ref EventDescriptor eventDescriptor,
Guid* activityId,
Guid* relatedActivityId,
int userDataCount,
EventProvider.EventData* userData)
{
int HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, relatedActivityId, userDataCount, userData);
if (HResult == ERROR_INVALID_PARAMETER && relatedActivityId == null)
{
Guid emptyGuid = Guid.Empty;
HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, &emptyGuid, userDataCount, userData);
}
return HResult;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
private static extern int EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
internal enum ActivityControl : uint
{
EVENT_ACTIVITY_CTRL_GET_ID = 1,
EVENT_ACTIVITY_CTRL_SET_ID = 2,
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventActivityIdControl([In] ActivityControl ControlCode, [In][Out] ref Guid ActivityId);
internal enum EVENT_INFO_CLASS
{
BinaryTrackInfo,
SetEnableAllKeywords,
SetTraits,
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventSetInformation", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventSetInformation(
[In] long registrationHandle,
[In] EVENT_INFO_CLASS informationClass,
[In] void* eventInformation,
[In] int informationLength);
// Support for EnumerateTraceGuidsEx
internal enum TRACE_QUERY_INFO_CLASS
{
TraceGuidQueryList,
TraceGuidQueryInfo,
TraceGuidQueryProcess,
TraceStackTracingInfo,
MaxTraceSetInfoClass
};
internal struct TRACE_GUID_INFO
{
public int InstanceCount;
public int Reserved;
};
internal struct TRACE_PROVIDER_INSTANCE_INFO
{
public int NextOffset;
public int EnableCount;
public int Pid;
public int Flags;
};
internal struct TRACE_ENABLE_INFO
{
public int IsEnabled;
public byte Level;
public byte Reserved1;
public ushort LoggerId;
public int EnableProperty;
public int Reserved2;
public long MatchAnyKeyword;
public long MatchAllKeyword;
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EnumerateTraceGuidsEx", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EnumerateTraceGuidsEx(
TRACE_QUERY_INFO_CLASS TraceQueryInfoClass,
void* InBuffer,
int InBufferSize,
void* OutBuffer,
int OutBufferSize,
ref int ReturnLength);
}
#if FEATURE_COMINTEROP
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
[In] ref Guid iid,
[Out,MarshalAs(UnmanagedType.IInspectable)] out Object factory);
#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.
/* TEST: Usage
* DESCRIPTION: Three usage scenarios that monitor the number of live handles and GC Collections
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
// the class that holds the HandleCollectors
public class HandleCollectorTest
{
private static HandleCollector s_hc = new HandleCollector("hc", 100);
public HandleCollectorTest()
{
s_hc.Add();
}
public static int Count
{
get { return s_hc.Count; }
}
~HandleCollectorTest()
{
s_hc.Remove();
}
public static void Reset()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
s_hc = new HandleCollector("hc", 100);
}
}
public class Usage
{
private int _numTests = 0;
private int _numInstances = 100;
private const int deltaPercent = 10;
// ensures GC Collections occur when handle count exceeds maximum
private bool Case1()
{
_numTests++;
// clear GC
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
HandleCollectorTest h;
int original = GC.CollectionCount(0);
// create objects and let them go out of scope
for (int i = 0; i < _numInstances; i++)
h = new HandleCollectorTest();
h = null;
GC.WaitForPendingFinalizers();
// Collection should not have occurred
if (GC.CollectionCount(0) != original)
{
Console.WriteLine("Early collection!");
Console.WriteLine("Case 1 Failed!");
return false;
}
new HandleCollectorTest();
if ((GC.CollectionCount(0) - original) > 0)
{
Console.WriteLine("Case 1 Passed!");
return true;
}
Console.WriteLine("Expected collection did not occur!");
Console.WriteLine("Case 1 Failed!");
return false;
}
// ensures GC Collection does not occur when handle count stays below maximum
private bool Case2()
{
_numTests++;
int handleCount = 0;
for (int i = 0; i < _numInstances; i++)
{
new HandleCollectorTest();
GC.WaitForPendingFinalizers();
handleCount = HandleCollectorTest.Count;
//Note that the GC should occur when handle count is 101 but it will happen at anytime after a creation and we stick to the previous
//count to avoid error
}
Console.WriteLine("{0}, {1}", handleCount, _numInstances);
if (handleCount == _numInstances)
{
Console.WriteLine("Case 2 Passed!");
return true;
}
Console.WriteLine("Case 2 Failed!");
return false;
}
// ensures GC Collections frequency decrease by threshold
private bool Case3()
{
_numTests++;
int gcCount = GC.CollectionCount(2);
int handleCount = HandleCollectorTest.Count;
int prevHandleCount = HandleCollectorTest.Count;
List<HandleCollectorTest> list = new List<HandleCollectorTest>();
for (int i = 0; i < deltaPercent; i++)
{
do
{
HandleCollectorTest h = new HandleCollectorTest();
if ((HandleCollectorTest.Count % 2) == 0)
list.Add(h);
GC.WaitForPendingFinalizers();
if (GC.CollectionCount(2) != gcCount)
{
gcCount = GC.CollectionCount(2);
break;
}
else
handleCount = HandleCollectorTest.Count;
} while (true);
// ensure threshold is increasing
if (!CheckPercentageIncrease(handleCount, prevHandleCount))
{
Console.WriteLine("Percentage not increasing, performing Collect/WFPF/Collect cycle");
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
if (handleCount == HandleCollectorTest.Count)
{
Console.WriteLine("No handles finalized in Collect/WFPF/Collect cycle");
return false;
}
}
prevHandleCount = handleCount;
}
Console.WriteLine("Case 3 Passed!");
return true;
}
// Checks that the threshold increases are within 0.2 error margine of deltaPercent
private bool CheckPercentageIncrease(int current, int previous)
{
bool retValue = true;
if (previous != 0)
{
double value = ((double)(current - previous)) / (double)previous;
double expected = (double)deltaPercent / 100;
double errorMargin = Math.Abs((double)(value - expected) / (double)expected);
retValue = (errorMargin < 0.2);
}
return retValue;
}
public bool RunTest()
{
int numPassed = 0;
if (Case1())
{
numPassed++;
}
HandleCollectorTest.Reset();
if (Case2())
{
numPassed++;
}
HandleCollectorTest.Reset();
if (Case3())
{
numPassed++;
}
return (numPassed == _numTests);
}
public static int Main()
{
if (GC.CollectionCount(0) > 20)
{
Console.WriteLine("GC Stress is enabled");
Console.WriteLine("Abort Test");
return 100;
}
Usage u = new Usage();
if (u.RunTest())
{
Console.WriteLine();
Console.WriteLine("Test Passed!");
return 100;
}
Console.WriteLine();
Console.WriteLine("Test Failed!");
return 1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text.RegularExpressions
{
public partial class Capture
{
internal Capture() { }
public int Index { get { throw null; } }
public int Length { get { throw null; } }
public string Value { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class CaptureCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Capture>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
internal CaptureCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Text.RegularExpressions.Capture this[int i] { get { throw null; } }
public object SyncRoot { get { throw null; } }
System.Text.RegularExpressions.Capture System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.this[int index] { get { throw null; } set { } }
bool System.Collections.IList.IsFixedSize { get { throw null; } }
object System.Collections.IList.this[int index] { get { throw null; } set { } }
public void CopyTo(System.Array array, int arrayIndex) { }
public void CopyTo(System.Text.RegularExpressions.Capture[] array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Add(System.Text.RegularExpressions.Capture item) { }
void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Clear() { }
bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Contains(System.Text.RegularExpressions.Capture item) { throw null; }
bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Remove(System.Text.RegularExpressions.Capture item) { throw null; }
System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Capture> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>.GetEnumerator() { throw null; }
int System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.IndexOf(System.Text.RegularExpressions.Capture item) { throw null; }
void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.Insert(int index, System.Text.RegularExpressions.Capture item) { }
void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.RemoveAt(int index) { }
int System.Collections.IList.Add(object value) { throw null; }
void System.Collections.IList.Clear() { }
bool System.Collections.IList.Contains(object value) { throw null; }
int System.Collections.IList.IndexOf(object value) { throw null; }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
void System.Collections.IList.RemoveAt(int index) { }
}
public partial class Group : System.Text.RegularExpressions.Capture
{
internal Group() { }
public System.Text.RegularExpressions.CaptureCollection Captures { get { throw null; } }
public string Name { get { throw null; } }
public bool Success { get { throw null; } }
public static System.Text.RegularExpressions.Group Synchronized(System.Text.RegularExpressions.Group inner) { throw null; }
}
public partial class GroupCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>, System.Collections.Generic.IList<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Group>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
internal GroupCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Text.RegularExpressions.Group this[int groupnum] { get { throw null; } }
public System.Text.RegularExpressions.Group this[string groupname] { get { throw null; } }
public object SyncRoot { get { throw null; } }
System.Text.RegularExpressions.Group System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.this[int index] { get { throw null; } set { } }
bool System.Collections.IList.IsFixedSize { get { throw null; } }
object System.Collections.IList.this[int index] { get { throw null; } set { } }
public void CopyTo(System.Array array, int arrayIndex) { }
public void CopyTo(System.Text.RegularExpressions.Group[] array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Add(System.Text.RegularExpressions.Group item) { }
void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Clear() { }
bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Contains(System.Text.RegularExpressions.Group item) { throw null; }
bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Remove(System.Text.RegularExpressions.Group item) { throw null; }
System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Group> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>.GetEnumerator() { throw null; }
int System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.IndexOf(System.Text.RegularExpressions.Group item) { throw null; }
void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.Insert(int index, System.Text.RegularExpressions.Group item) { }
void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.RemoveAt(int index) { }
int System.Collections.IList.Add(object value) { throw null; }
void System.Collections.IList.Clear() { }
bool System.Collections.IList.Contains(object value) { throw null; }
int System.Collections.IList.IndexOf(object value) { throw null; }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
void System.Collections.IList.RemoveAt(int index) { }
}
public partial class Match : System.Text.RegularExpressions.Group
{
internal Match() { }
public static System.Text.RegularExpressions.Match Empty { get { throw null; } }
public virtual System.Text.RegularExpressions.GroupCollection Groups { get { throw null; } }
public System.Text.RegularExpressions.Match NextMatch() { throw null; }
public virtual string Result(string replacement) { throw null; }
public static System.Text.RegularExpressions.Match Synchronized(System.Text.RegularExpressions.Match inner) { throw null; }
}
public partial class MatchCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>, System.Collections.Generic.IList<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Match>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
internal MatchCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Text.RegularExpressions.Match this[int i] { get { throw null; } }
public object SyncRoot { get { throw null; } }
System.Text.RegularExpressions.Match System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.this[int index] { get { throw null; } set { } }
bool System.Collections.IList.IsFixedSize { get { throw null; } }
object System.Collections.IList.this[int index] { get { throw null; } set { } }
public void CopyTo(System.Array array, int arrayIndex) { }
public void CopyTo(System.Text.RegularExpressions.Match[] array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Add(System.Text.RegularExpressions.Match item) { }
void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Clear() { }
bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Contains(System.Text.RegularExpressions.Match item) { throw null; }
bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Remove(System.Text.RegularExpressions.Match item) { throw null; }
System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Match> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>.GetEnumerator() { throw null; }
int System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.IndexOf(System.Text.RegularExpressions.Match item) { throw null; }
void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.Insert(int index, System.Text.RegularExpressions.Match item) { }
void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.RemoveAt(int index) { }
int System.Collections.IList.Add(object value) { throw null; }
void System.Collections.IList.Clear() { }
bool System.Collections.IList.Contains(object value) { throw null; }
int System.Collections.IList.IndexOf(object value) { throw null; }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
void System.Collections.IList.RemoveAt(int index) { }
}
public delegate string MatchEvaluator(System.Text.RegularExpressions.Match match);
public partial class Regex : System.Runtime.Serialization.ISerializable
{
protected internal System.Collections.Hashtable capnames;
protected internal System.Collections.Hashtable caps;
protected internal int capsize;
protected internal string[] capslist;
protected internal System.Text.RegularExpressions.RegexRunnerFactory factory;
public static readonly System.TimeSpan InfiniteMatchTimeout;
protected internal System.TimeSpan internalMatchTimeout;
protected internal string pattern;
protected internal System.Text.RegularExpressions.RegexOptions roptions;
protected Regex() { }
protected Regex(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public Regex(string pattern) { }
public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options) { }
public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { }
public static int CacheSize { get { throw null; } set { } }
[System.CLSCompliantAttribute(false)]
protected System.Collections.IDictionary CapNames { get { throw null; } set { } }
[System.CLSCompliantAttribute(false)]
protected System.Collections.IDictionary Caps { get { throw null; } set { } }
public System.TimeSpan MatchTimeout { get { throw null; } }
public System.Text.RegularExpressions.RegexOptions Options { get { throw null; } }
public bool RightToLeft { get { throw null; } }
//REFEMIT public static void CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname) { }
//REFEMIT public static void CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes) { }
//REFEMIT public static void CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile) { }
public static string Escape(string str) { throw null; }
public string[] GetGroupNames() { throw null; }
public int[] GetGroupNumbers() { throw null; }
public string GroupNameFromNumber(int i) { throw null; }
public int GroupNumberFromName(string name) { throw null; }
protected void InitializeReferences() { }
public bool IsMatch(string input) { throw null; }
public bool IsMatch(string input, int startat) { throw null; }
public static bool IsMatch(string input, string pattern) { throw null; }
public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public System.Text.RegularExpressions.Match Match(string input) { throw null; }
public System.Text.RegularExpressions.Match Match(string input, int startat) { throw null; }
public System.Text.RegularExpressions.Match Match(string input, int beginning, int length) { throw null; }
public static System.Text.RegularExpressions.Match Match(string input, string pattern) { throw null; }
public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public System.Text.RegularExpressions.MatchCollection Matches(string input) { throw null; }
public System.Text.RegularExpressions.MatchCollection Matches(string input, int startat) { throw null; }
public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern) { throw null; }
public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public string Replace(string input, string replacement) { throw null; }
public string Replace(string input, string replacement, int count) { throw null; }
public string Replace(string input, string replacement, int count, int startat) { throw null; }
public static string Replace(string input, string pattern, string replacement) { throw null; }
public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; }
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; }
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count) { throw null; }
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat) { throw null; }
public string[] Split(string input) { throw null; }
public string[] Split(string input, int count) { throw null; }
public string[] Split(string input, int count, int startat) { throw null; }
public static string[] Split(string input, string pattern) { throw null; }
public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
public static string Unescape(string str) { throw null; }
protected bool UseOptionC() { throw null; }
protected bool UseOptionR() { throw null; }
protected internal static void ValidateMatchTimeout(System.TimeSpan matchTimeout) { }
}
public partial class RegexMatchTimeoutException : System.TimeoutException, System.Runtime.Serialization.ISerializable
{
public RegexMatchTimeoutException() { }
protected RegexMatchTimeoutException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public RegexMatchTimeoutException(string message) { }
public RegexMatchTimeoutException(string message, System.Exception inner) { }
public RegexMatchTimeoutException(string regexInput, string regexPattern, System.TimeSpan matchTimeout) { }
public string Input { get { throw null; } }
public System.TimeSpan MatchTimeout { get { throw null; } }
public string Pattern { get { throw null; } }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
}
[System.FlagsAttribute]
public enum RegexOptions
{
Compiled = 8,
CultureInvariant = 512,
ECMAScript = 256,
ExplicitCapture = 4,
IgnoreCase = 1,
IgnorePatternWhitespace = 32,
Multiline = 2,
None = 0,
RightToLeft = 64,
Singleline = 16,
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public abstract partial class RegexRunner
{
protected internal int[] runcrawl;
protected internal int runcrawlpos;
protected internal System.Text.RegularExpressions.Match runmatch;
protected internal System.Text.RegularExpressions.Regex runregex;
protected internal int[] runstack;
protected internal int runstackpos;
protected internal string runtext;
protected internal int runtextbeg;
protected internal int runtextend;
protected internal int runtextpos;
protected internal int runtextstart;
protected internal int[] runtrack;
protected internal int runtrackcount;
protected internal int runtrackpos;
protected internal RegexRunner() { }
protected void Capture(int capnum, int start, int end) { }
protected static bool CharInClass(char ch, string charClass) { throw null; }
protected static bool CharInSet(char ch, string @set, string category) { throw null; }
protected void CheckTimeout() { }
protected void Crawl(int i) { }
protected int Crawlpos() { throw null; }
protected void DoubleCrawl() { }
protected void DoubleStack() { }
protected void DoubleTrack() { }
protected void EnsureStorage() { }
protected abstract bool FindFirstChar();
protected abstract void Go();
protected abstract void InitTrackCount();
protected bool IsBoundary(int index, int startpos, int endpos) { throw null; }
protected bool IsECMABoundary(int index, int startpos, int endpos) { throw null; }
protected bool IsMatched(int cap) { throw null; }
protected int MatchIndex(int cap) { throw null; }
protected int MatchLength(int cap) { throw null; }
protected int Popcrawl() { throw null; }
protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick) { throw null; }
protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, System.TimeSpan timeout) { throw null; }
protected void TransferCapture(int capnum, int uncapnum, int start, int end) { }
protected void Uncapture() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public abstract partial class RegexRunnerFactory
{
protected RegexRunnerFactory() { }
protected internal abstract System.Text.RegularExpressions.RegexRunner CreateInstance();
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.lang{
public class Function {
public Function(int arity, int type){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
this.__fn_type = type;
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
this.__hx_arity = arity;
}
#line default
}
public virtual object __hx_invokeDynamic(global::Array __fn_dynargs){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
switch (( (( __fn_dynargs == default(global::Array) )) ? (0) : (((int) (global::haxe.lang.Runtime.getField_f(__fn_dynargs, "length", 520590566, true)) )) )){
case 0:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke0_o();
}
case 1:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke1_o(0.0, ((object) (__fn_dynargs[0]) ));
}
case 2:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke2_o(0.0, ((object) (__fn_dynargs[0]) ), 0.0, ((object) (__fn_dynargs[1]) ));
}
case 3:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke3_o(0.0, ((object) (__fn_dynargs[0]) ), 0.0, ((object) (__fn_dynargs[1]) ), 0.0, ((object) (__fn_dynargs[2]) ));
}
case 4:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke4_o(0.0, ((object) (__fn_dynargs[0]) ), 0.0, ((object) (__fn_dynargs[1]) ), 0.0, ((object) (__fn_dynargs[2]) ), 0.0, ((object) (__fn_dynargs[3]) ));
}
case 5:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke5_o(0.0, ((object) (__fn_dynargs[0]) ), 0.0, ((object) (__fn_dynargs[1]) ), 0.0, ((object) (__fn_dynargs[2]) ), 0.0, ((object) (__fn_dynargs[3]) ), 0.0, ((object) (__fn_dynargs[4]) ));
}
case 6:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke6_o(0.0, ((object) (__fn_dynargs[0]) ), 0.0, ((object) (__fn_dynargs[1]) ), 0.0, ((object) (__fn_dynargs[2]) ), 0.0, ((object) (__fn_dynargs[3]) ), 0.0, ((object) (__fn_dynargs[4]) ), 0.0, ((object) (__fn_dynargs[5]) ));
}
default:
{
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Too many arguments");
}
}
}
#line default
}
public int __fn_type;
public int __hx_arity;
public virtual object __hx_invoke6_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5, double __fn_float6, object __fn_dyn6){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke6_f(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3, __fn_float4, __fn_dyn4, __fn_float5, __fn_dyn5, __fn_float6, __fn_dyn6);
}
}
#line default
}
public virtual double __hx_invoke6_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5, double __fn_float6, object __fn_dyn6){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke6_o(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3, __fn_float4, __fn_dyn4, __fn_float5, __fn_dyn5, __fn_float6, __fn_dyn6))) );
}
}
#line default
}
public virtual object __hx_invoke5_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke5_f(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3, __fn_float4, __fn_dyn4, __fn_float5, __fn_dyn5);
}
}
#line default
}
public virtual double __hx_invoke5_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke5_o(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3, __fn_float4, __fn_dyn4, __fn_float5, __fn_dyn5))) );
}
}
#line default
}
public virtual object __hx_invoke4_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke4_f(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3, __fn_float4, __fn_dyn4);
}
}
#line default
}
public virtual double __hx_invoke4_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke4_o(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3, __fn_float4, __fn_dyn4))) );
}
}
#line default
}
public virtual object __hx_invoke3_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke3_f(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3);
}
}
#line default
}
public virtual double __hx_invoke3_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke3_o(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2, __fn_float3, __fn_dyn3))) );
}
}
#line default
}
public virtual object __hx_invoke2_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke2_f(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2);
}
}
#line default
}
public virtual double __hx_invoke2_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke2_o(__fn_float1, __fn_dyn1, __fn_float2, __fn_dyn2))) );
}
}
#line default
}
public virtual object __hx_invoke1_o(double __fn_float1, object __fn_dyn1){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke1_f(__fn_float1, __fn_dyn1);
}
}
#line default
}
public virtual double __hx_invoke1_f(double __fn_float1, object __fn_dyn1){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke1_o(__fn_float1, __fn_dyn1))) );
}
}
#line default
}
public virtual object __hx_invoke0_o(){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 1 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invoke0_f();
}
}
#line default
}
public virtual double __hx_invoke0_f(){
unchecked {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
if (( this.__fn_type != 0 )) {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Wrong number of arguments");
}
else {
#line 30 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invoke0_o())) );
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.lang{
public class VarArgsBase : global::haxe.lang.Function {
public VarArgsBase(int arity, int type) : base(arity, type){
unchecked {
}
#line default
}
public override object __hx_invokeDynamic(global::Array dynArgs){
unchecked {
#line 42 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
throw global::haxe.lang.HaxeException.wrap("Abstract implementation");
}
#line default
}
public override object __hx_invoke6_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5, double __fn_float6, object __fn_dyn6){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn4, global::haxe.lang.Runtime.undefined)) ? (__fn_float4) : (((object) (__fn_dyn4) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn5, global::haxe.lang.Runtime.undefined)) ? (__fn_float5) : (((object) (__fn_dyn5) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn6, global::haxe.lang.Runtime.undefined)) ? (__fn_float6) : (((object) (__fn_dyn6) )) )}));
}
#line default
}
public override double __hx_invoke6_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5, double __fn_float6, object __fn_dyn6){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn4, global::haxe.lang.Runtime.undefined)) ? (__fn_float4) : (((object) (__fn_dyn4) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn5, global::haxe.lang.Runtime.undefined)) ? (__fn_float5) : (((object) (__fn_dyn5) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn6, global::haxe.lang.Runtime.undefined)) ? (__fn_float6) : (((object) (__fn_dyn6) )) )})))) );
}
#line default
}
public override object __hx_invoke5_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn4, global::haxe.lang.Runtime.undefined)) ? (__fn_float4) : (((object) (__fn_dyn4) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn5, global::haxe.lang.Runtime.undefined)) ? (__fn_float5) : (((object) (__fn_dyn5) )) )}));
}
#line default
}
public override double __hx_invoke5_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4, double __fn_float5, object __fn_dyn5){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn4, global::haxe.lang.Runtime.undefined)) ? (__fn_float4) : (((object) (__fn_dyn4) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn5, global::haxe.lang.Runtime.undefined)) ? (__fn_float5) : (((object) (__fn_dyn5) )) )})))) );
}
#line default
}
public override object __hx_invoke4_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn4, global::haxe.lang.Runtime.undefined)) ? (__fn_float4) : (((object) (__fn_dyn4) )) )}));
}
#line default
}
public override double __hx_invoke4_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3, double __fn_float4, object __fn_dyn4){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn4, global::haxe.lang.Runtime.undefined)) ? (__fn_float4) : (((object) (__fn_dyn4) )) )})))) );
}
#line default
}
public override object __hx_invoke3_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) )}));
}
#line default
}
public override double __hx_invoke3_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2, double __fn_float3, object __fn_dyn3){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn3, global::haxe.lang.Runtime.undefined)) ? (__fn_float3) : (((object) (__fn_dyn3) )) )})))) );
}
#line default
}
public override object __hx_invoke2_o(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) )}));
}
#line default
}
public override double __hx_invoke2_f(double __fn_float1, object __fn_dyn1, double __fn_float2, object __fn_dyn2){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) ), ( (global::haxe.lang.Runtime.eq(__fn_dyn2, global::haxe.lang.Runtime.undefined)) ? (__fn_float2) : (((object) (__fn_dyn2) )) )})))) );
}
#line default
}
public override object __hx_invoke1_o(double __fn_float1, object __fn_dyn1){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) )}));
}
#line default
}
public override double __hx_invoke1_f(double __fn_float1, object __fn_dyn1){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(new global::Array<object>(new object[]{( (global::haxe.lang.Runtime.eq(__fn_dyn1, global::haxe.lang.Runtime.undefined)) ? (__fn_float1) : (((object) (__fn_dyn1) )) )})))) );
}
#line default
}
public override object __hx_invoke0_o(){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return this.__hx_invokeDynamic(default(global::Array<object>));
}
#line default
}
public override double __hx_invoke0_f(){
unchecked {
#line 38 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.__hx_invokeDynamic(default(global::Array<object>)))) );
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.lang{
public class VarArgsFunction : global::haxe.lang.VarArgsBase {
public VarArgsFunction(global::haxe.lang.Function fun) : base(-1, -1){
unchecked {
#line 54 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
this.fun = fun;
}
#line default
}
public global::haxe.lang.Function fun;
public override object __hx_invokeDynamic(global::Array dynArgs){
unchecked {
#line 59 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return ((object) (this.fun.__hx_invoke1_o(default(double), dynArgs)) );
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.lang{
public class Closure : global::haxe.lang.VarArgsBase {
public Closure(object obj, string field, int hash) : base(-1, -1){
unchecked {
#line 72 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
this.obj = obj;
this.field = field;
this.hash = hash;
}
#line default
}
public object obj;
public string field;
public int hash;
public override object __hx_invokeDynamic(global::Array dynArgs){
unchecked {
#line 79 "C:\\HaxeToolkit\\haxe\\std\\cs\\internal\\Function.hx"
return global::haxe.lang.Runtime.callField(this.obj, this.field, this.hash, dynArgs);
}
#line default
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using Animation = OpenSim.Framework.Animation;
namespace OpenSim.Region.Framework.Scenes.Animation
{
[Serializable]
public class AnimationSet
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private OpenSim.Framework.Animation m_implicitDefaultAnimation = new OpenSim.Framework.Animation();
private OpenSim.Framework.Animation m_defaultAnimation = new OpenSim.Framework.Animation();
private List<OpenSim.Framework.Animation> m_animations = new List<OpenSim.Framework.Animation>();
public OpenSim.Framework.Animation DefaultAnimation
{
get { return m_defaultAnimation; }
}
public OpenSim.Framework.Animation ImplicitDefaultAnimation
{
get { return m_implicitDefaultAnimation; }
}
public AnimationSet()
{
ResetDefaultAnimation();
}
public AnimationSet(OSDArray pArray)
{
ResetDefaultAnimation();
FromOSDArray(pArray);
}
public bool HasAnimation(UUID animID)
{
if (m_defaultAnimation.AnimID == animID)
return true;
for (int i = 0; i < m_animations.Count; ++i)
{
if (m_animations[i].AnimID == animID)
return true;
}
return false;
}
public bool Add(UUID animID, int sequenceNum, UUID objectID)
{
lock (m_animations)
{
if (!HasAnimation(animID))
{
m_animations.Add(new OpenSim.Framework.Animation(animID, sequenceNum, objectID));
return true;
}
}
return false;
}
/// <summary>
/// Remove the specified animation
/// </summary>
/// <param name='animID'></param>
/// <param name='allowNoDefault'>
/// If true, then the default animation can be entirely removed.
/// If false, then removing the default animation will reset it to the simulator default (currently STAND).
/// </param>
public bool Remove(UUID animID, bool allowNoDefault)
{
lock (m_animations)
{
if (m_defaultAnimation.AnimID == animID)
{
if (allowNoDefault)
m_defaultAnimation = new OpenSim.Framework.Animation(UUID.Zero, 1, UUID.Zero);
else
ResetDefaultAnimation();
}
else if (HasAnimation(animID))
{
for (int i = 0; i < m_animations.Count; i++)
{
if (m_animations[i].AnimID == animID)
{
m_animations.RemoveAt(i);
return true;
}
}
}
}
return false;
}
public void Clear()
{
ResetDefaultAnimation();
m_animations.Clear();
}
/// <summary>
/// The default animation is reserved for "main" animations
/// that are mutually exclusive, e.g. flying and sitting.
/// </summary>
public bool SetDefaultAnimation(UUID animID, int sequenceNum, UUID objectID)
{
if (m_defaultAnimation.AnimID != animID)
{
m_defaultAnimation = new OpenSim.Framework.Animation(animID, sequenceNum, objectID);
m_implicitDefaultAnimation = m_defaultAnimation;
return true;
}
return false;
}
// Called from serialization only
public void SetImplicitDefaultAnimation(UUID animID, int sequenceNum, UUID objectID)
{
m_implicitDefaultAnimation = new OpenSim.Framework.Animation(animID, sequenceNum, objectID);
}
protected bool ResetDefaultAnimation()
{
return TrySetDefaultAnimation("STAND", 1, UUID.Zero);
}
/// <summary>
/// Set the animation as the default animation if it's known
/// </summary>
public bool TrySetDefaultAnimation(string anim, int sequenceNum, UUID objectID)
{
// m_log.DebugFormat(
// "[ANIMATION SET]: Setting default animation {0}, sequence number {1}, object id {2}",
// anim, sequenceNum, objectID);
if (DefaultAvatarAnimations.AnimsUUID.ContainsKey(anim))
{
return SetDefaultAnimation(DefaultAvatarAnimations.AnimsUUID[anim], sequenceNum, objectID);
}
return false;
}
public void GetArrays(out UUID[] animIDs, out int[] sequenceNums, out UUID[] objectIDs)
{
lock (m_animations)
{
int defaultSize = 0;
if (m_defaultAnimation.AnimID != UUID.Zero)
defaultSize++;
animIDs = new UUID[m_animations.Count + defaultSize];
sequenceNums = new int[m_animations.Count + defaultSize];
objectIDs = new UUID[m_animations.Count + defaultSize];
if (m_defaultAnimation.AnimID != UUID.Zero)
{
animIDs[0] = m_defaultAnimation.AnimID;
sequenceNums[0] = m_defaultAnimation.SequenceNum;
objectIDs[0] = m_defaultAnimation.ObjectID;
}
for (int i = 0; i < m_animations.Count; ++i)
{
animIDs[i + defaultSize] = m_animations[i].AnimID;
sequenceNums[i + defaultSize] = m_animations[i].SequenceNum;
objectIDs[i + defaultSize] = m_animations[i].ObjectID;
}
}
}
public OpenSim.Framework.Animation[] ToArray()
{
OpenSim.Framework.Animation[] theArray = new OpenSim.Framework.Animation[m_animations.Count];
uint i = 0;
try
{
foreach (OpenSim.Framework.Animation anim in m_animations)
theArray[i++] = anim;
}
catch
{
/* S%^t happens. Ignore. */
}
return theArray;
}
public void FromArray(OpenSim.Framework.Animation[] theArray)
{
foreach (OpenSim.Framework.Animation anim in theArray)
m_animations.Add(anim);
}
// Create representation of this AnimationSet as an OSDArray.
// First two entries in the array are the default and implicitDefault animations
// followed by the other animations.
public OSDArray ToOSDArray()
{
OSDArray ret = new OSDArray();
ret.Add(DefaultAnimation.PackUpdateMessage());
ret.Add(ImplicitDefaultAnimation.PackUpdateMessage());
foreach (OpenSim.Framework.Animation anim in m_animations)
ret.Add(anim.PackUpdateMessage());
return ret;
}
public void FromOSDArray(OSDArray pArray)
{
this.Clear();
if (pArray.Count >= 1)
{
m_defaultAnimation = new OpenSim.Framework.Animation((OSDMap)pArray[0]);
}
if (pArray.Count >= 2)
{
m_implicitDefaultAnimation = new OpenSim.Framework.Animation((OSDMap)pArray[1]);
}
for (int ii = 2; ii < pArray.Count; ii++)
{
m_animations.Add(new OpenSim.Framework.Animation((OSDMap)pArray[ii]));
}
}
// Compare two AnimationSets and return 'true' if the default animations are the same
// and all of the animations in the list are equal.
public override bool Equals(object obj)
{
AnimationSet other = obj as AnimationSet;
if (other != null)
{
if (this.DefaultAnimation.Equals(other.DefaultAnimation)
&& this.ImplicitDefaultAnimation.Equals(other.ImplicitDefaultAnimation))
{
// The defaults are the same. Is the list of animations the same?
OpenSim.Framework.Animation[] thisAnims = this.ToArray();
OpenSim.Framework.Animation[] otherAnims = other.ToArray();
if (thisAnims.Length == 0 && otherAnims.Length == 0)
return true; // the common case
if (thisAnims.Length == otherAnims.Length)
{
// Do this the hard way but since the list is usually short this won't take long.
foreach (OpenSim.Framework.Animation thisAnim in thisAnims)
{
bool found = false;
foreach (OpenSim.Framework.Animation otherAnim in otherAnims)
{
if (thisAnim.Equals(otherAnim))
{
found = true;
break;
}
}
if (!found)
{
// If anything is not in the other list, these are not equal
return false;
}
}
// Found everything in the other list. Since lists are equal length, they must be equal.
return true;
}
}
return false;
}
// Don't know what was passed, but the base system will figure it out for me.
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("dflt=");
buff.Append(DefaultAnimation.ToString());
buff.Append(",iDflt=");
if (DefaultAnimation.Equals(ImplicitDefaultAnimation))
buff.Append("same");
else
buff.Append(ImplicitDefaultAnimation.ToString());
if (m_animations.Count > 0)
{
buff.Append(",anims=");
bool firstTime = true;
foreach (OpenSim.Framework.Animation anim in m_animations)
{
if (!firstTime)
buff.Append(",");
buff.Append("<");
buff.Append(anim.ToString());
buff.Append(">");
firstTime = false;
}
}
return buff.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 ShiftRightLogical128BitLaneSByte1()
{
var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneSByte1();
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();
// 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();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmUnaryOpTest__ShiftRightLogical128BitLaneSByte1
{
private struct TestStruct
{
public Vector256<SByte> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical128BitLaneSByte1 testClass)
{
var result = Avx2.ShiftRightLogical128BitLane(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static SByte[] _data = new SByte[Op1ElementCount];
private static Vector256<SByte> _clsVar;
private Vector256<SByte> _fld;
private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable;
static ImmUnaryOpTest__ShiftRightLogical128BitLaneSByte1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
}
public ImmUnaryOpTest__ShiftRightLogical128BitLaneSByte1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[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.ShiftRightLogical128BitLane(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneSByte1();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(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<SByte> firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != 8)
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i == 31 || i == 15 ? result[i] != 0 : result[i] != 8))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<SByte>(Vector256<SByte><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Security;
using System.Globalization;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace System.Management.Automation
{
internal enum SuggestionMatchType
{
/// <summary>Match on a command.</summary>
Command = 0,
/// <summary>Match based on exception message.</summary>
Error = 1,
/// <summary>Match by running a script block.</summary>
Dynamic = 2,
/// <summary>Match by fully qualified ErrorId.</summary>
ErrorId = 3
}
#region Public HostUtilities Class
/// <summary>
/// Implements utility methods that might be used by Hosts.
/// </summary>
public static class HostUtilities
{
#region Internal Access
private static string s_checkForCommandInCurrentDirectoryScript = @"
[System.Diagnostics.DebuggerHidden()]
param()
$foundSuggestion = $false
if($lastError -and
($lastError.Exception -is ""System.Management.Automation.CommandNotFoundException""))
{
$escapedCommand = [System.Management.Automation.WildcardPattern]::Escape($lastError.TargetObject)
$foundSuggestion = @(Get-Command ($ExecutionContext.SessionState.Path.Combine(""."", $escapedCommand)) -ErrorAction Ignore).Count -gt 0
}
$foundSuggestion
";
private static string s_createCommandExistsInCurrentDirectoryScript = @"
[System.Diagnostics.DebuggerHidden()]
param([string] $formatString)
$formatString -f $lastError.TargetObject,"".\$($lastError.TargetObject)""
";
private static string s_getFuzzyMatchedCommands = @"
[System.Diagnostics.DebuggerHidden()]
param([string] $formatString)
$formatString -f [string]::Join(', ', (Get-Command $lastError.TargetObject -UseFuzzyMatch | Select-Object -First 10 -Unique -ExpandProperty Name))
";
private static ArrayList s_suggestions = InitializeSuggestions();
private static ArrayList InitializeSuggestions()
{
ArrayList suggestions = new ArrayList(
new Hashtable[]
{
NewSuggestion(
id: 1,
category: "Transactions",
matchType: SuggestionMatchType.Command,
rule: "^Start-Transaction",
suggestion: SuggestionStrings.Suggestion_StartTransaction,
enabled: true),
NewSuggestion(
id: 2,
category: "Transactions",
matchType: SuggestionMatchType.Command,
rule: "^Use-Transaction",
suggestion: SuggestionStrings.Suggestion_UseTransaction,
enabled: true),
NewSuggestion(
id: 3,
category: "General",
matchType: SuggestionMatchType.Dynamic,
rule: ScriptBlock.CreateDelayParsedScriptBlock(s_checkForCommandInCurrentDirectoryScript, isProductCode: true),
suggestion: ScriptBlock.CreateDelayParsedScriptBlock(s_createCommandExistsInCurrentDirectoryScript, isProductCode: true),
suggestionArgs: new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory) },
enabled: true)
});
if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion"))
{
suggestions.Add(
NewSuggestion(
id: 4,
category: "General",
matchType: SuggestionMatchType.ErrorId,
rule: "CommandNotFoundException",
suggestion: ScriptBlock.CreateDelayParsedScriptBlock(s_getFuzzyMatchedCommands, isProductCode: true),
suggestionArgs: new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandNotFound) },
enabled: true));
}
return suggestions;
}
#region GetProfileCommands
/// <summary>
/// Gets a PSObject whose base object is currentUserCurrentHost and with notes for the other 4 parameters.
/// </summary>
/// <param name="allUsersAllHosts">The profile file name for all users and all hosts.</param>
/// <param name="allUsersCurrentHost">The profile file name for all users and current host.</param>
/// <param name="currentUserAllHosts">The profile file name for current user and all hosts.</param>
/// <param name="currentUserCurrentHost">The profile name for current user and current host.</param>
/// <returns>A PSObject whose base object is currentUserCurrentHost and with notes for the other 4 parameters.</returns>
internal static PSObject GetDollarProfile(string allUsersAllHosts, string allUsersCurrentHost, string currentUserAllHosts, string currentUserCurrentHost)
{
PSObject returnValue = new PSObject(currentUserCurrentHost);
returnValue.Properties.Add(new PSNoteProperty("AllUsersAllHosts", allUsersAllHosts));
returnValue.Properties.Add(new PSNoteProperty("AllUsersCurrentHost", allUsersCurrentHost));
returnValue.Properties.Add(new PSNoteProperty("CurrentUserAllHosts", currentUserAllHosts));
returnValue.Properties.Add(new PSNoteProperty("CurrentUserCurrentHost", currentUserCurrentHost));
return returnValue;
}
/// <summary>
/// Gets an array of commands that can be run sequentially to set $profile and run the profile commands.
/// </summary>
/// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
/// <returns></returns>
internal static PSCommand[] GetProfileCommands(string shellId)
{
return HostUtilities.GetProfileCommands(shellId, false);
}
/// <summary>
/// Gets the object that serves as a value to $profile and the paths on it.
/// </summary>
/// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
/// <param name="useTestProfile">Used from test not to overwrite the profile file names from development boxes.</param>
/// <param name="allUsersAllHosts">Path for all users and all hosts.</param>
/// <param name="currentUserAllHosts">Path for current user and all hosts.</param>
/// <param name="allUsersCurrentHost">Path for all users current host.</param>
/// <param name="currentUserCurrentHost">Path for current user and current host.</param>
/// <param name="dollarProfile">The object that serves as a value to $profile.</param>
/// <returns></returns>
internal static void GetProfileObjectData(string shellId, bool useTestProfile, out string allUsersAllHosts, out string allUsersCurrentHost, out string currentUserAllHosts, out string currentUserCurrentHost, out PSObject dollarProfile)
{
allUsersAllHosts = HostUtilities.GetFullProfileFileName(null, false, useTestProfile);
allUsersCurrentHost = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile);
currentUserAllHosts = HostUtilities.GetFullProfileFileName(null, true, useTestProfile);
currentUserCurrentHost = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile);
dollarProfile = HostUtilities.GetDollarProfile(allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost);
}
/// <summary>
/// Gets an array of commands that can be run sequentially to set $profile and run the profile commands.
/// </summary>
/// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
/// <param name="useTestProfile">Used from test not to overwrite the profile file names from development boxes.</param>
/// <returns></returns>
internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile)
{
List<PSCommand> commands = new List<PSCommand>();
string allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost;
PSObject dollarProfile;
HostUtilities.GetProfileObjectData(shellId, useTestProfile, out allUsersAllHosts, out allUsersCurrentHost, out currentUserAllHosts, out currentUserCurrentHost, out dollarProfile);
PSCommand command = new PSCommand();
command.AddCommand("set-variable");
command.AddParameter("Name", "profile");
command.AddParameter("Value", dollarProfile);
command.AddParameter("Option", ScopedItemOptions.None);
commands.Add(command);
string[] profilePaths = new string[] { allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost };
foreach (string profilePath in profilePaths)
{
if (!System.IO.File.Exists(profilePath))
{
continue;
}
command = new PSCommand();
command.AddCommand(profilePath, false);
commands.Add(command);
}
return commands.ToArray();
}
/// <summary>
/// Used to get all profile file names for the current or all hosts and for the current or all users.
/// </summary>
/// <param name="shellId">Null for all hosts, not null for the specified host.</param>
/// <param name="forCurrentUser">False for all users, true for the current user.</param>
/// <returns>The profile file name matching the parameters.</returns>
internal static string GetFullProfileFileName(string shellId, bool forCurrentUser)
{
return HostUtilities.GetFullProfileFileName(shellId, forCurrentUser, false);
}
/// <summary>
/// Used to get all profile file names for the current or all hosts and for the current or all users.
/// </summary>
/// <param name="shellId">Null for all hosts, not null for the specified host.</param>
/// <param name="forCurrentUser">False for all users, true for the current user.</param>
/// <param name="useTestProfile">Used from test not to overwrite the profile file names from development boxes.</param>
/// <returns>The profile file name matching the parameters.</returns>
internal static string GetFullProfileFileName(string shellId, bool forCurrentUser, bool useTestProfile)
{
string basePath = null;
if (forCurrentUser)
{
basePath = Utils.GetUserConfigurationDirectory();
}
else
{
basePath = GetAllUsersFolderPath(shellId);
if (string.IsNullOrEmpty(basePath))
{
return string.Empty;
}
}
string profileName = useTestProfile ? "profile_test.ps1" : "profile.ps1";
if (!string.IsNullOrEmpty(shellId))
{
profileName = shellId + "_" + profileName;
}
string fullPath = basePath = IO.Path.Combine(basePath, profileName);
return fullPath;
}
/// <summary>
/// Used internally in GetFullProfileFileName to get the base path for all users profiles.
/// </summary>
/// <param name="shellId">The shellId to use.</param>
/// <returns>The base path for all users profiles.</returns>
private static string GetAllUsersFolderPath(string shellId)
{
string folderPath = string.Empty;
try
{
folderPath = Utils.GetApplicationBase(shellId);
}
catch (System.Security.SecurityException)
{
}
return folderPath;
}
#endregion GetProfileCommands
/// <summary>
/// Gets the first <paramref name="maxLines"/> lines of <paramref name="source"/>.
/// </summary>
/// <param name="source">String we want to limit the number of lines.</param>
/// <param name="maxLines">Maximum number of lines to be returned.</param>
/// <returns>The first lines of <paramref name="source"/>.</returns>
internal static string GetMaxLines(string source, int maxLines)
{
if (string.IsNullOrEmpty(source))
{
return string.Empty;
}
StringBuilder returnValue = new StringBuilder();
for (int i = 0, lineCount = 1; i < source.Length; i++)
{
char c = source[i];
if (c == '\n')
{
lineCount++;
}
returnValue.Append(c);
if (lineCount == maxLines)
{
returnValue.Append(PSObjectHelper.Ellipsis);
break;
}
}
return returnValue.ToString();
}
internal static ArrayList GetSuggestion(Runspace runspace)
{
LocalRunspace localRunspace = runspace as LocalRunspace;
if (localRunspace == null) { return new ArrayList(); }
// Get the last value of $?
bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue;
// Get the last history item
History history = localRunspace.History;
HistoryInfo[] entries = history.GetEntries(-1, 1, true);
if (entries.Length == 0)
return new ArrayList();
HistoryInfo lastHistory = entries[0];
// Get the last error
ArrayList errorList = (ArrayList)localRunspace.GetExecutionContext.DollarErrorVariable;
object lastError = null;
if (errorList.Count > 0)
{
lastError = errorList[0] as Exception;
ErrorRecord lastErrorRecord = null;
// The error was an actual ErrorRecord
if (lastError == null)
{
lastErrorRecord = errorList[0] as ErrorRecord;
}
else if (lastError is RuntimeException)
{
lastErrorRecord = ((RuntimeException)lastError).ErrorRecord;
}
// If we got information about the error invocation,
// we can be more careful with the errors we pass along
if ((lastErrorRecord != null) && (lastErrorRecord.InvocationInfo != null))
{
if (lastErrorRecord.InvocationInfo.HistoryId == lastHistory.Id)
lastError = lastErrorRecord;
else
lastError = null;
}
}
Runspace oldDefault = null;
bool changedDefault = false;
if (Runspace.DefaultRunspace != runspace)
{
oldDefault = Runspace.DefaultRunspace;
changedDefault = true;
Runspace.DefaultRunspace = runspace;
}
ArrayList suggestions = null;
try
{
suggestions = GetSuggestion(lastHistory, lastError, errorList);
}
finally
{
if (changedDefault)
{
Runspace.DefaultRunspace = oldDefault;
}
}
// Restore $?
localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue;
return suggestions;
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
internal static ArrayList GetSuggestion(HistoryInfo lastHistory, object lastError, ArrayList errorList)
{
ArrayList returnSuggestions = new ArrayList();
PSModuleInfo invocationModule = new PSModuleInfo(true);
invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory);
invocationModule.SessionState.PSVariable.Set("lastError", lastError);
int initialErrorCount = 0;
// Go through all of the suggestions
foreach (Hashtable suggestion in s_suggestions)
{
initialErrorCount = errorList.Count;
// Make sure the rule is enabled
if (!LanguagePrimitives.IsTrue(suggestion["Enabled"]))
continue;
SuggestionMatchType matchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(
suggestion["MatchType"],
typeof(SuggestionMatchType),
CultureInfo.InvariantCulture);
// If this is a dynamic match, evaluate the ScriptBlock
if (matchType == SuggestionMatchType.Dynamic)
{
object result = null;
ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock;
if (evaluator == null)
{
suggestion["Enabled"] = false;
throw new ArgumentException(
SuggestionStrings.RuleMustBeScriptBlock, "Rule");
}
try
{
result = invocationModule.Invoke(evaluator, null);
}
catch (Exception)
{
// Catch-all OK. This is a third-party call-out.
suggestion["Enabled"] = false;
continue;
}
// If it returned results, evaluate its suggestion
if (LanguagePrimitives.IsTrue(result))
{
string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);
if (!string.IsNullOrEmpty(suggestionText))
{
string returnString = string.Format(
CultureInfo.CurrentCulture,
"Suggestion [{0},{1}]: {2}",
(int)suggestion["Id"],
(string)suggestion["Category"],
suggestionText);
returnSuggestions.Add(returnString);
}
}
}
else
{
string matchText = string.Empty;
// Otherwise, this is a Regex match against the
// command or error
if (matchType == SuggestionMatchType.Command)
{
matchText = lastHistory.CommandLine;
}
else if (matchType == SuggestionMatchType.Error)
{
if (lastError != null)
{
Exception lastException = lastError as Exception;
if (lastException != null)
{
matchText = lastException.Message;
}
else
{
matchText = lastError.ToString();
}
}
}
else if (matchType == SuggestionMatchType.ErrorId)
{
if (lastError != null && lastError is ErrorRecord errorRecord)
{
matchText = errorRecord.FullyQualifiedErrorId;
}
}
else
{
suggestion["Enabled"] = false;
throw new ArgumentException(
SuggestionStrings.InvalidMatchType,
"MatchType");
}
// If the text matches, evaluate the suggestion
if (Regex.IsMatch(matchText, (string)suggestion["Rule"], RegexOptions.IgnoreCase))
{
string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);
if (!string.IsNullOrEmpty(suggestionText))
{
string returnString = string.Format(
CultureInfo.CurrentCulture,
"Suggestion [{0},{1}]: {2}",
(int)suggestion["Id"],
(string)suggestion["Category"],
suggestionText);
returnSuggestions.Add(returnString);
}
}
}
// If the rule generated an error, disable it
if (errorList.Count != initialErrorCount)
{
suggestion["Enabled"] = false;
}
}
return returnSuggestions;
}
/// <summary>
/// Remove the GUID from the message if the message is in the pre-defined format.
/// </summary>
/// <param name="message"></param>
/// <param name="matchPattern"></param>
/// <returns></returns>
internal static string RemoveGuidFromMessage(string message, out bool matchPattern)
{
matchPattern = false;
if (string.IsNullOrEmpty(message))
return message;
const string pattern = @"^([\d\w]{8}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{12}:).*";
Match matchResult = Regex.Match(message, pattern);
if (matchResult.Success)
{
string partToRemove = matchResult.Groups[1].Captures[0].Value;
message = message.Remove(0, partToRemove.Length);
matchPattern = true;
}
return message;
}
internal static string RemoveIdentifierInfoFromMessage(string message, out bool matchPattern)
{
matchPattern = false;
if (string.IsNullOrEmpty(message))
return message;
const string pattern = @"^([\d\w]{8}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{12}:\[.*\]:).*";
Match matchResult = Regex.Match(message, pattern);
if (matchResult.Success)
{
string partToRemove = matchResult.Groups[1].Captures[0].Value;
message = message.Remove(0, partToRemove.Length);
matchPattern = true;
}
return message;
}
/// <summary>
/// Create suggestion with string rule and suggestion.
/// </summary>
/// <param name="id">Identifier for the suggestion.</param>
/// <param name="category">Category for the suggestion.</param>
/// <param name="matchType">Suggestion match type.</param>
/// <param name="rule">Rule to match.</param>
/// <param name="suggestion">Suggestion to return.</param>
/// <param name="enabled">True if the suggestion is enabled.</param>
/// <returns>Hashtable representing the suggestion.</returns>
private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, string rule, string suggestion, bool enabled)
{
Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
result["Id"] = id;
result["Category"] = category;
result["MatchType"] = matchType;
result["Rule"] = rule;
result["Suggestion"] = suggestion;
result["Enabled"] = enabled;
return result;
}
/// <summary>
/// Create suggestion with string rule and scriptblock suggestion.
/// </summary>
/// <param name="id">Identifier for the suggestion.</param>
/// <param name="category">Category for the suggestion.</param>
/// <param name="matchType">Suggestion match type.</param>
/// <param name="rule">Rule to match.</param>
/// <param name="suggestion">Scriptblock to run that returns the suggestion.</param>
/// <param name="suggestionArgs">Arguments to pass to suggestion scriptblock.</param>
/// <param name="enabled">True if the suggestion is enabled.</param>
/// <returns>Hashtable representing the suggestion.</returns>
private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, string rule, ScriptBlock suggestion, object[] suggestionArgs, bool enabled)
{
Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
result["Id"] = id;
result["Category"] = category;
result["MatchType"] = matchType;
result["Rule"] = rule;
result["Suggestion"] = suggestion;
result["SuggestionArgs"] = suggestionArgs;
result["Enabled"] = enabled;
return result;
}
/// <summary>
/// Create suggestion with scriptblock rule and suggestion.
/// </summary>
private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, ScriptBlock rule, ScriptBlock suggestion, bool enabled)
{
Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
result["Id"] = id;
result["Category"] = category;
result["MatchType"] = matchType;
result["Rule"] = rule;
result["Suggestion"] = suggestion;
result["Enabled"] = enabled;
return result;
}
/// <summary>
/// Create suggestion with scriptblock rule and scriptblock suggestion with arguments.
/// </summary>
private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, ScriptBlock rule, ScriptBlock suggestion, object[] suggestionArgs, bool enabled)
{
Hashtable result = NewSuggestion(id, category, matchType, rule, suggestion, enabled);
result.Add("SuggestionArgs", suggestionArgs);
return result;
}
/// <summary>
/// Get suggestion text from suggestion scriptblock.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Need to keep this for legacy reflection based use")]
private static string GetSuggestionText(Object suggestion, PSModuleInfo invocationModule)
{
return GetSuggestionText(suggestion, null, invocationModule);
}
/// <summary>
/// Get suggestion text from suggestion scriptblock with arguments.
/// </summary>
private static string GetSuggestionText(Object suggestion, object[] suggestionArgs, PSModuleInfo invocationModule)
{
if (suggestion is ScriptBlock)
{
ScriptBlock suggestionScript = (ScriptBlock)suggestion;
object result = null;
try
{
result = invocationModule.Invoke(suggestionScript, suggestionArgs);
}
catch (Exception)
{
// Catch-all OK. This is a third-party call-out.
return string.Empty;
}
return (string)LanguagePrimitives.ConvertTo(result, typeof(string), CultureInfo.CurrentCulture);
}
else
{
return (string)LanguagePrimitives.ConvertTo(suggestion, typeof(string), CultureInfo.CurrentCulture);
}
}
internal static PSCredential CredUIPromptForCredential(
string caption,
string message,
string userName,
string targetName,
PSCredentialTypes allowedCredentialTypes,
PSCredentialUIOptions options,
IntPtr parentHWND)
{
PSCredential cred = null;
// From WinCred.h
const int CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256);
const int CRED_MAX_CREDENTIAL_BLOB_SIZE = 512;
const int CRED_MAX_PASSWORD_LENGTH = CRED_MAX_CREDENTIAL_BLOB_SIZE / 2;
const int CREDUI_MAX_MESSAGE_LENGTH = 1024;
const int CREDUI_MAX_CAPTION_LENGTH = 128;
// Populate the UI text with defaults, if required
if (string.IsNullOrEmpty(caption))
{
caption = CredUI.PromptForCredential_DefaultCaption;
}
if (string.IsNullOrEmpty(message))
{
message = CredUI.PromptForCredential_DefaultMessage;
}
if (caption.Length > CREDUI_MAX_CAPTION_LENGTH)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidCaption, CREDUI_MAX_CAPTION_LENGTH));
}
if (message.Length > CREDUI_MAX_MESSAGE_LENGTH)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidMessage, CREDUI_MAX_MESSAGE_LENGTH));
}
if (userName != null && userName.Length > CRED_MAX_USERNAME_LENGTH)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidUserName, CRED_MAX_USERNAME_LENGTH));
}
CREDUI_INFO credUiInfo = new CREDUI_INFO();
credUiInfo.pszCaptionText = caption;
credUiInfo.pszMessageText = message;
StringBuilder usernameBuilder = new StringBuilder(userName, CRED_MAX_USERNAME_LENGTH);
StringBuilder passwordBuilder = new StringBuilder(CRED_MAX_PASSWORD_LENGTH);
bool save = false;
int saveCredentials = Convert.ToInt32(save);
credUiInfo.cbSize = Marshal.SizeOf(credUiInfo);
credUiInfo.hwndParent = parentHWND;
CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;
// Set some of the flags if they have not requested a domain credential
if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
{
flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;
// If they've asked to always prompt, do so.
if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
}
// To prevent buffer overrun attack, only attempt call if buffer lengths are within bounds.
CredUIReturnCodes result = CredUIReturnCodes.ERROR_INVALID_PARAMETER;
if (usernameBuilder.Length <= CRED_MAX_USERNAME_LENGTH && passwordBuilder.Length <= CRED_MAX_PASSWORD_LENGTH)
{
result = CredUIPromptForCredentials(
ref credUiInfo,
targetName,
IntPtr.Zero,
0,
usernameBuilder,
CRED_MAX_USERNAME_LENGTH,
passwordBuilder,
CRED_MAX_PASSWORD_LENGTH,
ref saveCredentials,
flags);
}
if (result == CredUIReturnCodes.NO_ERROR)
{
// Extract the username
string credentialUsername = null;
if (usernameBuilder != null)
credentialUsername = usernameBuilder.ToString();
// Trim the leading '\' from the username, which CredUI automatically adds
// if you don't specify a domain.
// This is a really common bug in V1 and V2, causing everybody to have to do
// it themselves.
// This could be a breaking change for hosts that do hard-coded hacking:
// $cred.UserName.SubString(1, $cred.Username.Length - 1)
// But that's OK, because they would have an even worse bug when you've
// set the host (ConsolePrompting = true) configuration (which does not do this).
credentialUsername = credentialUsername.TrimStart('\\');
// Extract the password into a SecureString, zeroing out the memory
// as soon as possible.
SecureString password = new SecureString();
for (int counter = 0; counter < passwordBuilder.Length; counter++)
{
password.AppendChar(passwordBuilder[counter]);
passwordBuilder[counter] = (char)0;
}
if (!string.IsNullOrEmpty(credentialUsername))
cred = new PSCredential(credentialUsername, password);
else
cred = null;
}
else // result is not CredUIReturnCodes.NO_ERROR
{
cred = null;
}
return cred;
}
[DllImport("credui", EntryPoint = "CredUIPromptForCredentialsW", CharSet = CharSet.Unicode)]
private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO pUiInfo,
string pszTargetName, IntPtr Reserved, int dwAuthError, StringBuilder pszUserName,
int ulUserNameMaxChars, StringBuilder pszPassword, int ulPasswordMaxChars, ref int pfSave, CREDUI_FLAGS dwFlags);
[Flags]
private enum CREDUI_FLAGS
{
INCORRECT_PASSWORD = 0x1,
DO_NOT_PERSIST = 0x2,
REQUEST_ADMINISTRATOR = 0x4,
EXCLUDE_CERTIFICATES = 0x8,
REQUIRE_CERTIFICATE = 0x10,
SHOW_SAVE_CHECK_BOX = 0x40,
ALWAYS_SHOW_UI = 0x80,
REQUIRE_SMARTCARD = 0x100,
PASSWORD_ONLY_OK = 0x200,
VALIDATE_USERNAME = 0x400,
COMPLETE_USERNAME = 0x800,
PERSIST = 0x1000,
SERVER_CREDENTIAL = 0x4000,
EXPECT_CONFIRMATION = 0x20000,
GENERIC_CREDENTIALS = 0x40000,
USERNAME_TARGET_CREDENTIALS = 0x80000,
KEEP_USERNAME = 0x100000,
}
private struct CREDUI_INFO
{
public int cbSize;
public IntPtr hwndParent;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMessageText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCaptionText;
public IntPtr hbmBanner;
}
private enum CredUIReturnCodes
{
NO_ERROR = 0,
ERROR_CANCELLED = 1223,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_NOT_FOUND = 1168,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
}
/// <summary>
/// Returns the prompt used in remote sessions: "[machine]: basePrompt"
/// </summary>
internal static string GetRemotePrompt(RemoteRunspace runspace, string basePrompt, bool configuredSession = false)
{
if (configuredSession ||
runspace.ConnectionInfo is NamedPipeConnectionInfo ||
runspace.ConnectionInfo is VMConnectionInfo ||
runspace.ConnectionInfo is ContainerConnectionInfo)
{
return basePrompt;
}
SSHConnectionInfo sshConnectionInfo = runspace.ConnectionInfo as SSHConnectionInfo;
// Usernames are case-sensitive on Unix systems
if (sshConnectionInfo != null &&
!string.IsNullOrEmpty(sshConnectionInfo.UserName) &&
!System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal))
{
return string.Format(CultureInfo.InvariantCulture, "[{0}@{1}]: {2}", sshConnectionInfo.UserName, sshConnectionInfo.ComputerName, basePrompt);
}
return string.Format(CultureInfo.InvariantCulture, "[{0}]: {1}", runspace.ConnectionInfo.ComputerName, basePrompt);
}
internal static bool IsProcessInteractive(InvocationInfo invocationInfo)
{
#if CORECLR
return false;
#else
// CommandOrigin != Runspace means it is in a script
if (invocationInfo.CommandOrigin != CommandOrigin.Runspace)
return false;
// If we don't own the window handle, we've been invoked
// from another process that just calls "PowerShell -Command"
if (System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle == IntPtr.Zero)
return false;
// If the window has been idle for less than two seconds,
// they're probably still calling "PowerShell -Command"
// but from Start-Process, or the StartProcess API
try
{
System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
TimeSpan timeSinceStart = DateTime.Now - currentProcess.StartTime;
TimeSpan idleTime = timeSinceStart - currentProcess.TotalProcessorTime;
// Making it 2 seconds because of things like delayed prompt
if (idleTime.TotalSeconds > 2)
return true;
}
catch (System.ComponentModel.Win32Exception)
{
// Don't have access to the properties
return false;
}
return false;
#endif
}
/// <summary>
/// Create a configured remote runspace from provided name.
/// </summary>
/// <param name="configurationName"></param>
/// <param name="host"></param>
/// <returns></returns>
internal static RemoteRunspace CreateConfiguredRunspace(
string configurationName,
PSHost host)
{
// Create a loop-back remote runspace with network access enabled, and
// with the provided endpoint configurationname.
TypeTable typeTable = TypeTable.LoadDefaultTypeFiles();
var connectInfo = new WSManConnectionInfo();
connectInfo.ShellUri = configurationName.Trim();
connectInfo.EnableNetworkAccess = true;
RemoteRunspace remoteRunspace = null;
try
{
remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectInfo, host, typeTable);
remoteRunspace.Open();
}
catch (Exception e)
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotCreateConfiguredRunspace, configurationName),
e);
}
remoteRunspace.IsConfiguredLoopBack = true;
return remoteRunspace;
}
#endregion
#region Public Access
#region Runspace Invoke
/// <summary>
/// Helper method to invoke a PSCommand on a given runspace. This method correctly invokes the command for
/// these runspace cases:
/// 1. Local runspace. If the local runspace is busy it will invoke as a nested command.
/// 2. Remote runspace.
/// 3. Runspace that is stopped in the debugger at a breakpoint.
///
/// Error and information streams are ignored and only the command result output is returned.
///
/// This method is NOT thread safe. It does not support running commands from different threads on the
/// provided runspace. It assumes the thread invoking this method is the same that runs all other
/// commands on the provided runspace.
/// </summary>
/// <param name="runspace">Runspace to invoke the command on.</param>
/// <param name="command">Command to invoke.</param>
/// <returns>Collection of command output result objects.</returns>
public static Collection<PSObject> InvokeOnRunspace(PSCommand command, Runspace runspace)
{
if (command == null)
{
throw new PSArgumentNullException("command");
}
if (runspace == null)
{
throw new PSArgumentNullException("runspace");
}
if ((runspace.Debugger != null) && runspace.Debugger.InBreakpoint)
{
// Use the Debugger API to run the command when a runspace is stopped in the debugger.
PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
runspace.Debugger.ProcessCommand(
command,
output);
return new Collection<PSObject>(output);
}
// Otherwise run command directly in runspace.
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.IsRunspaceOwner = false;
if (runspace.ConnectionInfo == null)
{
// Local runspace. Make a nested PowerShell object as needed.
ps.SetIsNested(runspace.GetCurrentlyRunningPipeline() != null);
}
using (ps)
{
ps.Commands = command;
return ps.Invoke<PSObject>();
}
}
#endregion
#region PSEdit Support
/// <summary>
/// PSEditFunction script string.
/// </summary>
public const string PSEditFunction = @"
param (
[Parameter(Mandatory=$true)] [string[]] $FileName
)
foreach ($file in $FileName)
{
Get-ChildItem $file -File | ForEach-Object {
$filePathName = $_.FullName
# Get file contents
$contentBytes = Get-Content -Path $filePathName -Raw -Encoding Byte
# Notify client for file open.
New-Event -SourceIdentifier PSISERemoteSessionOpenFile -EventArguments @($filePathName, $contentBytes) > $null
}
}
";
/// <summary>
/// CreatePSEditFunction script string.
/// </summary>
public const string CreatePSEditFunction = @"
param (
[string] $PSEditFunction
)
Register-EngineEvent -SourceIdentifier PSISERemoteSessionOpenFile -Forward -SupportEvent
if ((Test-Path -Path 'function:\global:PSEdit') -eq $false)
{
Set-Item -Path 'function:\global:PSEdit' -Value $PSEditFunction
}
";
/// <summary>
/// RemovePSEditFunction script string.
/// </summary>
public const string RemovePSEditFunction = @"
if ((Test-Path -Path 'function:\global:PSEdit') -eq $true)
{
Remove-Item -Path 'function:\global:PSEdit' -Force
}
Unregister-Event -SourceIdentifier PSISERemoteSessionOpenFile -Force -ErrorAction Ignore
";
/// <summary>
/// Open file event.
/// </summary>
public const string RemoteSessionOpenFileEvent = "PSISERemoteSessionOpenFile";
#endregion
#endregion
}
#endregion
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define GC_PRECISE_PROFILING
//#define DEBUG_MARK_SWEEP
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
public abstract class MarkAndSweepCollector : GarbageCollectionManager
{
protected interface MarkAndSweepStackWalker
{
void Process( Processor.Context ctx );
}
//--//
struct MarkStackForArrays
{
//
// State
//
private UIntPtr m_address;
private uint m_elementSize;
private int m_numOfElements;
private TS.VTable m_vTableElement;
//
// Helper Methods
//
#if !GC_PRECISE_PROFILING
[Inline]
#endif
internal unsafe void Push( ArrayImpl array ,
uint elementSize ,
int numOfElements ,
TS.VTable vTableElement )
{
m_address = new UIntPtr( array.GetDataPointer() );
m_elementSize = elementSize;
m_numOfElements = numOfElements;
m_vTableElement = vTableElement;
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
internal unsafe void Visit( MarkAndSweepCollector owner )
{
UIntPtr address = m_address;
TS.VTable vTable = m_vTableElement;
if(--m_numOfElements == 0)
{
//
// Pop entry.
//
m_address = new UIntPtr();
m_vTableElement = null;
owner.m_markStackForArrays_Pos--;
}
else
{
//
// Move to next element.
//
m_address = AddressMath.Increment( m_address, m_elementSize );
}
if(vTable != null)
{
owner.VisitHeapObjectFields( address, vTable );
}
else
{
UIntPtr* ptr = (UIntPtr*)address.ToPointer();
UIntPtr obj = ptr[0];
if(obj != UIntPtr.Zero)
{
owner.VisitHeapObject( obj );
}
}
}
}
//
// State
//
private OutOfMemoryException m_outOfMemoryException;
private MarkAndSweepStackWalker m_stackWalker;
private bool m_fFirstLevel;
private UIntPtr[] m_maskStackForObjects;
private int m_maskStackForObjects_Pos;
private MarkStackForArrays[] m_markStackForArrays;
private int m_markStackForArrays_Pos;
private ObjectHeader.GarbageCollectorFlags m_markForNonHeap;
private uint[] m_trackFreeBlocks;
private int m_perf_gapCount;
private int m_perf_freeCount;
private int m_perf_deadCount;
private int m_perf_objectCount;
private int m_perf_stat_calls;
private uint m_perf_stat_freeMem;
private long m_perf_time_baseline;
private long m_perf_time_start;
private long m_perf_time_walk;
private long m_perf_time_global;
private long m_perf_time_sweep;
private long m_perf_time_ret;
//
// Helper Methods
//
protected virtual int MarkStackForObjectsSize
{
get { return 1024; }
}
protected virtual int MarkStackForArraysSize
{
get { return 128; }
}
//--//
protected abstract MarkAndSweepStackWalker CreateStackWalker( );
public unsafe override void InitializeGarbageCollectionManager()
{
m_outOfMemoryException = new OutOfMemoryException();
m_stackWalker = CreateStackWalker();
m_maskStackForObjects = new UIntPtr [ MarkStackForObjectsSize ];
m_markStackForArrays = new MarkStackForArrays[ MarkStackForArraysSize ];
if(Configuration.TraceFreeBlocks)
{
m_trackFreeBlocks = new uint[32];
}
//--//
foreach(var handler in this.ExtensionHandlers)
{
handler.Initialize();
}
//--//
MemorySegment* heapLow = null;
MemorySegment* heapHigh = null;
for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next)
{
if(heapLow == null || AddressMath.IsGreaterThan( heapLow->Beginning, heap->Beginning ))
{
heapLow = heap;
}
if(heapHigh == null || AddressMath.IsLessThan( heapHigh->End, heap->End ))
{
heapHigh = heap;
}
}
BugCheck.Assert( heapLow != null && heapHigh != null, BugCheck.StopCode.NoMemory );
BrickTable.Instance.Initialize( heapLow->Beginning.ToUInt32(), heapHigh->End.ToUInt32() );
RebuildBrickTable();
if(Configuration.ValidateHeap)
{
VerifyBrickTable();
}
}
[Inline]
public override void NotifyNewObject( UIntPtr ptr ,
uint size )
{
BrickTable.Instance.MarkObject( ptr, size );
}
public override UIntPtr FindObject( UIntPtr interiorPtr )
{
UIntPtr address = BrickTable.Instance.FindLowerBoundForObjectPointer( interiorPtr );
if(address != UIntPtr.Zero)
{
while(true)
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address );
ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState;
switch(flags)
{
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked :
{
UIntPtr nextAddress = oh.GetNextObjectPointer();
if(AddressMath.IsLessThan( interiorPtr, nextAddress ))
{
//
// Don't return the address of a heap free block.
//
return UIntPtr.Zero;
}
address = nextAddress;
}
break;
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked :
address = AddressMath.Increment( address, sizeof(uint) );
break;
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return UIntPtr.Zero;
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return UIntPtr.Zero;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked:
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked:
{
UIntPtr nextAddress = oh.GetNextObjectPointer();
if(AddressMath.IsLessThan( interiorPtr, nextAddress ))
{
return oh.Pack( ).ToPointer( );
}
address = nextAddress;
}
break;
default:
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return UIntPtr.Zero;
}
}
}
return UIntPtr.Zero;
}
public override uint Collect()
{
#if DEBUG_MARK_SWEEP
BugCheck.Log( "Collecting on Thread 0x%x", (int)ObjectHeader.Unpack( ThreadManager.Instance.CurrentThread ).ToPointer( ) );
#endif
if(Configuration.CollectPerformanceStatistics)
{
m_perf_stat_calls++;
m_perf_time_baseline = System.Diagnostics.Stopwatch.GetTimestamp();
}
uint mem;
long gcTime;
// Take the memory manager lock so we make sure there's no in-process memory allocation as we
// mark and sweep the memory.
using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock ))
{
while(true)
{
using(SmartHandles.InterruptState hnd2 = SmartHandles.InterruptState.Disable())
{
if(IsThisAGoodPlaceToStopTheWorld())
{
if(Configuration.CollectPerformanceStatistics)
{
m_perf_time_start = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline;
}
long gc_start = 0;
long gc_stop = 0;
if(Configuration.CollectMinimalPerformanceStatistics)
{
gc_start = System.Diagnostics.Stopwatch.GetTimestamp();
}
StartCollection();
if(Configuration.CollectMinimalPerformanceStatistics)
{
gc_stop = System.Diagnostics.Stopwatch.GetTimestamp();
}
gcTime = gc_stop - gc_start;
mem = MemoryManager.Instance.AvailableMemory;
if(Configuration.CollectPerformanceStatistics)
{
m_perf_time_ret = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline;
m_perf_stat_freeMem = mem;
}
break;
}
}
ThreadImpl.CurrentThread.Yield();
}
}
foreach(var handler in this.ExtensionHandlers)
{
handler.RestartExecution();
}
DumpFreeBlockTracking();
if(Configuration.CollectMinimalPerformanceStatistics)
{
BugCheck.WriteLineFormat( "GC: Free mem: {0} Time: {1}msec", mem, ToMilliseconds( gcTime ) );
}
if(Configuration.CollectPerformanceStatistics)
{
BugCheck.WriteLineFormat( "m_perf_gapCount : {0,9}", m_perf_gapCount );
BugCheck.WriteLineFormat( "m_perf_freeCount : {0,9}", m_perf_freeCount );
BugCheck.WriteLineFormat( "m_perf_deadCount : {0,9}", m_perf_deadCount );
BugCheck.WriteLineFormat( "m_perf_objectCount: {0,9}", m_perf_objectCount );
BugCheck.WriteLineFormat( "m_perf_time_start : {0}msec", ToMilliseconds( m_perf_time_start ) );
BugCheck.WriteLineFormat( "m_perf_time_walk : {0}msec", ToMilliseconds( m_perf_time_walk ) );
BugCheck.WriteLineFormat( "m_perf_time_global: {0}msec", ToMilliseconds( m_perf_time_global ) );
BugCheck.WriteLineFormat( "m_perf_time_sweep : {0}msec", ToMilliseconds( m_perf_time_sweep ) );
BugCheck.WriteLineFormat( "m_perf_time_ret : {0}msec", ToMilliseconds( m_perf_time_ret ) );
}
return mem;
}
private static int ToMilliseconds( long ticks )
{
return (int)(1000.0 * ticks / System.Diagnostics.Stopwatch.Frequency);
}
public override long GetTotalMemory()
{
return MemoryManager.Instance.AllocatedMemory;
}
public override void ThrowOutOfMemory( TS.VTable vTable )
{
throw m_outOfMemoryException;
}
public override bool IsMarked( object obj )
{
if(obj == null)
{
return true;
}
ObjectHeader oh = ObjectHeader.Unpack( obj );
ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState;
switch(flags)
{
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked :
return true;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
return false;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked :
return true;
default:
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return false;
}
}
public override void ExtendMarking( object obj )
{
var objImpl = (ObjectImpl)obj;
if(objImpl != null)
{
VisitHeapObject( objImpl.ToPointer() );
}
}
//--//
protected virtual bool IsThisAGoodPlaceToStopTheWorld()
{
ThreadImpl thisThread = ThreadImpl.CurrentThread;
Processor.Context ctx = thisThread.ThrowContext; // Reuse the throw context for the current thread to unwind the stack.
//
// TODO: LT72: Only the RT.Threadmanager can implement this method correctly at this time
//
ThreadManager tm = ThreadManager.Instance;
for(KernelNode< ThreadImpl > node = tm.StartOfForwardWalkThroughAllThreads; node.IsValidForForwardMove; node = node.Next)
{
ThreadImpl thread = node.Target;
if(thread == thisThread)
{
continue;
}
if(thread.IsAtSafePoint( ctx ) == false)
{
return false;
}
}
return true;
}
private void StartCollection()
{
m_fFirstLevel = true;
m_maskStackForObjects_Pos = -1;
m_markStackForArrays_Pos = -1;
m_markForNonHeap ^= ObjectHeader.GarbageCollectorFlags.Marked;
foreach(var handler in this.ExtensionHandlers)
{
handler.StartOfMarkPhase( this );
}
WalkStackFrames();
if(Configuration.CollectPerformanceStatistics)
{
m_perf_time_walk = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline;
}
MarkGlobalRoot();
ProcessMarkStack();
foreach(var handler in this.ExtensionHandlers)
{
handler.EndOfMarkPhase( this );
}
if(Configuration.CollectPerformanceStatistics)
{
m_perf_time_global = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline;
}
foreach(var handler in this.ExtensionHandlers)
{
handler.StartOfSweepPhase( this );
}
Sweep();
foreach(var handler in this.ExtensionHandlers)
{
handler.EndOfSweepPhase( this );
}
if(Configuration.CollectPerformanceStatistics)
{
m_perf_time_sweep = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline;
}
if(Configuration.ValidateHeap)
{
VerifyBrickTable();
}
}
protected virtual void WalkStackFrames()
{
ThreadImpl thisThread = ThreadImpl.CurrentThread;
Processor.Context ctx = thisThread.ThrowContext; // Reuse the throw context for the current thread to unwind the stack.
//
// TODO: LT72: Only the RT.Threadmanager can implement this method correctly at this time
//
ThreadManager tm = ThreadManager.Instance;
for(KernelNode< ThreadImpl > node = tm.StartOfForwardWalkThroughAllThreads; node.IsValidForForwardMove; node = node.Next)
{
ThreadImpl thread = node.Target;
if(thread == thisThread)
{
ctx.Populate();
}
else
{
ctx.Populate( thread.SwappedOutContext );
}
#if DEBUG_MARK_SWEEP
BugCheck.Log(
"Walking thread stack 0x%x, 0x%x -> 0x%x",
(int)ObjectHeader.Unpack( thread ).ToPointer( ),
(int)ctx.StackPointer,
(int)ctx.BaseStackPointer );
#endif
m_stackWalker.Process( ctx );
}
}
private void MarkGlobalRoot()
{
object root = TS.GlobalRoot.Instance;
UIntPtr address = ((ObjectImpl)root).ToPointer();
VisitHeapObject( address );
}
private unsafe void Sweep()
{
ResetFreeBlockTracking();
var brickTable = BrickTable.Instance;
brickTable.Reset();
if(Configuration.CollectPerformanceStatistics)
{
m_perf_gapCount = 0;
m_perf_freeCount = 0;
m_perf_deadCount = 0;
m_perf_objectCount = 0;
}
for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next)
{
UIntPtr address = heap->FirstBlock;
UIntPtr end = heap->End;
bool fLastWasFree = false;
UIntPtr freeStart = UIntPtr.Zero;
heap->FirstFreeBlock = null;
heap->LastFreeBlock = null;
while(AddressMath.IsLessThan( address, end ))
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address );
ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState;
bool fFree = true;
UIntPtr addressNext;
switch(flags)
{
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked :
if(Configuration.CollectPerformanceStatistics)
{
m_perf_freeCount++;
}
addressNext = oh.GetNextObjectPointer();
break;
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked :
if(Configuration.CollectPerformanceStatistics)
{
m_perf_gapCount++;
}
addressNext = AddressMath.Increment( address, sizeof(uint) );
break;
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked:
if(Configuration.CollectPerformanceStatistics)
{
m_perf_deadCount++;
}
#if DEBUG_MARK_SWEEP
BugCheck.Log( "Object swept up: 0x%08x, size: %d", (int)oh.ToPointer( ), (int)oh.TotalSize );
String name;
if(flags == ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes)
{
name = "<raw bytes>";
}
else
{
var type = oh.VirtualTable.TypeInfo;
if(type is TS.SzArrayReferenceTypeRepresentation)
{
var arrayType = (TS.SzArrayReferenceTypeRepresentation)type;
BugCheck.Log( "Array of:" );
name = arrayType.UnderlyingType.Name ?? "<unknown>";
}
else
{
name = type?.Name ?? "<unknown>";
}
}
BugCheck.Log( name );
#endif
addressNext = oh.GetNextObjectPointer();
break;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked :
if(Configuration.CollectPerformanceStatistics)
{
m_perf_objectCount++;
}
addressNext = oh.GetNextObjectPointer();
oh.GarbageCollectorState = (flags & ~ObjectHeader.GarbageCollectorFlags.Marked);
brickTable.MarkObject( address, AddressMath.RangeSize( address, addressNext ) );
fFree = false;
break;
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
if(Configuration.CollectPerformanceStatistics)
{
m_perf_deadCount++;
}
addressNext = oh.GetNextObjectPointer();
break;
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked :
{
if(Configuration.CollectPerformanceStatistics)
{
m_perf_objectCount++;
}
addressNext = oh.GetNextObjectPointer();
var ext = FindExtensionHandler( oh.VirtualTable );
if(ext == null)
{
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
}
else
{
ext.Sweep( this, oh.Pack() );
}
oh.GarbageCollectorState = (flags & ~ObjectHeader.GarbageCollectorFlags.Marked);
brickTable.MarkObject( address, AddressMath.RangeSize( address, addressNext ) );
fFree = false;
break;
}
default:
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
}
if(fLastWasFree != fFree)
{
if(fFree)
{
freeStart = address;
}
else
{
TrackFreeBlock( freeStart, address );
heap->LinkNewFreeBlock( freeStart, address );
}
fLastWasFree = fFree;
}
address = addressNext;
}
if(fLastWasFree)
{
TrackFreeBlock( freeStart, end );
heap->LinkNewFreeBlock( freeStart, end );
}
}
}
//--//
private void ResetFreeBlockTracking()
{
if(Configuration.TraceFreeBlocks)
{
Array.Clear( m_trackFreeBlocks, 0, m_trackFreeBlocks.Length );
}
}
private void TrackFreeBlock( UIntPtr start ,
UIntPtr end )
{
if(Configuration.TraceFreeBlocks)
{
uint size = AddressMath.RangeSize( start, end );
for(int i = 0; i < 32; i++)
{
if(size < (1u << i))
{
m_trackFreeBlocks[i]++;
break;
}
}
}
}
private void DumpFreeBlockTracking()
{
if(Configuration.TraceFreeBlocks)
{
for(int i = 0; i < 32; i++)
{
if(m_trackFreeBlocks[i] != 0)
{
BugCheck.WriteLineFormat( "Size: {0,9} = {1}", 1u << i, m_trackFreeBlocks[i] );
}
}
}
}
//--//
[NoInline]
protected void VisitInternalPointer( UIntPtr address )
{
VisitInternalPointerInline( address );
}
[NoInline]
protected void VisitHeapObject( UIntPtr address )
{
VisitHeapObjectInline( address );
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
private void VisitInternalPointerInline( UIntPtr address )
{
UIntPtr objAddress = FindObject( address );
if(objAddress != UIntPtr.Zero)
{
VisitHeapObject( objAddress );
}
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
private void VisitHeapObjectInline( UIntPtr address )
{
if(Configuration.ValidateHeap)
{
BugCheck.Assert( MemoryManager.Instance.RefersToMemory( address ), BugCheck.StopCode.NotAMemoryReference );
}
ObjectHeader oh = ObjectHeader.Unpack( ObjectImpl.FromPointer( address ) );
ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState;
switch(flags)
{
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked :
return;
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked :
return;
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked :
return;
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked:
oh.GarbageCollectorState = flags | ObjectHeader.GarbageCollectorFlags.Marked;
return;
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked:
return;
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
if(m_markForNonHeap == ObjectHeader.GarbageCollectorFlags.Unmarked)
{
return;
}
flags ^= ObjectHeader.GarbageCollectorFlags.Marked;
break;
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked :
if(m_markForNonHeap == ObjectHeader.GarbageCollectorFlags.Marked)
{
return;
}
flags ^= ObjectHeader.GarbageCollectorFlags.Marked;
break;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
flags |= ObjectHeader.GarbageCollectorFlags.Marked;
break;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked :
return;
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
{
var ext = FindExtensionHandler( oh.VirtualTable );
if(ext == null)
{
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
}
else
{
ext.Mark( this, oh.Pack() );
}
flags |= ObjectHeader.GarbageCollectorFlags.Marked;
break;
}
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked :
return;
default:
{
BugCheck.Log ( "Corruption! address=0x%08x, flags=0x%08x", (int)address.ToUInt32( ), (int)flags );
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
}
return;
}
oh.GarbageCollectorState = flags;
TS.VTable vTable = oh.VirtualTable;
if(vTable.IsArray)
{
PushArrayReference( address, vTable );
}
else
{
PushObjectReference( address, vTable );
}
}
[NoInline]
private void VisitHeapObjectFields( UIntPtr fieldAddress ,
TS.VTable vTable )
{
VisitHeapObjectFieldsInline( fieldAddress, vTable );
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
private void VisitHeapObjectFieldsInline( UIntPtr fieldAddress ,
TS.VTable vTable )
{
TS.GCInfo.Pointer[] pointers = vTable.GCInfo.Pointers;
int numOfPointers = pointers.Length;
for(int i = 0; i < numOfPointers; i++)
{
VisitHeapObjectField( fieldAddress, ref pointers[i] );
}
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
private unsafe void VisitHeapObjectField( UIntPtr fieldAddress ,
ref TS.GCInfo.Pointer pointer )
{
UIntPtr* field = (UIntPtr*)fieldAddress.ToPointer( );
UIntPtr referenceAddress = field[pointer.OffsetInWords];
if(referenceAddress != UIntPtr.Zero)
{
switch(pointer.Kind)
{
case TS.GCInfo.Kind.Heap:
VisitHeapObjectInline( referenceAddress );
break;
case TS.GCInfo.Kind.Internal:
case TS.GCInfo.Kind.Potential:
VisitInternalPointerInline( referenceAddress );
break;
}
}
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
private void PushObjectReference( UIntPtr address ,
TS.VTable vTable )
{
TS.GCInfo.Pointer[] pointers = vTable.GCInfo.Pointers;
if(pointers == null)
{
//
// No pointers, nothing to do.
//
return;
}
if(m_fFirstLevel)
{
m_fFirstLevel = false;
int numOfPointers = pointers.Length;
UIntPtr fieldAddress = ObjectImpl.FromPointer( address ).GetFieldPointer( );
for(int i = 0; i < numOfPointers; i++)
{
VisitHeapObjectField( fieldAddress, ref pointers[i] );
}
ProcessMarkStack();
m_fFirstLevel = true;
}
else
{
BugCheck.Assert( m_maskStackForObjects_Pos < MarkStackForObjectsSize - 1, BugCheck.StopCode.NoMarkStack );
m_maskStackForObjects[++m_maskStackForObjects_Pos] = address;
}
}
#if !GC_PRECISE_PROFILING
[Inline]
#endif
private void PushArrayReference( UIntPtr address ,
TS.VTable vTable )
{
ArrayImpl array = ArrayImpl.CastAsArray( ObjectImpl.FromPointer( address ) );
int numOfElements = array.Length;
if(numOfElements == 0)
{
//
// Empty array, nothing to do.
//
return;
}
TS.VTable vTableElement = vTable.TypeInfo.ContainedType.VirtualTable;
if(vTableElement.IsValueType)
{
if(vTableElement.GCInfo.Pointers == null)
{
//
// It's an array of value types with no pointers, no need to push it.
//
return;
}
//
// The address is for an array with embedded structures.
//
}
else
{
//
// The address is for an object reference.
//
vTableElement = null;
}
BugCheck.Assert( m_markStackForArrays_Pos < MarkStackForArraysSize - 1, BugCheck.StopCode.NoMarkStack );
m_markStackForArrays[++m_markStackForArrays_Pos].Push( array, vTable.ElementSize, numOfElements, vTableElement );
if(m_fFirstLevel)
{
m_fFirstLevel = false;
ProcessMarkStack();
m_fFirstLevel = true;
}
}
private void ProcessMarkStack()
{
while(true)
{
int pos;
pos = m_maskStackForObjects_Pos;
if(pos >= 0)
{
UIntPtr address = m_maskStackForObjects[pos];
m_maskStackForObjects_Pos = pos - 1;
ObjectImpl obj = ObjectImpl.FromPointer( address );
TS.VTable vTable = TS.VTable.Get( obj );
VisitHeapObjectFieldsInline( obj.GetFieldPointer(), vTable );
continue;
}
pos = m_markStackForArrays_Pos;
if(pos >= 0)
{
m_markStackForArrays[pos].Visit( this );
continue;
}
break;
}
}
//--//
private unsafe void RebuildBrickTable()
{
var brickTable = BrickTable.Instance;
brickTable.Reset();
for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next)
{
UIntPtr address = heap->FirstBlock;
UIntPtr end = heap->End;
while(AddressMath.IsLessThan( address, end ))
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address );
ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState;
switch(flags)
{
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked :
{
UIntPtr addressNext = oh.GetNextObjectPointer();
//
// The arrays used to wrap the free blocks are marked as outside the heap.
// We should not add them to the brick table, because otherwise the whole brick table will look allocated
// and we don't care for pointers into the free list.
//
address = addressNext;
}
break;
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked :
address = AddressMath.Increment( address, sizeof(uint) );
break;
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked :
{
UIntPtr addressNext = oh.GetNextObjectPointer();
brickTable.MarkObject( address, AddressMath.RangeSize( address, addressNext ) );
address = addressNext;
}
break;
default:
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
}
}
}
}
//--//
[TS.WellKnownMethod( "DebugBrickTable_VerifyBrickTable" )]
private unsafe void VerifyBrickTable()
{
for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next)
{
UIntPtr address = heap->FirstBlock;
UIntPtr end = heap->End;
while(AddressMath.IsLessThan( address, end ))
{
FindObject( AddressMath.Increment( address, sizeof(uint) ) );
ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address );
ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState;
switch(flags)
{
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked :
{
UIntPtr addressNext = oh.GetNextObjectPointer();
address = addressNext;
}
break;
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked :
address = AddressMath.Increment( address, sizeof(uint) );
break;
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked :
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked :
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked:
case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked :
{
UIntPtr addressNext = oh.GetNextObjectPointer();
address = addressNext;
}
break;
default:
BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected );
return;
}
}
}
}
//
// Access Methods
//
}
}
| |
// ZlibCodec.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2009-November-03 15:40:51>
//
// ------------------------------------------------------------------
//
// This module defines a Codec for ZLIB compression and
// decompression. This code extends code that was based the jzlib
// implementation of zlib, but this code is completely novel. The codec
// class is new, and encapsulates some behaviors that are new, and some
// that were present in other classes in the jzlib code base. In
// keeping with the license for jzlib, the copyright to the jzlib code
// is included below.
//
// ------------------------------------------------------------------
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// -----------------------------------------------------------------------
//
// This program is based on zlib-1.1.3; credit to authors
// Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
// and contributors of zlib.
//
// -----------------------------------------------------------------------
using System;
using Interop=System.Runtime.InteropServices;
namespace Ionic.Zlib
{
/// <summary>
/// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
/// </summary>
///
/// <remarks>
/// This class compresses and decompresses data according to the Deflate algorithm
/// and optionally, the ZLIB format, as documented in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>.
/// </remarks>
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000D")]
[Interop.ComVisible(true)]
#if !NETCF
[Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)]
#endif
sealed public class ZlibCodec
{
/// <summary>
/// The buffer from which data is taken.
/// </summary>
public byte[] InputBuffer;
/// <summary>
/// An index into the InputBuffer array, indicating where to start reading.
/// </summary>
public int NextIn;
/// <summary>
/// The number of bytes available in the InputBuffer, starting at NextIn.
/// </summary>
/// <remarks>
/// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
/// The class will update this number as calls to Inflate/Deflate are made.
/// </remarks>
public int AvailableBytesIn;
/// <summary>
/// Total number of bytes read so far, through all calls to Inflate()/Deflate().
/// </summary>
public long TotalBytesIn;
/// <summary>
/// Buffer to store output data.
/// </summary>
public byte[] OutputBuffer;
/// <summary>
/// An index into the OutputBuffer array, indicating where to start writing.
/// </summary>
public int NextOut;
/// <summary>
/// The number of bytes available in the OutputBuffer, starting at NextOut.
/// </summary>
/// <remarks>
/// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
/// The class will update this number as calls to Inflate/Deflate are made.
/// </remarks>
public int AvailableBytesOut;
/// <summary>
/// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
/// </summary>
public long TotalBytesOut;
/// <summary>
/// used for diagnostics, when something goes wrong!
/// </summary>
public System.String Message;
internal DeflateManager dstate;
internal InflateManager istate;
internal uint _Adler32;
/// <summary>
/// The compression level to use in this codec. Useful only in compression mode.
/// </summary>
public CompressionLevel CompressLevel = CompressionLevel.Default;
/// <summary>
/// The number of Window Bits to use.
/// </summary>
/// <remarks>
/// This gauges the size of the sliding window, and hence the
/// compression effectiveness as well as memory consumption. It's best to just leave this
/// setting alone if you don't know what it is. The maximum value is 15 bits, which implies
/// a 32k window.
/// </remarks>
public int WindowBits = ZlibConstants.WindowBitsDefault;
/// <summary>
/// The compression strategy to use.
/// </summary>
/// <remarks>
/// This is only effective in compression. The theory offered by ZLIB is that different
/// strategies could potentially produce significant differences in compression behavior
/// for different data sets. Unfortunately I don't have any good recommendations for how
/// to set it differently. When I tested changing the strategy I got minimally different
/// compression performance. It's best to leave this property alone if you don't have a
/// good feel for it. Or, you may want to produce a test harness that runs through the
/// different strategy options and evaluates them on different file types. If you do that,
/// let me know your results.
/// </remarks>
public CompressionStrategy Strategy = CompressionStrategy.Default;
/// <summary>
/// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
/// </summary>
public int Adler32 { get { return (int)_Adler32; } }
/// <summary>
/// Create a ZlibCodec.
/// </summary>
/// <remarks>
/// If you use this default constructor, you will later have to explicitly call
/// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
/// or decompress.
/// </remarks>
public ZlibCodec() { }
/// <summary>
/// Create a ZlibCodec that either compresses or decompresses.
/// </summary>
/// <param name="mode">
/// Indicates whether the codec should compress (deflate) or decompress (inflate).
/// </param>
public ZlibCodec(CompressionMode mode)
{
if (mode == CompressionMode.Compress)
{
int rc = InitializeDeflate();
if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate.");
}
else if (mode == CompressionMode.Decompress)
{
int rc = InitializeInflate();
if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate.");
}
else throw new ZlibException("Invalid ZlibStreamFlavor.");
}
/// <summary>
/// Initialize the inflation state.
/// </summary>
/// <remarks>
/// It is not necessary to call this before using the ZlibCodec to inflate data;
/// It is implicitly called when you call the constructor.
/// </remarks>
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate()
{
return InitializeInflate(this.WindowBits);
}
/// <summary>
/// Initialize the inflation state with an explicit flag to
/// govern the handling of RFC1950 header bytes.
/// </summary>
///
/// <remarks>
/// By default, the ZLIB header defined in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If
/// you want to read a zlib stream you should specify true for
/// expectRfc1950Header. If you have a deflate stream, you will want to specify
/// false. It is only necessary to invoke this initializer explicitly if you
/// want to specify false.
/// </remarks>
///
/// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte
/// pair when reading the stream of data to be inflated.</param>
///
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate(bool expectRfc1950Header)
{
return InitializeInflate(this.WindowBits, expectRfc1950Header);
}
/// <summary>
/// Initialize the ZlibCodec for inflation, with the specified number of window bits.
/// </summary>
/// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
/// then you shouldn't be calling this initializer.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeInflate(int windowBits)
{
this.WindowBits = windowBits;
return InitializeInflate(windowBits, true);
}
/// <summary>
/// Initialize the inflation state with an explicit flag to govern the handling of
/// RFC1950 header bytes.
/// </summary>
///
/// <remarks>
/// If you want to read a zlib stream you should specify true for
/// expectRfc1950Header. In this case, the library will expect to find a ZLIB
/// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or
/// GZIP stream, which does not have such a header, you will want to specify
/// false.
/// </remarks>
///
/// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading
/// the stream of data to be inflated.</param>
/// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
/// then you shouldn't be calling this initializer.</param>
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate(int windowBits, bool expectRfc1950Header)
{
this.WindowBits = windowBits;
if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate().");
istate = new InflateManager(expectRfc1950Header);
return istate.Initialize(this, windowBits);
}
/// <summary>
/// Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
/// </summary>
/// <remarks>
/// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
/// AvailableBytesOut before calling this method.
/// </remarks>
/// <example>
/// <code>
/// private void InflateBuffer()
/// {
/// int bufferSize = 1024;
/// byte[] buffer = new byte[bufferSize];
/// ZlibCodec decompressor = new ZlibCodec();
///
/// Logger.Log("\n============================================");
/// Logger.Log("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
/// MemoryStream ms = new MemoryStream(DecompressedBytes);
///
/// int rc = decompressor.InitializeInflate();
///
/// decompressor.InputBuffer = CompressedBytes;
/// decompressor.NextIn = 0;
/// decompressor.AvailableBytesIn = CompressedBytes.Length;
///
/// decompressor.OutputBuffer = buffer;
///
/// // pass 1: inflate
/// do
/// {
/// decompressor.NextOut = 0;
/// decompressor.AvailableBytesOut = buffer.Length;
/// rc = decompressor.Inflate(FlushType.None);
///
/// if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
/// throw new Exception("inflating: " + decompressor.Message);
///
/// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
/// }
/// while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
///
/// // pass 2: finish and flush
/// do
/// {
/// decompressor.NextOut = 0;
/// decompressor.AvailableBytesOut = buffer.Length;
/// rc = decompressor.Inflate(FlushType.Finish);
///
/// if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
/// throw new Exception("inflating: " + decompressor.Message);
///
/// if (buffer.Length - decompressor.AvailableBytesOut > 0)
/// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
/// }
/// while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
///
/// decompressor.EndInflate();
/// }
///
/// </code>
/// </example>
/// <param name="flush">The flush to use when inflating.</param>
/// <returns>Z_OK if everything goes well.</returns>
public int Inflate(FlushType flush)
{
if (istate == null)
throw new ZlibException("No Inflate State!");
return istate.Inflate(flush);
}
/// <summary>
/// Ends an inflation session.
/// </summary>
/// <remarks>
/// Call this after successively calling Inflate(). This will cause all buffers to be flushed.
/// After calling this you cannot call Inflate() without a intervening call to one of the
/// InitializeInflate() overloads.
/// </remarks>
/// <returns>Z_OK if everything goes well.</returns>
public int EndInflate()
{
if (istate == null)
throw new ZlibException("No Inflate State!");
int ret = istate.End();
istate = null;
return ret;
}
/// <summary>
/// I don't know what this does!
/// </summary>
/// <returns>Z_OK if everything goes well.</returns>
public int SyncInflate()
{
if (istate == null)
throw new ZlibException("No Inflate State!");
return istate.Sync();
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation.
/// </summary>
/// <remarks>
/// The codec will use the MAX window bits and the default level of compression.
/// </remarks>
/// <example>
/// <code>
/// int bufferSize = 40000;
/// byte[] CompressedBytes = new byte[bufferSize];
/// byte[] DecompressedBytes = new byte[bufferSize];
///
/// ZlibCodec compressor = new ZlibCodec();
///
/// compressor.InitializeDeflate(CompressionLevel.Default);
///
/// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
/// compressor.NextIn = 0;
/// compressor.AvailableBytesIn = compressor.InputBuffer.Length;
///
/// compressor.OutputBuffer = CompressedBytes;
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = CompressedBytes.Length;
///
/// while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
/// {
/// compressor.Deflate(FlushType.None);
/// }
///
/// while (true)
/// {
/// int rc= compressor.Deflate(FlushType.Finish);
/// if (rc == ZlibConstants.Z_STREAM_END) break;
/// }
///
/// compressor.EndDeflate();
///
/// </code>
/// </example>
/// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns>
public int InitializeDeflate()
{
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
/// </summary>
/// <remarks>
/// The codec will use the maximum window bits (15) and the specified
/// CompressionLevel. It will emit a ZLIB stream as it compresses.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level)
{
this.CompressLevel = level;
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
/// and the explicit flag governing whether to emit an RFC1950 header byte pair.
/// </summary>
/// <remarks>
/// The codec will use the maximum window bits (15) and the specified CompressionLevel.
/// If you want to generate a zlib stream, you should specify true for
/// wantRfc1950Header. In this case, the library will emit a ZLIB
/// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950</see>, in the compressed stream.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header)
{
this.CompressLevel = level;
return _InternalInitializeDeflate(wantRfc1950Header);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
/// and the specified number of window bits.
/// </summary>
/// <remarks>
/// The codec will use the specified number of window bits and the specified CompressionLevel.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, int bits)
{
this.CompressLevel = level;
this.WindowBits = bits;
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified
/// CompressionLevel, the specified number of window bits, and the explicit flag
/// governing whether to emit an RFC1950 header byte pair.
/// </summary>
///
/// <param name="level">The compression level for the codec.</param>
/// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
/// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header)
{
this.CompressLevel = level;
this.WindowBits = bits;
return _InternalInitializeDeflate(wantRfc1950Header);
}
private int _InternalInitializeDeflate(bool wantRfc1950Header)
{
if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate().");
dstate = new DeflateManager();
dstate.WantRfc1950HeaderBytes = wantRfc1950Header;
return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy);
}
/// <summary>
/// Deflate one batch of data.
/// </summary>
/// <remarks>
/// You must have set InputBuffer and OutputBuffer before calling this method.
/// </remarks>
/// <example>
/// <code>
/// private void DeflateBuffer(CompressionLevel level)
/// {
/// int bufferSize = 1024;
/// byte[] buffer = new byte[bufferSize];
/// ZlibCodec compressor = new ZlibCodec();
///
/// Logger.Log("\n============================================");
/// Logger.Log("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
/// MemoryStream ms = new MemoryStream();
///
/// int rc = compressor.InitializeDeflate(level);
///
/// compressor.InputBuffer = UncompressedBytes;
/// compressor.NextIn = 0;
/// compressor.AvailableBytesIn = UncompressedBytes.Length;
///
/// compressor.OutputBuffer = buffer;
///
/// // pass 1: deflate
/// do
/// {
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = buffer.Length;
/// rc = compressor.Deflate(FlushType.None);
///
/// if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
/// throw new Exception("deflating: " + compressor.Message);
///
/// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
/// }
/// while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
///
/// // pass 2: finish and flush
/// do
/// {
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = buffer.Length;
/// rc = compressor.Deflate(FlushType.Finish);
///
/// if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
/// throw new Exception("deflating: " + compressor.Message);
///
/// if (buffer.Length - compressor.AvailableBytesOut > 0)
/// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
/// }
/// while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
///
/// compressor.EndDeflate();
///
/// ms.Seek(0, SeekOrigin.Begin);
/// CompressedBytes = new byte[compressor.TotalBytesOut];
/// ms.Read(CompressedBytes, 0, CompressedBytes.Length);
/// }
/// </code>
/// </example>
/// <param name="flush">whether to flush all data as you deflate. Generally you will want to
/// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
/// flush everything.
/// </param>
/// <returns>Z_OK if all goes well.</returns>
public int Deflate(FlushType flush)
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
return dstate.Deflate(flush);
}
/// <summary>
/// End a deflation session.
/// </summary>
/// <remarks>
/// Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
/// </remarks>
/// <returns>Z_OK if all goes well.</returns>
public int EndDeflate()
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
// TODO: dinoch Tue, 03 Nov 2009 15:39 (test this)
//int ret = dstate.End();
dstate = null;
return ZlibConstants.Z_OK; //ret;
}
/// <summary>
/// Reset a codec for another deflation session.
/// </summary>
/// <remarks>
/// Call this to reset the deflation state. For example if a thread is deflating
/// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
/// block and before the next Deflate(None) of the second block.
/// </remarks>
/// <returns>Z_OK if all goes well.</returns>
public void ResetDeflate()
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
dstate.Reset();
}
/// <summary>
/// Set the CompressionStrategy and CompressionLevel for a deflation session.
/// </summary>
/// <param name="level">the level of compression to use.</param>
/// <param name="strategy">the strategy to use for compression.</param>
/// <returns>Z_OK if all goes well.</returns>
public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy)
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
return dstate.SetParams(level, strategy);
}
/// <summary>
/// Set the dictionary to be used for either Inflation or Deflation.
/// </summary>
/// <param name="dictionary">The dictionary bytes to use.</param>
/// <returns>Z_OK if all goes well.</returns>
public int SetDictionary(byte[] dictionary)
{
if (istate != null)
return istate.SetDictionary(dictionary);
if (dstate != null)
return dstate.SetDictionary(dictionary);
throw new ZlibException("No Inflate or Deflate state!");
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
internal void flush_pending()
{
int len = dstate.pendingCount;
if (len > AvailableBytesOut)
len = AvailableBytesOut;
if (len == 0)
return;
if (dstate.pending.Length <= dstate.nextPending ||
OutputBuffer.Length <= NextOut ||
dstate.pending.Length < (dstate.nextPending + len) ||
OutputBuffer.Length < (NextOut + len))
{
throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})",
dstate.pending.Length, dstate.pendingCount));
}
Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len);
NextOut += len;
dstate.nextPending += len;
TotalBytesOut += len;
AvailableBytesOut -= len;
dstate.pendingCount -= len;
if (dstate.pendingCount == 0)
{
dstate.nextPending = 0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
internal int read_buf(byte[] buf, int start, int size)
{
int len = AvailableBytesIn;
if (len > size)
len = size;
if (len == 0)
return 0;
AvailableBytesIn -= len;
if (dstate.WantRfc1950HeaderBytes)
{
_Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len);
}
Array.Copy(InputBuffer, NextIn, buf, start, len);
NextIn += len;
TotalBytesIn += len;
return len;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ILCompiler.Compiler.CppCodeGen;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
using Internal.IL;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler.CppCodeGen
{
internal class CppWriter
{
private CppCodegenCompilation _compilation;
private void SetWellKnownTypeSignatureName(WellKnownType wellKnownType, string mangledSignatureName)
{
var type = _compilation.TypeSystemContext.GetWellKnownType(wellKnownType);
var typeNode = _compilation.NodeFactory.ConstructedTypeSymbol(type);
_cppSignatureNames.Add(type, mangledSignatureName);
}
public CppWriter(CppCodegenCompilation compilation, string outputFilePath)
{
_compilation = compilation;
_out = new StreamWriter(new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, false));
// Unify this list with the one in CppCodegenNodeFactory
SetWellKnownTypeSignatureName(WellKnownType.Void, "void");
SetWellKnownTypeSignatureName(WellKnownType.Boolean, "uint8_t");
SetWellKnownTypeSignatureName(WellKnownType.Char, "uint16_t");
SetWellKnownTypeSignatureName(WellKnownType.SByte, "int8_t");
SetWellKnownTypeSignatureName(WellKnownType.Byte, "uint8_t");
SetWellKnownTypeSignatureName(WellKnownType.Int16, "int16_t");
SetWellKnownTypeSignatureName(WellKnownType.UInt16, "uint16_t");
SetWellKnownTypeSignatureName(WellKnownType.Int32, "int32_t");
SetWellKnownTypeSignatureName(WellKnownType.UInt32, "uint32_t");
SetWellKnownTypeSignatureName(WellKnownType.Int64, "int64_t");
SetWellKnownTypeSignatureName(WellKnownType.UInt64, "uint64_t");
SetWellKnownTypeSignatureName(WellKnownType.IntPtr, "intptr_t");
SetWellKnownTypeSignatureName(WellKnownType.UIntPtr, "uintptr_t");
SetWellKnownTypeSignatureName(WellKnownType.Single, "float");
SetWellKnownTypeSignatureName(WellKnownType.Double, "double");
BuildExternCSignatureMap();
}
private Dictionary<TypeDesc, string> _cppSignatureNames = new Dictionary<TypeDesc, string>();
public string GetCppSignatureTypeName(TypeDesc type)
{
string mangledName;
if (_cppSignatureNames.TryGetValue(type, out mangledName))
return mangledName;
// TODO: Use friendly names for enums
if (type.IsEnum)
mangledName = GetCppSignatureTypeName(type.UnderlyingType);
else
mangledName = GetCppTypeName(type);
if (!type.IsValueType && !type.IsByRef && !type.IsPointer)
mangledName += "*";
_cppSignatureNames.Add(type, mangledName);
return mangledName;
}
// extern "C" methods are sometimes referenced via different signatures.
// _externCSignatureMap contains the canonical signature of the extern "C" import. References
// via other signatures are required to use casts.
private Dictionary<string, MethodSignature> _externCSignatureMap = new Dictionary<string, MethodSignature>();
private void BuildExternCSignatureMap()
{
foreach (var nodeAlias in _compilation.NodeFactory.NodeAliases)
{
var methodNode = (CppMethodCodeNode)nodeAlias.Key;
_externCSignatureMap.Add(nodeAlias.Value, methodNode.Method.Signature);
}
}
private IEnumerable<string> GetParameterNamesForMethod(MethodDesc method)
{
// TODO: The uses of this method need revision. The right way to get to this info is from
// a MethodIL. For declarations, we don't need names.
method = method.GetTypicalMethodDefinition();
var ecmaMethod = method as EcmaMethod;
if (ecmaMethod != null && ecmaMethod.Module.PdbReader != null)
{
return (new EcmaMethodDebugInformation(ecmaMethod)).GetParameterNames();
}
return null;
}
public void AppendCppMethodDeclaration(CppGenerationBuffer sb, MethodDesc method, bool implementation, string externalMethodName = null, MethodSignature methodSignature = null)
{
if (methodSignature == null)
methodSignature = method.Signature;
if (externalMethodName != null)
{
sb.Append("extern \"C\" ");
}
else
{
if (!implementation)
{
sb.Append("static ");
}
}
sb.Append(GetCppSignatureTypeName(methodSignature.ReturnType));
sb.Append(" ");
if (externalMethodName != null)
{
sb.Append(externalMethodName);
}
else
{
if (implementation)
{
sb.Append(GetCppMethodDeclarationName(method.OwningType, GetCppMethodName(method)));
}
else
{
sb.Append(GetCppMethodName(method));
}
}
sb.Append("(");
bool hasThis = !methodSignature.IsStatic;
int argCount = methodSignature.Length;
if (hasThis)
argCount++;
List<string> parameterNames = null;
if (method != null)
{
IEnumerable<string> parameters = GetParameterNamesForMethod(method);
if (parameters != null)
{
parameterNames = new List<string>(parameters);
if (parameterNames.Count != 0)
{
System.Diagnostics.Debug.Assert(parameterNames.Count == argCount);
}
else
{
parameterNames = null;
}
}
}
for (int i = 0; i < argCount; i++)
{
if (hasThis)
{
if (i == 0)
{
var thisType = method.OwningType;
if (thisType.IsValueType)
thisType = thisType.MakeByRefType();
sb.Append(GetCppSignatureTypeName(thisType));
}
else
{
sb.Append(GetCppSignatureTypeName(methodSignature[i - 1]));
}
}
else
{
sb.Append(GetCppSignatureTypeName(methodSignature[i]));
}
if (implementation)
{
sb.Append(" ");
if (parameterNames != null)
{
sb.Append(SanitizeCppVarName(parameterNames[i]));
}
else
{
sb.Append("_a");
sb.Append(i.ToStringInvariant());
}
}
if (i != argCount - 1)
sb.Append(", ");
}
sb.Append(")");
if (!implementation)
sb.Append(";");
}
public void AppendCppMethodCallParamList(CppGenerationBuffer sb, MethodDesc method)
{
var methodSignature = method.Signature;
bool hasThis = !methodSignature.IsStatic;
int argCount = methodSignature.Length;
if (hasThis)
argCount++;
List<string> parameterNames = null;
IEnumerable<string> parameters = GetParameterNamesForMethod(method);
if (parameters != null)
{
parameterNames = new List<string>(parameters);
if (parameterNames.Count != 0)
{
System.Diagnostics.Debug.Assert(parameterNames.Count == argCount);
}
else
{
parameterNames = null;
}
}
for (int i = 0; i < argCount; i++)
{
if (parameterNames != null)
{
sb.Append(SanitizeCppVarName(parameterNames[i]));
}
else
{
sb.Append("_a");
sb.Append(i.ToStringInvariant());
}
if (i != argCount - 1)
sb.Append(", ");
}
}
public string GetCppTypeName(TypeDesc type)
{
switch (type.Category)
{
case TypeFlags.ByRef:
case TypeFlags.Pointer:
return GetCppSignatureTypeName(((ParameterizedType)type).ParameterType) + "*";
default:
return _compilation.NameMangler.GetMangledTypeName(type).ToString();
}
}
/// <summary>
/// Compute a proper declaration for <param name="methodName"/> defined in <param name="owningType"/>.
/// Usually the C++ name for a type is prefixed by "::" but this is not a valid way to declare a method,
/// so we need to strip it if present.
/// </summary>
/// <param name="owningType">Type where <param name="methodName"/> belongs.</param>
/// <param name="methodName">Name of method from <param name="owningType"/>.</param>
/// <returns>C++ declaration name for <param name="methodName"/>.</returns>
public string GetCppMethodDeclarationName(TypeDesc owningType, string methodName, bool isDeclaration = true)
{
var s = _compilation.NameMangler.GetMangledTypeName(owningType);
if (isDeclaration && s.StartsWith("::"))
{
// For a Method declaration we do not need the starting ::
s = s.Substring(2, s.Length - 2);
}
return string.Concat(s, "::", methodName);
}
public string GetCppMethodName(MethodDesc method)
{
return _compilation.NameMangler.GetMangledMethodName(method).ToString();
}
public string GetCppFieldName(FieldDesc field)
{
return _compilation.NameMangler.GetMangledFieldName(field).ToString();
}
public string GetCppStaticFieldName(FieldDesc field)
{
TypeDesc type = field.OwningType;
string typeName = GetCppTypeName(type);
return typeName.Replace("::", "__") + "__" + _compilation.NameMangler.GetMangledFieldName(field);
}
public string SanitizeCppVarName(string varName)
{
// TODO: name mangling robustness
if (varName == "errno" || varName == "environ" || varName == "template" || varName == "typename") // some names collide with CRT headers
return "_" + varName + "_";
return _compilation.NameMangler.SanitizeName(varName);
}
private void CompileExternMethod(CppMethodCodeNode methodCodeNodeNeedingCode, string importName)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
MethodSignature methodSignature = method.Signature;
bool slotCastRequired = false;
MethodSignature externCSignature;
if (_externCSignatureMap.TryGetValue(importName, out externCSignature))
{
slotCastRequired = !externCSignature.Equals(methodSignature);
}
else
{
_externCSignatureMap.Add(importName, methodSignature);
externCSignature = methodSignature;
}
var sb = new CppGenerationBuffer();
sb.AppendLine();
AppendCppMethodDeclaration(sb, method, true);
sb.AppendLine();
sb.Append("{");
sb.Indent();
if (slotCastRequired)
{
AppendSlotTypeDef(sb, method);
}
sb.AppendLine();
if (!method.Signature.ReturnType.IsVoid)
{
sb.Append("return ");
}
if (slotCastRequired)
sb.Append("((__slot__" + GetCppMethodName(method) + ")");
sb.Append("::");
sb.Append(importName);
if (slotCastRequired)
sb.Append(")");
sb.Append("(");
AppendCppMethodCallParamList(sb, method);
sb.Append(");");
sb.Exdent();
sb.AppendLine();
sb.Append("}");
methodCodeNodeNeedingCode.SetCode(sb.ToString(), Array.Empty<Object>());
}
public void CompileMethod(CppMethodCodeNode methodCodeNodeNeedingCode)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
_compilation.Logger.Writer.WriteLine("Compiling " + method.ToString());
if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute"))
{
CompileExternMethod(methodCodeNodeNeedingCode, ((EcmaMethod)method).GetRuntimeImportName());
return;
}
if (method.IsRawPInvoke())
{
CompileExternMethod(methodCodeNodeNeedingCode, method.GetPInvokeMethodMetadata().Name ?? method.Name);
return;
}
var methodIL = _compilation.GetMethodIL(method);
if (methodIL == null)
return;
try
{
// TODO: hacky special-case
if (method.Name == "_ecvt_s")
throw new NotImplementedException();
var ilImporter = new ILImporter(_compilation, this, method, methodIL);
CompilerTypeSystemContext typeSystemContext = _compilation.TypeSystemContext;
MethodDebugInformation debugInfo = _compilation.GetDebugInfo(methodIL);
if (!_compilation.Options.HasOption(CppCodegenConfigProvider.NoLineNumbersString))
{
IEnumerable<ILSequencePoint> sequencePoints = debugInfo.GetSequencePoints();
if (sequencePoints != null)
ilImporter.SetSequencePoints(sequencePoints);
}
IEnumerable<ILLocalVariable> localVariables = debugInfo.GetLocalVariables();
if (localVariables != null)
ilImporter.SetLocalVariables(localVariables);
IEnumerable<string> parameters = GetParameterNamesForMethod(method);
if (parameters != null)
ilImporter.SetParameterNames(parameters);
ilImporter.Compile(methodCodeNodeNeedingCode);
}
catch (Exception e)
{
_compilation.Logger.Writer.WriteLine(e.Message + " (" + method + ")");
var sb = new CppGenerationBuffer();
sb.AppendLine();
AppendCppMethodDeclaration(sb, method, true);
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("throw 0xC000C000;");
sb.Exdent();
sb.AppendLine();
sb.Append("}");
methodCodeNodeNeedingCode.SetCode(sb.ToString(), Array.Empty<Object>());
}
}
private TextWriter Out
{
get
{
return _out;
}
}
private StreamWriter _out;
private Dictionary<TypeDesc, List<MethodDesc>> _methodLists;
private CppGenerationBuffer _statics;
private CppGenerationBuffer _gcStatics;
private CppGenerationBuffer _threadStatics;
private CppGenerationBuffer _gcThreadStatics;
// Base classes and valuetypes has to be emitted before they are used.
private HashSet<TypeDesc> _emittedTypes;
private TypeDesc GetFieldTypeOrPlaceholder(FieldDesc field)
{
try
{
return field.FieldType;
}
catch
{
// TODO: For now, catch errors due to missing dependencies
return _compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Boolean);
}
}
private void OutputTypeFields(CppGenerationBuffer sb, TypeDesc t)
{
bool explicitLayout = false;
ClassLayoutMetadata classLayoutMetadata = default(ClassLayoutMetadata);
if (t.IsValueType)
{
MetadataType metadataType = (MetadataType)t;
if (metadataType.IsExplicitLayout)
{
explicitLayout = true;
classLayoutMetadata = metadataType.GetClassLayout();
}
}
int instanceFieldIndex = 0;
if (explicitLayout)
{
sb.AppendLine();
sb.Append("union {");
sb.Indent();
}
foreach (var field in t.GetFields())
{
if (field.IsStatic)
{
if (field.IsLiteral)
continue;
TypeDesc fieldType = GetFieldTypeOrPlaceholder(field);
CppGenerationBuffer builder;
if (!fieldType.IsValueType)
{
builder = _gcStatics;
}
else
{
// TODO: Valuetype statics with GC references
builder = _statics;
}
builder.AppendLine();
builder.Append(GetCppSignatureTypeName(fieldType));
builder.Append(" ");
builder.Append(GetCppStaticFieldName(field) + ";");
}
else
{
if (explicitLayout)
{
sb.AppendLine();
sb.Append("struct {");
sb.Indent();
int offset = classLayoutMetadata.Offsets[instanceFieldIndex].Offset.AsInt;
if (offset > 0)
{
sb.AppendLine();
sb.Append("char __pad" + instanceFieldIndex + "[" + offset + "];");
}
}
sb.AppendLine();
sb.Append(GetCppSignatureTypeName(GetFieldTypeOrPlaceholder(field)) + " " + GetCppFieldName(field) + ";");
if (explicitLayout)
{
sb.Exdent();
sb.AppendLine();
sb.Append("};");
}
instanceFieldIndex++;
}
}
if (explicitLayout)
{
sb.Exdent();
sb.AppendLine();
sb.Append("};");
}
}
private void AppendSlotTypeDef(CppGenerationBuffer sb, MethodDesc method)
{
MethodSignature methodSignature = method.Signature;
TypeDesc thisArgument = null;
if (!methodSignature.IsStatic)
thisArgument = method.OwningType;
AppendSignatureTypeDef(sb, "__slot__" + GetCppMethodName(method), methodSignature, thisArgument);
}
internal void AppendSignatureTypeDef(CppGenerationBuffer sb, string name, MethodSignature methodSignature, TypeDesc thisArgument)
{
sb.AppendLine();
sb.Append("typedef ");
sb.Append(GetCppSignatureTypeName(methodSignature.ReturnType));
sb.Append("(*");
sb.Append(name);
sb.Append(")(");
int argCount = methodSignature.Length;
if (thisArgument != null)
argCount++;
for (int i = 0; i < argCount; i++)
{
if (thisArgument != null)
{
if (i == 0)
{
sb.Append(GetCppSignatureTypeName(thisArgument));
}
else
{
sb.Append(GetCppSignatureTypeName(methodSignature[i - 1]));
}
}
else
{
sb.Append(GetCppSignatureTypeName(methodSignature[i]));
}
if (i != argCount - 1)
sb.Append(", ");
}
sb.Append(");");
}
private String GetCodeForDelegate(TypeDesc delegateType)
{
var sb = new CppGenerationBuffer();
MethodDesc method = delegateType.GetKnownMethod("Invoke", null);
AppendSlotTypeDef(sb, method);
sb.AppendLine();
sb.Append("static __slot__");
sb.Append(GetCppMethodName(method));
sb.Append(" __invoke__");
sb.Append(GetCppMethodName(method));
sb.Append("(void * pThis)");
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("return (__slot__");
sb.Append(GetCppMethodName(method));
sb.Append(")(((");
sb.Append(GetCppSignatureTypeName(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.MulticastDelegate)));
sb.Append(")pThis)->m_functionPointer);");
sb.Exdent();
sb.AppendLine();
sb.Append("};");
return sb.ToString();
}
private String GetCodeForVirtualMethod(MethodDesc method, int slot)
{
var sb = new CppGenerationBuffer();
sb.Indent();
if (method.OwningType.IsInterface)
{
AppendSlotTypeDef(sb, method);
sb.Indent();
sb.AppendLine();
sb.Append("static uint16_t");
sb.Append(" __getslot__");
sb.Append(GetCppMethodName(method));
sb.Append("(void * pThis)");
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("return ");
sb.Append(slot);
sb.Append(";");
sb.AppendLine();
}
else
{
AppendSlotTypeDef(sb, method);
sb.Indent();
sb.AppendLine();
sb.Append("static __slot__");
sb.Append(GetCppMethodName(method));
sb.Append(" __getslot__");
sb.Append(GetCppMethodName(method));
sb.Append("(void * pThis)");
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append(" return (__slot__");
sb.Append(GetCppMethodName(method));
sb.Append(")*((void **)(*((RawEEType **)pThis) + 1) + ");
sb.Append(slot.ToStringInvariant());
sb.Append(");");
}
sb.Exdent();
sb.AppendLine();
sb.Append("};");
sb.Exdent();
return sb.ToString();
}
private String GetCodeForObjectNode(ObjectNode node, NodeFactory factory)
{
// virtual slots
var nodeData = node.GetData(factory, false);
CppGenerationBuffer nodeCode = new CppGenerationBuffer();
/* Create list of byte data. Used to divide contents between reloc and byte data
* First val - isReloc
* Second val - size of byte data if first value of tuple is false
*/
List<NodeDataSection> nodeDataSections = new List<NodeDataSection>();
byte[] actualData = new byte[nodeData.Data.Length];
Relocation[] relocs = nodeData.Relocs;
int nextRelocOffset = -1;
int nextRelocIndex = -1;
int lastByteIndex = 0;
if (relocs.Length > 0)
{
nextRelocOffset = relocs[0].Offset;
nextRelocIndex = 0;
}
int i = 0;
int offset = 0;
CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();
if (node is ISymbolDefinitionNode)
{
offset = (node as ISymbolDefinitionNode).Offset;
i = offset;
lastByteIndex = offset;
}
while (i < nodeData.Data.Length)
{
if (i == nextRelocOffset)
{
Relocation reloc = relocs[nextRelocIndex];
int size = _compilation.TypeSystemContext.Target.PointerSize;
// Make sure we've gotten the correct size for the reloc
System.Diagnostics.Debug.Assert(reloc.RelocType == (size == 8 ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW));
// Update nextRelocIndex/Offset
if (++nextRelocIndex < relocs.Length)
{
nextRelocOffset = relocs[nextRelocIndex].Offset;
}
nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.Relocation, size));
i += size;
lastByteIndex = i;
}
else
{
i++;
if (i + 1 == nextRelocOffset || i + 1 == nodeData.Data.Length)
{
nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.ByteData, (i + 1) - lastByteIndex));
}
}
}
string pointerType = node is EETypeNode ? "MethodTable * " : "void* ";
nodeCode.Append(pointerType);
if (node is EETypeNode)
{
nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable"));
}
else
{
string mangledName = ((ISymbolNode)node).GetMangledName(factory.NameMangler);
// Rename generic composition and optional fields nodes to avoid name clash with types
bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode;
nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName);
}
nodeCode.Append("()");
nodeCode.AppendLine();
nodeCode.Append("{");
nodeCode.Indent();
nodeCode.AppendLine();
nodeCode.Append("static struct {");
nodeCode.AppendLine();
nodeCode.Append(GetCodeForNodeStruct(nodeDataSections, node));
nodeCode.AppendLine();
nodeCode.Append("} mt = {");
nodeCode.Append(GetCodeForNodeData(nodeDataSections, relocs, nodeData.Data, node, offset, factory));
nodeCode.Append("};");
nodeCode.AppendLine();
nodeCode.Append("return ( ");
nodeCode.Append(pointerType);
nodeCode.Append(")&mt;");
nodeCode.Exdent();
nodeCode.AppendLine();
nodeCode.Append("}");
nodeCode.AppendLine();
return nodeCode.ToString();
}
private String GetCodeForNodeData(List<NodeDataSection> nodeDataSections, Relocation[] relocs, byte[] byteData, DependencyNode node, int offset, NodeFactory factory)
{
CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();
int relocCounter = 0;
int divisionStartIndex = offset;
nodeDataDecl.Indent();
nodeDataDecl.Indent();
nodeDataDecl.AppendLine();
for (int i = 0; i < nodeDataSections.Count; i++)
{
if (nodeDataSections[i].SectionType == NodeDataSectionType.Relocation)
{
Relocation reloc = relocs[relocCounter];
nodeDataDecl.Append(GetCodeForReloc(reloc, node, factory));
nodeDataDecl.Append(",");
relocCounter++;
}
else
{
AppendFormattedByteArray(nodeDataDecl, byteData, divisionStartIndex, divisionStartIndex + nodeDataSections[i].SectionSize);
nodeDataDecl.Append(",");
}
divisionStartIndex += nodeDataSections[i].SectionSize;
nodeDataDecl.AppendLine();
}
return nodeDataDecl.ToString();
}
private String GetCodeForReloc(Relocation reloc, DependencyNode node, NodeFactory factory)
{
CppGenerationBuffer relocCode = new CppGenerationBuffer();
if (reloc.Target is CppMethodCodeNode)
{
var method = reloc.Target as CppMethodCodeNode;
relocCode.Append("(void*)&");
relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, GetCppMethodName(method.Method), false));
}
else if (reloc.Target is EETypeNode && node is EETypeNode)
{
relocCode.Append(GetCppMethodDeclarationName((reloc.Target as EETypeNode).Type, "__getMethodTable", false));
relocCode.Append("()");
}
// Node is either an non-emitted type or a generic composition - both are ignored for CPP codegen
else if ((reloc.Target is TypeManagerIndirectionNode || reloc.Target is InterfaceDispatchMapNode || reloc.Target is EETypeOptionalFieldsNode || reloc.Target is GenericCompositionNode) && !(reloc.Target as ObjectNode).ShouldSkipEmittingObjectNode(factory))
{
string mangledTargetName = reloc.Target.GetMangledName(factory.NameMangler);
bool shouldReplaceNamespaceQualifier = reloc.Target is GenericCompositionNode || reloc.Target is EETypeOptionalFieldsNode;
relocCode.Append(shouldReplaceNamespaceQualifier ? mangledTargetName.Replace("::", "_") : mangledTargetName);
relocCode.Append("()");
}
else if (reloc.Target is ObjectAndOffsetSymbolNode &&
(reloc.Target as ObjectAndOffsetSymbolNode).Target is ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode>)
{
relocCode.Append("dispatchMapModule");
}
else
{
relocCode.Append("NULL");
}
return relocCode.ToString();
}
private String GetCodeForNodeStruct(List<NodeDataSection> nodeDataDivs, DependencyNode node)
{
CppGenerationBuffer nodeStructDecl = new CppGenerationBuffer();
int relocCounter = 1;
int i = 0;
nodeStructDecl.Indent();
for (i = 0; i < nodeDataDivs.Count; i++)
{
NodeDataSection section = nodeDataDivs[i];
if (section.SectionType == NodeDataSectionType.Relocation)
{
nodeStructDecl.Append("void* reloc");
nodeStructDecl.Append(relocCounter);
nodeStructDecl.Append(";");
relocCounter++;
}
else
{
nodeStructDecl.Append("unsigned char data");
nodeStructDecl.Append((i + 1) - relocCounter);
nodeStructDecl.Append("[");
nodeStructDecl.Append(section.SectionSize);
nodeStructDecl.Append("];");
}
nodeStructDecl.AppendLine();
}
nodeStructDecl.Exdent();
return nodeStructDecl.ToString();
}
private static void AppendFormattedByteArray(CppGenerationBuffer sb, byte[] array, int startIndex, int endIndex)
{
sb.Append("{");
sb.Append("0x");
sb.Append(BitConverter.ToString(array, startIndex, endIndex - startIndex).Replace("-", ",0x"));
sb.Append("}");
}
private void BuildMethodLists(IEnumerable<DependencyNode> nodes)
{
_methodLists = new Dictionary<TypeDesc, List<MethodDesc>>();
foreach (var node in nodes)
{
if (node is CppMethodCodeNode)
{
CppMethodCodeNode methodCodeNode = (CppMethodCodeNode)node;
var method = methodCodeNode.Method;
var type = method.OwningType;
List<MethodDesc> methodList;
if (!_methodLists.TryGetValue(type, out methodList))
{
GetCppSignatureTypeName(type);
methodList = new List<MethodDesc>();
_methodLists.Add(type, methodList);
}
methodList.Add(method);
}
else
if (node is IEETypeNode)
{
IEETypeNode eeTypeNode = (IEETypeNode)node;
if (eeTypeNode.Type.IsGenericDefinition)
{
// TODO: CppWriter can't handle generic type definition EETypes
}
else
GetCppSignatureTypeName(eeTypeNode.Type);
}
}
}
/// <summary>
/// Output C++ code via a given dependency graph
/// </summary>
/// <param name="nodes">A set of dependency nodes</param>
/// <param name="entrypoint">Code entrypoint</param>
/// <param name="factory">Associated NodeFactory instance</param>
/// <param name="definitions">Text buffer in which the type and method definitions will be written</param>
/// <param name="implementation">Text buffer in which the method implementations will be written</param>
public void OutputNodes(IEnumerable<DependencyNode> nodes, NodeFactory factory)
{
CppGenerationBuffer dispatchPointers = new CppGenerationBuffer();
CppGenerationBuffer forwardDefinitions = new CppGenerationBuffer();
CppGenerationBuffer typeDefinitions = new CppGenerationBuffer();
CppGenerationBuffer methodTables = new CppGenerationBuffer();
CppGenerationBuffer additionalNodes = new CppGenerationBuffer();
DependencyNodeIterator nodeIterator = new DependencyNodeIterator(nodes);
// Number of InterfaceDispatchMapNodes needs to be declared explicitly for Ubuntu and OSX
int dispatchMapCount = 0;
dispatchPointers.AppendLine();
dispatchPointers.Indent();
//RTR header needs to be declared after all modules have already been output
string rtrHeader = string.Empty;
// Iterate through nodes
foreach (var node in nodeIterator.GetNodes())
{
if (node is EETypeNode)
OutputTypeNode(node as EETypeNode, factory, forwardDefinitions, typeDefinitions, methodTables);
else if ((node is EETypeOptionalFieldsNode || node is TypeManagerIndirectionNode || node is GenericCompositionNode) && !(node as ObjectNode).ShouldSkipEmittingObjectNode(factory))
additionalNodes.Append(GetCodeForObjectNode(node as ObjectNode, factory));
else if (node is InterfaceDispatchMapNode)
{
dispatchPointers.Append("(void *)");
dispatchPointers.Append(((ISymbolNode)node).GetMangledName(factory.NameMangler));
dispatchPointers.Append("(),");
dispatchPointers.AppendLine();
dispatchMapCount++;
additionalNodes.Append(GetCodeForObjectNode(node as ObjectNode, factory));
}
else if (node is ReadyToRunHeaderNode)
rtrHeader = GetCodeForReadyToRunHeader(node as ReadyToRunHeaderNode, factory);
}
dispatchPointers.AppendLine();
dispatchPointers.Exdent();
Out.Write(forwardDefinitions.ToString());
Out.Write(typeDefinitions.ToString());
Out.Write(additionalNodes.ToString());
Out.Write(methodTables.ToString());
// Emit pointers to dispatch map nodes, to be used in interface dispatch
Out.Write("void * dispatchMapModule[");
Out.Write(dispatchMapCount);
Out.Write("] = {");
Out.Write(dispatchPointers.ToString());
Out.Write("};");
Out.Write(rtrHeader);
}
/// <summary>
/// Output C++ code for a given codeNode
/// </summary>
/// <param name="methodCodeNode">The code node to be output</param>
/// <param name="methodImplementations">The buffer in which to write out the C++ code</param>
private void OutputMethodNode(CppMethodCodeNode methodCodeNode)
{
Out.WriteLine();
Out.Write(methodCodeNode.CppCode);
var alternateName = _compilation.NodeFactory.GetSymbolAlternateName(methodCodeNode);
if (alternateName != null)
{
CppGenerationBuffer sb = new CppGenerationBuffer();
sb.AppendLine();
AppendCppMethodDeclaration(sb, methodCodeNode.Method, true, alternateName);
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
if (!methodCodeNode.Method.Signature.ReturnType.IsVoid)
{
sb.Append("return ");
}
sb.Append(GetCppMethodDeclarationName(methodCodeNode.Method.OwningType, GetCppMethodName(methodCodeNode.Method)));
sb.Append("(");
AppendCppMethodCallParamList(sb, methodCodeNode.Method);
sb.Append(");");
sb.Exdent();
sb.AppendLine();
sb.Append("}");
Out.Write(sb.ToString());
}
}
private void OutputTypeNode(IEETypeNode typeNode, NodeFactory factory, CppGenerationBuffer forwardDefinitions, CppGenerationBuffer typeDefinitions, CppGenerationBuffer methodTable)
{
if (_emittedTypes == null)
{
_emittedTypes = new HashSet<TypeDesc>();
}
TypeDesc nodeType = typeNode.Type;
if (_emittedTypes.Contains(nodeType))
return;
_emittedTypes.Add(nodeType);
// Create Namespaces
string mangledName = _compilation.NameMangler.GetMangledTypeName(nodeType);
int nesting = 0;
int current = 0;
forwardDefinitions.AppendLine();
for (;;)
{
int sep = mangledName.IndexOf("::", current);
if (sep < 0)
break;
if (sep != 0)
{
// Case of a name not starting with ::
forwardDefinitions.Append("namespace " + mangledName.Substring(current, sep - current) + " { ");
typeDefinitions.Append("namespace " + mangledName.Substring(current, sep - current) + " { ");
typeDefinitions.Indent();
nesting++;
}
current = sep + 2;
}
forwardDefinitions.Append("class " + mangledName.Substring(current) + ";");
// type definition
typeDefinitions.Append("class " + mangledName.Substring(current));
if (!nodeType.IsValueType)
{
// Don't emit inheritance if base type has not been marked for emission
if (nodeType.BaseType != null && _emittedTypes.Contains(nodeType.BaseType))
{
typeDefinitions.Append(" : public " + GetCppTypeName(nodeType.BaseType));
}
}
typeDefinitions.Append(" {");
typeDefinitions.AppendLine();
typeDefinitions.Append("public:");
typeDefinitions.Indent();
// TODO: Enable once the dependencies are tracked for arrays
// if (((DependencyNode)_compilation.NodeFactory.ConstructedTypeSymbol(t)).Marked)
{
typeDefinitions.AppendLine();
typeDefinitions.Append("static MethodTable * __getMethodTable();");
}
if (typeNode is ConstructedEETypeNode)
{
OutputTypeFields(typeDefinitions, nodeType);
IReadOnlyList<MethodDesc> virtualSlots = _compilation.NodeFactory.VTable(nodeType).Slots;
int baseSlots = 0;
var baseType = nodeType.BaseType;
while (baseType != null)
{
IReadOnlyList<MethodDesc> baseVirtualSlots = _compilation.NodeFactory.VTable(baseType).Slots;
if (baseVirtualSlots != null)
baseSlots += baseVirtualSlots.Count;
baseType = baseType.BaseType;
}
for (int slot = 0; slot < virtualSlots.Count; slot++)
{
MethodDesc virtualMethod = virtualSlots[slot];
typeDefinitions.AppendLine();
typeDefinitions.Append(GetCodeForVirtualMethod(virtualMethod, baseSlots + slot));
}
if (nodeType.IsDelegate)
{
typeDefinitions.AppendLine();
typeDefinitions.Append(GetCodeForDelegate(nodeType));
}
}
if (nodeType.HasStaticConstructor)
{
_statics.AppendLine();
_statics.Append("bool __cctor_" + GetCppTypeName(nodeType).Replace("::", "__") + ";");
}
List<MethodDesc> methodList;
if (_methodLists.TryGetValue(nodeType, out methodList))
{
foreach (var m in methodList)
{
typeDefinitions.AppendLine();
AppendCppMethodDeclaration(typeDefinitions, m, false);
}
}
typeDefinitions.AppendEmptyLine();
typeDefinitions.Append("};");
typeDefinitions.AppendEmptyLine();
typeDefinitions.Exdent();
while (nesting > 0)
{
forwardDefinitions.Append("};");
typeDefinitions.Append("};");
typeDefinitions.Exdent();
nesting--;
}
typeDefinitions.AppendEmptyLine();
// declare method table
methodTable.Append(GetCodeForObjectNode(typeNode as ObjectNode, factory));
methodTable.AppendEmptyLine();
}
private String GetCodeForReadyToRunHeader(ReadyToRunHeaderNode headerNode, NodeFactory factory)
{
CppGenerationBuffer rtrHeader = new CppGenerationBuffer();
int pointerSize = _compilation.TypeSystemContext.Target.PointerSize;
rtrHeader.Append(GetCodeForObjectNode(headerNode, factory));
rtrHeader.AppendLine();
rtrHeader.Append("void* RtRHeaderWrapper() {");
rtrHeader.Indent();
rtrHeader.AppendLine();
rtrHeader.Append("static struct {");
rtrHeader.AppendLine();
if (pointerSize == 8)
rtrHeader.Append("unsigned char leftPadding[8];");
else
rtrHeader.Append("unsigned char leftPadding[4];");
rtrHeader.AppendLine();
rtrHeader.Append("void* rtrHeader;");
rtrHeader.AppendLine();
if (pointerSize == 8)
rtrHeader.Append("unsigned char rightPadding[8];");
else
rtrHeader.Append("unsigned char rightPadding[4];");
rtrHeader.AppendLine();
rtrHeader.Append("} rtrHeaderWrapper = {");
rtrHeader.Indent();
rtrHeader.AppendLine();
if (pointerSize == 8)
rtrHeader.Append("{ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },");
else
rtrHeader.Append("{ 0x00,0x00,0x00,0x00 },");
rtrHeader.AppendLine();
rtrHeader.Append("(void*)");
rtrHeader.Append(headerNode.GetMangledName(factory.NameMangler));
rtrHeader.Append("(),");
rtrHeader.AppendLine();
if (pointerSize == 8)
rtrHeader.Append("{ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }");
else
rtrHeader.Append("{ 0x00,0x00,0x00,0x00 },");
rtrHeader.AppendLine();
rtrHeader.Append("};");
rtrHeader.Exdent();
rtrHeader.AppendLine();
rtrHeader.Append("return (void *)&rtrHeaderWrapper;");
rtrHeader.Exdent();
rtrHeader.AppendLine();
rtrHeader.Append("}");
rtrHeader.AppendLine();
return rtrHeader.ToString();
}
private void OutputExternCSignatures()
{
var sb = new CppGenerationBuffer();
foreach (var externC in _externCSignatureMap)
{
string importName = externC.Key;
// TODO: hacky special-case
if (importName != "memmove" && importName != "malloc") // some methods are already declared by the CRT headers
{
sb.AppendLine();
AppendCppMethodDeclaration(sb, null, false, importName, externC.Value);
}
}
Out.Write(sb.ToString());
}
public void OutputCode(IEnumerable<DependencyNode> nodes, NodeFactory factory)
{
BuildMethodLists(nodes);
Out.WriteLine("#include \"common.h\"");
Out.WriteLine("#include \"CppCodeGen.h\"");
Out.WriteLine();
_statics = new CppGenerationBuffer();
_statics.Indent();
_gcStatics = new CppGenerationBuffer();
_gcStatics.Indent();
_threadStatics = new CppGenerationBuffer();
_threadStatics.Indent();
_gcThreadStatics = new CppGenerationBuffer();
_gcThreadStatics.Indent();
OutputNodes(nodes, factory);
Out.Write("struct {");
Out.Write(_statics.ToString());
Out.Write("} __statics;");
Out.Write("struct {");
Out.Write(_gcStatics.ToString());
Out.Write("} __gcStatics;");
Out.Write("struct {");
Out.Write(_gcStatics.ToString());
Out.Write("} __gcThreadStatics;");
OutputExternCSignatures();
foreach (var node in nodes)
{
if (node is CppMethodCodeNode)
OutputMethodNode(node as CppMethodCodeNode);
}
Out.Dispose();
}
}
}
| |
using System.Text.RegularExpressions;
using System.Diagnostics;
using System;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI;
using Microsoft.Win32;
using WeifenLuo;
using SoftLogik.Win.UI;
namespace SoftLogik.Win.UI.Support
{
sealed class ToolbarSupport
{
public class MasterToolbarButtonNames
{
public const string ToolbarNew = "NewRecord";
public const string ToolbarDelete = "DeleteRecord";
public const string ToolbarSave = "SaveRecord";
public const string ToolbarUndo = "UndoRecord";
public const string ToolbarCopy = "CopyRecord";
public const string ToolbarRefresh = "RefreshRecord";
public const string ToolbarSort = "SortRecord";
public const string ToolbarSearch = "SearchRecord";
public const string ToolbarLast = "LastRecord";
public const string ToolbarFirst = "FirstRecord";
public const string ToolbarNext = "NextRecord";
public const string ToolbarPrevious = "PreviousRecord";
public const string ToolbarClose = "CloseWindow";
}
public static void ToolbarToggle(ToolStrip tbrAny, bool InitialState)
{
try
{
if (InitialState)
{
ToolStrip with_1 = tbrAny;
with_1.Items[MasterToolbarButtonNames.ToolbarSave].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarUndo].Enabled = false;
}
}
catch (Exception)
{
}
}
public static void ToolbarToggleDefault(ref ToolStrip tbrAny)
{
ToolbarToggleDefault(tbrAny, null);
}
public static void ToolbarToggleDefault(ToolStrip tbrAny, DataTreeView treeVw)
{
//On Error Resume Next VBConversions Warning: On Error Resume Next not supported in C#
ToolStrip with_1 = tbrAny;
with_1.Items[MasterToolbarButtonNames.ToolbarSave].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarUndo].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarDelete].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarSearch].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarCopy].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarNew].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarRefresh].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarSort].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarFirst].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarNext].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarPrevious].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarLast].Enabled = true;
if (treeVw != null)
{
treeVw.Enabled = true;
}
}
public static void ToolbarToggleSave(ref ToolStrip tbrAny)
{
ToolbarToggleSave(tbrAny, null);
}
public static void ToolbarToggleSave(ToolStrip tbrAny, DataTreeView treeVw)
{
//On Error Resume Next VBConversions Warning: On Error Resume Next not supported in C#
ToolStrip with_1 = tbrAny;
with_1.Items[MasterToolbarButtonNames.ToolbarSave].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarUndo].Enabled = true;
with_1.Items[MasterToolbarButtonNames.ToolbarDelete].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarSearch].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarCopy].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarNew].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarRefresh].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarSort].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarFirst].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarNext].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarPrevious].Enabled = false;
with_1.Items[MasterToolbarButtonNames.ToolbarLast].Enabled = false;
if (treeVw != null)
{
treeVw.Enabled = false;
}
}
public static void ToolbarToggle(ToolStrip tbrAny)
{
try
{
ToolStrip with_1 = tbrAny;
with_1.Items[MasterToolbarButtonNames.ToolbarNew].Enabled = ! with_1.Items[MasterToolbarButtonNames.ToolbarNew].Enabled;
with_1.Items[MasterToolbarButtonNames.ToolbarDelete].Enabled = ! with_1.Items[MasterToolbarButtonNames.ToolbarDelete].Enabled;
with_1.Items[MasterToolbarButtonNames.ToolbarSave].Enabled = ! with_1.Items[MasterToolbarButtonNames.ToolbarSave].Enabled;
with_1.Items[MasterToolbarButtonNames.ToolbarUndo].Enabled = ! with_1.Items[MasterToolbarButtonNames.ToolbarUndo].Enabled;
with_1.Items[MasterToolbarButtonNames.ToolbarSearch].Enabled = ! with_1.Items[MasterToolbarButtonNames.ToolbarSearch].Enabled;
}
catch (Exception)
{
}
}
public static void TransactionToolStrip(ToolStrip SourceToolbar)
{
ToolStripItem btn = null;
try
{
ToolStrip with_1 = SourceToolbar;
with_1.Items.Add(new ToolStripSeparator()); //Add a Separator
btn = new ToolStripButton();
ToolStripButton with_2 = ((ToolStripButton) btn);
with_2.AutoToolTip = true;
with_2.ToolTipText = CultureSupport.TextDictionary("TT_SAVECHANGES", TextReturnTypeEnum.PureString);
with_2.Tag = "Save";
with_1.Items.Add(btn);
btn = new ToolStripButton();
ToolStripButton with_3 = ((ToolStripButton) btn);
with_3.AutoToolTip = true;
with_3.ToolTipText = CultureSupport.TextDictionary("TT_UNDOCHANGES", TextReturnTypeEnum.PureString);
with_3.Tag = "Undo";
with_1.Items.Add(btn);
with_1.Items.Add(new ToolStripSeparator());
btn = new ToolStripButton();
ToolStripButton with_4 = ((ToolStripButton) btn);
with_4.AutoToolTip = true;
with_4.ToolTipText = CultureSupport.TextDictionary("TT_CLOSE", TextReturnTypeEnum.PureString);
with_4.Tag = "Exit";
with_1.Items.Add(btn);
}
catch (Exception)
{
}
finally
{
btn.Dispose();
}
}
public static void MasterToolStrip(ToolStrip SourceToolbar)
{
ToolStripButton btn = null;
//This procedure assumes an Image List has been already attached to the
//supplied Toolbar with the required images in the required order
try
{
ToolStrip with_1 = SourceToolbar;
with_1.Items.Add(new ToolStripSeparator()); //Add a Separator
btn = new ToolStripButton();
ToolStripButton with_2 = btn;
with_2.AutoToolTip = true;
with_2.ToolTipText = CultureSupport.TextDictionary("TT_NEW", TextReturnTypeEnum.PureString);
with_2.Tag = "New";
with_2.ImageIndex = 0;
with_1.Items.Add(btn);
btn = new ToolStripButton();
ToolStripButton with_3 = btn;
with_3.AutoToolTip = true;
with_3.ToolTipText = CultureSupport.TextDictionary("TT_DELETE", TextReturnTypeEnum.PureString);
with_3.Tag = "Delete";
with_3.ImageIndex = 1;
with_1.Items.Add(btn);
btn = new ToolStripButton();
ToolStripButton with_4 = btn;
with_4.AutoToolTip = true;
with_4.ToolTipText = CultureSupport.TextDictionary("TT_SAVECHANGES", TextReturnTypeEnum.PureString);
with_4.Tag = "Save";
with_4.ImageIndex = 2;
with_1.Items.Add(btn);
btn = new ToolStripButton();
ToolStripButton with_5 = btn;
with_5.AutoToolTip = true;
with_5.ToolTipText = CultureSupport.TextDictionary("TT_UNDOCHANGES", TextReturnTypeEnum.PureString);
with_5.Tag = "Undo";
with_5.ImageIndex = 3;
with_1.Items.Add(btn);
with_1.Items.Add(new ToolStripSeparator());
btn = new ToolStripButton();
ToolStripButton with_6 = btn;
with_6.AutoToolTip = true;
with_6.ToolTipText = CultureSupport.TextDictionary("TT_FIND", TextReturnTypeEnum.PureString);
with_6.Tag = "Find";
with_6.ImageIndex = 4;
with_1.Items.Add(btn);
with_1.Items.Add(new ToolStripSeparator());
btn = new ToolStripButton();
ToolStripButton with_7 = btn;
with_7.AutoToolTip = true;
with_7.ToolTipText = CultureSupport.TextDictionary("TT_CLOSE", TextReturnTypeEnum.PureString);
with_7.Tag = "Exit";
with_7.ImageIndex = 5;
with_1.Items.Add(btn);
}
catch (Exception)
{
}
finally
{
btn.Dispose();
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 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;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class ConstraintFactory
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return Is.Not; }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return Has.No; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return Is.All; }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return Has.Some; }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return Has.None; }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public static ConstraintExpression Exactly(int expectedCount)
{
return Has.Exactly(expectedCount);
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return Has.Property(name);
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Has.Length; }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Has.Count; }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Has.Message; }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Has.InnerException; }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return Has.Attribute(expectedType);
}
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<TExpected>()
{
return Attribute(typeof(TExpected));
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region Zero
/// <summary>
/// Returns a constraint that tests for equality with zero
/// </summary>
public EqualConstraint Zero
{
get { return new EqualConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endif
#endregion
#region XmlSerializable
#if !SILVERLIGHT && !PORTABLE
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the supplied argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the supplied argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<TExpected>()
{
return new ExactTypeConstraint(typeof(TExpected));
}
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<TExpected>()
{
return new InstanceOfTypeConstraint(typeof(TExpected));
}
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<TExpected>()
{
return new AssignableFromConstraint(typeof(TExpected));
}
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<TExpected>()
{
return new AssignableToConstraint(typeof(TExpected));
}
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region SupersetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a superset of the collection supplied as an argument.
/// </summary>
public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
{
return new CollectionSupersetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region Member
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Member(object expected)
{
return new CollectionContainsConstraint(expected);
}
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Contains(object expected)
{
return new CollectionContainsConstraint(expected);
}
#endregion
#region Contains
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return new ContainsConstraint(expected);
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint ContainsSubstring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region DoesNotContain
/// <summary>
/// Returns a constraint that fails if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.Contain")]
public SubstringConstraint DoesNotContain(string expected)
{
return new ConstraintExpression().Not.ContainsSubstring(expected);
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.StartWith or StartsWith")]
public StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.StartWith")]
public StartsWithConstraint DoesNotStartWith(string expected)
{
return new ConstraintExpression().Not.StartsWith(expected);
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.EndWith or EndsWith")]
public EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.EndWith")]
public EndsWithConstraint DoesNotEndWith(string expected)
{
return new ConstraintExpression().Not.EndsWith(expected);
}
#endregion
#region Matches
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Match(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Match or Matches")]
public RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#region DoesNotMatch
/// <summary>
/// Returns a constraint that fails if the actual
/// value matches the pattern supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.Match")]
public RegexConstraint DoesNotMatch(string pattern)
{
return new ConstraintExpression().Not.Matches(pattern);
}
#endregion
#if !PORTABLE
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is a subpath of the expected path after canonicalization.
/// </summary>
public SubPathConstraint SubPathOf(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#endif
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Linq;
using Xunit;
namespace System.Runtime.CompilerServices.Tests
{
public partial class ConditionalWeakTableTests
{
[Fact]
public static void AddOrUpdateDataTest()
{
var cwt = new ConditionalWeakTable<string, string>();
string key = "key1";
cwt.AddOrUpdate(key, "value1");
string value;
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal(value, "value1");
Assert.Equal(value, cwt.GetOrCreateValue(key));
Assert.Equal(value, cwt.GetValue(key, k => "value1"));
Assert.Throws<ArgumentNullException>(() => cwt.AddOrUpdate(null, "value2"));
cwt.AddOrUpdate(key, "value2");
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal(value, "value2");
Assert.Equal(value, cwt.GetOrCreateValue(key));
Assert.Equal(value, cwt.GetValue(key, k => "value1"));
}
[Fact]
public static void Clear_EmptyTable()
{
var cwt = new ConditionalWeakTable<object, object>();
cwt.Clear(); // no exception
cwt.Clear();
}
[Fact]
public static void Clear_AddThenEmptyRepeatedly_ItemsRemoved()
{
var cwt = new ConditionalWeakTable<object, object>();
object key = new object(), value = new object();
object result;
for (int i = 0; i < 3; i++)
{
cwt.Add(key, value);
Assert.True(cwt.TryGetValue(key, out result));
Assert.Same(value, result);
cwt.Clear();
Assert.False(cwt.TryGetValue(key, out result));
Assert.Null(result);
}
}
[Fact]
public static void Clear_AddMany_Clear_AllItemsRemoved()
{
var cwt = new ConditionalWeakTable<object, object>();
object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray();
for (int i = 0; i < keys.Length; i++)
{
cwt.Add(keys[i], values[i]);
}
Assert.Equal(keys.Length, ((IEnumerable<KeyValuePair<object, object>>)cwt).Count());
cwt.Clear();
Assert.Equal(0, ((IEnumerable<KeyValuePair<object, object>>)cwt).Count());
GC.KeepAlive(keys);
GC.KeepAlive(values);
}
[Fact]
public static void GetEnumerator_Empty_ReturnsEmptyEnumerator()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
Assert.Equal(0, enumerable.Count());
}
[Fact]
public static void GetEnumerator_AddedAndRemovedItems_AppropriatelyShowUpInEnumeration()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), value1 = new object();
for (int i = 0; i < 20; i++) // adding and removing multiple times, across internal container boundary
{
cwt.Add(key1, value1);
Assert.Equal(1, enumerable.Count());
Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerable.First());
Assert.True(cwt.Remove(key1));
Assert.Equal(0, enumerable.Count());
}
GC.KeepAlive(key1);
GC.KeepAlive(value1);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void GetEnumerator_CollectedItemsNotEnumerated()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
// Delegate to add collectible items to the table, separated out
// to avoid the JIT extending the lifetimes of the temporaries
Action<ConditionalWeakTable<object, object>> addItem =
t => t.Add(new object(), new object());
for (int i = 0; i < 10; i++) addItem(cwt);
GC.Collect();
Assert.Equal(0, enumerable.Count());
}
[Fact]
public static void GetEnumerator_MultipleEnumeratorsReturnSameResults()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray();
for (int i = 0; i < keys.Length; i++)
{
cwt.Add(keys[i], values[i]);
}
using (IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator())
using (IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator())
{
while (enumerator1.MoveNext())
{
Assert.True(enumerator2.MoveNext());
Assert.Equal(enumerator1.Current, enumerator2.Current);
}
Assert.False(enumerator2.MoveNext());
}
GC.KeepAlive(keys);
GC.KeepAlive(values);
}
[Fact]
public static void GetEnumerator_RemovedItems_RemovedFromResults()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray();
for (int i = 0; i < keys.Length; i++)
{
cwt.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
Assert.Equal(keys.Length - i, enumerable.Count());
Assert.Equal(
Enumerable.Range(i, keys.Length - i).Select(j => new KeyValuePair<object, object>(keys[j], values[j])),
enumerable);
cwt.Remove(keys[i]);
}
Assert.Equal(0, enumerable.Count());
GC.KeepAlive(keys);
GC.KeepAlive(values);
}
[Fact]
public static void GetEnumerator_ItemsAddedAfterGetEnumeratorNotIncluded()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object();
cwt.Add(key1, value1);
IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator();
cwt.Add(key2, value2);
IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator();
Assert.True(enumerator1.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerator1.Current);
Assert.False(enumerator1.MoveNext());
Assert.True(enumerator2.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerator2.Current);
Assert.True(enumerator2.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator2.Current);
Assert.False(enumerator2.MoveNext());
enumerator1.Dispose();
enumerator2.Dispose();
GC.KeepAlive(key1);
GC.KeepAlive(key2);
GC.KeepAlive(value1);
GC.KeepAlive(value2);
}
[Fact]
public static void GetEnumerator_ItemsRemovedAfterGetEnumeratorNotIncluded()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object();
cwt.Add(key1, value1);
cwt.Add(key2, value2);
IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator();
cwt.Remove(key1);
IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator();
Assert.True(enumerator1.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator1.Current);
Assert.False(enumerator1.MoveNext());
Assert.True(enumerator2.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator2.Current);
Assert.False(enumerator2.MoveNext());
enumerator1.Dispose();
enumerator2.Dispose();
GC.KeepAlive(key1);
GC.KeepAlive(key2);
GC.KeepAlive(value1);
GC.KeepAlive(value2);
}
[Fact]
public static void GetEnumerator_ItemsClearedAfterGetEnumeratorNotIncluded()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object();
cwt.Add(key1, value1);
cwt.Add(key2, value2);
IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator();
cwt.Clear();
IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator();
Assert.False(enumerator1.MoveNext());
Assert.False(enumerator2.MoveNext());
enumerator1.Dispose();
enumerator2.Dispose();
GC.KeepAlive(key1);
GC.KeepAlive(key2);
GC.KeepAlive(value1);
GC.KeepAlive(value2);
}
[Fact]
public static void GetEnumerator_Current_ThrowsOnInvalidUse()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), value1 = new object();
cwt.Add(key1, value1);
using (IEnumerator<KeyValuePair<object, object>> enumerator = enumerable.GetEnumerator())
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // before first MoveNext
}
GC.KeepAlive(key1);
GC.KeepAlive(value1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
namespace System.Transactions
{
internal enum EnlistmentType
{
Volatile = 0,
Durable = 1,
PromotableSinglePhase = 2
}
internal enum NotificationCall
{
// IEnlistmentNotification
Prepare = 0,
Commit = 1,
Rollback = 2,
InDoubt = 3,
// ISinglePhaseNotification
SinglePhaseCommit = 4,
// IPromotableSinglePhaseNotification
Promote = 5
}
internal enum TransactionScopeResult
{
CreatedTransaction = 0,
UsingExistingCurrent = 1,
TransactionPassed = 2,
DependentTransactionPassed = 3,
NoTransaction = 4
}
internal enum TransactionExceptionType
{
InvalidOperationException = 0,
TransactionAbortedException = 1,
TransactionException = 2,
TransactionInDoubtException = 3,
TransactionManagerCommunicationException = 4,
UnrecognizedRecoveryInformation = 5
}
internal enum TraceSourceType
{
TraceSourceBase = 0,
TraceSourceLtm = 1,
TraceSourceDistributed = 2
}
/// <summary>Provides an event source for tracing Transactions information.</summary>
[EventSource(
Name = "System.Transactions.TransactionsEventSource",
Guid = "8ac2d80a-1f1a-431b-ace4-bff8824aef0b",
LocalizationResources = "FxResources.System.Transactions.Local.SR")]
internal sealed class TransactionsEtwProvider : EventSource
{
/// <summary>
/// Defines the singleton instance for the Transactions ETW provider.
/// The Transactions provider GUID is {8ac2d80a-1f1a-431b-ace4-bff8824aef0b}.
/// </summary>
///
internal static readonly TransactionsEtwProvider Log = new TransactionsEtwProvider();
/// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary>
private TransactionsEtwProvider() { }
/// <summary>Enabled for all keywords.</summary>
private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1);
//-----------------------------------------------------------------------------------
//
// Transactions Event IDs (must be unique)
//
/// <summary>The event ID for configured default timeout adjusted event.</summary>
private const int CONFIGURED_DEFAULT_TIMEOUT_ADJUSTED_EVENTID = 1;
/// <summary>The event ID for the enlistment abort event.</summary>
private const int ENLISTMENT_ABORTED_EVENTID = 2;
/// <summary>The event ID for the enlistment commit event.</summary>
private const int ENLISTMENT_COMMITTED_EVENTID = 3;
/// <summary>The event ID for the enlistment done event.</summary>
private const int ENLISTMENT_DONE_EVENTID = 4;
/// <summary>The event ID for the enlistment status.</summary>
private const int ENLISTMENT_EVENTID = 5;
/// <summary>The event ID for the enlistment forcerollback event.</summary>
private const int ENLISTMENT_FORCEROLLBACK_EVENTID = 6;
/// <summary>The event ID for the enlistment indoubt event.</summary>
private const int ENLISTMENT_INDOUBT_EVENTID = 7;
/// <summary>The event ID for the enlistment prepared event.</summary>
private const int ENLISTMENT_PREPARED_EVENTID = 8;
/// <summary>The event ID for exception consumed event.</summary>
private const int EXCEPTION_CONSUMED_BASE_EVENTID = 9;
/// <summary>The event ID for exception consumed event.</summary>
private const int EXCEPTION_CONSUMED_LTM_EVENTID = 10;
/// <summary>The event ID for method enter event.</summary>
private const int METHOD_ENTER_LTM_EVENTID = 11;
/// <summary>The event ID for method exit event.</summary>
private const int METHOD_EXIT_LTM_EVENTID = 12;
/// <summary>The event ID for method enter event.</summary>
private const int METHOD_ENTER_BASE_EVENTID = 13;
/// <summary>The event ID for method exit event.</summary>
private const int METHOD_EXIT_BASE_EVENTID = 14;
/// <summary>The event ID for method enter event.</summary>
private const int METHOD_ENTER_DISTRIBUTED_EVENTID = 15;
/// <summary>The event ID for method exit event.</summary>
private const int METHOD_EXIT_DISTRIBUTED_EVENTID = 16;
/// <summary>The event ID for transaction aborted event.</summary>
private const int TRANSACTION_ABORTED_EVENTID = 17;
/// <summary>The event ID for the transaction clone create event.</summary>
private const int TRANSACTION_CLONECREATE_EVENTID = 18;
/// <summary>The event ID for the transaction commit event.</summary>
private const int TRANSACTION_COMMIT_EVENTID = 19;
/// <summary>The event ID for transaction committed event.</summary>
private const int TRANSACTION_COMMITTED_EVENTID = 20;
/// <summary>The event ID for when we encounter a new Transactions object that hasn't had its name traced to the trace file.</summary>
private const int TRANSACTION_CREATED_EVENTID = 21;
/// <summary>The event ID for the transaction dependent clone complete event.</summary>
private const int TRANSACTION_DEPENDENT_CLONE_COMPLETE_EVENTID = 22;
/// <summary>The event ID for the transaction exception event.</summary>
private const int TRANSACTION_EXCEPTION_LTM_EVENTID = 23;
/// <summary>The event ID for the transaction exception event.</summary>
private const int TRANSACTION_EXCEPTION_BASE_EVENTID = 24;
/// <summary>The event ID for transaction indoubt event.</summary>
private const int TRANSACTION_INDOUBT_EVENTID = 25;
/// <summary>The event ID for the transaction invalid operation event.</summary>
private const int TRANSACTION_INVALID_OPERATION_EVENTID = 26;
/// <summary>The event ID for transaction promoted event.</summary>
private const int TRANSACTION_PROMOTED_EVENTID = 27;
/// <summary>The event ID for the transaction rollback event.</summary>
private const int TRANSACTION_ROLLBACK_EVENTID = 28;
/// <summary>The event ID for the transaction serialized event.</summary>
private const int TRANSACTION_SERIALIZED_EVENTID = 29;
/// <summary>The event ID for transaction timeout event.</summary>
private const int TRANSACTION_TIMEOUT_EVENTID = 30;
/// <summary>The event ID for transactionmanager recovery complete event.</summary>
private const int TRANSACTIONMANAGER_RECOVERY_COMPLETE_EVENTID = 31;
/// <summary>The event ID for transactionmanager reenlist event.</summary>
private const int TRANSACTIONMANAGER_REENLIST_EVENTID = 32;
/// <summary>The event ID for transactionscope created event.</summary>
private const int TRANSACTIONSCOPE_CREATED_EVENTID = 33;
/// <summary>The event ID for transactionscope current changed event.</summary>
private const int TRANSACTIONSCOPE_CURRENT_CHANGED_EVENTID = 34;
/// <summary>The event ID for transactionscope nested incorrectly event.</summary>
private const int TRANSACTIONSCOPE_DISPOSED_EVENTID = 35;
/// <summary>The event ID for transactionscope incomplete event.</summary>
private const int TRANSACTIONSCOPE_INCOMPLETE_EVENTID = 36;
/// <summary>The event ID for transactionscope internal error event.</summary>
private const int TRANSACTIONSCOPE_INTERNAL_ERROR_EVENTID = 37;
/// <summary>The event ID for transactionscope nested incorrectly event.</summary>
private const int TRANSACTIONSCOPE_NESTED_INCORRECTLY_EVENTID = 38;
/// <summary>The event ID for transactionscope timeout event.</summary>
private const int TRANSACTIONSCOPE_TIMEOUT_EVENTID = 39;
/// <summary>The event ID for enlistment event.</summary>
private const int TRANSACTIONSTATE_ENLIST_EVENTID = 40;
//-----------------------------------------------------------------------------------
//
// Transactions Events
//
private const string NullInstance = "(null)";
//-----------------------------------------------------------------------------------
//
// Transactions Events
//
[NonEvent]
public static string IdOf(object value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
[NonEvent]
public static int GetHashCode(object value) => value?.GetHashCode() ?? 0;
#region Transaction Creation
/// <summary>Trace an event when a new transaction is created.</summary>
/// <param name="transaction">The transaction that was created.</param>
/// <param name="type">The type of transaction.</param>Method
[NonEvent]
internal void TransactionCreated(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionCreated(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionCreated(string.Empty, type);
}
}
[Event(TRANSACTION_CREATED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.Create, Message = "Transaction Created. ID is {0}, type is {1}")]
private void TransactionCreated(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_CREATED_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Clone Create
/// <summary>Trace an event when a new transaction is clone created.</summary>
/// <param name="transaction">The transaction that was clone created.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionCloneCreate(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionCloneCreate(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionCloneCreate(string.Empty, type);
}
}
[Event(TRANSACTION_CLONECREATE_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.CloneCreate, Message = "Transaction Clone Created. ID is {0}, type is {1}")]
private void TransactionCloneCreate(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_CLONECREATE_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Serialized
/// <summary>Trace an event when a transaction is serialized.</summary>
/// <param name="transaction">The transaction that was serialized.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionSerialized(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionSerialized(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionSerialized(string.Empty, type);
}
}
[Event(TRANSACTION_SERIALIZED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.Serialized, Message = "Transaction Serialized. ID is {0}, type is {1}")]
private void TransactionSerialized(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_SERIALIZED_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Exception
/// <summary>Trace an event when an exception happens.</summary>
/// <param name="traceSource">trace source</param>
/// <param name="type">The type of transaction.</param>
/// <param name="message">The message for the exception.</param>
/// <param name="innerExceptionStr">The inner exception.</param>
[NonEvent]
internal void TransactionExceptionTrace(TraceSourceType traceSource, TransactionExceptionType type, string message, string innerExceptionStr)
{
if (IsEnabled(EventLevel.Error, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceBase)
{
TransactionExceptionBase(type.ToString(), message, innerExceptionStr);
}
else
{
TransactionExceptionLtm(type.ToString(), message, innerExceptionStr);
}
}
}
/// <summary>Trace an event when an exception happens.</summary>
/// <param name="type">The type of transaction.</param>
/// <param name="message">The message for the exception.</param>
/// <param name="innerExceptionStr">The inner exception.</param>
[NonEvent]
internal void TransactionExceptionTrace(TransactionExceptionType type, string message, string innerExceptionStr)
{
if (IsEnabled(EventLevel.Error, ALL_KEYWORDS))
{
TransactionExceptionLtm(type.ToString(), message, innerExceptionStr);
}
}
[Event(TRANSACTION_EXCEPTION_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Error, Task = Tasks.TransactionException, Message = "Transaction Exception. Type is {0}, message is {1}, InnerException is {2}")]
private void TransactionExceptionBase(string type, string message, string innerExceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTION_EXCEPTION_BASE_EVENTID, type, message, innerExceptionStr);
}
[Event(TRANSACTION_EXCEPTION_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Error, Task = Tasks.TransactionException, Message = "Transaction Exception. Type is {0}, message is {1}, InnerException is {2}")]
private void TransactionExceptionLtm(string type, string message, string innerExceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTION_EXCEPTION_LTM_EVENTID, type, message, innerExceptionStr);
}
#endregion
#region Transaction Invalid Operation
/// <summary>Trace an event when an invalid operation happened on a transaction.</summary>
/// <param name="type">The type of transaction.</param>
/// <param name="operation">The operationont the transaction.</param>
[NonEvent]
internal void InvalidOperation(string type, string operation)
{
if (IsEnabled(EventLevel.Error, ALL_KEYWORDS))
{
TransactionInvalidOperation(
string.Empty, type, operation);
}
}
[Event(TRANSACTION_INVALID_OPERATION_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Error, Task = Tasks.Transaction, Opcode = Opcodes.InvalidOperation, Message = "Transaction Invalid Operation. ID is {0}, type is {1} and operation is {2}")]
private void TransactionInvalidOperation(string transactionIdentifier, string type, string operation)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTION_INVALID_OPERATION_EVENTID, transactionIdentifier, type, operation);
}
#endregion
#region Transaction Rollback
/// <summary>Trace an event when rollback on a transaction.</summary>
/// <param name="transaction">The transaction to rollback.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionRollback(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionRollback(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionRollback(string.Empty, type);
}
}
[Event(TRANSACTION_ROLLBACK_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.Rollback, Message = "Transaction Rollback. ID is {0}, type is {1}")]
private void TransactionRollback(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_ROLLBACK_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Dependent Clone Complete
/// <summary>Trace an event when transaction dependent clone complete.</summary>
/// <param name="transaction">The transaction that do dependent clone.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionDependentCloneComplete(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionDependentCloneComplete(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionDependentCloneComplete(string.Empty, type);
}
}
[Event(TRANSACTION_DEPENDENT_CLONE_COMPLETE_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.DependentCloneComplete, Message = "Transaction Dependent Clone Completed. ID is {0}, type is {1}")]
private void TransactionDependentCloneComplete(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_DEPENDENT_CLONE_COMPLETE_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Commit
/// <summary>Trace an event when there is commit on that transaction.</summary>
/// <param name="transaction">The transaction to commit.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionCommit(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionCommit(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionCommit(string.Empty, type);
}
}
[Event(TRANSACTION_COMMIT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Transaction, Opcode = Opcodes.Commit, Message = "Transaction Commit: ID is {0}, type is {1}")]
private void TransactionCommit(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_COMMIT_EVENTID, transactionIdentifier, type);
}
#endregion
#region Enlistment
/// <summary>Trace an event for enlistment status.</summary>
/// <param name="enlistment">The enlistment to report status.</param>
/// <param name="notificationCall">The notification call on the enlistment.</param>
[NonEvent]
internal void EnlistmentStatus(InternalEnlistment enlistment, NotificationCall notificationCall)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentStatus(enlistment.EnlistmentTraceId.EnlistmentIdentifier, notificationCall.ToString());
else
EnlistmentStatus(0, notificationCall.ToString());
}
}
[Event(ENLISTMENT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Message = "Enlistment status: ID is {0}, notificationcall is {1}")]
private void EnlistmentStatus(int enlistmentIdentifier, string notificationCall)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_EVENTID, enlistmentIdentifier, notificationCall);
}
#endregion
#region Enlistment Done
/// <summary>Trace an event for enlistment done.</summary>
/// <param name="enlistment">The enlistment done.</param>
[NonEvent]
internal void EnlistmentDone(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentDone(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentDone(0);
}
}
[Event(ENLISTMENT_DONE_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Opcode = Opcodes.Done, Message = "Enlistment.Done: ID is {0}")]
private void EnlistmentDone(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_DONE_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment Prepared
/// <summary>Trace an event for enlistment prepared.</summary>
/// <param name="enlistment">The enlistment prepared.</param>
[NonEvent]
internal void EnlistmentPrepared(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentPrepared(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentPrepared(0);
}
}
[Event(ENLISTMENT_PREPARED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Opcode = Opcodes.Prepared, Message = "PreparingEnlistment.Prepared: ID is {0}")]
private void EnlistmentPrepared(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_PREPARED_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment ForceRollback
/// <summary>Trace an enlistment that will forcerollback.</summary>
/// <param name="enlistment">The enlistment to forcerollback.</param>
[NonEvent]
internal void EnlistmentForceRollback(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentForceRollback(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentForceRollback(0);
}
}
[Event(ENLISTMENT_FORCEROLLBACK_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Enlistment, Opcode = Opcodes.ForceRollback, Message = "Enlistment forceRollback: ID is {0}")]
private void EnlistmentForceRollback(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_FORCEROLLBACK_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment Aborted
/// <summary>Trace an enlistment that aborted.</summary>
/// <param name="enlistment">The enlistment aborted.</param>
[NonEvent]
internal void EnlistmentAborted(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentAborted(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentAborted(0);
}
}
[Event(ENLISTMENT_ABORTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Enlistment, Opcode = Opcodes.Aborted, Message = "Enlistment SinglePhase Aborted: ID is {0}")]
private void EnlistmentAborted(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_ABORTED_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment Committed
/// <summary>Trace an enlistment that committed.</summary>
/// <param name="enlistment">The enlistment committed.</param>
[NonEvent]
internal void EnlistmentCommitted(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentCommitted(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentCommitted(0);
}
}
[Event(ENLISTMENT_COMMITTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Opcode = Opcodes.Committed, Message = "Enlistment Committed: ID is {0}")]
private void EnlistmentCommitted(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_COMMITTED_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment InDoubt
/// <summary>Trace an enlistment that InDoubt.</summary>
/// <param name="enlistment">The enlistment Indoubt.</param>
[NonEvent]
internal void EnlistmentInDoubt(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentInDoubt(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentInDoubt(0);
}
}
[Event(ENLISTMENT_INDOUBT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Enlistment, Opcode = Opcodes.InDoubt, Message = "Enlistment SinglePhase InDoubt: ID is {0}")]
private void EnlistmentInDoubt(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_INDOUBT_EVENTID, enlistmentIdentifier);
}
#endregion
#region Method Enter
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="thisOrContextObject">'this', or another object that serves to provide context for the operation.</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodEnter(TraceSourceType traceSource, object thisOrContextObject, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodEnterTraceLtm(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodEnterTraceBase(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodEnterTraceDistributed(IdOf(thisOrContextObject), methodname);
}
}
}
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodEnter(TraceSourceType traceSource, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodEnterTraceLtm(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodEnterTraceBase(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodEnterTraceDistributed(string.Empty, methodname);
}
}
}
[Event(METHOD_ENTER_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Enter, Message = "Enter method : {0}.{1}")]
private void MethodEnterTraceLtm(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_ENTER_LTM_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_ENTER_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Enter, Message = "Enter method : {0}.{1}")]
private void MethodEnterTraceBase(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_ENTER_BASE_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_ENTER_DISTRIBUTED_EVENTID, Keywords = Keywords.TraceDistributed, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Enter, Message = "Enter method : {0}.{1}")]
private void MethodEnterTraceDistributed(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_ENTER_DISTRIBUTED_EVENTID, thisOrContextObject, methodname);
}
#endregion
#region Method Exit
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="thisOrContextObject">'this', or another object that serves to provide context for the operation.</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodExit(TraceSourceType traceSource, object thisOrContextObject, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodExitTraceLtm(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodExitTraceBase(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodExitTraceDistributed(IdOf(thisOrContextObject), methodname);
}
}
}
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodExit(TraceSourceType traceSource, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodExitTraceLtm(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodExitTraceBase(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodExitTraceDistributed(string.Empty, methodname);
}
}
}
[Event(METHOD_EXIT_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Exit, Message = "Exit method: {0}.{1}")]
private void MethodExitTraceLtm(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_EXIT_LTM_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_EXIT_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Exit, Message = "Exit method: {0}.{1}")]
private void MethodExitTraceBase(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_EXIT_BASE_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_EXIT_DISTRIBUTED_EVENTID, Keywords = Keywords.TraceDistributed, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Exit, Message = "Exit method: {0}.{1}")]
private void MethodExitTraceDistributed(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_EXIT_DISTRIBUTED_EVENTID, thisOrContextObject, methodname);
}
#endregion
#region Exception Consumed
/// <summary>Trace an event when exception consumed.</summary>
/// <param name="traceSource">trace source</param>
/// <param name="exception">The exception.</param>
[NonEvent]
internal void ExceptionConsumed(TraceSourceType traceSource, Exception exception)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceBase)
{
ExceptionConsumedBase(exception.ToString());
}
else
{
ExceptionConsumedLtm(exception.ToString());
}
}
}
/// <summary>Trace an event when exception consumed.</summary>
/// <param name="exception">The exception.</param>
[NonEvent]
internal void ExceptionConsumed(Exception exception)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
ExceptionConsumedLtm(exception.ToString());
}
}
[Event(EXCEPTION_CONSUMED_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Verbose, Opcode = Opcodes.ExceptionConsumed, Message = "Exception consumed: {0}")]
private void ExceptionConsumedBase(string exceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(EXCEPTION_CONSUMED_BASE_EVENTID, exceptionStr);
}
[Event(EXCEPTION_CONSUMED_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Opcode = Opcodes.ExceptionConsumed, Message = "Exception consumed: {0}")]
private void ExceptionConsumedLtm(string exceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(EXCEPTION_CONSUMED_LTM_EVENTID, exceptionStr);
}
#endregion
#region TransactionManager Reenlist
/// <summary>Trace an event when reenlist transactionmanager.</summary>
/// <param name="resourceManagerID">The resource manager ID.</param>
[NonEvent]
internal void TransactionManagerReenlist(Guid resourceManagerID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionManagerReenlistTrace(resourceManagerID.ToString());
}
}
[Event(TRANSACTIONMANAGER_REENLIST_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionManager, Opcode = Opcodes.Reenlist, Message = "Reenlist in: {0}")]
private void TransactionManagerReenlistTrace(string rmID)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONMANAGER_REENLIST_EVENTID, rmID);
}
#endregion
#region TransactionManager Recovery Complete
/// <summary>Trace an event when transactionmanager recovery complete.</summary>
/// <param name="resourceManagerID">The resource manager ID.</param>
[NonEvent]
internal void TransactionManagerRecoveryComplete(Guid resourceManagerID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionManagerRecoveryComplete(resourceManagerID.ToString());
}
}
[Event(TRANSACTIONMANAGER_RECOVERY_COMPLETE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionManager, Opcode = Opcodes.RecoveryComplete, Message = "Recovery complete: {0}")]
private void TransactionManagerRecoveryComplete(string rmID)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONMANAGER_RECOVERY_COMPLETE_EVENTID, rmID);
}
#endregion
#region Configured Default Timeout Adjusted
/// <summary>Trace an event when configured default timeout adjusted.</summary>
[NonEvent]
internal void ConfiguredDefaultTimeoutAdjusted()
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
ConfiguredDefaultTimeoutAdjustedTrace();
}
}
[Event(CONFIGURED_DEFAULT_TIMEOUT_ADJUSTED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.ConfiguredDefaultTimeout, Opcode = Opcodes.Adjusted, Message = "Configured Default Timeout Adjusted")]
private void ConfiguredDefaultTimeoutAdjustedTrace()
{
SetActivityId(string.Empty);
WriteEvent(CONFIGURED_DEFAULT_TIMEOUT_ADJUSTED_EVENTID);
}
#endregion
#region Transactionscope Created
/// <summary>Trace an event when a transactionscope is created.</summary>
/// <param name="transactionID">The transaction ID.</param>
/// <param name="transactionScopeResult">The transaction scope result.</param>
[NonEvent]
internal void TransactionScopeCreated(TransactionTraceIdentifier transactionID, TransactionScopeResult transactionScopeResult)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionScopeCreated(transactionID.TransactionIdentifier ?? string.Empty, transactionScopeResult);
}
}
[Event(TRANSACTIONSCOPE_CREATED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionScope, Opcode = Opcodes.Created, Message = "Transactionscope was created: Transaction ID is {0}, TransactionScope Result is {1}")]
private void TransactionScopeCreated(string transactionID, TransactionScopeResult transactionScopeResult)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_CREATED_EVENTID, transactionID, transactionScopeResult);
}
#endregion
#region Transactionscope Current Changed
/// <summary>Trace an event when a transactionscope current transaction changed.</summary>
/// <param name="currenttransactionID">The transaction ID.</param>
/// <param name="newtransactionID">The new transaction ID.</param>
[NonEvent]
internal void TransactionScopeCurrentChanged(TransactionTraceIdentifier currenttransactionID, TransactionTraceIdentifier newtransactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
string currentId = string.Empty;
string newId = string.Empty;
if (currenttransactionID.TransactionIdentifier != null)
{
currentId = currenttransactionID.TransactionIdentifier.ToString();
}
if (newtransactionID.TransactionIdentifier != null)
{
newId = newtransactionID.TransactionIdentifier.ToString();
}
TransactionScopeCurrentChanged(currentId, newId);
}
}
[Event(TRANSACTIONSCOPE_CURRENT_CHANGED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.CurrentChanged, Message = "Transactionscope current transaction ID changed from {0} to {1}")]
private void TransactionScopeCurrentChanged(string currenttransactionID, string newtransactionID)
{
SetActivityId(newtransactionID);
WriteEvent(TRANSACTIONSCOPE_CURRENT_CHANGED_EVENTID, currenttransactionID, newtransactionID);
}
#endregion
#region Transactionscope Nested Incorrectly
/// <summary>Trace an event when a transactionscope is nested incorrectly.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeNestedIncorrectly(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionScopeNestedIncorrectly(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_NESTED_INCORRECTLY_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.NestedIncorrectly, Message = "Transactionscope nested incorrectly: transaction ID is {0}")]
private void TransactionScopeNestedIncorrectly(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_NESTED_INCORRECTLY_EVENTID, transactionID);
}
#endregion
#region Transactionscope Disposed
/// <summary>Trace an event when a transactionscope is disposed.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeDisposed(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionScopeDisposed(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_DISPOSED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionScope, Opcode = Opcodes.Disposed, Message = "Transactionscope disposed: transaction ID is {0}")]
private void TransactionScopeDisposed(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_DISPOSED_EVENTID, transactionID);
}
#endregion
#region Transactionscope Incomplete
/// <summary>Trace an event when a transactionscope incomplete.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeIncomplete(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionScopeIncomplete(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_INCOMPLETE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.Incomplete, Message = "Transactionscope incomplete: transaction ID is {0}")]
private void TransactionScopeIncomplete(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_INCOMPLETE_EVENTID, transactionID);
}
#endregion
#region Transactionscope Internal Error
/// <summary>Trace an event when there is an internal error on transactionscope.</summary>
/// <param name="error">The error information.</param>
[NonEvent]
internal void TransactionScopeInternalError(string error)
{
if (IsEnabled(EventLevel.Critical, ALL_KEYWORDS))
{
TransactionScopeInternalErrorTrace(error);
}
}
[Event(TRANSACTIONSCOPE_INTERNAL_ERROR_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Critical, Task = Tasks.TransactionScope, Opcode = Opcodes.InternalError, Message = "Transactionscope internal error: {0}")]
private void TransactionScopeInternalErrorTrace(string error)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONSCOPE_INTERNAL_ERROR_EVENTID, error);
}
#endregion
#region Transactionscope Timeout
/// <summary>Trace an event when there is timeout on transactionscope.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeTimeout(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionScopeTimeout(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_TIMEOUT_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.Timeout, Message = "Transactionscope timeout: transaction ID is {0}")]
private void TransactionScopeTimeout(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_TIMEOUT_EVENTID, transactionID);
}
#endregion
#region Transaction Timeout
/// <summary>Trace an event when there is timeout on transaction.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionTimeout(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionTimeout(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_TIMEOUT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.Timeout, Message = "Transaction timeout: transaction ID is {0}")]
private void TransactionTimeout(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_TIMEOUT_EVENTID, transactionID);
}
#endregion
#region Transactionstate Enlist
/// <summary>Trace an event when there is enlist.</summary>
/// <param name="enlistmentID">The enlistment ID.</param>
/// <param name="enlistmentType">The enlistment type.</param>
/// <param name="enlistmentOption">The enlistment option.</param>
[NonEvent]
internal void TransactionstateEnlist(EnlistmentTraceIdentifier enlistmentID, EnlistmentType enlistmentType, EnlistmentOptions enlistmentOption)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (enlistmentID.EnlistmentIdentifier != 0)
TransactionstateEnlist(enlistmentID.EnlistmentIdentifier.ToString(), enlistmentType.ToString(), enlistmentOption.ToString());
else
TransactionstateEnlist(string.Empty, enlistmentType.ToString(), enlistmentOption.ToString());
}
}
[Event(TRANSACTIONSTATE_ENLIST_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.TransactionState, Opcode = Opcodes.Enlist, Message = "Transactionstate enlist: Enlistment ID is {0}, type is {1} and options is {2}")]
private void TransactionstateEnlist(string enlistmentID, string type, string option)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONSTATE_ENLIST_EVENTID, enlistmentID, type, option);
}
#endregion
#region Transactionstate committed
/// <summary>Trace an event when transaction is committed.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionCommitted(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
TransactionCommitted(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_COMMITTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Transaction, Opcode = Opcodes.Committed, Message = "Transaction committed: transaction ID is {0}")]
private void TransactionCommitted(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_COMMITTED_EVENTID, transactionID);
}
#endregion
#region Transactionstate indoubt
/// <summary>Trace an event when transaction is indoubt.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionInDoubt(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionInDoubt(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_INDOUBT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.InDoubt, Message = "Transaction indoubt: transaction ID is {0}")]
private void TransactionInDoubt(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_INDOUBT_EVENTID, transactionID);
}
#endregion
#region Transactionstate promoted
/// <summary>Trace an event when transaction is promoted.</summary>
/// <param name="transactionID">The transaction ID.</param>
/// <param name="distributedTxID">The distributed transaction ID.</param>
[NonEvent]
internal void TransactionPromoted(TransactionTraceIdentifier transactionID, TransactionTraceIdentifier distributedTxID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionPromoted(transactionID.TransactionIdentifier ?? string.Empty, distributedTxID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_PROMOTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.Promoted, Message = "Transaction promoted: transaction ID is {0} and distributed transaction ID is {1}")]
private void TransactionPromoted(string transactionID, string distributedTxID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_PROMOTED_EVENTID, transactionID, distributedTxID);
}
#endregion
#region Transactionstate aborted
/// <summary>Trace an event when transaction is aborted.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionAborted(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionAborted(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_ABORTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.Aborted, Message = "Transaction aborted: transaction ID is {0}")]
private void TransactionAborted(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_ABORTED_EVENTID, transactionID);
}
#endregion
public class Opcodes
{
public const EventOpcode Aborted = (EventOpcode)100;
public const EventOpcode Activity = (EventOpcode)101;
public const EventOpcode Adjusted = (EventOpcode)102;
public const EventOpcode CloneCreate = (EventOpcode)103;
public const EventOpcode Commit = (EventOpcode)104;
public const EventOpcode Committed = (EventOpcode)105;
public const EventOpcode Create = (EventOpcode)106;
public const EventOpcode Created = (EventOpcode)107;
public const EventOpcode CurrentChanged = (EventOpcode)108;
public const EventOpcode DependentCloneComplete = (EventOpcode)109;
public const EventOpcode Disposed = (EventOpcode)110;
public const EventOpcode Done = (EventOpcode)111;
public const EventOpcode Enlist = (EventOpcode)112;
public const EventOpcode Enter = (EventOpcode)113;
public const EventOpcode ExceptionConsumed = (EventOpcode)114;
public const EventOpcode Exit = (EventOpcode)115;
public const EventOpcode ForceRollback = (EventOpcode)116;
public const EventOpcode Incomplete = (EventOpcode)117;
public const EventOpcode InDoubt = (EventOpcode)118;
public const EventOpcode InternalError = (EventOpcode)119;
public const EventOpcode InvalidOperation = (EventOpcode)120;
public const EventOpcode NestedIncorrectly = (EventOpcode)121;
public const EventOpcode Prepared = (EventOpcode)122;
public const EventOpcode Promoted = (EventOpcode)123;
public const EventOpcode RecoveryComplete = (EventOpcode)124;
public const EventOpcode Reenlist = (EventOpcode)125;
public const EventOpcode Rollback = (EventOpcode)126;
public const EventOpcode Serialized = (EventOpcode)127;
public const EventOpcode Timeout = (EventOpcode)128;
}
public class Tasks
{
public const EventTask ConfiguredDefaultTimeout = (EventTask)1;
public const EventTask Enlistment = (EventTask)2;
public const EventTask ResourceManager = (EventTask)3;
public const EventTask Method = (EventTask)4;
public const EventTask Transaction = (EventTask)5;
public const EventTask TransactionException = (EventTask)6;
public const EventTask TransactionManager = (EventTask)7;
public const EventTask TransactionScope = (EventTask)8;
public const EventTask TransactionState = (EventTask)9;
}
public class Keywords
{
public const EventKeywords TraceBase = (EventKeywords)0x0001;
public const EventKeywords TraceLtm = (EventKeywords)0x0002;
public const EventKeywords TraceDistributed = (EventKeywords)0x0004;
}
void SetActivityId(string str)
{
Guid guid = Guid.Empty;
if (str.Contains('-'))
{ // GUID with dash
if (str.Length >= 36)
{
string str_part1 = str.Substring(0, 36);
Guid.TryParse(str_part1, out guid);
}
}
else
{
if (str.Length >= 32)
{
string str_part1 = str.Substring(0, 32);
Guid.TryParse(str_part1, out guid);
}
}
SetCurrentThreadActivityId(guid);
}
}
}
| |
// 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;
internal class TestApp
{
private static unsafe long test_2(B* pb)
{
return (pb++)->m_bval;
}
private static unsafe long test_9(B[,] ab, long i, long j)
{
fixed (B* pb = &ab[i, j])
{
return pb->m_bval;
}
}
private static unsafe long test_16(B* pb1)
{
B* pb;
return (pb = pb1 - 8)->m_bval;
}
private static unsafe long test_23(B* pb, B* pb1, B* pb2)
{
return (pb = pb + (pb2 - pb1))->m_bval;
}
private static unsafe long test_30(B* pb1, bool trig)
{
fixed (B* pb = &AA.s_x.m_b)
{
return (trig ? pb : pb1)->m_bval;
}
}
private static unsafe long test_37(byte* pb)
{
return ((B*)(pb + 7))->m_bval;
}
private static unsafe long test_44(B b)
{
return (&b)[0].m_bval;
}
private static unsafe long test_51()
{
fixed (B* pb = &AA.s_x.m_b)
{
return pb[0].m_bval;
}
}
private static unsafe long test_58(B* pb, long i)
{
return (&pb[i * 2])[0].m_bval;
}
private static unsafe long test_65(B* pb1, B* pb2)
{
return (pb1 >= pb2 ? pb1 : null)[0].m_bval;
}
private static unsafe long test_72(long pb)
{
return ((B*)pb)[0].m_bval;
}
private static unsafe long test_79(B* pb)
{
return AA.get_bv1(pb);
}
private static unsafe long test_86(B[] ab, long i)
{
fixed (B* pb = &ab[i])
{
return AA.get_bv1(pb);
}
}
private static unsafe long test_93(B* pb)
{
return AA.get_bv1((pb += 6));
}
private static unsafe long test_100(B* pb, long[,,] i, long ii)
{
return AA.get_bv1((&pb[++i[--ii, 0, 0]]));
}
private static unsafe long test_107(AA* px)
{
return AA.get_bv1(((B*)AA.get_pb_i(px)));
}
private static unsafe long test_114(byte diff, A* pa)
{
return AA.get_bv1(((B*)(((byte*)pa) + diff)));
}
private static unsafe long test_121()
{
AA loc_x = new AA(0, 100);
return AA.get_bv2(*(&loc_x.m_b));
}
private static unsafe long test_128(B[][] ab, long i, long j)
{
fixed (B* pb = &ab[i][j])
{
return AA.get_bv2(*pb);
}
}
private static unsafe long test_135(B* pb1, long i)
{
B* pb;
return AA.get_bv2(*(pb = (B*)(((byte*)pb1) + i * sizeof(B))));
}
private static unsafe long test_142(B* pb, long[,,] i, long ii, byte jj)
{
return AA.get_bv2(*(&pb[i[ii - jj, 0, ii - jj] = ii - 1]));
}
private static unsafe long test_149(ulong ub, byte lb)
{
return AA.get_bv2(*((B*)(ub | lb)));
}
private static unsafe long test_156(long p, long s)
{
return AA.get_bv2(*((B*)((p >> 4) | s)));
}
private static unsafe long test_163(B[] ab)
{
fixed (B* pb = &ab[0])
{
return AA.get_bv3(ref *pb);
}
}
private static unsafe long test_170(B* pb)
{
return AA.get_bv3(ref *(++pb));
}
private static unsafe long test_177(B* pb, long[] i, long ii)
{
return AA.get_bv3(ref *(&pb[i[ii]]));
}
private static unsafe long test_184(AA* px)
{
return AA.get_bv3(ref *(AA.get_pb_1(px) + 1));
}
private static unsafe long test_191(long pb)
{
return AA.get_bv3(ref *((B*)checked(((long)pb) + 1)));
}
private static unsafe long test_198(B* pb)
{
return (pb--)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_205(AA[,] ab, long i)
{
long j = 0;
fixed (B* pb = &ab[--i, ++j].m_b)
{
return pb->m_bval == 100 ? 100 : 101;
}
}
private static unsafe long test_212(B* pb1, long i)
{
B* pb;
return (pb = pb1 + i)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_219(B* pb1, B* pb2)
{
return (pb1 > pb2 ? pb2 : null)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_226(long pb)
{
return ((B*)pb)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_233(double* pb, long i)
{
return ((B*)(pb + i))->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_240(ref B b)
{
fixed (B* pb = &b)
{
return AA.get_i1(&pb->m_bval);
}
}
private static unsafe long test_247(B* pb)
{
return AA.get_i1(&(--pb)->m_bval);
}
private static unsafe long test_254(B* pb, long i)
{
return AA.get_i1(&(&pb[-(i << (int)i)])->m_bval);
}
private static unsafe long test_261(AA* px)
{
return AA.get_i1(&AA.get_pb(px)->m_bval);
}
private static unsafe long test_268(long pb)
{
return AA.get_i1(&((B*)checked((long)pb))->m_bval);
}
private static unsafe long test_275(B* pb)
{
return AA.get_i2((pb++)->m_bval);
}
private static unsafe long test_282(B[,] ab, long i, long j)
{
fixed (B* pb = &ab[i, j])
{
return AA.get_i2(pb->m_bval);
}
}
private static unsafe long test_289(B* pb1)
{
B* pb;
return AA.get_i2((pb = pb1 - 8)->m_bval);
}
private static unsafe long test_296(B* pb, B* pb1, B* pb2)
{
return AA.get_i2((pb = pb + (pb2 - pb1))->m_bval);
}
private static unsafe long test_303(B* pb1, bool trig)
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_i2((trig ? pb : pb1)->m_bval);
}
}
private static unsafe long test_310(byte* pb)
{
return AA.get_i2(((B*)(pb + 7))->m_bval);
}
private static unsafe long test_317(B b)
{
return AA.get_i3(ref (&b)->m_bval);
}
private static unsafe long test_324()
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_i3(ref pb->m_bval);
}
}
private static unsafe long test_331(B* pb, long i)
{
return AA.get_i3(ref (&pb[i * 2])->m_bval);
}
private static unsafe long test_338(B* pb1, B* pb2)
{
return AA.get_i3(ref (pb1 >= pb2 ? pb1 : null)->m_bval);
}
private static unsafe long test_345(long pb)
{
return AA.get_i3(ref ((B*)pb)->m_bval);
}
private static unsafe long test_352(B* pb)
{
return AA.get_bv1(pb) != 100 ? 99 : 100;
}
private static unsafe long test_359(B[] ab, long i)
{
fixed (B* pb = &ab[i])
{
return AA.get_bv1(pb) != 100 ? 99 : 100;
}
}
private static unsafe long test_366(B* pb)
{
return AA.get_bv1((pb += 6)) != 100 ? 99 : 100;
}
private static unsafe long test_373(B* pb, long[,,] i, long ii)
{
return AA.get_bv1((&pb[++i[--ii, 0, 0]])) != 100 ? 99 : 100;
}
private static unsafe long test_380(AA* px)
{
return AA.get_bv1(((B*)AA.get_pb_i(px))) != 100 ? 99 : 100;
}
private static unsafe long test_387(byte diff, A* pa)
{
return AA.get_bv1(((B*)(((byte*)pa) + diff))) != 100 ? 99 : 100;
}
private static unsafe long test_394(B* pb1, B* pb2)
{
return pb1 >= pb2 ? 100 : 101;
}
private static unsafe int Main()
{
AA loc_x = new AA(0, 100);
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_2(&loc_x.m_b) != 100)
{
Console.WriteLine("test_2() failed.");
return 102;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_9(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_9() failed.");
return 109;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_16(&loc_x.m_b + 8) != 100)
{
Console.WriteLine("test_16() failed.");
return 116;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_23(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_23() failed.");
return 123;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_30(&loc_x.m_b, true) != 100)
{
Console.WriteLine("test_30() failed.");
return 130;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_37(((byte*)(&loc_x.m_b)) - 7) != 100)
{
Console.WriteLine("test_37() failed.");
return 137;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_44(loc_x.m_b) != 100)
{
Console.WriteLine("test_44() failed.");
return 144;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_51() != 100)
{
Console.WriteLine("test_51() failed.");
return 151;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_58(&loc_x.m_b - 2, 1) != 100)
{
Console.WriteLine("test_58() failed.");
return 158;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_65(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_65() failed.");
return 165;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_72((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_72() failed.");
return 172;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_79(&loc_x.m_b) != 100)
{
Console.WriteLine("test_79() failed.");
return 179;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_86(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100)
{
Console.WriteLine("test_86() failed.");
return 186;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_93(&loc_x.m_b - 6) != 100)
{
Console.WriteLine("test_93() failed.");
return 193;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_100(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100)
{
Console.WriteLine("test_100() failed.");
return 200;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_107(&loc_x) != 100)
{
Console.WriteLine("test_107() failed.");
return 207;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_114((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100)
{
Console.WriteLine("test_114() failed.");
return 214;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_121() != 100)
{
Console.WriteLine("test_121() failed.");
return 221;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_128(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_128() failed.");
return 228;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_135(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_135() failed.");
return 235;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_142(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100)
{
Console.WriteLine("test_142() failed.");
return 242;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_149(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100)
{
Console.WriteLine("test_149() failed.");
return 249;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_156(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100)
{
Console.WriteLine("test_156() failed.");
return 256;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_163(new B[] { loc_x.m_b }) != 100)
{
Console.WriteLine("test_163() failed.");
return 263;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_170(&loc_x.m_b - 1) != 100)
{
Console.WriteLine("test_170() failed.");
return 270;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_177(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100)
{
Console.WriteLine("test_177() failed.");
return 277;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_184(&loc_x) != 100)
{
Console.WriteLine("test_184() failed.");
return 284;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_191((long)(((long)&loc_x.m_b) - 1)) != 100)
{
Console.WriteLine("test_191() failed.");
return 291;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_198(&loc_x.m_b) != 100)
{
Console.WriteLine("test_198() failed.");
return 298;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_205(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100)
{
Console.WriteLine("test_205() failed.");
return 305;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_212(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_212() failed.");
return 312;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_219(&loc_x.m_b + 1, &loc_x.m_b) != 100)
{
Console.WriteLine("test_219() failed.");
return 319;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_226((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_226() failed.");
return 326;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_233(((double*)(&loc_x.m_b)) - 4, 4) != 100)
{
Console.WriteLine("test_233() failed.");
return 333;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_240(ref loc_x.m_b) != 100)
{
Console.WriteLine("test_240() failed.");
return 340;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_247(&loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_247() failed.");
return 347;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_254(&loc_x.m_b + 2, 1) != 100)
{
Console.WriteLine("test_254() failed.");
return 354;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_261(&loc_x) != 100)
{
Console.WriteLine("test_261() failed.");
return 361;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_268((long)(long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_268() failed.");
return 368;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_275(&loc_x.m_b) != 100)
{
Console.WriteLine("test_275() failed.");
return 375;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_282(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_282() failed.");
return 382;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_289(&loc_x.m_b + 8) != 100)
{
Console.WriteLine("test_289() failed.");
return 389;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_296(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_296() failed.");
return 396;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_303(&loc_x.m_b, true) != 100)
{
Console.WriteLine("test_303() failed.");
return 403;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_310(((byte*)(&loc_x.m_b)) - 7) != 100)
{
Console.WriteLine("test_310() failed.");
return 410;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_317(loc_x.m_b) != 100)
{
Console.WriteLine("test_317() failed.");
return 417;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_324() != 100)
{
Console.WriteLine("test_324() failed.");
return 424;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_331(&loc_x.m_b - 2, 1) != 100)
{
Console.WriteLine("test_331() failed.");
return 431;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_338(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_338() failed.");
return 438;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_345((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_345() failed.");
return 445;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_352(&loc_x.m_b) != 100)
{
Console.WriteLine("test_352() failed.");
return 452;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_359(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100)
{
Console.WriteLine("test_359() failed.");
return 459;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_366(&loc_x.m_b - 6) != 100)
{
Console.WriteLine("test_366() failed.");
return 466;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_373(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100)
{
Console.WriteLine("test_373() failed.");
return 473;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_380(&loc_x) != 100)
{
Console.WriteLine("test_380() failed.");
return 480;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_387((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100)
{
Console.WriteLine("test_387() failed.");
return 487;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_394(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_394() failed.");
return 494;
}
Console.WriteLine("All tests passed.");
return 100;
}
}
| |
//
// Copyright (c) 2004-2021 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.UnitTests.Conditions
{
using NLog.Internal;
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using Xunit;
public class ConditionParserTests : NLogTestBase
{
[Fact]
public void ParseNullText()
{
Assert.Null(ConditionParser.ParseExpression(null));
}
[Fact]
public void ParseEmptyText()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression(""));
}
[Fact]
public void ImplicitOperatorTest()
{
ConditionExpression cond = "true and true";
Assert.IsType<ConditionAndExpression>(cond);
}
[Fact]
public void NullLiteralTest()
{
Assert.Equal("null", ConditionParser.ParseExpression("null").ToString());
}
[Fact]
public void BooleanLiteralTest()
{
Assert.Equal("True", ConditionParser.ParseExpression("true").ToString());
Assert.Equal("True", ConditionParser.ParseExpression("tRuE").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("false").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("fAlSe").ToString());
}
[Fact]
public void AndTest()
{
Assert.Equal("(True and True)", ConditionParser.ParseExpression("true and true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE AND true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("true and true && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE AND true and true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE && true AND true").ToString());
}
[Fact]
public void OrTest()
{
Assert.Equal("(True or True)", ConditionParser.ParseExpression("true or true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE OR true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("true or true || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE OR true or true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE || true OR true").ToString());
}
[Fact]
public void NotTest()
{
Assert.Equal("(not True)", ConditionParser.ParseExpression("not true").ToString());
Assert.Equal("(not (not True))", ConditionParser.ParseExpression("not not true").ToString());
Assert.Equal("(not (not (not True)))", ConditionParser.ParseExpression("not not not true").ToString());
}
[Fact]
public void StringTest()
{
Assert.Equal("''", ConditionParser.ParseExpression("''").ToString());
Assert.Equal("'Foo'", ConditionParser.ParseExpression("'Foo'").ToString());
Assert.Equal("'Bar'", ConditionParser.ParseExpression("'Bar'").ToString());
Assert.Equal("'d'Artagnan'", ConditionParser.ParseExpression("'d''Artagnan'").ToString());
var cle = ConditionParser.ParseExpression("'${message} ${level}'") as ConditionLayoutExpression;
Assert.NotNull(cle);
SimpleLayout sl = cle.Layout as SimpleLayout;
Assert.NotNull(sl);
Assert.Equal(3, sl.Renderers.Count);
Assert.IsType<MessageLayoutRenderer>(sl.Renderers[0]);
Assert.IsType<LiteralLayoutRenderer>(sl.Renderers[1]);
Assert.IsType<LevelLayoutRenderer>(sl.Renderers[2]);
}
[Fact]
public void LogLevelTest()
{
var result = ConditionParser.ParseExpression("LogLevel.Info") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Info, result.LiteralValue);
result = ConditionParser.ParseExpression("LogLevel.Trace") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Trace, result.LiteralValue);
}
[Fact]
public void RelationalOperatorTest()
{
RelationalOperatorTestInner("=", "==");
RelationalOperatorTestInner("==", "==");
RelationalOperatorTestInner("!=", "!=");
RelationalOperatorTestInner("<>", "!=");
RelationalOperatorTestInner("<", "<");
RelationalOperatorTestInner(">", ">");
RelationalOperatorTestInner("<=", "<=");
RelationalOperatorTestInner(">=", ">=");
}
[Fact]
public void NumberTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("3.141592").ToString());
Assert.Equal("42", ConditionParser.ParseExpression("42").ToString());
Assert.Equal("-42", ConditionParser.ParseExpression("-42").ToString());
Assert.Equal("-3.141592", ConditionParser.ParseExpression("-3.141592").ToString());
}
[Fact]
public void ExtraParenthesisTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("(((3.141592)))").ToString());
}
[Fact]
public void MessageTest()
{
var result = ConditionParser.ParseExpression("message");
Assert.IsType<ConditionMessageExpression>(result);
Assert.Equal("message", result.ToString());
}
[Fact]
public void LevelTest()
{
var result = ConditionParser.ParseExpression("level");
Assert.IsType<ConditionLevelExpression>(result);
Assert.Equal("level", result.ToString());
}
[Fact]
public void LoggerTest()
{
var result = ConditionParser.ParseExpression("logger");
Assert.IsType<ConditionLoggerNameExpression>(result);
Assert.Equal("logger", result.ToString());
}
[Fact]
public void ConditionFunctionTests()
{
var result = ConditionParser.ParseExpression("starts-with(logger, 'x${message}')") as ConditionMethodExpression;
Assert.NotNull(result);
Assert.Equal("starts-with(logger, 'x${message}')", result.ToString());
Assert.Equal("StartsWith", result.MethodInfo.Name);
Assert.Equal(typeof(ConditionMethods), result.MethodInfo.DeclaringType);
}
[Fact]
public void CustomNLogFactoriesTest()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("check('${foo}')", configurationItemFactory);
}
[Fact]
public void MethodNameWithUnderscores()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("__check__('${foo}')", configurationItemFactory);
}
[Fact]
public void UnbalancedParenthesis1Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("check("));
}
[Fact]
public void UnbalancedParenthesis2Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("((1)"));
}
[Fact]
public void UnbalancedParenthesis3Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("(1))"));
}
[Fact]
public void LogLevelWithoutAName()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("LogLevel.'somestring'"));
}
[Fact]
public void InvalidNumberWithUnaryMinusTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-a31"));
}
[Fact]
public void InvalidNumberTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-123.4a"));
}
[Fact]
public void UnclosedString()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("'Hello world"));
}
[Fact]
public void UnrecognizedToken()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("somecompletelyunrecognizedtoken"));
}
[Fact]
public void UnrecognizedPunctuation()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("#"));
}
[Fact]
public void UnrecognizedUnicodeChar()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0090"));
}
[Fact]
public void UnrecognizedUnicodeChar2()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0015"));
}
[Fact]
public void UnrecognizedMethod()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("unrecognized-method()"));
}
[Fact]
public void TokenizerEOFTest()
{
var tokenizer = new ConditionTokenizer(new SimpleStringReader(string.Empty));
Assert.Throws<ConditionParseException>(() => tokenizer.GetNextToken());
}
private void RelationalOperatorTestInner(string op, string result)
{
string operand1 = "3";
string operand2 = "7";
string input = operand1 + " " + op + " " + operand2;
string expectedOutput = "(" + operand1 + " " + result + " " + operand2 + ")";
var condition = ConditionParser.ParseExpression(input);
Assert.Equal(expectedOutput, condition.ToString());
}
public class FooLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent)
{
throw new System.NotImplementedException();
}
}
public class MyConditionMethods
{
public static bool CheckIt(string s)
{
return s == "X";
}
}
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
namespace Org.Apache.Etch.Bindings.Csharp.Msg
{
/// <summary>
/// Type denotes the type of a struct or message. When used with a
/// message it typically denotes an action or event.
/// </summary>
public class XType : IdName
{
/// <summary>Constructs the Type.</summary>
/// <param name="id">id of the type.</param>
/// <param name="name">name of the type.</param>
public XType( int id, String name )
: base( id, name )
{
// nothing else.
}
/// <summary>Constructs the Type, computing the appropriate value for the id.</summary>
/// <param name="name">name the name of the type.</param>
public XType( String name )
: base( name )
{
// nothing else.
}
public Validator GetValidator( Field key )
{
Validator v;
return validators.TryGetValue(key, out v) ? v : null;
}
private readonly FieldMap fieldMap = new FieldMap();
/// <summary>
/// Adds the validator to the chain for this key.
/// </summary>
/// <param name="key"></param>
/// <param name="vldtr"></param>
public void PutValidator( Field key, Validator vldtr )
{
CheckNotLocked();
if ( vldtr == null )
return;
if ( fieldMap.Get( key.Id ) == null )
AddField( key );
Validator v;
if (validators.TryGetValue(key, out v))
validators[key] = new ComboValidator(v, vldtr);
else
validators[key] = vldtr;
}
/// <summary>
/// Removes the validator chain for this key
/// </summary>
/// <param name="key"></param>
public void ClearValidator( Field key )
{
CheckNotLocked();
validators.Remove( key );
}
public Dictionary<Field, Validator> validators = new Dictionary<Field, Validator>();
/// <summary>
///
/// </summary>
/// <returns>the result type of this message type</returns>
public XType GetResult()
{
return rType;
}
public void SetResult( XType rType )
{
CheckNotLocked();
this.rType = rType;
}
private XType rType;
/// <summary>
///
/// </summary>
/// <returns>the associated import / export helper</returns>
public ImportExportHelper GetImportExportHelper()
{
return helper;
}
/// <summary>
/// Sets the associated import / export helper.
/// </summary>
/// <param name="helper"></param>
public void SetImportExportHelper( ImportExportHelper helper )
{
CheckNotLocked();
this.helper = helper;
}
private ImportExportHelper helper;
/// <summary>
///
/// </summary>
/// <returns>the associated component type for an array of this type</returns>
public Type GetComponentType()
{
return componentType;
}
/// <summary>
/// Sets the associated component type for an array of this type.
/// This type is not used when de-serializing the array components,
/// just when allocating the array itself.
/// </summary>
/// <param name="type"></param>
public void SetComponentType(Type type)
{
CheckNotLocked();
this.componentType = type;
}
private Type componentType;
/// <summary>
///
/// </summary>
/// <returns>an object to help dispatch the received message</returns>
public Object GetStubHelper()
{
return stubHelper;
}
/// <summary>
/// Sets an object to help the stub dispatch the received message
/// </summary>
/// <param name="stubHelper"></param>
public void SetStubHelper( Object stubHelper )
{
// CheckNotLocked(); called from stub and not from value factory.
if (this.stubHelper != null)
throw new Exception("this.stubHelper != null");
this.stubHelper = stubHelper;
}
private Object stubHelper;
///<summary>Locks the fields for this type.</summary>
public void Lock()
{
locked = true;
fieldMap.Lock();
}
private void CheckNotLocked()
{
if (locked)
throw new Exception("locked");
}
private bool locked;
///<summary>Adds a field to the set of fields.</summary>
///<param name="field"> A field to all </param>
///<returns>Returns the argument. If there is a collision with
/// an id and name, both associated with the same field,
/// then that field is returned instead of the argument </returns>
/// <Exception cref="ArgumentException">hrows IllegalArgumentException if there is a
/// collision in the id or name, or both id and name when not associated
/// with the same field.</Exception>
public Field AddField( Field field )
{
return fieldMap.Add( field );
}
///<summary>Translates a field id into the appropriate Field object.</summary>
///<param name="id">field id</param>
///<returns>id translated into the appropriate Field.</returns>
public Field GetField( int id )
{
return fieldMap.Get( id );
}
///<summary>Translates a field name into the appropriate Field.</summary>
///<param name="name">A field name</param>
///<returns>name translated into the appropriate Field.</returns>
public Field GetField( string name )
{
return fieldMap.Get( name );
}
///<returns>a set of all the fields.</returns>
public List<Field> GetFields()
{
return fieldMap.Values();
}
/// <summary>
/// Every type ( => message) carries a timeout
/// </summary>
private int timeout;
public int Timeout
{
get
{
return timeout;
}
set
{
CheckNotLocked();
timeout = value;
}
}
/// <summary>
/// Field containing result value
/// </summary>
private Field responseField;
public Field ResponseField
{
get
{
return responseField;
}
set
{
CheckNotLocked();
responseField = value;
}
}
///<summary>Checks whether this type is assignment compatible with other. This
///means that other is a subclass of this.</summary>
///<param name="other"></param>
///<returns>true if this type is assignable from other</returns>
public bool IsAssignableFrom( XType other )
{
return other != null && ( this.Equals( other ) || IsAssignableFrom( other.SuperType() ) );
}
public void CheckIsAssignableFrom( XType other )
{
if ( !IsAssignableFrom( other ) )
throw new ArgumentOutOfRangeException();
}
public XType SuperType()
{
return superType;
}
///<summary>Sets the super type of this type. If struct A extends B, then
///B is the super type of A.</summary>
///<param name="superType"></param>
public void SetSuperType( XType superType )
{
CheckNotLocked();
this.superType = superType;
}
private XType superType;
/// <summary>
/// Gets AsyncMode for this Type
/// </summary>
/// <returns>AsyncMode</returns>
public AsyncMode GetAsyncMode()
{
return asyncMode;
}
/// <summary>
/// Sets the AysncMode
/// </summary>
/// <param name="mode"></param>
public void SetAsyncMode(AsyncMode mode)
{
CheckNotLocked();
asyncMode = mode;
}
private AsyncMode asyncMode;
/// <summary>
/// Gets the message direction.
/// </summary>
/// <returns>the message direction</returns>
public Direction GetDirection()
{
return direction;
}
/// <summary>
/// Sets the message direction.
/// </summary>
/// <param name="direction"></param>
public void SetDirection(Direction direction)
{
CheckNotLocked();
this.direction = direction;
}
private Direction direction;
}
}
| |
#region Licence
/****************************************************************************
Copyright 1999-2015 Vincent J. Jacquet. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
****************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using WmcSoft.Text;
namespace WmcSoft
{
/// <summary>
/// Provides a set of static methods to extend the <see cref="Strip"/> class.
/// This is a static class.
/// </summary>
public static class StripExtensions
{
#region Any
public static bool ContainsAny(this Strip self, params char[] candidates)
{
return self.IndexOfAny(candidates) >= 0;
}
/// <summary>
/// Check if the string contains any of the candidates chars.
/// </summary>
/// <remarks>This optimized version relies on the fact that candidates is sorted.</remarks>
/// <param name="self">The char to test</param>
/// <param name="candidates">Candidates char to test against the char</param>
/// <returns>true if the char is any of the candidates, otherwise false.</returns>
public static bool BinaryContainsAny(this Strip self, params char[] candidates)
{
foreach (var c in self) {
if (Array.BinarySearch(candidates, c) >= 0)
return true;
}
return false;
}
public static bool EqualsAny(this Strip self, StringComparison comparisonType, params string[] candidates)
{
if (string.IsNullOrEmpty(self))
return false;
for (var i = 0; i < candidates.Length; i++) {
if (self.Equals(candidates[i], comparisonType))
return true;
}
return false;
}
public static bool EqualsAny(this Strip self, params string[] candidates)
{
return self.EqualsAny(StringComparison.CurrentCulture, candidates);
}
#endregion
#region Join
/// <summary>
/// Joins the sequence of strings into a single string.
/// </summary>
/// <param name="values">The sequence of strings.</param>
/// <returns>The joined string.</returns>
/// <remarks>The separator is CultureInfo.CurrentCulture.TextInfo.ListSeparator.</remarks>
public static string JoinWithListSeparator(this IEnumerable<Strip> values)
{
return JoinWith(values, CultureInfo.CurrentCulture.TextInfo.ListSeparator);
}
/// <summary>
/// Joins the sequence of strings into a single string.
/// </summary>
/// <param name="values">The sequence of strings.</param>
/// <returns>The joined string.</returns>
/// <remarks>The separator is currentCulture.TextInfo.ListSeparator.</remarks>
public static string JoinWithListSeparator(this IEnumerable<Strip> values, CultureInfo cultureInfo)
{
return JoinWith(values, (cultureInfo ?? CultureInfo.CurrentCulture).TextInfo.ListSeparator);
}
/// <summary>
/// Joins the sequence of strings into a single string, using the specified separator.
/// </summary>
/// <param name="values">The sequence of strings.</param>
/// <param name="separator">The separator.</param>
/// <returns>The joined string.</returns>
public static string JoinWith(this IEnumerable<Strip> values, string separator)
{
if (values == null) throw new ArgumentNullException(nameof(values));
return UnguardedJoin(separator, values);
}
/// <summary>
/// Joins the sequence of strings into a single string, using the specified separator.
/// </summary>
/// <param name="values">The sequence of strings.</param>
/// <param name="separator">The separator.</param>
/// <returns>The joined string.</returns>
public static string JoinWith(this IEnumerable<Strip> values, char separator)
{
return JoinWith(values, separator.ToString());
}
static string UnguardedJoin(string separator, IEnumerable<Strip> values)
{
var sb = new StringBuilder();
using (var enumerator = values.GetEnumerator()) {
if (enumerator.MoveNext()) {
enumerator.Current.AppendTo(sb);
while (enumerator.MoveNext())
sb.Append(separator);
enumerator.Current.AppendTo(sb);
}
}
return sb.ToString();
}
#endregion
#region Nullify methods
/// <summary>
/// Returns null if the string contains only whitespace.
/// </summary>
/// <param name="value">The string.</param>
/// <returns>Returns null if the string contains only whitespace; otherwise, the string.</returns>
public static Strip NullifyWhiteSpace(Strip value)
{
if (Strip.IsNullOrWhiteSpace(value))
return null;
return value;
}
/// <summary>
/// Returns null if the string is empty.
/// </summary>
/// <param name="value">The string.</param>
/// <returns>Returns null if the string is empty; otherwise, the string.</returns>
public static Strip NullifyEmpty(Strip value)
{
if (Strip.IsNullOrEmpty(value))
return null;
return value;
}
/// <summary>
/// Returns null if the string verifies a predicate.
/// </summary>
/// <param name="value">The string.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>Returns null if the string verifies the predicate; otherwise, the string.</returns>
public static Strip Nullify(Strip value, Predicate<Strip> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
if (value == null || predicate(value))
return null;
return value;
}
#endregion
#region Remove
/// <summary>
/// Removes the specified chars from the string.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="args">The chars to remove.</param>
/// <returns>The string without the specified chars.</returns>
public static string Remove(this Strip self, params char[] args)
{
if (self == null || self.Length == 0)
return self;
var adapter = new StripAdapter(self);
return adapter.Remove(args);
}
/// <summary>
/// Removes the specified substrings from the string.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="args">The substrings to remove.</param>
/// <returns>The string without the specified substrings.</returns>
public static string Remove(this Strip self, params string[] args)
{
if (Strip.IsNullOrEmpty(self))
return self;
var sb = self.ToStringBuilder(self.Length);
sb.Remove(args);
return sb.ToString();
}
#endregion
#region RemovePrefix/RemoveSuffix/RemoveAffixes
public static string RemovePrefix(this Strip self, string prefix)
{
return RemovePrefix(self, prefix, StringComparison.CurrentCulture);
}
public static string RemovePrefix(this Strip self, string prefix, StringComparison comparison)
{
if (self != null && self.StartsWith(prefix, comparison))
return self.Substring(prefix.Length);
return self;
}
public static string RemoveSuffix(this Strip self, string suffix)
{
return RemoveSuffix(self, suffix, StringComparison.CurrentCulture);
}
public static string RemoveSuffix(this Strip self, string suffix, StringComparison comparison)
{
if (self != null && self.EndsWith(suffix, comparison))
return self.Substring(0, self.Length - suffix.Length);
return self;
}
public static string RemoveAffixes(this Strip self, string affix)
{
return RemoveAffixes(self, affix, StringComparison.CurrentCulture);
}
public static Strip RemoveAffixes(this Strip self, string affix, StringComparison comparison)
{
if (self == null || self.Length < affix.Length)
return self;
var starts = self.StartsWith(affix, comparison);
var ends = self.EndsWith(affix, comparison);
if (starts & ends) {
if (self.Equals(affix, comparison))
return Strip.Empty;
return self.Substring(affix.Length, self.Length - 2 * affix.Length);
} else if (starts) {
return self.Substring(affix.Length);
} else if (ends) {
return self.Substring(0, self.Length - affix.Length);
}
return self;
}
public static string RemoveAffixes(this Strip self, string prefix, string suffix)
{
return RemoveAffixes(self, prefix, suffix, StringComparison.CurrentCulture);
}
public static string RemoveAffixes(this Strip self, string prefix, string suffix, StringComparison comparison)
{
if (self == null)
return self;
var starts = self.StartsWith(prefix, comparison);
var ends = self.EndsWith(suffix, comparison);
if (starts & ends) {
if ((prefix.Length + suffix.Length) >= self.Length)
return Strip.Empty;
return self.Substring(prefix.Length, self.Length - prefix.Length - suffix.Length);
} else if (starts) {
return self.Substring(prefix.Length);
} else if (ends) {
return self.Substring(0, self.Length - suffix.Length);
}
return self;
}
#endregion
#region StartsWith & EndsWith
public static bool StartsWith(this Strip self, char c)
{
if (string.IsNullOrEmpty(self))
return false;
return self.StartsWith(char.ToString(c));
}
public static bool StartsWith(this Strip self, char c, StringComparison comparison)
{
if (string.IsNullOrEmpty(self))
return false;
return self.StartsWith(char.ToString(c), comparison);
}
public static bool StartsWith(this Strip self, char c, bool ignoreCase, CultureInfo culture)
{
if (string.IsNullOrEmpty(self))
return false;
return self.StartsWith(char.ToString(c), ignoreCase, culture);
}
public static bool EndsWith(this Strip self, char c)
{
if (string.IsNullOrEmpty(self))
return false;
return self.EndsWith(char.ToString(c));
}
public static bool EndsWith(this Strip self, char c, StringComparison comparison)
{
if (string.IsNullOrEmpty(self))
return false;
return self.EndsWith(char.ToString(c), comparison);
}
public static bool EndsWith(this Strip self, char c, bool ignoreCase, CultureInfo culture)
{
if (string.IsNullOrEmpty(self))
return false;
return self.EndsWith(char.ToString(c), ignoreCase, culture);
}
#endregion
#region Substring
/// <summary>
/// Extracts the substring that precedes the <paramref name="value"/> char.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="value">The delimiter char to look for.</param>
/// <returns>Returns the substring that precedes the <paramref name="value"/> char, or null if the delimiter is not found.</returns>
public static Strip SubstringBefore(this Strip self, char value)
{
var index = self.IndexOf(value);
if (index < 0)
return null;
return self.Substring(0, index);
}
/// <summary>
/// Extracts the substring that precedes the <paramref name="find"/> char.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="find">The delimiter char to look for.</param>
/// <returns>Returns the substring that precedes the <paramref name="find"/> char, or the string if the delimiter is not found.</returns>
[Obsolete("Too complex.", true)]
public static Strip SubstringBeforeOrSelf(this Strip self, char find)
{
return SubstringBefore(self, find) ?? self;
}
/// <summary>
/// Extracts the substring that precedes the <paramref name="value"/> string.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="value">The delimiter string to look for.</param>
/// <returns>Returns the substring that precedes the <paramref name="value"/> string, or null if the delimiter is not found.</returns>
public static Strip SubstringBefore(this Strip self, string value)
{
if (string.IsNullOrEmpty(value))
return Strip.Empty;
var index = self.IndexOf(value, StringComparison.Ordinal);
if (index < 0)
return null;
return self.Substring(0, index);
}
/// <summary>
/// Extracts the substring that precedes the <paramref name="find"/> string.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="find">The delimiter string to look for.</param>
/// <returns>Returns the substring that precedes the <paramref name="find"/> string, or the string if the delimiter is not found.</returns>
[Obsolete("Too complex.", true)]
public static Strip SubstringBeforeOrSelf(this Strip self, string find)
{
return SubstringBefore(self, find) ?? self;
}
/// <summary>
/// Extracts the substring that follows the <paramref name="find"/> char.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="find">The delimiter char to look for.</param>
/// <returns>Returns the substring that follows the <paramref name="find"/> char, or null if the delimiter is not found.</returns>
public static Strip SubstringAfter(this Strip self, char find)
{
var index = self.IndexOf(find);
if (index < 0)
return null;
return self.Substring(index + 1);
}
/// <summary>
/// Extracts the substring that follows the <paramref name="find"/> char.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="find">The delimiter char to look for.</param>
/// <returns>Returns the substring that follows the <paramref name="find"/> char, or the string if the delimiter is not found.</returns>
[Obsolete("Too complex.", true)]
public static Strip SubstringAfterOrSelf(this Strip self, char find)
{
return SubstringAfter(self, find) ?? self;
}
/// <summary>
/// Extracts the substring that follows the <paramref name="value"/> string.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="value">The delimiter string to look for.</param>
/// <returns>Returns the substring that follows the <paramref name="value"/> string, or null if the delimiter is not found.</returns>
public static Strip SubstringAfter(this Strip self, string value)
{
if (string.IsNullOrEmpty(value))
return self;
var index = self.IndexOf(value, StringComparison.Ordinal);
if (index < 0)
return null;
return self.Substring(index + value.Length);
}
/// <summary>
/// Extracts the substring that follows the <paramref name="find"/> string.
/// </summary>
/// <param name="self">The initial string.</param>
/// <param name="find">The delimiter string to look for.</param>
/// <returns>Returns the substring that follows the <paramref name="find"/> string, or the string if the delimiter is not found.</returns>
[Obsolete("Too complex.", true)]
public static Strip SubstringAfterOrSelf(this Strip self, string find)
{
return SubstringAfter(self, find) ?? self;
}
/// <summary>
/// Extracts the substring between the prefix and the suffix.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="prefix">The prefix.</param>
/// <param name="suffix">The suffix.</param>
/// <returns>The substring between the prefix and the suffix, or null if the prefix or the suffix is not found.</returns>
public static Strip SubstringBetween(this Strip self, string prefix, string suffix)
{
if (string.IsNullOrEmpty(prefix))
return SubstringBefore(self, suffix);
else if (string.IsNullOrEmpty(suffix))
return SubstringAfter(self, prefix);
var start = self.IndexOf(prefix, StringComparison.Ordinal);
if (start < 0)
return null;
start += prefix.Length;
var end = self.IndexOf(suffix, start, StringComparison.Ordinal);
if (end < 0)
return null;
return self.Substring(start, end - start);
}
/// <summary>
/// Extracts the substring between the prefix and the suffix.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="prefix">The prefix.</param>
/// <param name="suffix">The suffix.</param>
/// <returns>The substring between the prefix and the suffix, or the string if the prefix or the suffix is not found.</returns>
[Obsolete("Too complex.", true)]
public static Strip SubstringBetweenOrSelf(this Strip self, string prefix, string suffix)
{
return SubstringBetween(self, prefix, suffix) ?? self;
}
/// <summary>
/// Extracts the <paramref name="length"/> chars at the left of the string.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="length">The length.</param>
/// <returns>The substring.</returns>
public static Strip Left(this Strip self, int length)
{
if (self == null)
return self;
if (length < 0)
length = self.Length - length;
if (length > self.Length)
return self;
return self.Substring(0, length);
}
/// <summary>
/// Extracts the <paramref name="length"/> chars at the right of the string.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="length">The length.</param>
/// <returns>The substring.</returns>
public static Strip Right(this Strip self, int length)
{
if (self == null)
return self;
if (length < 0)
length = self.Length - length;
if (length > self.Length)
return self;
return self.Substring(self.Length - length, length);
}
#endregion
#region Tokenize
#if false
/// <summary>
/// Returns the sequence of substrings of this instance using a tokenizer.
/// </summary>
/// <typeparam name="TTokenizer">The type of tokenizer.</typeparam>
/// <param name="self">The strings.</param>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns>The sequence of substrings.</returns>
public static IEnumerable<string> Tokenize<TTokenizer>(this string self, TTokenizer tokenizer)
where TTokenizer : ITokenizer<string, string> {
if (self == null)
return null;
return tokenizer.Tokenize(self);
}
/// <summary>
/// Returns the sequence of substrings of this instance that are delimited by a separator.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="separator">The separator.</param>
/// <returns>The sequence of substrings.</returns>
public static IEnumerable<string> Tokenize(this string self, char separator) {
return Tokenize(self, new CharTokenizer(separator));
}
/// <summary>
/// Returns the sequence of substrings of this instance that are delimited by a separator from a set.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="separators">The set of separators</param>
/// <returns>The sequence of substrings.</returns>
public static IEnumerable<string> Tokenize(this string self, params char[] separators) {
if (separators == null || separators.Length == 0)
return Tokenize(self, new PredicateTokenizer(char.IsWhiteSpace));
if (separators.Length == 1)
return Tokenize(self, new CharTokenizer(separators[0]));
return Tokenize(self, new CharsTokenizer(separators));
}
/// <summary>
/// Returns the sequence of substrings of this instance that are delimited by char for which a predidate returns true.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="isSeparator">The predicate.</param>
/// <returns>The sequence of substrings.</returns>
public static IEnumerable<string> Tokenize(this string self, Predicate<char> isSeparator) {
return Tokenize(self, new PredicateTokenizer(isSeparator));
}
/// <summary>
/// Returns the sequence of substrings of this instance that are delimited by whitespaces.
/// </summary>
/// <param name="self">The string.</param>
/// <returns>The sequence of substrings.</returns>
public static IEnumerable<string> Tokenize(this string self) {
return Tokenize(self, new PredicateTokenizer(char.IsWhiteSpace));
}
#endif
#endregion
#region Translate
/// <summary>
/// Translates the chars of the <paramref name="source "/> into the corresponding chars in the <paramref name="target"/>.
/// </summary>
/// <param name="self">The string.</param>
/// <param name="source">The source chars.</param>
/// <param name="target">The target chars.</param>
/// <returns>The translated string.</returns>
public static string Translate(this Strip self, string source, string target)
{
return StringExtensions.Translate(self.ToCharArray(), source, target);
}
#endregion
#region Truncate
/// <summary>
/// Shorten the string so that it is not longer than maxLength, the ellipsis string included.
/// </summary>
/// <param name="self">The string</param>
/// <param name="maxLength">The maximum length of the string</param>
/// <param name="ellipsis">The substring added at the end of the string when it is longer than the maxLenght.</param>
/// <returns>The shorten string when longer than the max length; otherwise, the string.</returns>
/// <remarks>The ellipsis may be empty but not null.</remarks>
public static string Truncate(this Strip self, int maxLength, string ellipsis = "\u2026")
{
if (ellipsis == null) throw new ArgumentNullException(nameof(ellipsis));
if (maxLength < ellipsis.Length) throw new ArgumentOutOfRangeException(nameof(maxLength));
if (!Strip.IsNullOrEmpty(self) && self.Length > maxLength)
return self.Substring(0, maxLength - ellipsis.Length) + ellipsis;
return self;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal struct CertificatePolicyMapping
{
public string IssuerDomainPolicy;
public string SubjectDomainPolicy;
}
internal sealed class CertificatePolicy
{
public bool ImplicitAnyCertificatePolicy { get; set; }
public bool SpecifiedAnyCertificatePolicy { get; set; }
public ISet<string> DeclaredCertificatePolicies { get; set; }
public bool ImplicitAnyApplicationPolicy { get; set; }
public bool SpecifiedAnyApplicationPolicy { get; set; }
public ISet<string> DeclaredApplicationPolicies { get; set; }
public int? InhibitAnyDepth { get; set; }
public List<CertificatePolicyMapping> PolicyMapping { get; set; }
public int? InhibitMappingDepth { get; set; }
public int? RequireExplicitPolicyDepth { get; set; }
public bool AllowsAnyCertificatePolicy
{
get { return ImplicitAnyCertificatePolicy || SpecifiedAnyCertificatePolicy; }
}
public bool AllowsAnyApplicationPolicy
{
get { return ImplicitAnyApplicationPolicy || SpecifiedAnyApplicationPolicy; }
}
}
internal sealed class CertificatePolicyChain
{
private readonly CertificatePolicy[] _policies;
private bool _failAllCertificatePolicies;
public CertificatePolicyChain(X509Certificate2Collection chain)
{
_policies = new CertificatePolicy[chain.Count];
ReadPolicies(chain);
}
internal bool MatchesCertificatePolicies(OidCollection policyOids)
{
foreach (Oid oid in policyOids)
{
if (!MatchesCertificatePolicies(oid))
{
return false;
}
}
return true;
}
internal bool MatchesCertificatePolicies(Oid policyOid)
{
if (_failAllCertificatePolicies)
{
return false;
}
string nextOid = policyOid.Value;
for (int i = 1; i <= _policies.Length; i++)
{
// The loop variable (i) matches the definition in RFC 3280,
// section 6.1.3. In that description i=1 is the root CA, and n
// is the EE/leaf certificate. In our chain object 0 is the EE cert
// and _policies.Length-1 is the root cert. So we will index things as
// _policies.Length - i (because i is 1 indexed).
int dataIdx = _policies.Length - i;
CertificatePolicy policy = _policies[dataIdx];
string oidToCheck = nextOid;
if (policy.PolicyMapping != null)
{
for (int iMapping = 0; iMapping < policy.PolicyMapping.Count; iMapping++)
{
CertificatePolicyMapping mapping = policy.PolicyMapping[iMapping];
if (StringComparer.Ordinal.Equals(mapping.IssuerDomainPolicy, oidToCheck))
{
nextOid = mapping.SubjectDomainPolicy;
}
}
}
if (policy.AllowsAnyCertificatePolicy)
{
continue;
}
if (policy.DeclaredCertificatePolicies == null)
{
return false;
}
if (!policy.DeclaredCertificatePolicies.Contains(oidToCheck))
{
return false;
}
}
return true;
}
internal bool MatchesApplicationPolicies(OidCollection policyOids)
{
foreach (Oid oid in policyOids)
{
if (!MatchesApplicationPolicies(oid))
{
return false;
}
}
return true;
}
internal bool MatchesApplicationPolicies(Oid policyOid)
{
string oidToCheck = policyOid.Value;
for (int i = 1; i <= _policies.Length; i++)
{
// The loop variable (i) matches the definition in RFC 3280,
// section 6.1.3. In that description i=1 is the root CA, and n
// is the EE/leaf certificate. In our chain object 0 is the EE cert
// and _policies.Length-1 is the root cert. So we will index things as
// _policies.Length - i (because i is 1 indexed).
int dataIdx = _policies.Length - i;
CertificatePolicy policy = _policies[dataIdx];
if (policy.AllowsAnyApplicationPolicy)
{
continue;
}
if (policy.DeclaredApplicationPolicies == null)
{
return false;
}
if (!policy.DeclaredApplicationPolicies.Contains(oidToCheck))
{
return false;
}
}
return true;
}
private void ReadPolicies(X509Certificate2Collection chain)
{
for (int i = 0; i < chain.Count; i++)
{
_policies[i] = ReadPolicy(chain[i]);
}
int explicitPolicyDepth = chain.Count;
int inhibitAnyPolicyDepth = explicitPolicyDepth;
int inhibitPolicyMappingDepth = explicitPolicyDepth;
for (int i = 1; i <= chain.Count; i++)
{
// The loop variable (i) matches the definition in RFC 3280,
// section 6.1.3. In that description i=1 is the root CA, and n
// is the EE/leaf certificate. In our chain object 0 is the EE cert
// and chain.Count-1 is the root cert. So we will index things as
// chain.Count - i (because i is 1 indexed).
int dataIdx = chain.Count - i;
CertificatePolicy policy = _policies[dataIdx];
if (policy.DeclaredCertificatePolicies == null && explicitPolicyDepth <= 0)
{
_failAllCertificatePolicies = true;
}
if (inhibitAnyPolicyDepth <= 0)
{
policy.ImplicitAnyCertificatePolicy = false;
policy.SpecifiedAnyCertificatePolicy = false;
}
else
{
inhibitAnyPolicyDepth--;
}
if (inhibitPolicyMappingDepth <= 0)
{
policy.PolicyMapping = null;
}
else
{
inhibitAnyPolicyDepth--;
}
if (explicitPolicyDepth <= 0)
{
policy.ImplicitAnyCertificatePolicy = false;
policy.ImplicitAnyApplicationPolicy = false;
}
else
{
explicitPolicyDepth--;
}
ApplyRestriction(ref inhibitAnyPolicyDepth, policy.InhibitAnyDepth);
ApplyRestriction(ref inhibitPolicyMappingDepth, policy.InhibitMappingDepth);
ApplyRestriction(ref explicitPolicyDepth, policy.RequireExplicitPolicyDepth);
}
}
private static void ApplyRestriction(ref int restriction, int? policyRestriction)
{
if (policyRestriction.HasValue)
{
restriction = Math.Min(restriction, policyRestriction.Value);
}
}
private static CertificatePolicy ReadPolicy(X509Certificate2 cert)
{
// If no ApplicationCertPolicies extension is provided then it uses the EKU
// OIDS.
ISet<string> applicationCertPolicies = null;
ISet<string> ekus = null;
CertificatePolicy policy = new CertificatePolicy();
foreach (X509Extension extension in cert.Extensions)
{
switch (extension.Oid.Value)
{
case Oids.ApplicationCertPolicies:
applicationCertPolicies = ReadCertPolicyExtension(extension);
break;
case Oids.CertPolicies:
policy.DeclaredCertificatePolicies = ReadCertPolicyExtension(extension);
break;
case Oids.CertPolicyMappings:
policy.PolicyMapping = ReadCertPolicyMappingsExtension(extension);
break;
case Oids.CertPolicyConstraints:
ReadCertPolicyConstraintsExtension(extension, policy);
break;
case Oids.EnhancedKeyUsage:
if (applicationCertPolicies == null)
{
// No reason to do this if the applicationCertPolicies was already read
ekus = ReadExtendedKeyUsageExtension(extension);
}
break;
case Oids.InhibitAnyPolicyExtension:
policy.InhibitAnyDepth = ReadInhibitAnyPolicyExtension(extension);
break;
}
}
policy.DeclaredApplicationPolicies = applicationCertPolicies ?? ekus;
policy.ImplicitAnyApplicationPolicy = policy.DeclaredApplicationPolicies == null;
policy.ImplicitAnyCertificatePolicy = policy.DeclaredCertificatePolicies == null;
policy.SpecifiedAnyApplicationPolicy = CheckExplicitAnyPolicy(policy.DeclaredApplicationPolicies);
policy.SpecifiedAnyCertificatePolicy = CheckExplicitAnyPolicy(policy.DeclaredCertificatePolicies);
return policy;
}
private static bool CheckExplicitAnyPolicy(ISet<string> declaredPolicies)
{
if (declaredPolicies == null)
{
return false;
}
return declaredPolicies.Remove(Oids.AnyCertPolicy);
}
private static int ReadInhibitAnyPolicyExtension(X509Extension extension)
{
DerSequenceReader reader = DerSequenceReader.CreateForPayload(extension.RawData);
return reader.ReadInteger();
}
private static void ReadCertPolicyConstraintsExtension(X509Extension extension, CertificatePolicy policy)
{
DerSequenceReader reader = new DerSequenceReader(extension.RawData);
while (reader.HasData)
{
// Policy Constraints context specific tag values are defined in RFC 3280 4.2.1.12,
// and restated (unchanged) in RFC 5280 4.2.1.11.
switch (reader.PeekTag())
{
case DerSequenceReader.ContextSpecificTagFlag | 0:
policy.RequireExplicitPolicyDepth = reader.ReadInteger();
break;
case DerSequenceReader.ContextSpecificTagFlag | 1:
policy.InhibitMappingDepth = reader.ReadInteger();
break;
default:
if (extension.Critical)
{
// If an unknown value is read, but we're marked as critical,
// then we don't know what we're doing and MUST fail validation
// (RFC 3280).
// If it isn't critical then it means we're allowed to be ignorant
// of data defined more recently than we understand.
throw new CryptographicException();
}
break;
}
}
}
private static ISet<string> ReadExtendedKeyUsageExtension(X509Extension extension)
{
X509EnhancedKeyUsageExtension ekusExtension = (X509EnhancedKeyUsageExtension)extension;
HashSet<string> oids = new HashSet<string>();
foreach (Oid oid in ekusExtension.EnhancedKeyUsages)
{
oids.Add(oid.Value);
}
return oids;
}
private static ISet<string> ReadCertPolicyExtension(X509Extension extension)
{
DerSequenceReader reader = new DerSequenceReader(extension.RawData);
HashSet<string> policies = new HashSet<string>();
while (reader.HasData)
{
DerSequenceReader policyInformation = reader.ReadSequence();
policies.Add(policyInformation.ReadOidAsString());
// There is an optional policy qualifier here, but it is for information
// purposes, there is no logic that would be changed.
// Since reader (the outer one) has already skipped past the rest of the
// sequence we don't particularly need to drain out here.
}
return policies;
}
private static List<CertificatePolicyMapping> ReadCertPolicyMappingsExtension(X509Extension extension)
{
DerSequenceReader reader = new DerSequenceReader(extension.RawData);
List<CertificatePolicyMapping> mappings = new List<CertificatePolicyMapping>();
while (reader.HasData)
{
DerSequenceReader mappingSequence = reader.ReadSequence();
mappings.Add(
new CertificatePolicyMapping
{
IssuerDomainPolicy = mappingSequence.ReadOidAsString(),
SubjectDomainPolicy = mappingSequence.ReadOidAsString(),
});
}
return mappings;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate001.dlgate001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate001.dlgate001;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is delegate creation expression;
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
c.E += new Dele(C.Foo);
if (c.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate002.dlgate002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate002.dlgate002;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is delegate creation expression; (no event accessor declaration)
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
c.E += new Dele(C.Foo);
if (c.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic001.dynamic001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic001.dynamic001;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is dynamic runtime delegate: with event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact(Skip = "875189")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new C();
dynamic c = new C();
c.E += (Dele)C.Foo;
d.E += c.E;
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic002.dynamic002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic002.dynamic002;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is dynamic runtime delegate: without event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new C();
dynamic c = new C();
c.E += (Dele)C.Foo;
d.E += c.E;
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic003.dynamic003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic003.dynamic003;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// lhs is static typed and rhs is dynamic runtime delegate: with event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public static int Foo(int i)
{
return i;
}
public event Dele E;
[Fact(Skip = "875189")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
C d = new C();
dynamic c = new C();
c.E += (Dele)C.Foo;
d.E += c.E;
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic004.dynamic004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic004.dynamic004;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// lhs is static typed and rhs is dynamic runtime delegate: without event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public static int Foo(int i)
{
return i;
}
public Dele E;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
C d = new C();
dynamic c = new C();
c.E += (Dele)C.Foo;
d.E += c.E;
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty001.fieldproperty001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty001.fieldproperty001;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is field/property of delegate type : with event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public Dele field;
public Dele Field
{
get
{
return field;
}
set
{
field = value;
}
}
public event Dele E;
public C()
{
field = C.Foo;
}
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new C();
//c.E += C.Foo;
C c = new C();
d.E += c.field;
if (d.DoEvent(9) != 9)
return 1;
d.E -= c.field;
d.E += c.Field;
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty002.fieldproperty002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty002.fieldproperty002;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is field/property of delegate type : without event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public Dele field;
public Dele Field
{
get
{
return field;
}
set
{
field = value;
}
}
public Dele E;
public C()
{
field = C.Foo;
}
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new C();
//c.E += C.Foo;
C c = new C();
d.E += c.field;
if (d.DoEvent(9) != 9)
return 1;
d.E -= c.field;
d.E += c.Field;
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null001.null001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null001.null001;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: rhs is null literal : lhs is not null
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
c.E += (Dele)C.Foo;
c.E += null;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null002.null002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null002.null002;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: rhs is null literal : lhs is null
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
int result = 0;
try
{
c.E += null;
result += 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.AmbigBinaryOps, e.Message, "+=", "<null>", "<null>"))
return 1;
}
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return001.return001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return001.return001;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is delegate invocation return delegate : with event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public static int Foo(int i)
{
return i;
}
public static Dele Bar()
{
return C.Foo;
}
public event Dele E;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new C();
d.E += C.Bar();
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return002.return002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return002.return002;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// rhs is delegate invocation return delegate : without event accessor
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public static int Foo(int i)
{
return i;
}
public static Dele Bar()
{
return C.Foo;
}
public Dele E;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new C();
d.E += C.Bar();
if (d.DoEvent(9) != 9)
return 1;
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.BasePages;
using umbraco.BusinessLogic.Utils;
using umbraco.cms;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.workflow;
using umbraco.interfaces;
using System.Text.RegularExpressions;
using System.Linq;
using TypeFinder = Umbraco.Core.TypeFinder;
namespace umbraco.BusinessLogic.Actions
{
/// <summary>
/// Actions and Actionhandlers are a key concept to umbraco and a developer whom wish to apply
/// businessrules whenever data is changed within umbraco, by implementing the IActionHandler
/// interface it's possible to invoke methods (foreign to umbraco) - this can be used whenever
/// there is a specific rule which needs to be applied to content.
///
/// The Action class itself has responsibility for registering actions and actionhandlers,
/// and contains methods which will be invoked whenever a change is made to ex. a document, media or member
///
/// An action/actionhandler will automatically be registered, using reflection
/// which is enabling thirdparty developers to extend the core functionality of
/// umbraco without changing the codebase.
/// </summary>
[Obsolete("Actions and ActionHandlers are obsolete and should no longer be used")]
public class Action
{
private static readonly List<IActionHandler> ActionHandlers = new List<IActionHandler>();
private static readonly Dictionary<string, string> ActionJs = new Dictionary<string, string>();
private static readonly object Lock = new object();
static Action()
{
ReRegisterActionsAndHandlers();
}
/// <summary>
/// This is used when an IAction or IActionHandler is installed into the system
/// and needs to be loaded into memory.
/// </summary>
/// <remarks>
/// TODO: this shouldn't be needed... we should restart the app pool when a package is installed!
/// </remarks>
public static void ReRegisterActionsAndHandlers()
{
lock (Lock)
{
using (Umbraco.Core.ObjectResolution.Resolution.DirtyBackdoorToConfiguration)
{
//TODO: Based on the above, this is a big hack as types should all be cleared on package install!
ActionsResolver.Reset();
ActionHandlers.Clear();
//TODO: Based on the above, this is a big hack as types should all be cleared on package install!
ActionsResolver.Current = new ActionsResolver(
() => TypeFinder.FindClassesOfType<IAction>(PluginManager.Current.AssembliesToScan));
RegisterIActionHandlers();
}
}
}
/// <summary>
/// Stores all IActionHandlers that have been loaded into memory into a list
/// </summary>
private static void RegisterIActionHandlers()
{
if (ActionHandlers.Count == 0)
{
ActionHandlers.AddRange(
PluginManager.Current.CreateInstances<IActionHandler>(
PluginManager.Current.ResolveActionHandlers()));
}
}
/// <summary>
/// Whenever an action is performed upon a document/media/member, this method is executed, ensuring that
/// all registered handlers will have an oppotunity to handle the action.
/// </summary>
/// <param name="d">The document being operated on</param>
/// <param name="action">The action triggered</param>
public static void RunActionHandlers(Document d, IAction action)
{
foreach (IActionHandler ia in ActionHandlers)
{
try
{
foreach (IAction a in ia.ReturnActions())
{
if (a.Alias == action.Alias)
{
// Uncommented for auto publish support
// System.Web.HttpContext.Current.Trace.Write("BusinessLogic.Action.RunActionHandlers", "Running " + ia.HandlerName() + " (matching action: " + a.Alias + ")");
ia.Execute(d, action);
}
}
}
catch (Exception iaExp)
{
LogHelper.Error<Action>(string.Format("Error loading actionhandler '{0}'", ia.HandlerName()), iaExp);
}
}
// Run notification
// Find current user
User u;
try
{
u = User.GetCurrent();
}
catch
{
u = User.GetUser(0);
}
if (u == null)
{
//GE 2012-02-29
//user will be null when using distributed calls
//can't easily get the real publishing user to bubble all the way through the distributed call framework
//so just check for it and set it to admin, so at least the notification gets sent
u = User.GetUser(0);
}
Notification.GetNotifications(d, u, action);
}
/// <summary>
/// Jacascript for the contextmenu
/// Suggestion: this method should be moved to the presentation layer.
/// </summary>
/// <param name="language"></param>
/// <returns>String representation</returns>
public string ReturnJavascript(string language)
{
return findActions(language);
}
/// <summary>
/// Returns a list of JavaScript file paths.
/// </summary>
/// <returns></returns>
public static List<string> GetJavaScriptFileReferences()
{
return ActionsResolver.Current.Actions
.Where(x => !string.IsNullOrWhiteSpace(x.JsSource))
.Select(x => x.JsSource).ToList();
//return ActionJsReference;
}
/// <summary>
/// Javascript menuitems - tree contextmenu
/// Umbraco console
///
/// Suggestion: this method should be moved to the presentation layer.
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
private static string findActions(string language)
{
if (!ActionJs.ContainsKey(language))
{
string _actionJsList = "";
foreach (IAction action in ActionsResolver.Current.Actions)
{
// Adding try/catch so this rutine doesn't fail if one of the actions fail
// Add to language JsList
try
{
// NH: Add support for css sprites
string icon = action.Icon;
if (!string.IsNullOrEmpty(icon) && icon.StartsWith("."))
icon = icon.Substring(1, icon.Length - 1);
else
icon = "images/" + icon;
_actionJsList += string.Format(",\n\tmenuItem(\"{0}\", \"{1}\", \"{2}\", \"{3}\")",
action.Letter, icon, ui.GetText("actions", action.Alias, language), action.JsFunctionName);
}
catch (Exception ee)
{
LogHelper.Error<Action>("Error registrering action to javascript", ee);
}
}
if (_actionJsList.Length > 0)
_actionJsList = _actionJsList.Substring(2, _actionJsList.Length - 2);
_actionJsList = "\nvar menuMethods = new Array(\n" + _actionJsList + "\n)\n";
ActionJs.Add(language, _actionJsList);
}
return ActionJs[language];
}
/// <summary>
///
/// </summary>
/// <returns>An arraylist containing all javascript variables for the contextmenu in the tree</returns>
[Obsolete("Use ActionsResolver.Current.Actions instead")]
public static ArrayList GetAll()
{
return new ArrayList(ActionsResolver.Current.Actions.ToList());
}
/// <summary>
/// This method will return a list of IAction's based on a string list. Each character in the list may represent
/// an IAction. This will associate any found IActions based on the Letter property of the IAction with the character being referenced.
/// </summary>
/// <param name="actions"></param>
/// <returns>returns a list of actions that have an associated letter found in the action string list</returns>
public static List<IAction> FromString(string actions)
{
List<IAction> list = new List<IAction>();
foreach (char c in actions.ToCharArray())
{
IAction action = ActionsResolver.Current.Actions.ToList().Find(
delegate(IAction a)
{
return a.Letter == c;
}
);
if (action != null)
list.Add(action);
}
return list;
}
/// <summary>
/// Returns the string representation of the actions that make up the actions collection
/// </summary>
/// <returns></returns>
public static string ToString(List<IAction> actions)
{
string[] strMenu = Array.ConvertAll<IAction, string>(actions.ToArray(), delegate(IAction a) { return (a.Letter.ToString()); });
return string.Join("", strMenu);
}
/// <summary>
/// Returns a list of IActions that are permission assignable
/// </summary>
/// <returns></returns>
public static List<IAction> GetPermissionAssignable()
{
return ActionsResolver.Current.Actions.ToList().FindAll(
delegate(IAction a)
{
return (a.CanBePermissionAssigned);
}
);
}
/// <summary>
/// Check if the current IAction is using legacy javascript methods
/// </summary>
/// <param name="action"></param>
/// <returns>false if the Iaction is incompatible with 4.5</returns>
public static bool ValidateActionJs(IAction action)
{
return !action.JsFunctionName.Contains("+");
}
/// <summary>
/// Method to convert the old modal calls to the new ones
/// </summary>
/// <param name="javascript"></param>
/// <returns></returns>
public static string ConvertLegacyJs(string javascript)
{
MatchCollection tags =
Regex.Matches(javascript, "openModal[^;]*;", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match tag in tags)
{
string[] function = tag.Value.Split(',');
if (function.Length > 0)
{
string newFunction = "UmbClientMgr.openModalWindow" + function[0].Substring(9).Replace("parent.nodeID", "UmbClientMgr.mainTree().getActionNode().nodeId").Replace("nodeID", "UmbClientMgr.mainTree().getActionNode().nodeId").Replace("parent.returnRandom()", "'" + Guid.NewGuid().ToString() + "'");
newFunction += ", " + function[1];
newFunction += ", true";
newFunction += ", " + function[2];
newFunction += ", " + function[3];
javascript = javascript.Replace(tag.Value, newFunction);
}
}
return javascript;
}
}
/// <summary>
/// This class is used to manipulate IActions that are implemented in a wrong way
/// For instance incompatible trees with 4.0 vs 4.5
/// </summary>
public class PlaceboAction : IAction
{
public char Letter { get; set; }
public bool ShowInNotifier { get; set; }
public bool CanBePermissionAssigned { get; set; }
public string Icon { get; set; }
public string Alias { get; set; }
public string JsFunctionName { get; set; }
public string JsSource { get; set; }
public PlaceboAction() { }
public PlaceboAction(IAction legacyAction)
{
Letter = legacyAction.Letter;
ShowInNotifier = legacyAction.ShowInNotifier;
CanBePermissionAssigned = legacyAction.CanBePermissionAssigned;
Icon = legacyAction.Icon;
Alias = legacyAction.Alias;
JsFunctionName = legacyAction.JsFunctionName;
JsSource = legacyAction.JsSource;
}
}
}
| |
/*
* Copyright (C) 2011 Mitsuaki Kuwahara
* Released under the MIT License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using UnitTest.Util;
using Nana.Syntaxes;
using Nana;
using Nana.Tokens;
namespace UnitTest.Syntaxes.CmdLnArgsFxt
{
[TestFixture]
public class PickOpt
{
[Test]
public void T001()
{
string label, input, expected;
label = "";
input = "/reference:System.Windows.Forms.dll";
expected =
@"opt[reference]
val[System.Windows.Forms.dll]
";
Run(label, input, expected);
}
[Test]
public void T002()
{
string label, input, expected;
label = "";
input = "-reference:System.Windows.Forms.dll";
expected =
@"opt[reference]
val[System.Windows.Forms.dll]
";
Run(label, input, expected);
}
[Test]
public void T003()
{
string label, input, expected;
label = "supply not supported option";
input = "/unknown:System.Windows.Forms.dll";
expected =
@"(null)";
Run(label, input, expected);
}
[Test]
public void T004()
{
string label, input, expected;
label = "supply no option";
input = "";
expected =
@"(null)";
Run(label, input, expected);
}
public void Run(string lable, string input, string expected)
{
new TestCase(lable, input, expected, Test).Run();
}
public string Test(TestCase c)
{
Token act = CmdLnArgs.PickOpt(c.Input);
return act == null
? "(null)"
: string.Format("opt[{0}]\r\nval[{1}]\r\n", act.Group, act.Value)
;
}
}
[TestFixture]
public class GetCmdLnArgs
{
[Test]
public void T001()
{
string label, inp, epc;
label = "";
inp = @"c:\dir\a.nana";
epc = @"/out:c:\dir\a.exe c:\dir\a.nana";
Run(label, inp, epc);
}
[Test]
public void T002()
{
string label, inp, epc;
label = "";
inp = "a.nana b.nana";
epc = "/out:a.exe a.nana b.nana";
Run(label, inp, epc);
}
[Test]
public void T003()
{
string label, inp, epc;
label = "";
inp = "/out:a.exe a.nana";
epc = "/out:a.exe a.nana";
Run(label, inp, epc);
}
[Test]
public void T004()
{
string label, inp, epc;
label = "";
inp = "/out:a.exe a.nana b.nana";
epc = "/out:a.exe a.nana b.nana";
Run(label, inp, epc);
}
[Test]
public void T005()
{
string label, inp, epc;
label = "";
inp = "/out:a.exe /reference:refa a.nana b.nana";
epc = "/out:a.exe /reference:refa a.nana b.nana";
Run(label, inp, epc);
}
public void Run(string lable, string input, string expected)
{
new TestCase(lable, input, expected, Test).Run();
}
public string Test(TestCase c)
{
string[] args = c.Input.Split(new char[] { ' ' });
Token act = CmdLnArgs.GetCmdLnArgs(args);
if (act == null) /**/ return "(act == null)";
Token[] cmpopts = act.Select("CompileOptions");
if (cmpopts == null || cmpopts.Length == 0) { return "(No CompileOptions token)"; }
if (cmpopts.Length > 1) { return "(Too many CompileOptions tokens)"; }
Token[] srcs = act.Select("Sources");
if (srcs == null || srcs.Length == 0) { return "(No Sources token)"; }
if (srcs.Length > 1) { return "(Too many Sources tokens)"; }
StringBuilder b = new StringBuilder();
string spl;
// opts
spl = "";
foreach (Token t in cmpopts[0].Follows)
{
b.Append(spl);
b.Append("/");
b.Append(t.Group);
b.Append(":");
b.Append(t.Value);
spl = " ";
}
// srcs
foreach (Token t in srcs[0].Follows)
{
b.Append(spl);
b.Append(t.Value);
spl = " ";
}
return b.ToString();
}
}
[TestFixture]
public class GetCmdLnArgs_Exceptions
{
[Test]
public void T001()
{
string label, inp, epc;
label = "";
inp = "(null)";
epc = @"ArgumentNullException";
Run(label, inp, epc);
}
//[Test]
//public void T002()
//{
// string label, inp, epc;
// label = "";
// inp = "";
// epc = "No source file specified: ";
// Run(label, inp, epc);
//}
[Test]
public void T003()
{
string label, inp, epc;
label = "";
inp = "/unknown:xxx";
epc = "Not supported option: /unknown:xxx";
Run(label, inp, epc);
}
public void Run(string lable, string input, string expected)
{
new TestCase(lable, input, expected, Test).Run();
}
public string Test(TestCase c)
{
string[] args = c.Input.Split(new char[] { ' ' });
if (args[0] == "(null)") args = null;
try
{
Token act = CmdLnArgs.GetCmdLnArgs(args);
return "(no exception)";
}
catch (ArgumentNullException ane)
{
return ane.GetType().Name;
}
catch (Exception e)
{
return e.Message;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// 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.Data.SqlTypes;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Xunit;
namespace System.Data.Tests.SqlTypes
{
public class SqlXmlTest : IDisposable
{
private CultureInfo _originalCulture;
public SqlXmlTest()
{
_originalCulture = CultureInfo.CurrentCulture; ;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
}
public void Dispose()
{
CultureInfo.CurrentCulture = _originalCulture;
}
// Test constructor
[Fact] // .ctor (Stream)
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
public void Constructor2_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
SqlXml xmlSql = new SqlXml(stream);
Assert.False(xmlSql.IsNull);
Assert.Equal(xmlStr, xmlSql.Value);
}
[Fact] // .ctor (Stream)
public void Constructor2_Stream_Empty()
{
MemoryStream ms = new MemoryStream();
SqlXml xmlSql = new SqlXml(ms);
Assert.False(xmlSql.IsNull);
Assert.Equal(string.Empty, xmlSql.Value);
}
[Fact]
public void Constructor2_Stream_Null()
{
SqlXml xmlSql = new SqlXml((Stream)null);
Assert.True(xmlSql.IsNull);
try
{
string value = xmlSql.Value;
Assert.False(true);
}
catch (SqlNullValueException)
{
}
}
[Fact] // .ctor (XmlReader)
public void Constructor3()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
XmlReader xrdr = new XmlTextReader(new StringReader(xmlStr));
SqlXml xmlSql = new SqlXml(xrdr);
Assert.False(xmlSql.IsNull);
Assert.Equal(xmlStr, xmlSql.Value);
}
[Fact] // .ctor (XmlReader)
public void Constructor3_XmlReader_Empty()
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader xrdr = XmlReader.Create(new StringReader(string.Empty), xs);
SqlXml xmlSql = new SqlXml(xrdr);
Assert.False(xmlSql.IsNull);
Assert.Equal(string.Empty, xmlSql.Value);
}
[Fact]
public void Constructor3_XmlReader_Null()
{
SqlXml xmlSql = new SqlXml((XmlReader)null);
Assert.True(xmlSql.IsNull);
try
{
string value = xmlSql.Value;
Assert.False(true);
}
catch (SqlNullValueException)
{
}
}
[Fact]
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
public void CreateReader_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
SqlXml xmlSql = new SqlXml(stream);
XmlReader xrdr = xmlSql.CreateReader();
xrdr.MoveToContent();
Assert.Equal(xmlStr, xrdr.ReadOuterXml());
}
[Fact]
public void SqlXml_fromXmlReader_CreateReaderTest()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
XmlReader rdr = new XmlTextReader(new StringReader(xmlStr));
SqlXml xmlSql = new SqlXml(rdr);
XmlReader xrdr = xmlSql.CreateReader();
xrdr.MoveToContent();
Assert.Equal(xmlStr, xrdr.ReadOuterXml());
}
[Fact]
public void SqlXml_fromZeroLengthStream_CreateReaderTest()
{
MemoryStream stream = new MemoryStream();
SqlXml xmlSql = new SqlXml(stream);
XmlReader xrdr = xmlSql.CreateReader();
Assert.Equal(false, xrdr.Read());
}
[Fact]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest_withFragment()
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader rdr = XmlReader.Create(new StringReader(string.Empty), xs);
SqlXml xmlSql = new SqlXml(rdr);
XmlReader xrdr = xmlSql.CreateReader();
Assert.Equal(false, xrdr.Read());
}
[Fact]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest()
{
XmlReader rdr = new XmlTextReader(new StringReader(string.Empty));
try
{
new SqlXml(rdr);
Assert.False(true);
}
catch (XmlException)
{
}
}
[Fact]
public void CreateReader_Stream_Null()
{
SqlXml xmlSql = new SqlXml((Stream)null);
try
{
xmlSql.CreateReader();
Assert.False(true);
}
catch (SqlNullValueException)
{
}
}
[Fact]
public void CreateReader_XmlReader_Null()
{
SqlXml xmlSql = new SqlXml((XmlReader)null);
try
{
xmlSql.CreateReader();
Assert.False(true);
}
catch (SqlNullValueException)
{
}
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
using Xunit.Sdk;
using Microsoft.Xunit.Performance;
namespace System.Numerics.Tests
{
public static class Constructor
{
private static Random s_random = new Random();
public const int DefaultInnerIterationsCount = 100000000;
#if netcoreapp
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_Byte()
{
byte[] arrValues = GenerateRandomValuesForVector<byte>();
var spanValues = new Span<byte>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<byte>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_SByte()
{
sbyte[] arrValues = GenerateRandomValuesForVector<sbyte>();
var spanValues = new Span<sbyte>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<sbyte>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_UInt16()
{
ushort[] arrValues = GenerateRandomValuesForVector<ushort>();
var spanValues = new Span<ushort>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<ushort>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_Int16()
{
short[] arrValues = GenerateRandomValuesForVector<short>();
var spanValues = new Span<short>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<short>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_UInt32()
{
uint[] arrValues = GenerateRandomValuesForVector<uint>();
var spanValues = new Span<uint>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<uint>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_Int32()
{
int[] arrValues = GenerateRandomValuesForVector<int>();
var spanValues = new Span<int>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<int>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_UInt64()
{
ulong[] arrValues = GenerateRandomValuesForVector<ulong>();
var spanValues = new Span<ulong>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<ulong>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_Int64()
{
long[] arrValues = GenerateRandomValuesForVector<long>();
var spanValues = new Span<long>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<long>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_Single()
{
float[] arrValues = GenerateRandomValuesForVector<float>();
var spanValues = new Span<float>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<float>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void ConstructorBenchmark_Double()
{
double[] arrValues = GenerateRandomValuesForVector<double>();
var spanValues = new Span<double>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
Construct<double>(spanValues);
}
}
}
public static void Construct<T>(Span<T> values) where T : struct
{
for (var iteration = 0; iteration < Benchmark.InnerIterationCount; iteration++)
{
Vector<T> vect = new Vector<T>(values);
}
}
#endif
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_Byte()
{
byte[] arrValues = GenerateRandomValuesForVector<byte>();
var spanValues = new ReadOnlySpan<byte>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<byte>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_SByte()
{
sbyte[] arrValues = GenerateRandomValuesForVector<sbyte>();
var spanValues = new ReadOnlySpan<sbyte>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<sbyte>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_UInt16()
{
ushort[] arrValues = GenerateRandomValuesForVector<ushort>();
var spanValues = new ReadOnlySpan<ushort>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<ushort>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_Int16()
{
short[] arrValues = GenerateRandomValuesForVector<short>();
var spanValues = new ReadOnlySpan<short>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<short>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_UInt32()
{
uint[] arrValues = GenerateRandomValuesForVector<uint>();
var spanValues = new ReadOnlySpan<uint>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<uint>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_Int32()
{
int[] arrValues = GenerateRandomValuesForVector<int>();
var spanValues = new ReadOnlySpan<int>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<int>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_UInt64()
{
ulong[] arrValues = GenerateRandomValuesForVector<ulong>();
var spanValues = new ReadOnlySpan<ulong>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<ulong>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_Int64()
{
long[] arrValues = GenerateRandomValuesForVector<long>();
var spanValues = new ReadOnlySpan<long>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<long>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_Single()
{
float[] arrValues = GenerateRandomValuesForVector<float>();
var spanValues = new ReadOnlySpan<float>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<float>(spanValues);
}
}
}
[Benchmark(InnerIterationCount = DefaultInnerIterationsCount)]
public static void SpanCastBenchmark_Double()
{
double[] arrValues = GenerateRandomValuesForVector<double>();
var spanValues = new ReadOnlySpan<double>(arrValues);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SpanCast<double>(spanValues);
}
}
}
public static void SpanCast<T>(ReadOnlySpan<T> values) where T : struct
{
for (var iteration = 0; iteration < Benchmark.InnerIterationCount; iteration++)
{
ReadOnlySpan<Vector<T>> vectors = MemoryMarshal.Cast<T, Vector<T>>(values);
Vector<T> vector = vectors[0];
}
}
internal static T[] GenerateRandomValuesForVector<T>() where T : struct
{
int minValue = GetMinValue<T>();
int maxValue = GetMaxValue<T>();
return Util.GenerateRandomValues<T>(Vector<T>.Count, minValue, maxValue);
}
internal static int GetMinValue<T>() where T : struct
{
if (typeof(T) == typeof(long) || typeof(T) == typeof(float) || typeof(T) == typeof(double) || typeof(T) == typeof(uint) || typeof(T) == typeof(ulong))
{
return int.MinValue;
}
TypeInfo typeInfo = typeof(T).GetTypeInfo();
FieldInfo field = typeInfo.GetDeclaredField("MinValue");
var value = field.GetValue(null);
return (int)(dynamic)value;
}
internal static int GetMaxValue<T>() where T : struct
{
if (typeof(T) == typeof(long) || typeof(T) == typeof(float) || typeof(T) == typeof(double) || typeof(T) == typeof(uint) || typeof(T) == typeof(ulong))
{
return int.MaxValue;
}
TypeInfo typeInfo = typeof(T).GetTypeInfo();
FieldInfo field = typeInfo.GetDeclaredField("MaxValue");
var value = field.GetValue(null);
return (int)(dynamic)value;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal partial class VisualStudioSymbolNavigationService : ForegroundThreadAffinitizedObject, ISymbolNavigationService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
private readonly OutliningTaggerProvider _outliningTaggerProvider;
public VisualStudioSymbolNavigationService(
SVsServiceProvider serviceProvider,
OutliningTaggerProvider outliningTaggerProvider)
{
_serviceProvider = serviceProvider;
_outliningTaggerProvider = outliningTaggerProvider;
var componentModel = GetService<SComponentModel, IComponentModel>();
_editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>();
_textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>();
_textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>();
_metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>();
}
public bool TryNavigateToSymbol(ISymbol symbol, Project project, bool usePreviewTab = false)
{
if (project == null || symbol == null)
{
return false;
}
symbol = symbol.OriginalDefinition;
// Prefer visible source locations if possible.
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
var sourceLocation = visibleSourceLocations.Any() ? visibleSourceLocations.First() : sourceLocations.FirstOrDefault();
if (sourceLocation != null)
{
var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
if (targetDocument != null)
{
var editorWorkspace = targetDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, usePreviewTab);
}
}
// We don't have a source document, so show the Metadata as Source view in a preview tab.
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
return false;
}
// Generate new source or retrieve existing source for the symbol in question
var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol).WaitAndGetResult(CancellationToken.None);
var vsRunningDocumentTable4 = GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>();
var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid((string)result.FilePath);
var openDocumentService = GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>();
IVsUIHierarchy hierarchy;
uint itemId;
IOleServiceProvider localServiceProvider;
IVsWindowFrame windowFrame;
openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame);
var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);
var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
var textBuffer = _editorAdaptersFactory.GetDataBuffer((IVsTextBuffer)vsTextBuffer);
if (!fileAlreadyOpen)
{
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
}
windowFrame.Show();
var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
if (openedDocument != null)
{
var editorWorkspace = openedDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, openedDocument.Id, result.IdentifierLocation.SourceSpan, usePreviewTab: true);
}
return true;
}
public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution)
{
return TryNotifyForSpecificSymbol(symbol, solution);
}
private bool TryNotifyForSpecificSymbol(ISymbol symbol, Solution solution)
{
AssertIsForeground();
IVsHierarchy hierarchy;
IVsSymbolicNavigationNotify navigationNotify;
string rqname;
uint itemID;
if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname))
{
return false;
}
int navigationHandled;
int returnCode = navigationNotify.OnBeforeNavigateToSymbol(
hierarchy,
itemID,
rqname,
out navigationHandled);
if (returnCode == VSConstants.S_OK && navigationHandled == 1)
{
return true;
}
return false;
}
public bool WouldNavigateToSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset)
{
if (WouldNotifyToSpecificSymbol(symbol, solution, out filePath, out lineNumber, out charOffset))
{
return true;
}
// If the symbol being considered is a constructor and no third parties choose to
// navigate to the constructor, then try the constructor's containing type.
if (symbol.IsConstructor() && WouldNotifyToSpecificSymbol(symbol.ContainingType, solution, out filePath, out lineNumber, out charOffset))
{
return true;
}
filePath = null;
lineNumber = 0;
charOffset = 0;
return false;
}
public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset)
{
AssertIsForeground();
filePath = null;
lineNumber = 0;
charOffset = 0;
IVsHierarchy hierarchy;
IVsSymbolicNavigationNotify navigationNotify;
string rqname;
uint itemID;
if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname))
{
return false;
}
IVsHierarchy navigateToHierarchy;
uint navigateToItem;
int wouldNavigate;
var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1];
int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol(
hierarchy,
itemID,
rqname,
out navigateToHierarchy,
out navigateToItem,
navigateToTextSpan,
out wouldNavigate);
if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1)
{
navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath);
lineNumber = navigateToTextSpan[0].iStartLine;
charOffset = navigateToTextSpan[0].iStartIndex;
return true;
}
return false;
}
private bool TryGetNavigationAPIRequiredArguments(
ISymbol symbol,
Solution solution,
out IVsHierarchy hierarchy,
out uint itemID,
out IVsSymbolicNavigationNotify navigationNotify,
out string rqname)
{
AssertIsForeground();
hierarchy = null;
navigationNotify = null;
rqname = null;
itemID = (uint)VSConstants.VSITEMID.Nil;
if (!symbol.Locations.Any())
{
return false;
}
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
if (!sourceLocations.Any())
{
return false;
}
var documents = sourceLocations.Select(loc => solution.GetDocument(loc.SourceTree)).WhereNotNull();
if (!documents.Any())
{
return false;
}
// We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from
// documents we consider to be "generated" to give external language services the best
// chance of participating.
var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
var generatedDocuments = documents.Where(d => generatedCodeRecognitionService.IsGeneratedCode(d));
var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First();
if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID))
{
return false;
}
navigationNotify = hierarchy as IVsSymbolicNavigationNotify;
if (navigationNotify == null)
{
return false;
}
rqname = LanguageServices.RQName.From(symbol);
return rqname != null;
}
private bool TryGetVsHierarchyAndItemId(Document document, out IVsHierarchy hierarchy, out uint itemID)
{
AssertIsForeground();
var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace != null)
{
var hostProject = visualStudioWorkspace.GetHostProject(document.Project.Id);
hierarchy = hostProject.Hierarchy;
itemID = hostProject.GetDocumentOrAdditionalDocument(document.Id).GetItemId();
return true;
}
hierarchy = null;
itemID = (uint)VSConstants.VSITEMID.Nil;
return false;
}
private I GetService<S, I>()
{
var service = (I)_serviceProvider.GetService(typeof(S));
Debug.Assert(service != null);
return service;
}
private IVsRunningDocumentTable GetRunningDocumentTable()
{
var runningDocumentTable = GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>();
Debug.Assert(runningDocumentTable != null);
return runningDocumentTable;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using Franson.BlueTools;
using System.IO;
using System.Text;
using Franson.BlueTools.SDP;
namespace FindAndConnect
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.Button discoverDevices;
private System.Windows.Forms.ListBox deviceList;
private System.Windows.Forms.Label networkLabel;
private System.Windows.Forms.ListBox serviceList;
private System.Windows.Forms.TextBox serviceOutput;
private System.Windows.Forms.Button closeConnection;
private System.Windows.Forms.Label deviceLabel;
private System.Windows.Forms.Label lStatus;
private System.Windows.Forms.Label lStackID;
private Manager manager = null;
private Network m_network = null;
private RemoteService currentService = null;
private Stream currentStream = null;
private System.Windows.Forms.Button bBond;
private System.Windows.Forms.TextBox txtPIN;
private byte[] m_buffer = new byte[25]; // Buffer to read data into
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(MainForm_Closing);
try
{
manager = Manager.GetManager();
switch(Manager.StackID)
{
case StackID.STACK_MICROSOFT:
lStackID.Text = "Microsoft Bluetooth Stack";
break;
case StackID.STACK_WIDCOMM:
lStackID.Text = "WidComm Bluetooth Stack";
break;
}
// You can get a valid evaluation key for BlueTools at
// http://franson.com/bluetools/
// That key will be valid for 14 days. Just cut and paste that key into the statement below.
// To get a key that do not expire you need to purchase a license
Franson.BlueTools.License license = new Franson.BlueTools.License();
license.LicenseKey = "WoK6IL43AA7CJOMQTWbZNjvRCRhtPYEXWrSE";
// Call events in GUI thread
manager.Parent = this;
// Call events in new thread (multi-threading)
// manager.Parent = null
// Get first netowrk (BlueTools 1.0 only supports one network == one dongle)
m_network = manager.Networks[0];
// Add events for device discovery
m_network.DeviceDiscovered += new BlueToolsEventHandler(network_DeviceDiscovered);
m_network.DeviceDiscoveryStarted += new BlueToolsEventHandler(network_DeviceDiscoveryStarted);
m_network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(network_DeviceDiscoveryCompleted);
m_network.DeviceLost += new BlueToolsEventHandler(m_network_DeviceLost);
// Stack version
Version versionStack = m_network.StackVersion;
lStackID.Text += " " + versionStack.ToString();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
discoverDevices.Enabled = false;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
try
{
//m_network.Dispose();
// Manager must be disposed!
Manager.GetManager().Dispose();
}
catch (Exception)
{
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainMenu = new System.Windows.Forms.MainMenu();
this.discoverDevices = new System.Windows.Forms.Button();
this.deviceList = new System.Windows.Forms.ListBox();
this.networkLabel = new System.Windows.Forms.Label();
this.serviceList = new System.Windows.Forms.ListBox();
this.serviceOutput = new System.Windows.Forms.TextBox();
this.closeConnection = new System.Windows.Forms.Button();
this.deviceLabel = new System.Windows.Forms.Label();
this.lStatus = new System.Windows.Forms.Label();
this.lStackID = new System.Windows.Forms.Label();
this.bBond = new System.Windows.Forms.Button();
this.txtPIN = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// discoverDevices
//
this.discoverDevices.Location = new System.Drawing.Point(8, 192);
this.discoverDevices.Name = "discoverDevices";
this.discoverDevices.Size = new System.Drawing.Size(120, 23);
this.discoverDevices.TabIndex = 6;
this.discoverDevices.Text = "Discover";
this.discoverDevices.Click += new System.EventHandler(this.discoverDevices_Click);
//
// deviceList
//
this.deviceList.Location = new System.Drawing.Point(8, 32);
this.deviceList.Name = "deviceList";
this.deviceList.Size = new System.Drawing.Size(120, 147);
this.deviceList.TabIndex = 5;
this.deviceList.SelectedIndexChanged += new System.EventHandler(this.deviceList_SelectedIndexChanged);
//
// networkLabel
//
this.networkLabel.Location = new System.Drawing.Point(8, 16);
this.networkLabel.Name = "networkLabel";
this.networkLabel.Size = new System.Drawing.Size(100, 16);
this.networkLabel.TabIndex = 4;
this.networkLabel.Text = "Network";
//
// serviceList
//
this.serviceList.Location = new System.Drawing.Point(136, 32);
this.serviceList.Name = "serviceList";
this.serviceList.Size = new System.Drawing.Size(120, 147);
this.serviceList.TabIndex = 3;
this.serviceList.SelectedIndexChanged += new System.EventHandler(this.serviceList_SelectedIndexChanged);
//
// serviceOutput
//
this.serviceOutput.Location = new System.Drawing.Point(8, 288);
this.serviceOutput.Multiline = true;
this.serviceOutput.Name = "serviceOutput";
this.serviceOutput.ReadOnly = true;
this.serviceOutput.Size = new System.Drawing.Size(248, 40);
this.serviceOutput.TabIndex = 2;
this.serviceOutput.Text = "";
//
// closeConnection
//
this.closeConnection.Enabled = false;
this.closeConnection.Location = new System.Drawing.Point(136, 192);
this.closeConnection.Name = "closeConnection";
this.closeConnection.Size = new System.Drawing.Size(120, 23);
this.closeConnection.TabIndex = 1;
this.closeConnection.Text = "Close";
this.closeConnection.Click += new System.EventHandler(this.closeConnection_Click);
//
// deviceLabel
//
this.deviceLabel.Location = new System.Drawing.Point(136, 16);
this.deviceLabel.Name = "deviceLabel";
this.deviceLabel.Size = new System.Drawing.Size(100, 16);
this.deviceLabel.TabIndex = 0;
this.deviceLabel.Text = "Device";
//
// lStatus
//
this.lStatus.Location = new System.Drawing.Point(8, 336);
this.lStatus.Name = "lStatus";
this.lStatus.Size = new System.Drawing.Size(248, 40);
this.lStatus.TabIndex = 18;
this.lStatus.Text = "Click Discover!";
//
// lStackID
//
this.lStackID.Location = new System.Drawing.Point(8, 376);
this.lStackID.Name = "lStackID";
this.lStackID.Size = new System.Drawing.Size(248, 16);
this.lStackID.TabIndex = 19;
//
// bBond
//
this.bBond.Location = new System.Drawing.Point(8, 248);
this.bBond.Name = "bBond";
this.bBond.Size = new System.Drawing.Size(120, 24);
this.bBond.TabIndex = 20;
this.bBond.Text = "Bond";
this.bBond.Click += new System.EventHandler(this.bBond_Click);
//
// txtPIN
//
this.txtPIN.Location = new System.Drawing.Point(8, 224);
this.txtPIN.Name = "txtPIN";
this.txtPIN.Size = new System.Drawing.Size(120, 20);
this.txtPIN.TabIndex = 21;
this.txtPIN.Text = "";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(272, 397);
this.Controls.Add(this.txtPIN);
this.Controls.Add(this.serviceOutput);
this.Controls.Add(this.bBond);
this.Controls.Add(this.lStackID);
this.Controls.Add(this.lStatus);
this.Controls.Add(this.deviceLabel);
this.Controls.Add(this.closeConnection);
this.Controls.Add(this.serviceList);
this.Controls.Add(this.networkLabel);
this.Controls.Add(this.deviceList);
this.Controls.Add(this.discoverDevices);
this.Menu = this.mainMenu;
this.Name = "MainForm";
this.Text = "Find And Discover";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new MainForm());
}
private void discoverDevices_Click(object sender, System.EventArgs e)
{
try
{
// Start looking for devices on the network
// Use Network.DiscoverDevices() if you don't want to use events.
m_network.DiscoverDevicesAsync();
}
catch (BlueToolsException exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
}
private void network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs)
{
// Search for devices on the network started
serviceList.Items.Clear();
discoverDevices.Enabled = false;
lStatus.Text = "Discovering devices...";
}
private void network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs)
{
// A new device was discovered!
// Note that this event is only called for NEW devices on the network
// Use Network.Devices for a complete list of discovered devices.
RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery;
deviceList.Items.Add(device);
}
private void network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs)
{
// Search for devices on the network ended.
lStatus.Text = "Click on a Device!";
discoverDevices.Enabled = true;
}
private void deviceList_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Get the remote device that is currently selected
RemoteDevice device = (RemoteDevice)deviceList.SelectedItem;
if(device != null)
{
try
{
// Disable the device list so the user doesn't attempt to select a device while
// the service lookup is pending
deviceList.Enabled = false;
// Remove the existing items from the service list
serviceList.Items.Clear();
// Add a DiscoveryListener so we get service discovery events
device.ServiceDiscovered += new BlueToolsEventHandler(device_ServiceDiscovered);
// Add a DiscoveryListener so we get service discovery completion events
device.ServiceDiscoveryCompleted += new BlueToolsEventHandler(device_ServiceDiscoveryCompleted);
device.Error += new BlueToolsEventHandler(device_Error);
// Cancel any ongoing device discovery
m_network.CancelDeviceDiscovery();
// Discover all services offered by the device
// Use e.g. ServiceType.SerialPort to list only serial port services
// Use Device.DiscoverServices() if you don't want to use events.
// device.DiscoverServicesAsync(ServiceType.SerialPort);
device.DiscoverServicesAsync(ServiceType.RFCOMM);
// Add already discovered services to list box (for this device)
serviceList.Items.Clear();
Service[] services = device.Services;
foreach(RemoteService service in services)
{
serviceList.Items.Add(service);
}
lStatus.Text = "Searching for Services...";
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
}
private void device_ServiceDiscovered(object sender, BlueToolsEventArgs eventArgs)
{
// A new serive found for device!
// Note that this event is only called for NEW services found
// Use Device.Services for a complete list of services for device
// Get the service associated with the discovery event
Service service = (Service)((DiscoveryEventArgs)eventArgs).Discovery;
// Add the newly discovered service to the service list
serviceList.Items.Add(service);
}
private void device_ServiceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs)
{
// All services for device discovered"
// Get the remote device that raised the event
RemoteDevice device = (RemoteDevice)sender;
// You find an array of all found services here.
// Or by using Device.Services
// Note that all services are RemoteService
Service[] services = (Service[])((DiscoveryEventArgs)eventArgs).Discovery;
// Remove event handlers
device.ServiceDiscovered -= new BlueToolsEventHandler(device_ServiceDiscovered);
device.ServiceDiscoveryCompleted -= new BlueToolsEventHandler(device_ServiceDiscoveryCompleted);
// Reenable the device list
deviceList.Enabled = true;
lStatus.Text = "Click on a Service";
}
private void serviceList_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Close any connections that are open
//
if(currentService != null)
{
currentStream.Close();
currentService = null;
currentStream = null;
}
// Attempt to connect to the service
//
// Get service object from list box
currentService = (RemoteService) serviceList.SelectedItem;
try
{
// Connect to service by reading its Stream
currentStream = currentService.Stream;
currentStream.BeginRead(m_buffer, 0, m_buffer.Length, new AsyncCallback(readCallback), currentStream);
closeConnection.Enabled = true;
serviceList.Enabled = false;
lStatus.Text = "Receiving data...";
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
currentService = null;
}
}
private void readCallback(IAsyncResult result)
{
byte[] buffer = null;
// result is always a BlueToolsAsyncResult object
BlueToolsAsyncResult blueAsyncResult = (BlueToolsAsyncResult) result;
// We passed on buffer as custom object, you can pass on any object here. We passed the stream object
ServiceStream stream = (ServiceStream) blueAsyncResult.AsyncState;
// The buffer used for reading can be found in the result object.
buffer = blueAsyncResult.Buffer;
try
{
// EndRead() must always be called!
// If stream has been closed due to an error, we'll have an excpetion here
int len = stream.EndRead(result);
System.Text.ASCIIEncoding enc = new ASCIIEncoding();
string str = enc.GetString(buffer, 0, len);
serviceOutput.Text = str;
// Start new async read
stream.BeginRead(m_buffer, 0, m_buffer.Length, new AsyncCallback(readCallback), stream);
}
catch(ObjectDisposedException ex)
{
// Thrown if stream has been closed.
closeConnection.Enabled = false;
serviceList.Enabled = true;
lStatus.Text = ex.Message;
}
}
private void closeConnection_Click(object sender, System.EventArgs e)
{
if(currentService != null)
{
currentStream.Close();
currentService = null;
currentStream = null;
}
closeConnection.Enabled = false;
serviceList.Enabled = true;
lStatus.Text = "OK";
}
private void device_Error(object sender, BlueToolsEventArgs eventArgs)
{
Franson.BlueTools.ErrorEventArgs errorEventArgs = (Franson.BlueTools.ErrorEventArgs)eventArgs;
MessageBox.Show(errorEventArgs.ErrorCode + ": " + errorEventArgs.Message);
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Dispose();
}
private void bBond_Click(object sender, System.EventArgs e)
{
RemoteDevice device = (RemoteDevice) deviceList.SelectedItem;
if(device == null)
{
MessageBox.Show("Select a device first!");
}
else
{
try
{
// Use RemoteDevice.BondAsync() for async version
device.Bond(txtPIN.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void m_network_DeviceLost(object sender, BlueToolsEventArgs eventArgs)
{
RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery;
deviceList.Items.Remove(device);
}
}
}
| |
// 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 Xunit;
using System.Threading.Tasks;
using TelemData = System.Collections.Generic.KeyValuePair<string, object>;
namespace System.Diagnostics.Tracing.Telemetry.Tests
{
/// <summary>
/// Tests for TelemetrySource and TelemetryListener
/// </summary>
public class TelemetryTest
{
/// <summary>
/// Trivial example of passing an integer
/// </summary>
[Fact]
public void IntPayload()
{
var result = new List<KeyValuePair<string, object>>();
var observer = new ObserverToList<TelemData>(result);
using (TelemetryListener.DefaultListener.Subscribe(new ObserverToList<TelemData>(result)))
{
TelemetrySource.DefaultSource.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
Assert.Equal("IntPayload", result[0].Key);
Assert.Equal(5, result[0].Value);
} // unsubscribe
// Make sure that after unsubscribing, we don't get more events.
TelemetrySource.DefaultSource.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
}
/// <summary>
/// slightly less trivial of passing a structure with a couple of fields
/// </summary>
[Fact]
public void StructPayload()
{
var result = new List<KeyValuePair<string, object>>();
using (TelemetryListener.DefaultListener.Subscribe(new ObserverToList<TelemData>(result)))
{
TelemetrySource.DefaultSource.WriteTelemetry("StructPayload", new Payload() { Name = "Hi", Id = 67 });
Assert.Equal(1, result.Count);
Assert.Equal("StructPayload", result[0].Key);
var payload = (Payload)result[0].Value;
Assert.Equal(67, payload.Id);
Assert.Equal("Hi", payload.Name);
}
TelemetrySource.DefaultSource.WriteTelemetry("StructPayload", new Payload() { Name = "Hi", Id = 67 });
Assert.Equal(1, result.Count);
}
/// <summary>
/// Tests the IObserver OnCompleted callback.
/// </summary>
[Fact]
public void Completed()
{
var result = new List<KeyValuePair<string, object>>();
var observer = new ObserverToList<TelemData>(result);
var listener = new TelemetryListener("MyListener");
var subscription = listener.Subscribe(observer);
listener.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
Assert.Equal("IntPayload", result[0].Key);
Assert.Equal(5, result[0].Value);
Assert.False(observer.Completed);
// The listener dies
listener.Dispose();
Assert.True(observer.Completed);
// confirm that we can unsubscribe without crashing
subscription.Dispose();
// If we resubscribe after dispose, but it does not do anything.
subscription = listener.Subscribe(observer);
listener.WriteTelemetry("IntPayload", 5);
Assert.Equal(1, result.Count);
}
/// <summary>
/// Simple tests for the IsEnabled method.
/// </summary>
[Fact]
public void BasicIsEnabled()
{
var result = new List<KeyValuePair<string, object>>();
bool seenUninteresting = false;
bool seenStructPayload = false;
Predicate<string> predicate = delegate (string telemetryName)
{
if (telemetryName == "Uninteresting")
seenUninteresting = true;
if (telemetryName == "StructPayload")
seenStructPayload = true;
return telemetryName == "StructPayload";
};
using (TelemetryListener.DefaultListener.Subscribe(new ObserverToList<TelemData>(result), predicate))
{
Assert.False(TelemetrySource.DefaultSource.IsEnabled("Uninteresting"));
Assert.True(TelemetrySource.DefaultSource.IsEnabled("StructPayload"));
Assert.True(seenUninteresting);
Assert.True(seenStructPayload);
}
}
/// <summary>
/// Test if it works when you have two subscribers active simultaneously
/// </summary>
[Fact]
public void MultiSubscriber()
{
var subscriber1Result = new List<KeyValuePair<string, object>>();
Predicate<string> subscriber1Predicate = telemetryName => (telemetryName == "DataForSubscriber1");
var subscriber1Oberserver = new ObserverToList<TelemData>(subscriber1Result);
var subscriber2Result = new List<KeyValuePair<string, object>>();
Predicate<string> subscriber2Predicate = telemetryName => (telemetryName == "DataForSubscriber2");
var subscriber2Oberserver = new ObserverToList<TelemData>(subscriber2Result);
// Get two subscribers going.
using (var subscription1 = TelemetryListener.DefaultListener.Subscribe(subscriber1Oberserver, subscriber1Predicate))
{
using (var subscription2 = TelemetryListener.DefaultListener.Subscribe(subscriber2Oberserver, subscriber2Predicate))
{
// Things that neither subscribe to get filtered out.
if (TelemetryListener.DefaultListener.IsEnabled("DataToFilterOut"))
TelemetryListener.DefaultListener.WriteTelemetry("DataToFilterOut", -1);
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// If a Source does not use the IsEnabled, then every subscriber gets it.
subscriber1Result.Clear();
subscriber2Result.Clear();
TelemetryListener.DefaultListener.WriteTelemetry("UnfilteredData", 3);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("UnfilteredData", subscriber1Result[0].Key);
Assert.Equal(3, (int)subscriber1Result[0].Value);
Assert.Equal(1, subscriber2Result.Count);
Assert.Equal("UnfilteredData", subscriber2Result[0].Key);
Assert.Equal(3, (int)subscriber2Result[0].Value);
/****************************************************/
// Filters not filter out everything, they are just a performance optimization.
// Here you actually get more than you want even though you use a filter
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber1"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber1", 1);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key);
Assert.Equal(1, (int)subscriber1Result[0].Value);
// Subscriber 2 happens to get it
Assert.Equal(1, subscriber2Result.Count);
Assert.Equal("DataForSubscriber1", subscriber2Result[0].Key);
Assert.Equal(1, (int)subscriber2Result[0].Value);
/****************************************************/
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber2"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber2", 2);
// Subscriber 1 happens to get it
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("DataForSubscriber2", subscriber1Result[0].Key);
Assert.Equal(2, (int)subscriber1Result[0].Value);
Assert.Equal(1, subscriber2Result.Count);
Assert.Equal("DataForSubscriber2", subscriber2Result[0].Key);
Assert.Equal(2, (int)subscriber2Result[0].Value);
} // subscriber2 drops out
/*********************************************************************/
/* Only Subscriber 1 is left */
/*********************************************************************/
// Things that neither subscribe to get filtered out.
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataToFilterOut"))
TelemetryListener.DefaultListener.WriteTelemetry("DataToFilterOut", -1);
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// If a Source does not use the IsEnabled, then every subscriber gets it.
subscriber1Result.Clear();
TelemetryListener.DefaultListener.WriteTelemetry("UnfilteredData", 3);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("UnfilteredData", subscriber1Result[0].Key);
Assert.Equal(3, (int)subscriber1Result[0].Value);
// Subscriber 2 has dropped out.
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// Filters not filter out everything, they are just a performance optimization.
// Here you actually get more than you want even though you use a filter
subscriber1Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber1"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber1", 1);
Assert.Equal(1, subscriber1Result.Count);
Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key);
Assert.Equal(1, (int)subscriber1Result[0].Value);
// Subscriber 2 has dropped out.
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
subscriber1Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber2"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber2", 2);
// Subscriber 1 filters
Assert.Equal(0, subscriber1Result.Count);
// Subscriber 2 has dropped out
Assert.Equal(0, subscriber2Result.Count);
} // subscriber1 drops out
/*********************************************************************/
/* No Subscribers are left */
/*********************************************************************/
// Things that neither subscribe to get filtered out.
subscriber1Result.Clear();
subscriber2Result.Clear();
if (TelemetryListener.DefaultListener.IsEnabled("DataToFilterOut"))
TelemetryListener.DefaultListener.WriteTelemetry("DataToFilterOut", -1);
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// If a Source does not use the IsEnabled, then every subscriber gets it.
TelemetryListener.DefaultListener.WriteTelemetry("UnfilteredData", 3);
// No one subscribing
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
// Filters not filter out everything, they are just a performance optimization.
// Here you actually get more than you want even though you use a filter
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber1"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber1", 1);
// No one subscribing
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
/****************************************************/
if (TelemetryListener.DefaultListener.IsEnabled("DataForSubscriber2"))
TelemetryListener.DefaultListener.WriteTelemetry("DataForSubscriber2", 2);
// No one subscribing
Assert.Equal(0, subscriber1Result.Count);
Assert.Equal(0, subscriber2Result.Count);
}
/// <summary>
/// Stresses the Subscription routine by having many threads subscribe and
/// unsubscribe concurrently
/// </summary>
[Fact]
public void MultiSubscriberStress()
{
var random = new Random();
// Beat on the default listener by subscribing and unsubscribing on many threads simultaneously.
var factory = new TaskFactory();
// To the whole stress test 10 times. This keeps the task array size needed down while still
// having lots of concurrency.
for (int j = 0; j < 20; j++)
{
// Spawn off lots of concurrent activity
var tasks = new Task[1000];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = factory.StartNew(delegate (object taskData)
{
int taskNum = (int)taskData;
var taskName = "Task" + taskNum;
var result = new List<KeyValuePair<string, object>>();
Predicate<string> predicate = (name) => name == taskName;
Predicate<KeyValuePair<string, object>> filter = (keyValue) => keyValue.Key == taskName;
// set up the observer to only see events set with the task name as the telemetry nname.
var observer = new ObserverToList<TelemData>(result, filter, taskName);
using (TelemetryListener.DefaultListener.Subscribe(observer, predicate))
{
TelemetrySource.DefaultSource.WriteTelemetry(taskName, taskNum);
Assert.Equal(1, result.Count);
Assert.Equal(taskName, result[0].Key);
Assert.Equal(taskNum, result[0].Value);
// Spin a bit randomly. This mixes of the lifetimes of the subscriptions and makes it
// more stressful
var cnt = random.Next(10, 100) * 1000;
while (0 < --cnt)
GC.KeepAlive("");
} // Unsubscribe
// Send the telemetry again, to see if it now does NOT come through (count remains unchanged).
TelemetrySource.DefaultSource.WriteTelemetry(taskName, -1);
Assert.Equal(1, result.Count);
}, i);
}
Task.WaitAll(tasks);
}
}
/// <summary>
/// Tests if as we create new TelemetryListerns, we get callbacks for them
/// </summary>
[Fact]
public void AllListenersAddRemove()
{
// This callback will return the listener that happens on the callback
TelemetryListener returnedListener = null;
Action<TelemetryListener> onNewListener = delegate (TelemetryListener listener)
{
Assert.Null(returnedListener);
Assert.NotNull(listener);
returnedListener = listener;
};
// Subscribe, which delivers catch-up event for the Default listener
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.Equal(TelemetryListener.DefaultListener, returnedListener);
returnedListener = null;
} // Now we unsubscribe
// Create an dispose a listener, but we won't get a callback for it.
using (new TelemetryListener("TestListen"))
{ }
Assert.Null(returnedListener); // No callback was made
// Resubscribe
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.Equal(TelemetryListener.DefaultListener, returnedListener);
returnedListener = null;
// add two new subscribers
using (var listener1 = new TelemetryListener("TestListen1"))
{
Assert.Equal(listener1.Name, "TestListen1");
Assert.Equal(listener1, returnedListener);
returnedListener = null;
using (var listener2 = new TelemetryListener("TestListen2"))
{
Assert.Equal(listener2.Name, "TestListen2");
Assert.Equal(listener2, returnedListener);
returnedListener = null;
} // Dispose of listener2
} // Dispose of listener1
} // Unsubscribe
// Check that we are back to just the DefaultListener.
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.Equal(TelemetryListener.DefaultListener, returnedListener);
returnedListener = null;
} // cleanup
}
/// <summary>
/// Tests that the 'catchupList' of active listeners is accurate even as we
/// add and remove TelemetryListeners randomly.
/// </summary>
[Fact]
public void AllListenersCheckCatchupList()
{
var expected = new List<TelemetryListener>();
var list = GetActiveNonDefaultListeners();
Assert.Equal(list, expected);
for (int i = 0; i < 50; i++)
{
expected.Insert(0, (new TelemetryListener("TestListener" + i)));
list = GetActiveNonDefaultListeners();
Assert.Equal(list, expected);
}
// Remove the element randomly.
var random = new Random(0);
while (0 < expected.Count)
{
var toRemoveIdx = random.Next(0, expected.Count - 1); // Always leave the Default listener.
var toRemoveListener = expected[toRemoveIdx];
toRemoveListener.Dispose(); // Kill it (which removes it from the list)
expected.RemoveAt(toRemoveIdx);
list = GetActiveNonDefaultListeners();
Assert.Equal(list.Count, expected.Count);
Assert.Equal(list, expected);
}
}
/// <summary>
/// Stresses the AllListeners by having many threads be added and removed.
/// </summary>
[Fact]
public void AllSubscriberStress()
{
var list = GetActiveNonDefaultListeners();
Assert.Equal(0, list.Count);
var factory = new TaskFactory();
// To the whole stress test 10 times. This keeps the task array size needed down while still
// having lots of concurrency.
for (int k = 0; k < 10; k++)
{
// TODO FIX NOW: Task[1] should be Task[100] but it fails.
var tasks = new Task[1];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = (factory.StartNew(delegate ()
{
// Create a set of TelemetryListeners (which add themselves to the AllListeners list.
var listeners = new List<TelemetryListener>();
for (int j = 0; j < 100; j++)
listeners.Insert(0, (new TelemetryListener("Task " + i + " TestListener" + j)));
// They are all in the list
list = GetActiveNonDefaultListeners();
foreach (var listener in listeners)
Assert.Contains(listener, list);
// Dispose them all, first the even then the odd, just to mix it up and be more stressful.
for (int j = 0; j < listeners.Count; j += 2) // Even
listeners[j].Dispose();
for (int j = 1; j < listeners.Count; j += 2) // odd
listeners[j].Dispose();
// And now they are not in the list.
list = GetActiveNonDefaultListeners();
foreach (var listener in listeners)
Assert.DoesNotContain(listener, list);
}));
}
// Wait for all the tasks to finish.
Task.WaitAll(tasks);
}
// There should be no listeners left.
list = GetActiveNonDefaultListeners();
Assert.Equal(0, list.Count);
}
[Fact]
public void DoubleDisposeOfListener()
{
var listener = new TelemetryListener("MyListener");
int completionCount = 0;
IDisposable subscription = listener.Subscribe(MakeObserver<KeyValuePair<string, object>>(_ => { }, () => completionCount++));
listener.Dispose();
listener.Dispose();
subscription.Dispose();
subscription.Dispose();
Assert.Equal(1, completionCount);
}
[Fact]
public void ListenerToString()
{
string name = Guid.NewGuid().ToString();
using (var listener = new TelemetryListener(name))
{
Assert.Equal(name, listener.ToString());
}
}
[Fact]
public void DisposeAllListenerSubscriptionInSameOrderSubscribed()
{
int count1 = 0, count2 = 0, count3 = 0;
IDisposable sub1 = TelemetryListener.AllListeners.Subscribe(MakeObserver<TelemetryListener>(onCompleted: () => count1++));
IDisposable sub2 = TelemetryListener.AllListeners.Subscribe(MakeObserver<TelemetryListener>(onCompleted: () => count2++));
IDisposable sub3 = TelemetryListener.AllListeners.Subscribe(MakeObserver<TelemetryListener>(onCompleted: () => count3++));
Assert.Equal(0, count1);
Assert.Equal(0, count2);
Assert.Equal(0, count3);
sub1.Dispose();
Assert.Equal(1, count1);
Assert.Equal(0, count2);
Assert.Equal(0, count3);
sub1.Dispose(); // dispose again just to make sure nothing bad happens
sub2.Dispose();
Assert.Equal(1, count1);
Assert.Equal(1, count2);
Assert.Equal(0, count3);
sub2.Dispose();
sub3.Dispose();
Assert.Equal(1, count1);
Assert.Equal(1, count2);
Assert.Equal(1, count3);
sub3.Dispose();
}
#region Helpers
/// <summary>
/// Returns the list of active telemetry listeners.
/// </summary>
/// <returns></returns>
private static List<TelemetryListener> GetActiveNonDefaultListeners()
{
var ret = new List<TelemetryListener>();
var seenDefault = false;
Action<TelemetryListener> onNewListener = delegate (TelemetryListener listener)
{
if (listener == TelemetryListener.DefaultListener)
{
Assert.False(seenDefault);
seenDefault = true;
}
else
ret.Add(listener);
};
// Subscribe, which gives you the list
using (var allListenerSubscription = TelemetryListener.AllListeners.Subscribe(MakeObserver(onNewListener)))
{
Assert.True(seenDefault);
} // Unsubscribe to remove side effects.
return ret;
}
/// <summary>
/// Used to make an observer out of a action delegate.
/// </summary>
private static IObserver<T> MakeObserver<T>(
Action<T> onNext = null, Action onCompleted = null)
{
return new Observer<T>(onNext, onCompleted);
}
/// <summary>
/// Used in the implementation of MakeObserver.
/// </summary>
/// <typeparam name="T"></typeparam>
private class Observer<T> : IObserver<T>
{
public Observer(Action<T> onNext, Action onCompleted)
{
_onNext = onNext ?? new Action<T>(_ => { });
_onCompleted = onCompleted ?? new Action(() => { });
}
public void OnCompleted() { _onCompleted(); }
public void OnError(Exception error) { }
public void OnNext(T value) { _onNext(value); }
private Action<T> _onNext;
private Action _onCompleted;
}
#endregion
}
// Takes an IObserver and returns a List<T> that are the elements observed.
// Will assert on error and 'Completed' is set if the 'OnCompleted' callback
// is issued.
internal class ObserverToList<T> : IObserver<T>
{
public ObserverToList(List<T> output, Predicate<T> filter = null, string name = null)
{
_output = output;
_output.Clear();
_filter = filter;
_name = name;
}
public bool Completed { get; private set; }
#region private
public void OnCompleted()
{
Completed = true;
}
public void OnError(Exception error)
{
Assert.True(false, "Error happened on IObserver");
}
public void OnNext(T value)
{
Assert.False(Completed);
if (_filter == null || _filter(value))
_output.Add(value);
}
private List<T> _output;
private Predicate<T> _filter;
private string _name; // for debugging
#endregion
}
/// <summary>
/// Trivial class used for payloads. (Usually anonymous types are used.
/// </summary>
internal class Payload
{
public string Name { get; set; }
public int Id { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
#if NETCOREAPP3_1 || NETSTANDARD2_1
using MemoryText = System.ReadOnlyMemory<char>;
using SpanText = System.ReadOnlySpan<char>;
#else
using MemoryText = System.String;
using SpanText = System.String;
#endif
namespace Csv
{
/// <summary>
/// Helper class to read csv (comma separated values) data.
/// </summary>
public static partial class CsvReader
{
/// <summary>
/// Reads the lines from the reader.
/// </summary>
/// <param name="reader">The text reader to read the data from.</param>
/// <param name="options">The optional options to use when reading.</param>
public static IEnumerable<ICsvLine> Read(TextReader reader, CsvOptions? options = null)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return ReadImpl(reader, options);
}
/// <summary>
/// Reads the lines from the stream.
/// </summary>
/// <param name="stream">The stream to read the data from.</param>
/// <param name="options">The optional options to use when reading.</param>
public static IEnumerable<ICsvLine> ReadFromStream(Stream stream, CsvOptions? options = null)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
return ReadFromStreamImpl(stream, options);
}
/// <summary>
/// Reads the lines from the csv string.
/// </summary>
/// <param name="csv">The csv string to read the data from.</param>
/// <param name="options">The optional options to use when reading.</param>
public static IEnumerable<ICsvLine> ReadFromText(string csv, CsvOptions? options = null)
{
if (csv == null)
throw new ArgumentNullException(nameof(csv));
return ReadFromTextImpl(csv, options);
}
private static IEnumerable<ICsvLine> ReadFromStreamImpl(Stream stream, CsvOptions? options)
{
using (var reader = new StreamReader(stream))
{
foreach (var line in ReadImpl(reader, options))
yield return line;
}
}
private static IEnumerable<ICsvLine> ReadFromTextImpl(string csv, CsvOptions? options)
{
using (var reader = new StringReader(csv))
{
foreach (var line in ReadImpl(reader, options))
yield return line;
}
}
private static IEnumerable<ICsvLine> ReadImpl(TextReader reader, CsvOptions? options)
{
// NOTE: Logic is copied in ReadImpl/ReadImplAsync/ReadFromMemory
options ??= new CsvOptions();
string? line;
var index = 0;
MemoryText[]? headers = null;
Dictionary<string, int>? headerLookup = null;
while ((line = reader.ReadLine()) != null)
{
index++;
var lineAsMemory = line.AsMemory();
if (index <= options.RowsToSkip || options.SkipRow?.Invoke(lineAsMemory, index) == true)
continue;
if (headers == null || headerLookup == null)
{
InitializeOptions(lineAsMemory.AsSpan(), options);
var skipInitialLine = options.HeaderMode == HeaderMode.HeaderPresent;
headers = skipInitialLine ? GetHeaders(lineAsMemory, options) : CreateDefaultHeaders(lineAsMemory, options);
try
{
headerLookup = headers
.Select((h, idx) => Tuple.Create(h, idx))
.ToDictionary(h => h.Item1.AsString(), h => h.Item2, options.Comparer);
}
catch (ArgumentException)
{
throw new InvalidOperationException("Duplicate headers detected in HeaderPresent mode. If you don't have a header you can set the HeaderMode to HeaderAbsent.");
}
var aliases = options.Aliases;
if (aliases != null)
{
// NOTE: For each group we need at most 1 match (i.e. SingleOrDefault)
foreach (var aliasGroup in aliases)
{
var groupIndex = -1;
foreach (var alias in aliasGroup)
{
if (headerLookup.TryGetValue(alias, out var aliasIndex))
{
if (groupIndex != -1)
throw new InvalidOperationException("Found multiple matches within alias group: " + string.Join(";", aliasGroup));
groupIndex = aliasIndex;
}
}
if (groupIndex != -1)
{
foreach (var alias in aliasGroup)
headerLookup[alias] = groupIndex;
}
}
}
if (skipInitialLine)
continue;
}
var record = new ReadLine(headers, headerLookup, index, line, options);
if (options.AllowNewLineInEnclosedFieldValues)
{
// TODO: Move to CsvLineSplitter?
// TODO: Shouldn't we only check the last part?
while (record.RawSplitLine.Any(f => CsvLineSplitter.IsUnterminatedQuotedValue(f.AsSpan(), options)))
{
var nextLine = reader.ReadLine();
if (nextLine == null)
break;
line += options.NewLine + nextLine;
record = new ReadLine(headers, headerLookup, index, line, options);
}
}
yield return record;
}
}
#if NETCOREAPP3_1 || NETSTANDARD2_1
/// <summary>
/// Reads the lines from the reader.
/// </summary>
/// <param name="reader">The text reader to read the data from.</param>
/// <param name="options">The optional options to use when reading.</param>
public static IAsyncEnumerable<ICsvLine> ReadAsync(TextReader reader, CsvOptions? options = null)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return ReadImplAsync(reader, options);
}
/// <summary>
/// Reads the lines from the stream.
/// </summary>
/// <param name="stream">The stream to read the data from.</param>
/// <param name="options">The optional options to use when reading.</param>
public static IAsyncEnumerable<ICsvLine> ReadFromStreamAsync(Stream stream, CsvOptions? options = null)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
static async IAsyncEnumerable<ICsvLine> Impl(Stream stream, CsvOptions? options)
{
using var reader = new StreamReader(stream);
await foreach (var line in ReadImplAsync(reader, options))
yield return line;
}
return Impl(stream, options);
}
/// <summary>
/// Reads the lines from the csv string.
/// </summary>
/// <param name="csv">The csv string to read the data from.</param>
/// <param name="options">The optional options to use when reading.</param>
public static IAsyncEnumerable<ICsvLine> ReadFromTextAsync(string csv, CsvOptions? options = null)
{
if (csv == null)
throw new ArgumentNullException(nameof(csv));
static async IAsyncEnumerable<ICsvLine> Impl(string csv, CsvOptions? options)
{
using var reader = new StringReader(csv);
await foreach (var line in ReadImplAsync(reader, options))
yield return line;
}
return Impl(csv, options);
}
private static async IAsyncEnumerable<ICsvLine> ReadImplAsync(TextReader reader, CsvOptions? options)
{
// NOTE: Logic is copied in ReadImpl/ReadImplAsync/ReadFromMemory
options ??= new CsvOptions();
string? line;
var index = 0;
MemoryText[]? headers = null;
Dictionary<string, int>? headerLookup = null;
while ((line = await reader.ReadLineAsync()) != null)
{
index++;
var lineAsMemory = line.AsMemory();
if (index <= options.RowsToSkip || options.SkipRow?.Invoke(lineAsMemory, index) == true)
continue;
if (headers == null || headerLookup == null)
{
InitializeOptions(lineAsMemory.Span, options);
var skipInitialLine = options.HeaderMode == HeaderMode.HeaderPresent;
headers = skipInitialLine ? GetHeaders(lineAsMemory, options) : CreateDefaultHeaders(lineAsMemory, options);
try
{
headerLookup = headers
.Select((h, idx) => (h, idx))
.ToDictionary(h => h.Item1.AsString(), h => h.Item2, options.Comparer);
}
catch (ArgumentException)
{
throw new InvalidOperationException("Duplicate headers detected in HeaderPresent mode. If you don't have a header you can set the HeaderMode to HeaderAbsent.");
}
var aliases = options.Aliases;
if (aliases != null)
{
// NOTE: For each group we need at most 1 match (i.e. SingleOrDefault)
foreach (var aliasGroup in aliases)
{
var groupIndex = -1;
foreach (var alias in aliasGroup)
{
if (headerLookup.TryGetValue(alias, out var aliasIndex))
{
if (groupIndex != -1)
throw new InvalidOperationException("Found multiple matches within alias group: " + string.Join(";", aliasGroup));
groupIndex = aliasIndex;
}
}
if (groupIndex != -1)
{
foreach (var alias in aliasGroup)
headerLookup[alias] = groupIndex;
}
}
}
if (skipInitialLine)
continue;
}
var record = new ReadLine(headers, headerLookup, index, line, options);
if (options.AllowNewLineInEnclosedFieldValues)
{
while (record.RawSplitLine.Any(f => CsvLineSplitter.IsUnterminatedQuotedValue(f.AsSpan(), options)))
{
var nextLine = await reader.ReadLineAsync();
if (nextLine == null)
break;
line += options.NewLine + nextLine;
record = new ReadLine(headers, headerLookup, index, line, options);
}
}
yield return record;
}
}
#endif
private static char AutoDetectSeparator(SpanText sampleLine)
{
// NOTE: Try simple 'detection' of possible separator
// ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
foreach (var ch in sampleLine)
{
if (ch == ';' || ch == '\t')
return ch;
}
return ',';
}
private static MemoryText[] CreateDefaultHeaders(MemoryText line, CsvOptions options)
{
var columnCount = options.Splitter.Split(line, options).Count;
var headers = new MemoryText[columnCount];
for (var i = 0; i < headers.Length; i++)
headers[i] = $"Column{i + 1}".AsMemory();
return headers;
}
private static MemoryText[] GetHeaders(MemoryText line, CsvOptions options)
{
return Trim(SplitLine(line, options), options);
}
private static void InitializeOptions(SpanText line, CsvOptions options)
{
if (options.Separator == '\0')
options.Separator = AutoDetectSeparator(line);
options.Splitter = CsvLineSplitter.Get(options);
}
private static IList<MemoryText> SplitLine(MemoryText line, CsvOptions options)
{
return options.Splitter.Split(line, options);
}
private static MemoryText[] Trim(IList<MemoryText> line, CsvOptions options)
{
var trimmed = new MemoryText[line.Count]; // TODO: Mutate existing array?
for (var i = 0; i < line.Count; i++)
{
var str = line[i];
if (options.TrimData)
str = str.Trim();
if (str.Length > 1)
{
#if NETCOREAPP3_1 || NETSTANDARD2_1
if (str.Span[0] == '"' && str.Span[^1] == '"')
{
str = str[1..^1].Unescape('"', '"');
if (options.AllowBackSlashToEscapeQuote)
str = str.Unescape('\\', '"');
}
else if (options.AllowSingleQuoteToEncloseFieldValues && str.Span[0] == '\'' && str.Span[^1] == '\'')
str = str[1..^1];
#else
if (str[0] == '"' && str[str.Length - 1] == '"')
{
str = str.Substring(1, str.Length - 2).Replace("\"\"", "\"");
if (options.AllowBackSlashToEscapeQuote)
str = str.Replace("\\\"", "\"");
}
else if (options.AllowSingleQuoteToEncloseFieldValues && str[0] == '\'' && str[str.Length - 1] == '\'')
str = str.Substring(1, str.Length - 2);
#endif
}
trimmed[i] = str;
}
return trimmed;
}
private sealed class ReadLine : ICsvLine
{
private readonly Dictionary<string, int> headerLookup;
private readonly CsvOptions options;
private readonly MemoryText[] headers;
private IList<MemoryText>? rawSplitLine;
private MemoryText[]? parsedLine;
public ReadLine(MemoryText[] headers, Dictionary<string, int> headerLookup, int index, string raw, CsvOptions options)
{
this.headerLookup = headerLookup;
this.options = options;
this.headers = headers;
Raw = raw;
Index = index;
}
public string[] Headers => headers.Select(it => it.AsString()).ToArray();
public string Raw { get; }
public int Index { get; }
public int ColumnCount => Line.Length;
public bool HasColumn(string name) => headerLookup.ContainsKey(name);
internal IList<MemoryText> RawSplitLine
{
get
{
#if NETCOREAPP3_1 || NETSTANDARD2_1
rawSplitLine ??= SplitLine(Raw.AsMemory(), options);
#else
rawSplitLine ??= SplitLine(Raw, options);
#endif
return rawSplitLine;
}
}
public string[] Values => Line.Select(it => it.AsString()).ToArray();
private MemoryText[] Line
{
get
{
if (parsedLine == null)
{
var raw = RawSplitLine;
if (options.ValidateColumnCount && raw.Count != Headers.Length)
throw new InvalidOperationException($"Expected {Headers.Length}, got {raw.Count} columns.");
parsedLine = Trim(raw, options);
}
return parsedLine;
}
}
string ICsvLine.this[string name]
{
get
{
if (!headerLookup.TryGetValue(name, out var index))
{
if (options.ReturnEmptyForMissingColumn)
return string.Empty;
throw new ArgumentOutOfRangeException(nameof(name), name, $"Header '{name}' does not exist. Expected one of {string.Join("; ", Headers)}");
}
try
{
return Line[index].AsString();
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException($"Invalid row, missing {name} header, expected {Headers.Length} columns, got {Line.Length} columns.");
}
}
}
string ICsvLine.this[int index] => Line[index].AsString();
public override string ToString()
{
return Raw;
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
namespace Avalonia.Controls
{
/// <summary>
/// Lays out child controls according to a grid.
/// </summary>
public class Grid : Panel
{
/// <summary>
/// Defines the Column attached property.
/// </summary>
public static readonly AttachedProperty<int> ColumnProperty =
AvaloniaProperty.RegisterAttached<Grid, Control, int>(
"Column",
validate: ValidateColumn);
/// <summary>
/// Defines the ColumnSpan attached property.
/// </summary>
public static readonly AttachedProperty<int> ColumnSpanProperty =
AvaloniaProperty.RegisterAttached<Grid, Control, int>("ColumnSpan", 1);
/// <summary>
/// Defines the Row attached property.
/// </summary>
public static readonly AttachedProperty<int> RowProperty =
AvaloniaProperty.RegisterAttached<Grid, Control, int>(
"Row",
validate: ValidateRow);
/// <summary>
/// Defines the RowSpan attached property.
/// </summary>
public static readonly AttachedProperty<int> RowSpanProperty =
AvaloniaProperty.RegisterAttached<Grid, Control, int>("RowSpan", 1);
private ColumnDefinitions _columnDefinitions;
private RowDefinitions _rowDefinitions;
private Segment[,] _rowMatrix;
private Segment[,] _colMatrix;
/// <summary>
/// Gets or sets the columns definitions for the grid.
/// </summary>
public ColumnDefinitions ColumnDefinitions
{
get
{
if (_columnDefinitions == null)
{
ColumnDefinitions = new ColumnDefinitions();
}
return _columnDefinitions;
}
set
{
if (_columnDefinitions != null)
{
throw new NotSupportedException("Reassigning ColumnDefinitions not yet implemented.");
}
_columnDefinitions = value;
_columnDefinitions.TrackItemPropertyChanged(_ => InvalidateMeasure());
}
}
/// <summary>
/// Gets or sets the row definitions for the grid.
/// </summary>
public RowDefinitions RowDefinitions
{
get
{
if (_rowDefinitions == null)
{
RowDefinitions = new RowDefinitions();
}
return _rowDefinitions;
}
set
{
if (_rowDefinitions != null)
{
throw new NotSupportedException("Reassigning RowDefinitions not yet implemented.");
}
_rowDefinitions = value;
_rowDefinitions.TrackItemPropertyChanged(_ => InvalidateMeasure());
}
}
/// <summary>
/// Gets the value of the Column attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's column.</returns>
public static int GetColumn(AvaloniaObject element)
{
return element.GetValue(ColumnProperty);
}
/// <summary>
/// Gets the value of the ColumnSpan attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's column span.</returns>
public static int GetColumnSpan(AvaloniaObject element)
{
return element.GetValue(ColumnSpanProperty);
}
/// <summary>
/// Gets the value of the Row attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's row.</returns>
public static int GetRow(AvaloniaObject element)
{
return element.GetValue(RowProperty);
}
/// <summary>
/// Gets the value of the RowSpan attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's row span.</returns>
public static int GetRowSpan(AvaloniaObject element)
{
return element.GetValue(RowSpanProperty);
}
/// <summary>
/// Sets the value of the Column attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The column value.</param>
public static void SetColumn(AvaloniaObject element, int value)
{
element.SetValue(ColumnProperty, value);
}
/// <summary>
/// Sets the value of the ColumnSpan attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The column span value.</param>
public static void SetColumnSpan(AvaloniaObject element, int value)
{
element.SetValue(ColumnSpanProperty, value);
}
/// <summary>
/// Sets the value of the Row attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The row value.</param>
public static void SetRow(AvaloniaObject element, int value)
{
element.SetValue(RowProperty, value);
}
/// <summary>
/// Sets the value of the RowSpan attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The row span value.</param>
public static void SetRowSpan(AvaloniaObject element, int value)
{
element.SetValue(RowSpanProperty, value);
}
/// <summary>
/// Measures the grid.
/// </summary>
/// <param name="constraint">The available size.</param>
/// <returns>The desired size of the control.</returns>
protected override Size MeasureOverride(Size constraint)
{
Size totalSize = constraint;
int colCount = ColumnDefinitions.Count;
int rowCount = RowDefinitions.Count;
double totalStarsX = 0;
double totalStarsY = 0;
bool emptyRows = rowCount == 0;
bool emptyCols = colCount == 0;
bool hasChildren = Children.Count > 0;
if (emptyRows)
{
rowCount = 1;
}
if (emptyCols)
{
colCount = 1;
}
CreateMatrices(rowCount, colCount);
if (emptyRows)
{
_rowMatrix[0, 0] = new Segment(0, 0, double.PositiveInfinity, GridUnitType.Star);
_rowMatrix[0, 0].Stars = 1.0;
totalStarsY += 1.0;
}
else
{
for (int i = 0; i < rowCount; i++)
{
RowDefinition rowdef = RowDefinitions[i];
GridLength height = rowdef.Height;
rowdef.ActualHeight = double.PositiveInfinity;
_rowMatrix[i, i] = new Segment(0, rowdef.MinHeight, rowdef.MaxHeight, height.GridUnitType);
if (height.GridUnitType == GridUnitType.Pixel)
{
_rowMatrix[i, i].OfferedSize = Clamp(height.Value, _rowMatrix[i, i].Min, _rowMatrix[i, i].Max);
_rowMatrix[i, i].DesiredSize = _rowMatrix[i, i].OfferedSize;
rowdef.ActualHeight = _rowMatrix[i, i].OfferedSize;
}
else if (height.GridUnitType == GridUnitType.Star)
{
_rowMatrix[i, i].Stars = height.Value;
totalStarsY += height.Value;
}
else if (height.GridUnitType == GridUnitType.Auto)
{
_rowMatrix[i, i].OfferedSize = Clamp(0, _rowMatrix[i, i].Min, _rowMatrix[i, i].Max);
_rowMatrix[i, i].DesiredSize = _rowMatrix[i, i].OfferedSize;
}
}
}
if (emptyCols)
{
_colMatrix[0, 0] = new Segment(0, 0, double.PositiveInfinity, GridUnitType.Star);
_colMatrix[0, 0].Stars = 1.0;
totalStarsX += 1.0;
}
else
{
for (int i = 0; i < colCount; i++)
{
ColumnDefinition coldef = ColumnDefinitions[i];
GridLength width = coldef.Width;
coldef.ActualWidth = double.PositiveInfinity;
_colMatrix[i, i] = new Segment(0, coldef.MinWidth, coldef.MaxWidth, width.GridUnitType);
if (width.GridUnitType == GridUnitType.Pixel)
{
_colMatrix[i, i].OfferedSize = Clamp(width.Value, _colMatrix[i, i].Min, _colMatrix[i, i].Max);
_colMatrix[i, i].DesiredSize = _colMatrix[i, i].OfferedSize;
coldef.ActualWidth = _colMatrix[i, i].OfferedSize;
}
else if (width.GridUnitType == GridUnitType.Star)
{
_colMatrix[i, i].Stars = width.Value;
totalStarsX += width.Value;
}
else if (width.GridUnitType == GridUnitType.Auto)
{
_colMatrix[i, i].OfferedSize = Clamp(0, _colMatrix[i, i].Min, _colMatrix[i, i].Max);
_colMatrix[i, i].DesiredSize = _colMatrix[i, i].OfferedSize;
}
}
}
List<GridNode> sizes = new List<GridNode>();
GridNode node;
GridNode separator = new GridNode(null, 0, 0, 0);
int separatorIndex;
sizes.Add(separator);
// Pre-process the grid children so that we know what types of elements we have so
// we can apply our special measuring rules.
GridWalker gridWalker = new GridWalker(this, _rowMatrix, _colMatrix);
for (int i = 0; i < 6; i++)
{
// These bools tell us which grid element type we should be measuring. i.e.
// 'star/auto' means we should measure elements with a star row and auto col
bool autoAuto = i == 0;
bool starAuto = i == 1;
bool autoStar = i == 2;
bool starAutoAgain = i == 3;
bool nonStar = i == 4;
bool remainingStar = i == 5;
if (hasChildren)
{
ExpandStarCols(totalSize);
ExpandStarRows(totalSize);
}
foreach (Control child in Children)
{
int col, row;
int colspan, rowspan;
double childSizeX = 0;
double childSizeY = 0;
bool starCol = false;
bool starRow = false;
bool autoCol = false;
bool autoRow = false;
col = Math.Min(GetColumn(child), colCount - 1);
row = Math.Min(GetRow(child), rowCount - 1);
colspan = Math.Min(GetColumnSpan(child), colCount - col);
rowspan = Math.Min(GetRowSpan(child), rowCount - row);
for (int r = row; r < row + rowspan; r++)
{
starRow |= _rowMatrix[r, r].Type == GridUnitType.Star;
autoRow |= _rowMatrix[r, r].Type == GridUnitType.Auto;
}
for (int c = col; c < col + colspan; c++)
{
starCol |= _colMatrix[c, c].Type == GridUnitType.Star;
autoCol |= _colMatrix[c, c].Type == GridUnitType.Auto;
}
// This series of if statements checks whether or not we should measure
// the current element and also if we need to override the sizes
// passed to the Measure call.
// If the element has Auto rows and Auto columns and does not span Star
// rows/cols it should only be measured in the auto_auto phase.
// There are similar rules governing auto/star and star/auto elements.
// NOTE: star/auto elements are measured twice. The first time with
// an override for height, the second time without it.
if (autoRow && autoCol && !starRow && !starCol)
{
if (!autoAuto)
{
continue;
}
childSizeX = double.PositiveInfinity;
childSizeY = double.PositiveInfinity;
}
else if (starRow && autoCol && !starCol)
{
if (!(starAuto || starAutoAgain))
{
continue;
}
if (starAuto && gridWalker.HasAutoStar)
{
childSizeY = double.PositiveInfinity;
}
childSizeX = double.PositiveInfinity;
}
else if (autoRow && starCol && !starRow)
{
if (!autoStar)
{
continue;
}
childSizeY = double.PositiveInfinity;
}
else if ((autoRow || autoCol) && !(starRow || starCol))
{
if (!nonStar)
{
continue;
}
if (autoRow)
{
childSizeY = double.PositiveInfinity;
}
if (autoCol)
{
childSizeX = double.PositiveInfinity;
}
}
else if (!(starRow || starCol))
{
if (!nonStar)
{
continue;
}
}
else
{
if (!remainingStar)
{
continue;
}
}
for (int r = row; r < row + rowspan; r++)
{
childSizeY += _rowMatrix[r, r].OfferedSize;
}
for (int c = col; c < col + colspan; c++)
{
childSizeX += _colMatrix[c, c].OfferedSize;
}
child.Measure(new Size(childSizeX, childSizeY));
Size desired = child.DesiredSize;
// Elements distribute their height based on two rules:
// 1) Elements with rowspan/colspan == 1 distribute their height first
// 2) Everything else distributes in a LIFO manner.
// As such, add all UIElements with rowspan/colspan == 1 after the separator in
// the list and everything else before it. Then to process, just keep popping
// elements off the end of the list.
if (!starAuto)
{
node = new GridNode(_rowMatrix, row + rowspan - 1, row, desired.Height);
separatorIndex = sizes.IndexOf(separator);
sizes.Insert(node.Row == node.Column ? separatorIndex + 1 : separatorIndex, node);
}
node = new GridNode(_colMatrix, col + colspan - 1, col, desired.Width);
separatorIndex = sizes.IndexOf(separator);
sizes.Insert(node.Row == node.Column ? separatorIndex + 1 : separatorIndex, node);
}
sizes.Remove(separator);
while (sizes.Count > 0)
{
node = sizes.Last();
node.Matrix[node.Row, node.Column].DesiredSize = Math.Max(node.Matrix[node.Row, node.Column].DesiredSize, node.Size);
AllocateDesiredSize(rowCount, colCount);
sizes.Remove(node);
}
sizes.Add(separator);
}
// Once we have measured and distributed all sizes, we have to store
// the results. Every time we want to expand the rows/cols, this will
// be used as the baseline.
SaveMeasureResults();
sizes.Remove(separator);
double gridSizeX = 0;
double gridSizeY = 0;
for (int c = 0; c < colCount; c++)
{
gridSizeX += _colMatrix[c, c].DesiredSize;
}
for (int r = 0; r < rowCount; r++)
{
gridSizeY += _rowMatrix[r, r].DesiredSize;
}
return new Size(gridSizeX, gridSizeY);
}
/// <summary>
/// Arranges the grid's children.
/// </summary>
/// <param name="finalSize">The size allocated to the control.</param>
/// <returns>The space taken.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
int colCount = ColumnDefinitions.Count;
int rowCount = RowDefinitions.Count;
int colMatrixDim = _colMatrix.GetLength(0);
int rowMatrixDim = _rowMatrix.GetLength(0);
RestoreMeasureResults();
double totalConsumedX = 0;
double totalConsumedY = 0;
for (int c = 0; c < colMatrixDim; c++)
{
_colMatrix[c, c].OfferedSize = _colMatrix[c, c].DesiredSize;
totalConsumedX += _colMatrix[c, c].OfferedSize;
}
for (int r = 0; r < rowMatrixDim; r++)
{
_rowMatrix[r, r].OfferedSize = _rowMatrix[r, r].DesiredSize;
totalConsumedY += _rowMatrix[r, r].OfferedSize;
}
if (totalConsumedX != finalSize.Width)
{
ExpandStarCols(finalSize);
}
if (totalConsumedY != finalSize.Height)
{
ExpandStarRows(finalSize);
}
for (int c = 0; c < colCount; c++)
{
ColumnDefinitions[c].ActualWidth = _colMatrix[c, c].OfferedSize;
}
for (int r = 0; r < rowCount; r++)
{
RowDefinitions[r].ActualHeight = _rowMatrix[r, r].OfferedSize;
}
foreach (Control child in Children)
{
int col = Math.Min(GetColumn(child), colMatrixDim - 1);
int row = Math.Min(GetRow(child), rowMatrixDim - 1);
int colspan = Math.Min(GetColumnSpan(child), colMatrixDim - col);
int rowspan = Math.Min(GetRowSpan(child), rowMatrixDim - row);
double childFinalX = 0;
double childFinalY = 0;
double childFinalW = 0;
double childFinalH = 0;
for (int c = 0; c < col; c++)
{
childFinalX += _colMatrix[c, c].OfferedSize;
}
for (int c = col; c < col + colspan; c++)
{
childFinalW += _colMatrix[c, c].OfferedSize;
}
for (int r = 0; r < row; r++)
{
childFinalY += _rowMatrix[r, r].OfferedSize;
}
for (int r = row; r < row + rowspan; r++)
{
childFinalH += _rowMatrix[r, r].OfferedSize;
}
child.Arrange(new Rect(childFinalX, childFinalY, childFinalW, childFinalH));
}
return finalSize;
}
private static double Clamp(double val, double min, double max)
{
if (val < min)
{
return min;
}
else if (val > max)
{
return max;
}
else
{
return val;
}
}
private static int ValidateColumn(AvaloniaObject o, int value)
{
if (value < 0)
{
throw new ArgumentException("Invalid Grid.Column value.");
}
return value;
}
private static int ValidateRow(AvaloniaObject o, int value)
{
if (value < 0)
{
throw new ArgumentException("Invalid Grid.Row value.");
}
return value;
}
private void CreateMatrices(int rowCount, int colCount)
{
if (_rowMatrix == null || _colMatrix == null ||
_rowMatrix.GetLength(0) != rowCount ||
_colMatrix.GetLength(0) != colCount)
{
_rowMatrix = new Segment[rowCount, rowCount];
_colMatrix = new Segment[colCount, colCount];
}
else
{
Array.Clear(_rowMatrix, 0, _rowMatrix.Length);
Array.Clear(_colMatrix, 0, _colMatrix.Length);
}
}
private void ExpandStarCols(Size availableSize)
{
int matrixCount = _colMatrix.GetLength(0);
int columnsCount = ColumnDefinitions.Count;
double width = availableSize.Width;
for (int i = 0; i < matrixCount; i++)
{
if (_colMatrix[i, i].Type == GridUnitType.Star)
{
_colMatrix[i, i].OfferedSize = 0;
}
else
{
width = Math.Max(width - _colMatrix[i, i].OfferedSize, 0);
}
}
AssignSize(_colMatrix, 0, matrixCount - 1, ref width, GridUnitType.Star, false);
width = Math.Max(0, width);
if (columnsCount > 0)
{
for (int i = 0; i < matrixCount; i++)
{
if (_colMatrix[i, i].Type == GridUnitType.Star)
{
ColumnDefinitions[i].ActualWidth = _colMatrix[i, i].OfferedSize;
}
}
}
}
private void ExpandStarRows(Size availableSize)
{
int matrixCount = _rowMatrix.GetLength(0);
int rowCount = RowDefinitions.Count;
double height = availableSize.Height;
// When expanding star rows, we need to zero out their height before
// calling AssignSize. AssignSize takes care of distributing the
// available size when there are Mins and Maxs applied.
for (int i = 0; i < matrixCount; i++)
{
if (_rowMatrix[i, i].Type == GridUnitType.Star)
{
_rowMatrix[i, i].OfferedSize = 0.0;
}
else
{
height = Math.Max(height - _rowMatrix[i, i].OfferedSize, 0);
}
}
AssignSize(_rowMatrix, 0, matrixCount - 1, ref height, GridUnitType.Star, false);
if (rowCount > 0)
{
for (int i = 0; i < matrixCount; i++)
{
if (_rowMatrix[i, i].Type == GridUnitType.Star)
{
RowDefinitions[i].ActualHeight = _rowMatrix[i, i].OfferedSize;
}
}
}
}
private void AssignSize(
Segment[,] matrix,
int start,
int end,
ref double size,
GridUnitType type,
bool desiredSize)
{
double count = 0;
bool assigned;
// Count how many segments are of the correct type. If we're measuring Star rows/cols
// we need to count the number of stars instead.
for (int i = start; i <= end; i++)
{
double segmentSize = desiredSize ? matrix[i, i].DesiredSize : matrix[i, i].OfferedSize;
if (segmentSize < matrix[i, i].Max)
{
count += type == GridUnitType.Star ? matrix[i, i].Stars : 1;
}
}
do
{
double contribution = size / count;
assigned = false;
for (int i = start; i <= end; i++)
{
double segmentSize = desiredSize ? matrix[i, i].DesiredSize : matrix[i, i].OfferedSize;
if (!(matrix[i, i].Type == type && segmentSize < matrix[i, i].Max))
{
continue;
}
double newsize = segmentSize;
newsize += contribution * (type == GridUnitType.Star ? matrix[i, i].Stars : 1);
newsize = Math.Min(newsize, matrix[i, i].Max);
assigned |= newsize > segmentSize;
size -= newsize - segmentSize;
if (desiredSize)
{
matrix[i, i].DesiredSize = newsize;
}
else
{
matrix[i, i].OfferedSize = newsize;
}
}
}
while (assigned);
}
private void AllocateDesiredSize(int rowCount, int colCount)
{
// First allocate the heights of the RowDefinitions, then allocate
// the widths of the ColumnDefinitions.
for (int i = 0; i < 2; i++)
{
Segment[,] matrix = i == 0 ? _rowMatrix : _colMatrix;
int count = i == 0 ? rowCount : colCount;
for (int row = count - 1; row >= 0; row--)
{
for (int col = row; col >= 0; col--)
{
bool spansStar = false;
for (int j = row; j >= col; j--)
{
spansStar |= matrix[j, j].Type == GridUnitType.Star;
}
// This is the amount of pixels which must be available between the grid rows
// at index 'col' and 'row'. i.e. if 'row' == 0 and 'col' == 2, there must
// be at least 'matrix [row][col].size' pixels of height allocated between
// all the rows in the range col -> row.
double current = matrix[row, col].DesiredSize;
// Count how many pixels have already been allocated between the grid rows
// in the range col -> row. The amount of pixels allocated to each grid row/column
// is found on the diagonal of the matrix.
double totalAllocated = 0;
for (int k = row; k >= col; k--)
{
totalAllocated += matrix[k, k].DesiredSize;
}
// If the size requirement has not been met, allocate the additional required
// size between 'pixel' rows, then 'star' rows, finally 'auto' rows, until all
// height has been assigned.
if (totalAllocated < current)
{
double additional = current - totalAllocated;
if (spansStar)
{
AssignSize(matrix, col, row, ref additional, GridUnitType.Star, true);
}
else
{
AssignSize(matrix, col, row, ref additional, GridUnitType.Pixel, true);
AssignSize(matrix, col, row, ref additional, GridUnitType.Auto, true);
}
}
}
}
}
int rowMatrixDim = _rowMatrix.GetLength(0);
int colMatrixDim = _colMatrix.GetLength(0);
for (int r = 0; r < rowMatrixDim; r++)
{
_rowMatrix[r, r].OfferedSize = _rowMatrix[r, r].DesiredSize;
}
for (int c = 0; c < colMatrixDim; c++)
{
_colMatrix[c, c].OfferedSize = _colMatrix[c, c].DesiredSize;
}
}
private void SaveMeasureResults()
{
int rowMatrixDim = _rowMatrix.GetLength(0);
int colMatrixDim = _colMatrix.GetLength(0);
for (int i = 0; i < rowMatrixDim; i++)
{
for (int j = 0; j < rowMatrixDim; j++)
{
_rowMatrix[i, j].OriginalSize = _rowMatrix[i, j].OfferedSize;
}
}
for (int i = 0; i < colMatrixDim; i++)
{
for (int j = 0; j < colMatrixDim; j++)
{
_colMatrix[i, j].OriginalSize = _colMatrix[i, j].OfferedSize;
}
}
}
private void RestoreMeasureResults()
{
int rowMatrixDim = _rowMatrix.GetLength(0);
int colMatrixDim = _colMatrix.GetLength(0);
for (int i = 0; i < rowMatrixDim; i++)
{
for (int j = 0; j < rowMatrixDim; j++)
{
_rowMatrix[i, j].OfferedSize = _rowMatrix[i, j].OriginalSize;
}
}
for (int i = 0; i < colMatrixDim; i++)
{
for (int j = 0; j < colMatrixDim; j++)
{
_colMatrix[i, j].OfferedSize = _colMatrix[i, j].OriginalSize;
}
}
}
private struct Segment
{
public double OriginalSize;
public double Max;
public double Min;
public double DesiredSize;
public double OfferedSize;
public double Stars;
public GridUnitType Type;
public Segment(double offeredSize, double min, double max, GridUnitType type)
{
OriginalSize = 0;
Min = min;
Max = max;
DesiredSize = 0;
OfferedSize = offeredSize;
Stars = 0;
Type = type;
}
}
private struct GridNode
{
public readonly int Row;
public readonly int Column;
public readonly double Size;
public readonly Segment[,] Matrix;
public GridNode(Segment[,] matrix, int row, int col, double size)
{
Matrix = matrix;
Row = row;
Column = col;
Size = size;
}
}
private class GridWalker
{
public GridWalker(Grid grid, Segment[,] rowMatrix, Segment[,] colMatrix)
{
int rowMatrixDim = rowMatrix.GetLength(0);
int colMatrixDim = colMatrix.GetLength(0);
foreach (Control child in grid.Children)
{
bool starCol = false;
bool starRow = false;
bool autoCol = false;
bool autoRow = false;
int col = Math.Min(GetColumn(child), colMatrixDim - 1);
int row = Math.Min(GetRow(child), rowMatrixDim - 1);
int colspan = Math.Min(GetColumnSpan(child), colMatrixDim - 1);
int rowspan = Math.Min(GetRowSpan(child), rowMatrixDim - 1);
for (int r = row; r < row + rowspan; r++)
{
starRow |= rowMatrix[r, r].Type == GridUnitType.Star;
autoRow |= rowMatrix[r, r].Type == GridUnitType.Auto;
}
for (int c = col; c < col + colspan; c++)
{
starCol |= colMatrix[c, c].Type == GridUnitType.Star;
autoCol |= colMatrix[c, c].Type == GridUnitType.Auto;
}
HasAutoAuto |= autoRow && autoCol && !starRow && !starCol;
HasStarAuto |= starRow && autoCol;
HasAutoStar |= autoRow && starCol;
}
}
public bool HasAutoAuto { get; }
public bool HasStarAuto { get; }
public bool HasAutoStar { get; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using Xamarin.Forms.GoogleMaps.Internals;
using Xamarin.Forms.GoogleMaps.Helpers;
using System.Threading.Tasks;
using Xamarin.Forms.GoogleMaps.Extensions;
namespace Xamarin.Forms.GoogleMaps
{
public class Map : View, IEnumerable<Pin>
{
public static readonly BindableProperty MapTypeProperty = BindableProperty.Create(nameof(MapType), typeof(MapType), typeof(Map), default(MapType));
#pragma warning disable CS0618 // Type or member is obsolete
public static readonly BindableProperty IsShowingUserProperty = BindableProperty.Create(nameof(IsShowingUser), typeof(bool), typeof(Map), default(bool));
public static readonly BindableProperty MyLocationEnabledProperty = BindableProperty.Create(nameof(MyLocationEnabled), typeof(bool), typeof(Map), default(bool));
public static readonly BindableProperty HasScrollEnabledProperty = BindableProperty.Create(nameof(HasScrollEnabled), typeof(bool), typeof(Map), true);
public static readonly BindableProperty HasZoomEnabledProperty = BindableProperty.Create(nameof(HasZoomEnabled), typeof(bool), typeof(Map), true);
public static readonly BindableProperty HasRotationEnabledProperty = BindableProperty.Create(nameof(HasRotationEnabled), typeof(bool), typeof(Map), true);
#pragma warning restore CS0618 // Type or member is obsolete
public static readonly BindableProperty SelectedPinProperty = BindableProperty.Create(nameof(SelectedPin), typeof(Pin), typeof(Map), default(Pin), defaultBindingMode: BindingMode.TwoWay);
public static readonly BindableProperty IsTrafficEnabledProperty = BindableProperty.Create(nameof(IsTrafficEnabled), typeof(bool), typeof(Map), false);
public static readonly BindableProperty IndoorEnabledProperty = BindableProperty.Create(nameof(IsIndoorEnabled), typeof(bool), typeof(Map), true);
public static readonly BindableProperty InitialCameraUpdateProperty = BindableProperty.Create(
nameof(InitialCameraUpdate), typeof(CameraUpdate), typeof(Map),
CameraUpdateFactory.NewPositionZoom(new Position(41.89, 12.49), 10), // center on Rome by default
propertyChanged: (bindable, oldValue, newValue) =>
{
((Map)bindable)._useMoveToRegisonAsInitialBounds = false;
});
public static readonly BindableProperty PaddingProperty = BindableProperty.Create(nameof(PaddingProperty), typeof(Thickness), typeof(Map), default(Thickness));
bool _useMoveToRegisonAsInitialBounds = true;
public static readonly BindableProperty CameraPositionProperty = BindableProperty.Create(
nameof(CameraPosition), typeof(CameraPosition), typeof(Map),
defaultValueCreator: (bindable) => new CameraPosition(((Map)bindable).InitialCameraUpdate.Position, 10),
defaultBindingMode: BindingMode.TwoWay);
public static readonly BindableProperty MapStyleProperty = BindableProperty.Create(nameof(MapStyle), typeof(MapStyle), typeof(Map), null);
readonly ObservableCollection<Pin> _pins = new ObservableCollection<Pin>();
readonly ObservableCollection<Polyline> _polylines = new ObservableCollection<Polyline>();
readonly ObservableCollection<Polygon> _polygons = new ObservableCollection<Polygon>();
readonly ObservableCollection<Circle> _circles = new ObservableCollection<Circle>();
readonly ObservableCollection<TileLayer> _tileLayers = new ObservableCollection<TileLayer>();
readonly ObservableCollection<GroundOverlay> _groundOverlays = new ObservableCollection<GroundOverlay>();
public event EventHandler<PinClickedEventArgs> PinClicked;
public event EventHandler<SelectedPinChangedEventArgs> SelectedPinChanged;
public event EventHandler<InfoWindowClickedEventArgs> InfoWindowClicked;
public event EventHandler<InfoWindowLongClickedEventArgs> InfoWindowLongClicked;
public event EventHandler<PinDragEventArgs> PinDragStart;
public event EventHandler<PinDragEventArgs> PinDragEnd;
public event EventHandler<PinDragEventArgs> PinDragging;
public event EventHandler<MapClickedEventArgs> MapClicked;
public event EventHandler<MapLongClickedEventArgs> MapLongClicked;
public event EventHandler<MyLocationButtonClickedEventArgs> MyLocationButtonClicked;
[Obsolete("Please use Map.CameraIdled instead of this")]
public event EventHandler<CameraChangedEventArgs> CameraChanged;
public event EventHandler<CameraMoveStartedEventArgs> CameraMoveStarted;
public event EventHandler<CameraMovingEventArgs> CameraMoving;
public event EventHandler<CameraIdledEventArgs> CameraIdled;
internal Action<MoveToRegionMessage> OnMoveToRegion { get; set; }
internal Action<CameraUpdateMessage> OnMoveCamera { get; set; }
internal Action<CameraUpdateMessage> OnAnimateCamera { get; set; }
internal Action<TakeSnapshotMessage> OnSnapshot{ get; set; }
MapSpan _visibleRegion;
MapRegion _region;
//// Simone Marra
//public static Position _TopLeft = new Position();
//public static Position _TopRight = new Position();
//public static Position _BottomLeft = new Position();
//public static Position _BottomRight = new Position();
//// End Simone Marra
public Map()
{
VerticalOptions = HorizontalOptions = LayoutOptions.FillAndExpand;
_pins.CollectionChanged += PinsOnCollectionChanged;
_polylines.CollectionChanged += PolylinesOnCollectionChanged;
_polygons.CollectionChanged += PolygonsOnCollectionChanged;
_circles.CollectionChanged += CirclesOnCollectionChanged;
_tileLayers.CollectionChanged += TileLayersOnCollectionChanged;
_groundOverlays.CollectionChanged += GroundOverlays_CollectionChanged;
}
[Obsolete("Please use Map.UiSettings.ScrollGesturesEnabled instead of this")]
public bool HasScrollEnabled
{
get { return (bool)GetValue(HasScrollEnabledProperty); }
set { SetValue(HasScrollEnabledProperty, value); }
}
[Obsolete("Please use Map.UiSettings.ZoomGesturesEnabled and ZoomControlsEnabled instead of this")]
public bool HasZoomEnabled
{
get { return (bool)GetValue(HasZoomEnabledProperty); }
set { SetValue(HasZoomEnabledProperty, value); }
}
[Obsolete("Please use Map.UiSettings.RotateGesturesEnabled instead of this")]
public bool HasRotationEnabled
{
get { return (bool)GetValue(HasRotationEnabledProperty); }
set { SetValue(HasRotationEnabledProperty, value); }
}
public bool IsTrafficEnabled
{
get { return (bool)GetValue(IsTrafficEnabledProperty); }
set { SetValue(IsTrafficEnabledProperty, value); }
}
public bool IsIndoorEnabled
{
get { return (bool) GetValue(IndoorEnabledProperty); }
set { SetValue(IndoorEnabledProperty, value);}
}
[Obsolete("Please use Map.MyLocationEnabled and Map.UiSettings.MyLocationButtonEnabled instead of this")]
public bool IsShowingUser
{
get { return (bool)GetValue(IsShowingUserProperty); }
set { SetValue(IsShowingUserProperty, value); }
}
public bool MyLocationEnabled
{
get { return (bool)GetValue(MyLocationEnabledProperty); }
set { SetValue(MyLocationEnabledProperty, value); }
}
public MapType MapType
{
get { return (MapType)GetValue(MapTypeProperty); }
set { SetValue(MapTypeProperty, value); }
}
public Pin SelectedPin
{
get { return (Pin)GetValue(SelectedPinProperty); }
set { SetValue(SelectedPinProperty, value); }
}
[TypeConverter(typeof(CameraUpdateConverter))]
public CameraUpdate InitialCameraUpdate
{
get { return (CameraUpdate)GetValue(InitialCameraUpdateProperty); }
set { SetValue(InitialCameraUpdateProperty, value); }
}
public CameraPosition CameraPosition
{
get { return (CameraPosition)GetValue(CameraPositionProperty); }
internal set { SetValue(CameraPositionProperty, value); }
}
public Thickness Padding
{
get { return (Thickness)GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
public MapStyle MapStyle
{
get { return (MapStyle)GetValue(MapStyleProperty); }
set { SetValue(MapStyleProperty, value); }
}
public IList<Pin> Pins
{
get { return _pins; }
}
public IList<Polyline> Polylines
{
get { return _polylines; }
}
public IList<Polygon> Polygons
{
get { return _polygons; }
}
public IList<Circle> Circles
{
get { return _circles; }
}
public IList<TileLayer> TileLayers
{
get { return _tileLayers; }
}
public IList<GroundOverlay> GroundOverlays
{
get { return _groundOverlays; }
}
[Obsolete("Please use Map.Region instead of this")]
public MapSpan VisibleRegion
{
get { return _visibleRegion; }
internal set
{
if (_visibleRegion == value)
return;
if (value == null)
throw new ArgumentNullException(nameof(value));
OnPropertyChanging();
_visibleRegion = value;
OnPropertyChanged();
}
}
public MapRegion Region
{
get { return _region; }
internal set
{
if (_region == value)
return;
if (value == null)
throw new ArgumentNullException(nameof(value));
OnPropertyChanging();
_region = value;
OnPropertyChanged();
}
}
public UiSettings UiSettings { get; } = new UiSettings();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<Pin> GetEnumerator()
{
return _pins.GetEnumerator();
}
public void MoveToRegion(MapSpan mapSpan, bool animate = true)
{
if (mapSpan == null)
throw new ArgumentNullException(nameof(mapSpan));
if (_useMoveToRegisonAsInitialBounds)
{
InitialCameraUpdate = CameraUpdateFactory.NewBounds(mapSpan.ToBounds(), 0);
_useMoveToRegisonAsInitialBounds = false;
}
SendMoveToRegion(new MoveToRegionMessage(mapSpan, animate));
}
public Task<AnimationStatus> MoveCamera(CameraUpdate cameraUpdate)
{
var comp = new TaskCompletionSource<AnimationStatus>();
SendMoveCamera(new CameraUpdateMessage(cameraUpdate, null, new DelegateAnimationCallback(
() => comp.SetResult(AnimationStatus.Finished),
() => comp.SetResult(AnimationStatus.Canceled))));
return comp.Task;
}
public Task<AnimationStatus> AnimateCamera(CameraUpdate cameraUpdate, TimeSpan? duration = null)
{
var comp = new TaskCompletionSource<AnimationStatus>();
SendAnimateCamera(new CameraUpdateMessage(cameraUpdate, duration, new DelegateAnimationCallback(
() => comp.SetResult(AnimationStatus.Finished),
() => comp.SetResult(AnimationStatus.Canceled))));
return comp.Task;
}
public Task<Stream> TakeSnapshot()
{
var comp = new TaskCompletionSource<Stream>();
SendTakeSnapshot(new TakeSnapshotMessage(image => comp.SetResult(image)));
return comp.Task;
}
void PinsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Cast<Pin>().Any(pin => pin.Label == null))
throw new ArgumentException("Pin must have a Label to be added to a map");
}
void PolylinesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Cast<Polyline>().Any(polyline => polyline.Positions.Count < 2))
throw new ArgumentException("Polyline must have a 2 positions to be added to a map");
}
void PolygonsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Cast<Polygon>().Any(polygon => polygon.Positions.Count < 3))
throw new ArgumentException("Polygon must have a 3 positions to be added to a map");
}
void CirclesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Cast<Circle>().Any(circle => (
circle?.Center == null || circle?.Radius == null || circle.Radius.Meters <= 0f)))
throw new ArgumentException("Circle must have a center and radius");
}
void TileLayersOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//if (e.NewItems != null && e.NewItems.Cast<ITileLayer>().Any(tileLayer => (circle.Center == null || circle.Radius == null || circle.Radius.Meters <= 0f)))
// throw new ArgumentException("Circle must have a center and radius");
}
void GroundOverlays_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}
internal void SendSelectedPinChanged(Pin selectedPin)
{
SelectedPinChanged?.Invoke(this, new SelectedPinChangedEventArgs(selectedPin));
}
internal bool SendPinClicked(Pin pin)
{
var args = new PinClickedEventArgs(pin);
PinClicked?.Invoke(this, args);
return args.Handled;
}
internal void SendInfoWindowClicked(Pin pin)
{
var args = new InfoWindowClickedEventArgs(pin);
InfoWindowClicked?.Invoke(this, args);
}
internal void SendInfoWindowLongClicked(Pin pin)
{
var args = new InfoWindowLongClickedEventArgs(pin);
InfoWindowLongClicked?.Invoke(this, args);
}
internal void SendPinDragStart(Pin pin)
{
PinDragStart?.Invoke(this, new PinDragEventArgs(pin));
}
internal void SendPinDragEnd(Pin pin)
{
PinDragEnd?.Invoke(this, new PinDragEventArgs(pin));
}
internal void SendPinDragging(Pin pin)
{
PinDragging?.Invoke(this, new PinDragEventArgs(pin));
}
internal void SendMapClicked(Position point)
{
MapClicked?.Invoke(this, new MapClickedEventArgs(point));
}
internal void SendMapLongClicked(Position point)
{
MapLongClicked?.Invoke(this, new MapLongClickedEventArgs(point));
}
internal bool SendMyLocationClicked()
{
var args = new MyLocationButtonClickedEventArgs();
MyLocationButtonClicked?.Invoke(this, args);
return args.Handled;
}
internal void SendCameraChanged(CameraPosition position)
{
CameraChanged?.Invoke(this, new CameraChangedEventArgs(position));
}
internal void SendCameraMoveStarted(bool isGesture)
{
CameraMoveStarted?.Invoke(this, new CameraMoveStartedEventArgs(isGesture));
}
internal void SendCameraMoving(CameraPosition position)
{
CameraMoving?.Invoke(this, new CameraMovingEventArgs(position));
}
internal void SendCameraIdled(CameraPosition position)
{
CameraIdled?.Invoke(this, new CameraIdledEventArgs(position));
}
private void SendMoveToRegion(MoveToRegionMessage message)
{
OnMoveToRegion?.Invoke(message);
}
void SendMoveCamera(CameraUpdateMessage message)
{
OnMoveCamera?.Invoke(message);
}
void SendAnimateCamera(CameraUpdateMessage message)
{
OnAnimateCamera?.Invoke(message);
}
void SendTakeSnapshot(TakeSnapshotMessage message)
{
OnSnapshot?.Invoke(message);
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Dazinator.AspNet.Extensions.FileProviders
{
public class SubPathInfo
{
private static char[] _directorySeperator = new char[] { '/' };
// private string _directory;
protected SubPathInfo(string directory, string name)
{
Directory = directory;
Name = name;
CheckPattern();
CoerceNameToDirectoryIfNecessary();
IsEmpty = string.IsNullOrWhiteSpace(Directory) && string.IsNullOrWhiteSpace(Name);
}
public string Name { get; private set; }
public string Directory { get; private set; }
public bool IsPattern { get; set; }
public bool IsFile { get; set; }
public bool IsEmpty { get; private set; }
public void CheckPattern()
{
bool patternValidationEnabled = true;
bool isWithinRangeBlock = false;
var allChars = this.ToString();
for (int i = 0; i <= allChars.Length - 1; i++)
{
var currentChar = allChars[i];
if (patternValidationEnabled)
{
if (IsStarOrQuestionMarkChar(currentChar))
{
IsPattern = true;
}
else if (IsStartRangeChar(currentChar))
{
if (isWithinRangeBlock)
{
throw new ArgumentException(
"Unsupported globbing pattern. A pattern cannot use nested [ characters. Expected a cosing bracket.");
}
isWithinRangeBlock = true;
IsPattern = true;
}
else if (IsEndRangeChar(currentChar))
{
// maybe at end of range block.
if (!isWithinRangeBlock)
{
throw new ArgumentException(
"Unsupported globbing pattern. A pattern cannot use a ] character without an opening [ character. Expected an opening bracket.");
}
isWithinRangeBlock = false;
}
}
}
}
public void CoerceNameToDirectoryIfNecessary()
{
// This is tricky and not perfect, because paths like the following could all be either
// files or directories.
// somefolder/.git
// somefolder/folder.old
// somefolder/somefile.old
// Therefore we use a simplistic heuristic
// For a path to be considered a file:
// 1. It can't be pattern like (i.e it can;t contain * or ? etc.
// 2. It can't end in a "/" (this is the same as the Name being null or empty)
// 3. It must have a "." in the Name, but not at the end.
// return !IsPattern && !string.IsNullOrWhiteSpace(Name) && Name.Contains('.') && !Name.EndsWith(".");
bool isEmptyName = string.IsNullOrWhiteSpace(Name);
IsFile = !IsPattern && !isEmptyName && Name.Contains('.') && !Name.EndsWith(".");
// If we detected that the name should be treated as a directory, then appened it to the directory, and blank the name.
if (!IsFile)
{
if (!isEmptyName)
{
if (!string.IsNullOrWhiteSpace(Directory))
{
Directory = Directory + "/" + Name;
}
else
{
Directory = Name;
}
Name = string.Empty;
}
}
}
public static SubPathInfo Parse(string subpath)
{
if (string.IsNullOrWhiteSpace(subpath))
{
return new SubPathInfo(string.Empty, string.Empty);
// throw new ArgumentException("subpath");
}
var builder = new StringBuilder(subpath.Length);
var indexOfLastSeperator = subpath.LastIndexOf('/');
if (indexOfLastSeperator != -1)
{
// has directory portion.
for (int i = 0; i <= indexOfLastSeperator; i++)
{
var currentChar = subpath[i];
if (currentChar == '/')
{
if (i == 0 || i == indexOfLastSeperator) // omit a starting and trailing slash (/)
{
continue;
}
}
builder.Append(currentChar);
}
}
var directory = builder.ToString();
builder.Clear();
// now append Name portion
if (subpath.Length > indexOfLastSeperator + 1)
{
for (int c = indexOfLastSeperator + 1; c < subpath.Length; c++)
{
var currentChar = subpath[c];
builder.Append(currentChar);
}
}
var name = builder.ToString();
var subPath = new SubPathInfo(directory, name);
return subPath;
}
public static bool IsStarOrQuestionMarkChar(char currentChar)
{
if (currentChar == '*' || currentChar == '?')
{
return true;
}
return false;
}
public static bool IsStartRangeChar(char currentChar)
{
if (currentChar == '[')
{
return true;
}
return false;
}
public static bool IsEndRangeChar(char currentChar)
{
if (currentChar == ']')
{
return true;
}
return false;
}
public override string ToString()
{
if (string.IsNullOrWhiteSpace(Directory))
{
return Name;
}
if (string.IsNullOrWhiteSpace(Name))
{
return Directory;
}
if (Directory.EndsWith("/"))
{
return $"{Directory}{Name}";
}
return $"{Directory}/{Name}";
}
public bool IsMatch(SubPathInfo subPath)
{
if (subPath.IsPattern)
{
return this.Like(subPath.ToString());
}
if (string.IsNullOrEmpty(subPath.Name) && IsInSameDirectory(subPath))
{
return true;
}
return this.Equals(subPath);
}
public bool IsInSameDirectory(SubPathInfo directory)
{
var match = directory.Directory == Directory;
return match;
}
/// <summary>
/// Compares the subpath against a given pattern.
/// </summary>
/// <param name="pattern">The pattern to match, where "*" means any sequence of characters, and "?" means any single character.</param>
/// <returns><c>true</c> if the subpath matches the given pattern; otherwise <c>false</c>.</returns>
public bool Like(string pattern)
{
var regex = new Regex("^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
var path = this.ToString();
var isMatch = regex.IsMatch(path);
return isMatch;
}
public override bool Equals(object obj)
{
// If parameter cannot be cast to Point return false.
SubPathInfo p = obj as SubPathInfo;
if (p == null)
{
string pathString = obj as string;
if (pathString == null)
{
return false;
}
try
{
p = SubPathInfo.Parse(pathString);
}
catch (Exception e)
{
return false;
}
}
// Return true if the fields match:
//todo: make case sensitivity depend on platform?
// ie windows file system is not case sensitive..
return (Directory.Equals(p.Directory, StringComparison.OrdinalIgnoreCase))
&& (Name.Equals(p.Name, StringComparison.OrdinalIgnoreCase));
}
public override int GetHashCode()
{
int hashCode = Directory.GetHashCode() + Name.GetHashCode();
return hashCode;
}
public string[] GetDirectorySegments()
{
return PathUtils.SplitPathIntoSegments(this.ToString());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Slices.Tests
{
public class SlicesTests
{
[Fact]
public void ByteSpanEmptyCreateArrayTest()
{
var empty = Span<byte>.Empty;
var array = empty.CreateArray();
Assert.Equal(0, array.Length);
}
[Fact]
public void ByteReadOnlySpanEmptyCreateArrayTest()
{
var empty = ReadOnlySpan<byte>.Empty;
var array = empty.CreateArray();
Assert.Equal(0, array.Length);
}
[Fact]
public unsafe void ByteSpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
Span<byte> b1 = new Span<byte>(buffer1pinned, bufferLength);
Span<byte> b2 = new Span<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Fact]
public unsafe void ByteReadOnlySpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
ReadOnlySpan<byte> b1 = new ReadOnlySpan<byte>(buffer1pinned, bufferLength);
ReadOnlySpan<byte> b2 = new ReadOnlySpan<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteReadOnlySpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length);
}
[Fact]
public void ByteSpanCtorWithRangeThrowsArgumentExceptionOnNull()
{
Assert.Throws<ArgumentException>(() => { Span<byte> span = new Span<byte>(null, 0, 0); });
}
[Fact]
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentExceptionOnNull()
{
Assert.Throws<ArgumentException>(() => { ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(null, 0, 0); });
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
Assert.Throws<ArgumentOutOfRangeException>(() => { Span<byte> span = new Span<byte>(bytes, start, length); });
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanSliceWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanSliceWithRangeThrowsArgumentOutOfRangeException1(byte[] bytes, int start, int length)
{
var span = new Span<byte>(bytes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
Span<byte> slice = span.Slice(start, length);
});
}
[Theory]
[InlineData(new byte[0], 0)]
[InlineData(new byte[1] { 0 }, 0)]
[InlineData(new byte[1] { 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 0)]
[InlineData(new byte[2] { 0, 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 1)]
[InlineData(new byte[3] { 0, 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 3)]
public void ByteSpanSliceWithStartRangeValidCases(byte[] bytes, int start)
{
Span<byte> span = new Span<byte>(bytes).Slice(start);
}
[Theory]
[InlineData(new byte[0], int.MinValue)]
[InlineData(new byte[0], -1)]
[InlineData(new byte[0], 1)]
[InlineData(new byte[0], int.MaxValue)]
[InlineData(new byte[1] { 0 }, int.MinValue)]
[InlineData(new byte[1] { 0 }, -1)]
[InlineData(new byte[1] { 0 }, 2)]
[InlineData(new byte[1] { 0 }, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, -1)]
[InlineData(new byte[2] { 0, 0 }, 3)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue)]
public void ByteSpanSliceWithStartRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start)
{
var span = new Span<byte>(bytes);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
Span<byte> slice = span.Slice(start);
});
}
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
Assert.Throws<ArgumentOutOfRangeException>(() => { ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length); });
}
[Fact]
public void SetSpan()
{
var destination = new Span<byte>(new byte[100]);
var source = new Span<byte>(new byte[] { 1, 2, 3 });
destination.Set(source);
for(int i=0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void SetArray()
{
var destination = new Span<byte>(new byte[100]);
var source = new byte[] { 1, 2, 3 };
destination.Set(source);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void GetArray()
{
var original = new int[] { 1, 2, 3 };
ArraySegment<int> array;
Span<int> slice;
slice = new Span<int>(original, 1, 2);
unsafe
{
Assert.True(slice.TryGetArray(null, out array));
}
Assert.Equal(2, array.Array[array.Offset + 0]);
Assert.Equal(3, array.Array[array.Offset + 1]);
slice = new Span<int>(original, 0, 3);
unsafe
{
Assert.True(slice.TryGetArray(null, out array));
}
Assert.Equal(1, array.Array[array.Offset + 0]);
Assert.Equal(2, array.Array[array.Offset + 1]);
Assert.Equal(3, array.Array[array.Offset + 2]);
slice = new Span<int>(original, 0, 0);
unsafe
{
Assert.True(slice.TryGetArray(null, out array));
}
Assert.Equal(0, array.Offset);
Assert.Equal(original, array.Array);
Assert.Equal(0, array.Count);
}
}
}
| |
/*
* 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.Compute
{
using System;
using System.Collections.Generic;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests task result.
/// </summary>
public class TaskResultTest : AbstractTaskTest
{
/** Grid name. */
private static volatile string _gridName;
/// <summary>
/// Constructor.
/// </summary>
public TaskResultTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="forked">Fork flag.</param>
protected TaskResultTest(bool forked) : base(forked) { }
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestTaskResultInt()
{
TestTask<int> task = new TestTask<int>();
int res = Grid1.GetCompute().Execute(task, new Tuple<bool, int>(true, 10));
Assert.AreEqual(10, res);
res = Grid1.GetCompute().Execute(task, new Tuple<bool, int>(false, 11));
Assert.AreEqual(11, res);
}
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestTaskResultLong()
{
TestTask<long> task = new TestTask<long>();
long res = Grid1.GetCompute().Execute(task, new Tuple<bool, long>(true, 10000000000));
Assert.AreEqual(10000000000, res);
res = Grid1.GetCompute().Execute(task, new Tuple<bool, long>(false, 10000000001));
Assert.AreEqual(10000000001, res);
}
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestTaskResultFloat()
{
TestTask<float> task = new TestTask<float>();
float res = Grid1.GetCompute().Execute(task, new Tuple<bool, float>(true, 1.1f));
Assert.AreEqual(1.1f, res);
res = Grid1.GetCompute().Execute(task, new Tuple<bool, float>(false, -1.1f));
Assert.AreEqual(-1.1f, res);
}
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestTaskResultBinarizable()
{
TestTask<BinarizableResult> task = new TestTask<BinarizableResult>();
BinarizableResult val = new BinarizableResult(100);
BinarizableResult res = Grid1.GetCompute().Execute(task, new Tuple<bool, BinarizableResult>(true, val));
Assert.AreEqual(val.Val, res.Val);
val.Val = 101;
res = Grid1.GetCompute().Execute(task, new Tuple<bool, BinarizableResult>(false, val));
Assert.AreEqual(val.Val, res.Val);
}
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestTaskResultSerializable()
{
TestTask<SerializableResult> task = new TestTask<SerializableResult>();
SerializableResult val = new SerializableResult(100);
SerializableResult res = Grid1.GetCompute().Execute(task, new Tuple<bool, SerializableResult>(true, val));
Assert.AreEqual(val.Val, res.Val);
val.Val = 101;
res = Grid1.GetCompute().Execute(task, new Tuple<bool, SerializableResult>(false, val));
Assert.AreEqual(val.Val, res.Val);
}
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestTaskResultLarge()
{
TestTask<byte[]> task = new TestTask<byte[]>();
byte[] res = Grid1.GetCompute().Execute(task,
new Tuple<bool, byte[]>(true, new byte[100 * 1024]));
Assert.AreEqual(100 * 1024, res.Length);
res = Grid1.GetCompute().Execute(task, new Tuple<bool, byte[]>(false, new byte[101 * 1024]));
Assert.AreEqual(101 * 1024, res.Length);
}
/** <inheritDoc /> */
protected override ICollection<Type> GetBinaryTypes()
{
return new[]
{
typeof(BinarizableResult),
typeof(TestBinarizableJob),
typeof(BinarizableOutFunc),
typeof(BinarizableFunc)
};
}
[Test]
public void TestOutFuncResultPrimitive1()
{
ICollection<int> res = Grid1.GetCompute().Broadcast(new BinarizableOutFunc());
Assert.AreEqual(2, res.Count);
foreach (int r in res)
Assert.AreEqual(10, r);
}
[Test]
public void TestOutFuncResultPrimitive2()
{
ICollection<int> res = Grid1.GetCompute().Broadcast(new SerializableOutFunc());
Assert.AreEqual(2, res.Count);
foreach (int r in res)
Assert.AreEqual(10, r);
}
[Test]
public void TestFuncResultPrimitive1()
{
ICollection<int> res = Grid1.GetCompute().Broadcast(new BinarizableFunc(), 10);
Assert.AreEqual(2, res.Count);
foreach (int r in res)
Assert.AreEqual(11, r);
}
[Test]
public void TestFuncResultPrimitive2()
{
ICollection<int> res = Grid1.GetCompute().Broadcast(new SerializableFunc(), 10);
Assert.AreEqual(2, res.Count);
foreach (int r in res)
Assert.AreEqual(11, r);
}
interface IUserInterface<in T, out TR>
{
TR Invoke(T arg);
}
/// <summary>
/// Test function.
/// </summary>
public class BinarizableFunc : IComputeFunc<int, int>, IUserInterface<int, int>
{
int IComputeFunc<int, int>.Invoke(int arg)
{
return arg + 1;
}
int IUserInterface<int, int>.Invoke(int arg)
{
// Same signature as IComputeFunc<int, int>, but from different interface
throw new Exception("Invalid method");
}
public int Invoke(int arg)
{
// Same signature as IComputeFunc<int, int>,
// but due to explicit interface implementation this is a wrong method
throw new Exception("Invalid method");
}
}
/// <summary>
/// Test function.
/// </summary>
[Serializable]
public class SerializableFunc : IComputeFunc<int, int>
{
public int Invoke(int arg)
{
return arg + 1;
}
}
/// <summary>
/// Test function.
/// </summary>
public class BinarizableOutFunc : IComputeFunc<int>
{
public int Invoke()
{
return 10;
}
}
/// <summary>
/// Test function.
/// </summary>
[Serializable]
public class SerializableOutFunc : IComputeFunc<int>
{
public int Invoke()
{
return 10;
}
}
/// <summary>
/// Test task.
/// </summary>
public class TestTask<T> : ComputeTaskAdapter<Tuple<bool, T>, T, T>
{
/** <inheritDoc /> */
override public IDictionary<IComputeJob<T>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, T> arg)
{
_gridName = null;
Assert.AreEqual(2, subgrid.Count);
bool local = arg.Item1;
T res = arg.Item2;
var jobs = new Dictionary<IComputeJob<T>, IClusterNode>();
IComputeJob<T> job;
if (res is BinarizableResult)
{
TestBinarizableJob job0 = new TestBinarizableJob();
job0.SetArguments(res);
job = (IComputeJob<T>) job0;
}
else
{
TestJob<T> job0 = new TestJob<T>();
job0.SetArguments(res);
job = job0;
}
foreach (IClusterNode node in subgrid)
{
bool add = local ? node.IsLocal : !node.IsLocal;
if (add)
{
jobs.Add(job, node);
break;
}
}
Assert.AreEqual(1, jobs.Count);
return jobs;
}
/** <inheritDoc /> */
override public T Reduce(IList<IComputeJobResult<T>> results)
{
Assert.AreEqual(1, results.Count);
var res = results[0];
Assert.IsNull(res.Exception);
Assert.IsFalse(res.Cancelled);
Assert.IsNotNull(_gridName);
Assert.AreEqual(GridId(_gridName), res.NodeId);
var job = res.Job;
Assert.IsNotNull(job);
return res.Data;
}
}
private static Guid GridId(string gridName)
{
if (gridName.Equals(Grid1Name))
return Ignition.GetIgnite(Grid1Name).GetCluster().GetLocalNode().Id;
if (gridName.Equals(Grid2Name))
return Ignition.GetIgnite(Grid2Name).GetCluster().GetLocalNode().Id;
if (gridName.Equals(Grid3Name))
return Ignition.GetIgnite(Grid3Name).GetCluster().GetLocalNode().Id;
Assert.Fail("Failed to find grid " + gridName);
return new Guid();
}
/// <summary>
///
/// </summary>
class BinarizableResult
{
/** */
public int Val;
public BinarizableResult(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
[Serializable]
class SerializableResult
{
/** */
public int Val;
public SerializableResult(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
[Serializable]
class TestJob<T> : ComputeJobAdapter<T>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** <inheritDoc /> */
override public T Execute()
{
Assert.IsNotNull(_grid);
_gridName = _grid.Name;
T res = GetArgument<T>(0);
return res;
}
}
/// <summary>
///
/// </summary>
class TestBinarizableJob : ComputeJobAdapter<BinarizableResult>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** <inheritDoc /> */
override public BinarizableResult Execute()
{
Assert.IsNotNull(_grid);
_gridName = _grid.Name;
BinarizableResult res = GetArgument<BinarizableResult>(0);
return res;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright
// file="ReportBuilderTest.cs"
// company="Schley Andrew Kutz">
// Copyright (c) Schley Andrew Kutz. All rights reserved.
// </copyright>
// <authors>
// <author>Schley Andrew Kutz</author>
// </authors>
//------------------------------------------------------------------------------
/*******************************************************************************
* Copyright (c) 2008, Schley Andrew Kutz <sakutz@gmail.com>
* 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 Schley Andrew Kutz 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 StyleCopCmd.Core.Test
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
/// <summary>
/// Tests the ReportBuilder class.
/// </summary>
[TestFixture]
public class ReportBuilderTest
{
/// <summary>
/// Constant test name for testing the StyleCop calls
/// </summary>
private const string TestName = "StyleCopTestProject";
/// <summary>
/// The base path for testing.
/// </summary>
private static readonly string BasePath = GetTestSolutionPath();
/// <summary>
/// The solution path.
/// </summary>
private static readonly string Solution = JoinAll(BasePath, TestName + ".sln");
/// <summary>
/// The project path.
/// </summary>
private static readonly string Project = JoinAll(BasePath, TestName, TestName + ".csproj");
/// <summary>
/// The project path for wildcards
/// </summary>
private static readonly string WildCardProject = JoinAll(BasePath, TestName, TestName + "WildCard.csproj");
/// <summary>
/// The directory path for testing
/// </summary>
private static readonly string DirectoryPath = JoinAll(BasePath, TestName) + Path.DirectorySeparatorChar;
/// <summary>
/// Tests the WithSolutionFiles method.
/// </summary>
[Test]
public void WithSolutionFilesTest()
{
var report = new ReportBuilder()
.WithSolutionsFiles(new List<string>() { Solution });
var result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
}
/// <summary>
/// Solution loading but unloading a project
/// </summary>
[Test]
public void WithProjectUnload()
{
var report = new ReportBuilder()
.WithSolutionsFiles(new List<string>() { Solution })
.WithProjectUnloads(new List<string>() { TestName });
var result = ExecuteTest(report, null);
Assert.AreEqual(1, result.Count, BasePath);
Assert.AreEqual("No violations encountered", result[0]);
// Now with an unload that doesn't match
report = new ReportBuilder()
.WithSolutionsFiles(new List<string>() { Solution })
.WithProjectUnloads(new List<string>() { "non-matching-regex" });
result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
// Doesn't work against projects (or anything but solutions)
report = new ReportBuilder()
.WithProjectFiles(new List<string>() { Project })
.WithProjectUnloads(new List<string>() { TestName });
result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
}
/// <summary>
/// With multiple solution files test.
/// </summary>
[Test]
public void WithMultipleSolutionFilesTest()
{
var report = new ReportBuilder()
.WithSolutionsFiles(new List<string>() { Solution, Solution });
var result = ExecuteTest(report, null);
Assert.AreEqual(7, result.Count, BasePath);
Assert.AreEqual("16 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("AssemblyInfo.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassOne.cs"), result[3]);
Assert.IsTrue(result[4].EndsWith("ClassOne.cs"), result[4]);
Assert.IsTrue(result[5].EndsWith("ClassTwo.cs"), result[5]);
Assert.IsTrue(result[6].EndsWith("ClassTwo.cs"), result[6]);
}
/// <summary>
/// Tests with no real settings
/// </summary>
[Test]
public void WithNothingTest()
{
var report = new ReportBuilder();
var result = ExecuteTest(report, null);
Assert.AreEqual(1, result.Count, BasePath);
Assert.AreEqual("No violations encountered", result[0]);
}
/// <summary>
/// Tests the WithProjectFiles method.
/// </summary>
[Test]
public void WithProjectFilesTest()
{
var report = new ReportBuilder()
.WithProjectFiles(new List<string>() { Project });
var result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
}
/// <summary>
/// With multiple project files test.
/// </summary>
[Test]
public void WithMultipleProjectFilesTest()
{
var report = new ReportBuilder()
.WithProjectFiles(new List<string>() { Project, Project });
var result = ExecuteTest(report, null);
Assert.AreEqual(7, result.Count, BasePath);
Assert.AreEqual("16 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("AssemblyInfo.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassOne.cs"), result[3]);
Assert.IsTrue(result[4].EndsWith("ClassOne.cs"), result[4]);
Assert.IsTrue(result[5].EndsWith("ClassTwo.cs"), result[5]);
Assert.IsTrue(result[6].EndsWith("ClassTwo.cs"), result[6]);
}
/// <summary>
/// Tests the WithDirectories method.
/// </summary>
[Test]
public void WithDirectoriesTest()
{
var report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath });
var result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("3 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
}
/// <summary>
/// With multiple directories test.
/// </summary>
[Test]
public void WithMultipleDirectoriesTest()
{
var report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath, DirectoryPath });
var result = ExecuteTest(report, null);
Assert.AreEqual(3, result.Count, BasePath);
Assert.AreEqual("6 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
}
/// <summary>
/// Tests the WithFiles method.
/// </summary>
[Test]
public void WithFilesTest()
{
var report = new ReportBuilder()
.WithFiles(new List<string>() { DirectoryPath + "ClassOne.cs" });
var result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("3 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
}
/// <summary>
/// With multiple files test.
/// </summary>
[Test]
public void WithMultipleFilesTest()
{
var report = new ReportBuilder()
.WithFiles(new List<string>() { DirectoryPath + "ClassOne.cs", DirectoryPath + "SubNamespace" + Path.DirectorySeparatorChar + "ClassTwo.cs" });
var result = ExecuteTest(report, null);
Assert.AreEqual(3, result.Count, BasePath);
Assert.AreEqual("7 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassTwo.cs"), result[2]);
}
/// <summary>
/// Tests the WithIgnorePatterns method.
/// </summary>
[Test]
public void WithIgnorePatternsTest()
{
var report = new ReportBuilder()
.WithProjectFiles(new List<string>() { Project })
.WithIgnorePatterns(new List<string>() { "ClassOne" });
var result = ExecuteTest(report, null);
Assert.AreEqual(3, result.Count, BasePath);
Assert.AreEqual("5 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassTwo.cs"), result[2]);
}
/// <summary>
/// With multiple patterns test.
/// </summary>
[Test]
public void WithMultiplePatternsTest()
{
var report = new ReportBuilder()
.WithProjectFiles(new List<string>() { Project })
.WithIgnorePatterns(new List<string>() { "ClassOne", "Info" });
var result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("4 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassTwo.cs"), result[1]);
}
/// <summary>
/// Tests the WithRecursion method.
/// </summary>
[Test]
public void WithRecursionTest()
{
var report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath })
.WithRecursion();
var result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("AssemblyInfo.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
}
/// <summary>
/// Tests the WithProcessorSymbols method.
/// </summary>
[Test]
public void WithProcessorSymbolsTest()
{
var report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath })
.WithProcessorSymbols(new List<string>() { "SOMEOTHER" });
var result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("6 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
}
/// <summary>
/// With multiple symbols test.
/// </summary>
[Test]
public void WithMultipleSymbolsTest()
{
var report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath })
.WithProcessorSymbols(new List<string>() { "SOMEOTHER", "SOMECONDITIONAL" });
var result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath })
.WithProcessorSymbols(new List<string>() { "!SOMEOTHER", "SOMECONDITIONAL" });
result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("5 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath })
.WithProcessorSymbols(new List<string>() { "SOMEOTHER", "!SOMECONDITIONAL" });
result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("6 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
report = new ReportBuilder()
.WithDirectories(new List<string>() { DirectoryPath })
.WithProcessorSymbols(new List<string>() { "!SOMEOTHER", "!SOMECONDITIONAL" });
result = ExecuteTest(report, null);
Assert.AreEqual(2, result.Count, BasePath);
Assert.AreEqual("3 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("ClassOne.cs"), result[1]);
}
/// <summary>
/// Tests the WithStyleCopSettingsFile method.
/// </summary>
[Test]
public void WithStyleCopSettingsFileTest()
{
var report = new ReportBuilder()
.WithSolutionsFiles(new List<string>() { Solution })
.WithStyleCopSettingsFile(JoinAll(BasePath, "LocalSettings.Setting"));
var result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("7 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
}
/// <summary>
/// Output report test.
/// </summary>
[Test]
public void OutputReportTest()
{
var testReport = "test-output";
var testReportFull = string.Format("{0}.xml", testReport);
if (File.Exists(testReportFull))
{
File.Delete(testReportFull);
}
var report = new ReportBuilder();
ExecuteTest(report, testReport + ".xml");
Assert.IsTrue(File.Exists(testReportFull));
}
/// <summary>
/// Verbose output test
/// </summary>
[Test]
public void ViolationsTest()
{
var violationList = new List<string>();
var report = new ReportBuilder()
.WithSolutionsFiles(new List<string>() { Solution })
.WithViolationEventHandler((x, y) => { violationList.Add(((StyleCop.ViolationEventArgs)y).Message); });
ExecuteTest(report, null);
violationList = violationList.OrderBy(value => value).ToList();
Assert.AreEqual(8, violationList.Count);
Assert.AreEqual("A closing curly bracket must not be preceded by a blank line.", violationList[0]);
Assert.AreEqual("A closing curly bracket must not be preceded by a blank line.", violationList[1]);
Assert.AreEqual("All using directives must be placed inside of the namespace.", violationList[2]);
Assert.AreEqual("An opening curly bracket must not be followed by a blank line.", violationList[3]);
Assert.AreEqual("An opening curly bracket must not be followed by a blank line.", violationList[4]);
Assert.AreEqual("The class must have a documentation header.", violationList[5]);
Assert.AreEqual("The class must have a documentation header.", violationList[6]);
Assert.AreEqual("The file has no header, the header Xml is invalid, or the header is not located at the top of the file.", violationList[7]);
}
/// <summary>
/// Tests the usage of wildcards in the project file
/// </summary>
[Test]
public void WildCardTest()
{
var report = new ReportBuilder()
.WithProjectFiles(new List<string>() { WildCardProject });
var result = ExecuteTest(report, null);
Assert.AreEqual(10, result.Count, BasePath);
Assert.AreEqual("26 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("AssemblyInfo.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassOne.cs"), result[3]);
Assert.IsTrue(result[4].EndsWith("ClassOne.cs"), result[4]);
Assert.IsTrue(result[5].EndsWith("ClassOne.cs"), result[5]);
Assert.IsTrue(result[6].EndsWith("ClassOne.cs"), result[6]);
Assert.IsTrue(result[7].EndsWith("ClassTwo.cs"), result[7]);
Assert.IsTrue(result[8].EndsWith("ClassTwo.cs"), result[8]);
Assert.IsTrue(result[9].EndsWith("ClassTwo.cs"), result[9]);
}
/// <summary>
/// Checking the debug settings
/// </summary>
[Test]
public void DebugTesting()
{
var list = new List<string>();
var report = new ReportBuilder()
.WithProjectFiles(new List<string>() { WildCardProject })
.WithDebug(x => { list.Add(x); });
ExecuteTest(report, null);
Assert.IsTrue(list.Count > 0);
}
/// <summary>
/// Removing duplicates during checks
/// </summary>
[Test]
public void DedupeReportTest()
{
var report = new ReportBuilder()
.WithDedupe()
.WithProjectFiles(new List<string>() { WildCardProject });
var result = ExecuteTest(report, null);
Assert.AreEqual(4, result.Count, BasePath);
Assert.AreEqual("8 violations encountered.", result[0]);
Assert.IsTrue(result[1].EndsWith("AssemblyInfo.cs"), result[1]);
Assert.IsTrue(result[2].EndsWith("ClassOne.cs"), result[2]);
Assert.IsTrue(result[3].EndsWith("ClassTwo.cs"), result[3]);
}
/// <summary>
/// XML output
/// </summary>
[Test]
public void XmlWriterTest()
{
var report = new ReportBuilder()
.WithFiles(new List<string>() { DirectoryPath + "ClassOne.cs", DirectoryPath + "SubNamespace" + Path.DirectorySeparatorChar + "ClassTwo.cs" });
var result = new List<string>();
report.WithOutputEventHandler((x, y) => { result.Add(((StyleCop.OutputEventArgs)y).Output); });
var runner = new XmlRunner();
report.Create(runner);
// Only 1 item should be reported
Assert.AreEqual(1, result.Count, BasePath);
Assert.AreEqual("Violations were encountered.", result[0]);
}
/// <summary>
/// Getting version output information
/// </summary>
[Test]
public void GetVersionInfo()
{
var result = new List<string>();
ReportBuilder.PrintFileInformation(x => { result.Add(x); }, this.GetType());
Assert.AreEqual(5, result.Count, "Should be 4 internals + 1 given");
Assert.AreEqual(1, result.Where(x => x.StartsWith("StyleCop ")).Count());
Assert.AreEqual(1, result.Where(x => x.StartsWith("StyleCop.CSharp ")).Count());
Assert.AreEqual(1, result.Where(x => x.StartsWith("StyleCop.CSharp.Rules ")).Count());
Assert.AreEqual(1, result.Where(x => x.StartsWith("StyleCopCmd.Core ")).Count());
Assert.AreEqual(1, result.Where(x => x.StartsWith("StyleCopCmd.Core.Test ")).Count());
}
/// <summary>
/// Executes the test.
/// </summary>
/// <returns>
/// The output from StyleCop event output
/// </returns>
/// <param name='builder'>
/// Input report for testing
/// </param>
/// <param name='outputFile'>
/// Output file.
/// </param>
private static IList<string> ExecuteTest(ReportBuilder builder, string outputFile)
{
var outputList = new List<string>();
builder.WithOutputEventHandler((x, y) => { outputList.Add(((StyleCop.OutputEventArgs)y).Output); });
var runner = new ConsoleRunner();
runner.OutputFile = outputFile;
builder.Create(runner);
return outputList.OrderBy(value => value).ToList();
}
/// <summary>
/// Joins all paths into a single path
/// </summary>
/// <returns>
/// The complete path
/// </returns>
/// <param name='path'>
/// Path base.
/// </param>
/// <param name='paths'>
/// Paths to append.
/// </param>
private static string JoinAll(string path, params string[] paths)
{
string output = path;
if (paths != null && paths.Length > 0)
{
foreach (var item in paths)
{
output = Path.Combine(output, item);
}
}
return output;
}
/// <summary>
/// Gets the path to the test solution.
/// </summary>
/// <returns>
/// The path to the test solution.
/// </returns>
private static string GetTestSolutionPath()
{
var d = new DirectoryInfo(".");
// Move backwards to the root of the solution.
while (d != null)
{
// Is the solution in this directory?
if (d.GetFiles().FirstOrDefault(f => f.Extension == ".sln") !=
null)
{
break;
}
d = d.Parent;
}
var r = string.Join(
Path.DirectorySeparatorChar.ToString(),
new string[] { d.FullName, "StyleCopCmd.Core.Test", "data", TestName });
return r;
}
}
}
| |
// Original source: http://servicestack.googlecode.com/svn/trunk/Common/ServiceStack.Redis/ServiceStack.Redis/Support/OrderedDictionary.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace BitSharper.Collections.Generic
{
/// <summary>
/// Represents a generic collection of key/value pairs that are ordered independently of the key and value.
/// </summary>
/// <typeparam name="TKey">The type of the keys in the dictionary</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary</typeparam>
internal class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
{
private const int _defaultInitialCapacity = 0;
private static readonly string _keyTypeName = typeof (TKey).FullName;
private static readonly string _valueTypeName = typeof (TValue).FullName;
private static readonly bool _valueTypeIsReferenceType = !typeof (ValueType).IsAssignableFrom(typeof (TValue));
private Dictionary<TKey, TValue> _dictionary;
private List<KeyValuePair<TKey, TValue>> _list;
private readonly IEqualityComparer<TKey> _comparer;
private object _syncRoot;
private readonly int _initialCapacity;
/// <summary>
/// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class.
/// </summary>
public OrderedDictionary()
: this(_defaultInitialCapacity, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class using the specified initial capacity.
/// </summary>
/// <param name="capacity">The initial number of elements that the <see cref="OrderedDictionary{TKey,TValue}"/> can contain.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception>
public OrderedDictionary(int capacity)
: this(capacity, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class using the specified comparer.
/// </summary>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> to use when comparing keys, or <null/> to use the default <see cref="EqualityComparer{TKey}"/> for the type of the key.</param>
public OrderedDictionary(IEqualityComparer<TKey> comparer)
: this(_defaultInitialCapacity, comparer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class using the specified initial capacity and comparer.
/// </summary>
/// <param name="capacity">The initial number of elements that the <see cref="OrderedDictionary{TKey,TValue}"/> collection can contain.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> to use when comparing keys, or <null/> to use the default <see cref="EqualityComparer{TKey}"/> for the type of the key.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception>
public OrderedDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
if (0 > capacity)
throw new ArgumentOutOfRangeException("capacity", "'capacity' must be non-negative");
_initialCapacity = capacity;
_comparer = comparer;
}
/// <summary>
/// Converts the object passed as a key to the key type of the dictionary
/// </summary>
/// <param name="keyObject">The key object to check</param>
/// <returns>The key object, cast as the key type of the dictionary</returns>
/// <exception cref="ArgumentNullException"><paramref name="keyObject"/> is <null/>.</exception>
/// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="keyObject"/>.</exception>
private static TKey ConvertToKeyType(object keyObject)
{
if (keyObject == null)
{
throw new ArgumentNullException("keyObject");
}
if (!(keyObject is TKey))
{
throw new ArgumentException("'key' must be of type " + _keyTypeName, "keyObject");
}
return (TKey) keyObject;
}
/// <summary>
/// Converts the object passed as a value to the value type of the dictionary
/// </summary>
/// <param name="value">The object to convert to the value type of the dictionary</param>
/// <returns>The value object, converted to the value type of the dictionary</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is a value type.</exception>
/// <exception cref="ArgumentException">The value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="value"/>.</exception>
private static TValue ConvertToValueType(object value)
{
if (value == null)
{
if (!_valueTypeIsReferenceType)
throw new ArgumentNullException("value");
return default(TValue);
}
if (!(value is TValue))
throw new ArgumentException("'value' must be of type " + _valueTypeName, "value");
return (TValue) value;
}
/// <summary>
/// Gets the dictionary object that stores the keys and values
/// </summary>
/// <value>The dictionary object that stores the keys and values for the <see cref="OrderedDictionary{TKey,TValue}"/></value>
/// <remarks>Accessing this property will create the dictionary object if necessary</remarks>
private Dictionary<TKey, TValue> Dictionary
{
get { return _dictionary ?? (_dictionary = new Dictionary<TKey, TValue>(_initialCapacity, _comparer)); }
}
/// <summary>
/// Gets the list object that stores the key/value pairs.
/// </summary>
/// <value>The list object that stores the key/value pairs for the <see cref="OrderedDictionary{TKey,TValue}"/></value>
/// <remarks>Accessing this property will create the list object if necessary.</remarks>
private List<KeyValuePair<TKey, TValue>> List
{
get { return _list ?? (_list = new List<KeyValuePair<TKey, TValue>>(_initialCapacity)); }
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return Dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return List.GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return List.GetEnumerator();
}
/// <summary>
/// Inserts a new entry into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the specified key and value at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which the element should be inserted.</param>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add. The value can be <null/> if the type of the values in the dictionary is a reference type.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/>
/// -or-<br/>
/// <paramref name="index"/> is greater than <see cref="Count"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.</exception>
/// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/>.</exception>
public void Insert(int index, TKey key, TValue value)
{
if (index > Count || index < 0)
throw new ArgumentOutOfRangeException("index");
Dictionary.Add(key, value);
List.Insert(index, new KeyValuePair<TKey, TValue>(key, value));
}
/// <summary>
/// Removes the entry at the specified index from the <see cref="OrderedDictionary{TKey,TValue}"/> collection.
/// </summary>
/// <param name="index">The zero-based index of the entry to remove.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/>
/// -or-<br/>
/// index is equal to or greater than <see cref="Count"/>.</exception>
public void RemoveAt(int index)
{
if (index >= Count || index < 0)
throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection");
var key = List[index].Key;
List.RemoveAt(index);
Dictionary.Remove(key);
}
/// <summary>
/// Gets or sets the value at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the value to get or set.</param>
/// <value>The value of the item at the specified index.</value>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/>
/// -or-<br/>
/// index is equal to or greater than <see cref="Count"/>.</exception>
public TValue this[int index]
{
get { return List[index].Value; }
set
{
if (index >= Count || index < 0)
throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection");
var key = List[index].Key;
List[index] = new KeyValuePair<TKey, TValue>(key, value);
Dictionary[key] = value;
}
}
/// <summary>
/// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the lowest available index.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add. This value can be <null/>.</param>
/// <remarks>A key cannot be <null/>, but a value can be.
/// <para>You can also use the indexer property to add new elements by setting the value of a key that does not exist in the <see cref="OrderedDictionary{TKey,TValue}"/> collection; however, if the specified key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/>, setting the indexer property overwrites the old value. In contrast, the <see cref="Add"/> method does not modify existing elements.</para></remarks>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception>
/// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/></exception>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
Add(key, value);
}
/// <summary>
/// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the lowest available index.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add. This value can be <null/>.</param>
/// <returns>The index of the newly added entry</returns>
/// <remarks>A key cannot be <null/>, but a value can be.
/// <para>You can also use the indexer property to add new elements by setting the value of a key that does not exist in the <see cref="OrderedDictionary{TKey,TValue}"/> collection; however, if the specified key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/>, setting the indexer property overwrites the old value. In contrast, the <see cref="Add"/> method does not modify existing elements.</para></remarks>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception>
/// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/></exception>
public int Add(TKey key, TValue value)
{
Dictionary.Add(key, value);
List.Add(new KeyValuePair<TKey, TValue>(key, value));
return Count - 1;
}
/// <summary>
/// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the lowest available index.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add. This value can be <null/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.<br/>
/// -or-<br/>
/// <paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is a value type.</exception>
/// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="key"/>.<br/>
/// -or-<br/>
/// The value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="value"/>.</exception>
void IDictionary.Add(object key, object value)
{
Add(ConvertToKeyType(key), ConvertToValueType(value));
}
/// <summary>
/// Removes all elements from the <see cref="OrderedDictionary{TKey,TValue}"/> collection.
/// </summary>
/// <remarks>The capacity is not changed as a result of calling this method.</remarks>
public void Clear()
{
Dictionary.Clear();
List.Clear();
}
/// <summary>
/// Determines whether the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</param>
/// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains an element with the specified key; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception>
public bool ContainsKey(TKey key)
{
return Dictionary.ContainsKey(key);
}
/// <summary>
/// Determines whether the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</param>
/// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains an element with the specified key; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception>
/// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="key"/>.</exception>
bool IDictionary.Contains(object key)
{
return ContainsKey(ConvertToKeyType(key));
}
/// <summary>
/// Gets a value indicating whether the <see cref="OrderedDictionary{TKey,TValue}"/> has a fixed size.
/// </summary>
/// <value><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> has a fixed size; otherwise, <see langword="false"/>. The default is <see langword="false"/>.</value>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="OrderedDictionary{TKey,TValue}"/> collection is read-only.
/// </summary>
/// <value><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> is read-only; otherwise, <see langword="false"/>. The default is <see langword="false"/>.</value>
/// <remarks>
/// A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created.
/// <para>A collection that is read-only is simply a collection with a wrapper that prevents modification of the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.</para>
/// </remarks>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="ICollection"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>.
/// </summary>
/// <value>An <see cref="ICollection"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>.</value>
/// <remarks>The returned <see cref="ICollection"/> object is not a static copy; instead, the collection refers back to the keys in the original <see cref="OrderedDictionary{TKey,TValue}"/>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the key collection.</remarks>
ICollection IDictionary.Keys
{
get { return (ICollection) Keys; }
}
/// <summary>
/// Returns the zero-based index of the specified key in the <see cref="OrderedDictionary{TKey,TValue}"/>
/// </summary>
/// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}"/></param>
/// <returns>The zero-based index of <paramref name="key"/>, if <paramref name="key"/> is found in the <see cref="OrderedDictionary{TKey,TValue}"/>; otherwise, -1</returns>
/// <remarks>This method performs a linear search; therefore it has a cost of O(n) at worst.</remarks>
public int IndexOfKey(TKey key)
{
if (Equals(key, default (TKey)))
throw new ArgumentNullException("key");
for (var index = 0; index < List.Count; index++)
{
var entry = List[index];
var next = entry.Key;
if (null != _comparer)
{
if (_comparer.Equals(next, key))
{
return index;
}
}
else if (next.Equals(key))
{
return index;
}
}
return -1;
}
/// <summary>
/// Removes the entry with the specified key from the <see cref="OrderedDictionary{TKey,TValue}"/> collection.
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <returns><see langword="true"/> if the key was found and the corresponding element was removed; otherwise, <see langword="false"/></returns>
public bool Remove(TKey key)
{
if (Equals(key, default(TKey)))
throw new ArgumentNullException("key");
var index = IndexOfKey(key);
if (index >= 0)
{
if (Dictionary.Remove(key))
{
List.RemoveAt(index);
return true;
}
}
return false;
}
/// <summary>
/// Removes the entry with the specified key from the <see cref="OrderedDictionary{TKey,TValue}"/> collection.
/// </summary>
/// <param name="key">The key of the entry to remove</param>
void IDictionary.Remove(object key)
{
Remove(ConvertToKeyType(key));
}
/// <summary>
/// Gets an <see cref="ICollection"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.
/// </summary>
/// <value>An <see cref="ICollection"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</value>
/// <remarks>The returned <see cref="ICollection"/> object is not a static copy; instead, the <see cref="ICollection"/> refers back to the values in the original <see cref="OrderedDictionary{TKey,TValue}"/> collection. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the <see cref="ICollection"/>.</remarks>
ICollection IDictionary.Values
{
get { return (ICollection) Values; }
}
/// <summary>
/// Gets or sets the value with the specified key.
/// </summary>
/// <param name="key">The key of the value to get or set.</param>
/// <value>The value associated with the specified key. If the specified key is not found, attempting to get it returns <null/>, and attempting to set it creates a new element using the specified key.</value>
public TValue this[TKey key]
{
get { return Dictionary[key]; }
set
{
if (Dictionary.ContainsKey(key))
{
Dictionary[key] = value;
List[IndexOfKey(key)] = new KeyValuePair<TKey, TValue>(key, value);
}
else
{
Add(key, value);
}
}
}
/// <summary>
/// Gets or sets the value with the specified key.
/// </summary>
/// <param name="key">The key of the value to get or set.</param>
/// <value>The value associated with the specified key. If the specified key is not found, attempting to get it returns <null/>, and attempting to set it creates a new element using the specified key.</value>
object IDictionary.this[object key]
{
get { return this[ConvertToKeyType(key)]; }
set { this[ConvertToKeyType(key)] = ConvertToValueType(value); }
}
/// <summary>
/// Copies the elements of the <see cref="OrderedDictionary{TKey,TValue}"/> elements to a one-dimensional Array object at the specified index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> object that is the destination of the <see cref="KeyValuePair{TKey,TValue}"/> objects copied from the <see cref="OrderedDictionary{TKey,TValue}"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <remarks>The <see cref="ICollection.CopyTo(Array,int)"/> method preserves the order of the elements in the <see cref="OrderedDictionary{TKey,TValue}"/></remarks>
void ICollection.CopyTo(Array array, int index)
{
((ICollection) List).CopyTo(array, index);
}
/// <summary>
/// Gets the number of key/values pairs contained in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.
/// </summary>
/// <value>The number of key/value pairs contained in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</value>
public int Count
{
get { return List.Count; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="OrderedDictionary{TKey,TValue}"/> object is synchronized (thread-safe).
/// </summary>
/// <value>This method always returns false.</value>
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="OrderedDictionary{TKey,TValue}"/> object.
/// </summary>
/// <value>An object that can be used to synchronize access to the <see cref="OrderedDictionary{TKey,TValue}"/> object.</value>
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
/// <summary>
/// Gets an <see cref="System.Collections.Generic.ICollection{TKey}"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>.
/// </summary>
/// <value>An <see cref="System.Collections.Generic.ICollection{TKey}"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>.</value>
/// <remarks>The returned <see cref="System.Collections.Generic.ICollection{TKey}"/> object is not a static copy; instead, the collection refers back to the keys in the original <see cref="OrderedDictionary{TKey,TValue}"/>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the key collection.</remarks>
public ICollection<TKey> Keys
{
get { return Dictionary.Keys; }
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of <paramref name="value"/>. This parameter can be passed uninitialized.</param>
/// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> contains an element with the specified key; otherwise, <see langword="false"/>.</returns>
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Gets an <see cref="ICollection{TValue}"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/>.
/// </summary>
/// <value>An <see cref="ICollection{TValue}"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/>.</value>
/// <remarks>The returned <see cref="ICollection{TValue}"/> object is not a static copy; instead, the collection refers back to the values in the original <see cref="OrderedDictionary{TKey,TValue}"/>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the value collection.</remarks>
public ICollection<TValue> Values
{
get { return Dictionary.Values; }
}
/// <summary>
/// Adds the specified value to the <see cref="OrderedDictionary{TKey,TValue}"/> with the specified key.
/// </summary>
/// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> structure representing the key and value to add to the <see cref="OrderedDictionary{TKey,TValue}"/>.</param>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
/// <summary>
/// Determines whether the <see cref="OrderedDictionary{TKey,TValue}"/> contains a specific key and value.
/// </summary>
/// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> structure to locate in the <see cref="OrderedDictionary{TKey,TValue}"/>.</param>
/// <returns><see langword="true"/> if <paramref name="item"/> is found in the <see cref="OrderedDictionary{TKey,TValue}"/>; otherwise, <see langword="false"/>.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<TKey, TValue>>) Dictionary).Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="OrderedDictionary{TKey,TValue}"/> to an array of type <see cref="KeyValuePair{TKey,TValue}"/>, starting at the specified index.
/// </summary>
/// <param name="array">The one-dimensional array of type <see cref="KeyValuePair{TKey,TValue}"/> that is the destination of the <see cref="KeyValuePair{TKey,TValue}"/> elements copied from the <see cref="OrderedDictionary{TKey,TValue}"/>. The array must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, TValue>>) Dictionary).CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes a key and value from the dictionary.
/// </summary>
/// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> structure representing the key and value to remove from the <see cref="OrderedDictionary{TKey,TValue}"/>.</param>
/// <returns><see langword="true"/> if the key and value represented by <paramref name="item"/> is successfully found and removed; otherwise, <see langword="false"/>. This method returns <see langword="false"/> if <paramref name="item"/> is not found in the <see cref="OrderedDictionary{TKey,TValue}"/>.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
return Remove(item.Key);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
using Point = Microsoft.Xna.Framework.Point;
using Color = Microsoft.Xna.Framework.Color;
using System.Runtime.InteropServices;
namespace FlatRedBall.Graphics.Texture
{
public partial class ImageData
{
#region Fields
private int width;
private int height;
#if FRB_XNA
// default to color, but could be something else when calling
// This isn't use dI don't think...
//SurfaceFormat surfaceFormat = SurfaceFormat.Color;
#endif
// if SurfaceFormat.Color, use these
private Color[] mData;
static Color[] mStaticData = new Color[128 * 128];
// if SurfaceFormat.DXT3, use these
private byte[] mByteData;
#endregion
#region Properties
public int Width
{
get
{
return width;
}
}
public int Height
{
get
{
return height;
}
}
public Color[] Data
{
get
{
return mData;
}
}
#endregion
#region Methods
#region Constructor
public ImageData(int width, int height)
: this(width, height, new Color[width * height])
{
}
public ImageData(int width, int height, Color[] data)
{
this.width = width;
this.height = height;
this.mData = data;
}
public ImageData(int width, int height, byte[] data)
{
this.width = width;
this.height = height;
this.mByteData = data;
}
#endregion
#region Public Static Methods
public static ImageData FromTexture2D(Texture2D texture2D)
{
#if DEBUG
if (texture2D.IsDisposed)
{
throw new Exception("The texture by the name " + texture2D.Name + " is disposed, so its data can't be accessed");
}
#endif
ImageData imageData = null;
// Might need to make this FRB MDX as well.
#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
switch (texture2D.Format)
{
#if !XNA4 && !MONOGAME
case SurfaceFormat.Bgr32:
{
Color[] data = new Color[texture2D.Width * texture2D.Height];
texture2D.GetData<Color>(data);
// BRG doesn't have alpha, so we'll assume an alpha of 1:
for (int i = 0; i < data.Length; i++)
{
data[i].A = 255;
}
imageData = new ImageData(
texture2D.Width, texture2D.Height, data);
}
break;
#endif
case SurfaceFormat.Color:
{
Color[] data = new Color[texture2D.Width * texture2D.Height];
texture2D.GetData<Color>(data);
imageData = new ImageData(
texture2D.Width, texture2D.Height, data);
}
break;
case SurfaceFormat.Dxt3:
Byte[] byteData = new byte[texture2D.Width * texture2D.Height];
texture2D.GetData<byte>(byteData);
imageData = new ImageData(texture2D.Width, texture2D.Height, byteData);
break;
default:
throw new NotImplementedException("The format " + texture2D.Format + " isn't supported.");
//break;
}
#endif
return imageData;
}
#endregion
#region Public Methods
public void ApplyColorOperation(ColorOperation colorOperation, float red, float green, float blue, float alpha)
{
Color appliedColor;
#if FRB_MDX
// passed values from MDX will be 0-255 instead of 0-1 so we simply cast into a byte (Justin 5/15/2012)
appliedColor = Color.FromArgb(
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(alpha),
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(red),
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(green),
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(blue)
);
#else
// passed values from XNA will be 0-1, use the float constructor to create a color object (Justin 5/15/2012)
appliedColor = new Color(red, green, blue, alpha);
#endif
ApplyColorOperation(colorOperation, appliedColor);
}
public void ApplyColorOperation(ColorOperation colorOperation, Color appliedColor)
{
Color baseColor;
switch (colorOperation)
{
case ColorOperation.Add:
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < height; y++)
{
baseColor = GetPixelColor(x, y);
#if FRB_MDX
// System.Drawing.Color doesn't have setters for A, R, G, B
// so we have to do it a more inefficient way in FRB MDX
Color combinedColor = Color.FromArgb(
baseColor.A,
(byte)System.Math.Min((baseColor.R + appliedColor.R), 255),
(byte)System.Math.Min((baseColor.G + appliedColor.G), 255),
(byte)System.Math.Min((baseColor.B + appliedColor.B), 255));
baseColor = combinedColor;
#elif XNA4
baseColor.R = (byte)(System.Math.Min((baseColor.R + appliedColor.R), 255) * baseColor.A / 255);
baseColor.G = (byte)(System.Math.Min((baseColor.G + appliedColor.G), 255) * baseColor.A / 255);
baseColor.B = (byte)(System.Math.Min((baseColor.B + appliedColor.B), 255) * baseColor.A / 255);
#else
baseColor.R = (byte)System.Math.Min((baseColor.R + appliedColor.R), 255);
baseColor.G = (byte)System.Math.Min((baseColor.G + appliedColor.G), 255);
baseColor.B = (byte)System.Math.Min((baseColor.B + appliedColor.B), 255);
#endif
SetPixel(x, y, baseColor);
}
}
break;
case ColorOperation.Modulate:
// Justin Johnson - May 15, 2012 - pre-multiply so we don't calculate every iteration (Justin 5/15/2012)
float red = appliedColor.R / 255f;
float green = appliedColor.G / 255f;
float blue = appliedColor.B / 255f;
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < height; y++)
{
baseColor = GetPixelColor(x, y);
#if FRB_MDX
// System.Drawing.Color doesn't have setters for A, R, G, B
// so we have to do it a more inefficient way in FRB MDX
Color combinedColor = Color.FromArgb(
baseColor.A,
(byte)(baseColor.R * red),
(byte)(baseColor.G * green),
(byte)(baseColor.B * blue));
baseColor = combinedColor;
#else
baseColor.R = (byte)(baseColor.R * red);
baseColor.G = (byte)(baseColor.G * green);
baseColor.B = (byte)(baseColor.B * blue);
#endif
SetPixel(x, y, baseColor);
}
}
break;
case ColorOperation.Texture:
// no-op
break;
default:
throw new NotImplementedException();
}
}
public void Blit(Texture2D source, Rectangle sourceRectangle, Point destination)
{
ImageData sourceAsImageData = ImageData.FromTexture2D(source);
Blit(sourceAsImageData, sourceRectangle, destination);
}
public void Blit(ImageData source, Rectangle sourceRectangle, Point destination)
{
for (int y = 0; y < sourceRectangle.Height; y++)
{
for (int x = 0; x < sourceRectangle.Width; x++)
{
int sourceX = x + sourceRectangle.X;
int sourceY = y + sourceRectangle.Y;
int destinationX = x + destination.X;
int destinationY = y + destination.Y;
this.SetPixel(destinationX, destinationY, source.GetPixelColor(sourceX, sourceY));
}
}
}
#if !FRB_MDX
public void CopyFrom(Texture2D texture2D)
{
texture2D.GetData<Color>(mData, 0, texture2D.Width * texture2D.Height);
}
#endif
public void CopyTo(ImageData destination, int xOffset, int yOffset)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
destination.mData[(y + yOffset) * destination.width + (x + xOffset)] = this.mData[y * width + x];
}
}
}
public void ExpandIfNecessary(int desiredWidth, int desiredHeight)
{
if (desiredWidth * desiredHeight > mData.Length)
{
SetDataDimensions(desiredWidth, desiredHeight);
}
}
public void Fill(Color fillColor)
{
int length = Data.Length;
for (int i = 0; i < length; i++)
{
Data[i] = fillColor;
}
}
public void Fill(Color fillColor, Rectangle rectangle)
{
for (int y = 0; y < rectangle.Height; y++)
{
for (int x = 0; x < rectangle.Width; x++)
{
SetPixel(rectangle.X + x, rectangle.Y + y, fillColor);
}
}
}
public void FlipHorizontal()
{
int halfWidth = width / 2;
int widthMinusOne = width - 1;
// This currently assumes Color. Update to use DXT.
for (int x = 0; x < halfWidth; x++)
{
for (int y = 0; y < height; y++)
{
Color temp = mData[x + y * Width];
mData[x + y * width] = mData[(widthMinusOne - x) + y * width];
mData[widthMinusOne - x + y * width] = temp;
}
}
}
public void FlipVertical()
{
int halfHeight = height / 2;
int heightMinusOne = height - 1;
// This currently assumes Color. Update to use DXT.
for (int x = 0; x < width; x++)
{
for (int y = 0; y < halfHeight; y++)
{
Color temp = mData[x + y * Width];
mData[x + y * width] = mData[x + (heightMinusOne - y) * width];
mData[x + (heightMinusOne - y) * width] = temp;
}
}
}
public Color GetPixelColor(int x, int y)
{
return this.Data[x + y * Width];
}
public void GetXAndY(int absoluteIndex, out int x, out int y)
{
y = absoluteIndex / this.Width;
x = absoluteIndex % width;
}
public void RemoveColumn(int columnToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
int newWidth = width - 1;
for (int y = 0; y < height; y++)
{
destinationX = 0;
for (int x = 0; x < width; x++)
{
if (x == columnToRemove)
{
continue;
}
newData[destinationY * newWidth + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
width = newWidth;
mData = newData;
}
public void RemoveColumns(IList<int> columnsToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
int newWidth = width - columnsToRemove.Count;
for (int y = 0; y < height; y++)
{
destinationX = 0;
for (int x = 0; x < width; x++)
{
if (columnsToRemove.Contains(x))
{
continue;
}
newData[destinationY * newWidth + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
width = newWidth;
mData = newData;
}
#region XML Docs
/// <summary>
/// Removes the index row from the contained data. Row 0 is the top of the texture.
/// </summary>
/// <param name="rowToRemove">The index of the row to remove. Index 0 is the top row.</param>
#endregion
public void RemoveRow(int rowToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
for (int y = 0; y < height; y++)
{
if (y == rowToRemove)
{
continue;
}
destinationX = 0;
for (int x = 0; x < width; x++)
{
newData[destinationY * width + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
height--;
mData = newData;
}
public void RemoveRows(IList<int> rowsToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
for (int y = 0; y < height; y++)
{
if (rowsToRemove.Contains(y))
{
continue;
}
destinationX = 0;
for (int x = 0; x < width; x++)
{
newData[destinationY * width + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
height -= rowsToRemove.Count;
mData = newData;
}
public void Replace(Color oldColor, Color newColor)
{
for (int i = 0; i < mData.Length; i++)
{
if (mData[i] == oldColor)
{
mData[i] = newColor;
}
}
}
public void RotateClockwise90()
{
Color[] newData = new Color[width * height];
int newWidth = height;
int newHeight = width;
int xToPullFrom;
int yToPullFrom;
for (int x = 0; x < newWidth; x++)
{
for (int y = 0; y < newHeight; y++)
{
xToPullFrom = newHeight - 1 - y;
yToPullFrom = x;
newData[y * newWidth + x] =
mData[yToPullFrom * width + xToPullFrom];
}
}
width = newWidth;
height = newHeight;
mData = newData;
}
public void SetDataDimensions(int desiredWidth, int desiredHeight)
{
mData = new Color[desiredHeight * desiredWidth];
width = desiredWidth;
height = desiredHeight;
}
public void SetPixel(int x, int y, Color color)
{
Data[y * width + x] = color;
}
public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D()
{
return ToTexture2D(true, FlatRedBallServices.GraphicsDevice);
}
public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(bool generateMipmaps)
{
return ToTexture2D(generateMipmaps, FlatRedBallServices.GraphicsDevice);
}
public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(bool generateMipmaps, GraphicsDevice graphicsDevice)
{
int textureWidth = Width;
int textureHeight = Height;
#if FRB_MDX
if (!Math.MathFunctions.IsPowerOfTwo(textureWidth) ||
!Math.MathFunctions.IsPowerOfTwo(textureHeight))
{
if (graphicsDevice.DeviceCaps.TextureCaps.SupportsPower2)
{
textureHeight = Math.MathFunctions.NextPowerOfTwo(textureHeight);
textureWidth = Math.MathFunctions.NextPowerOfTwo(textureWidth);
}
}
#endif
if (textureWidth != Width || textureHeight != Height)
{
float ratioX = width / (float)textureWidth;
float ratioY = height / (float)textureHeight;
if (textureHeight * textureWidth > mStaticData.Length)
{
mStaticData = new Color[textureHeight * textureWidth];
}
for (int y = 0; y < textureHeight; y++)
{
for (int x = 0; x < textureWidth; x++)
{
//try
{
int sourcePixelX = (int)(x * ratioX);
int sourcePixelY = (int)(y * ratioY);
// temporary for testing
mStaticData[y * textureWidth + x] =
mData[((int)(sourcePixelY * Width) + (int)(sourcePixelX))];
}
//catch
//{
// int m = 3;
//}
}
}
#if FRB_MDX
// Even though the texture's bigger, give it a smaller size so that
// pixel size stuff works right.
Microsoft.Xna.Framework.Graphics.Texture2D textureToReturn = ToTexture2D(mStaticData, textureWidth, textureHeight);
textureToReturn.Width = Width;
textureToReturn.Height = Height;
return textureToReturn;
#else
return ToTexture2D(mStaticData, textureWidth, textureHeight, generateMipmaps, graphicsDevice);
#endif
}
else
{
return ToTexture2D(mData, textureWidth, textureHeight, generateMipmaps, graphicsDevice);
}
}
#if !FRB_MDX
public void ToTexture2D(Texture2D textureToFill)
{
lock (Renderer.Graphics.GraphicsDevice)
{
// If it's disposed that means that the user is exiting the game, so we shouldn't
// do anything
#if !SILVERLIGHT
if (!Renderer.Graphics.GraphicsDevice.IsDisposed)
#endif
{
#if XNA4 && !MONOGAME
textureToFill.SetData<Color>(this.mData, 0, textureToFill.Width * textureToFill.Height);
#else
textureToFill.SetData<Color>(this.mData);
#endif
}
}
}
#endif
#endregion
#region Internal Methods
#if !FRB_MDX
internal void MakePremultiplied()
{
MakePremultiplied(mData.Length);
}
internal void MakePremultiplied(int count)
{
for (int i = count - 1; i > -1; i--)
{
Color color = mData[i];
float multiplier = color.A / 255.0f;
color.R = (byte)(color.R * multiplier);
color.B = (byte)(color.B * multiplier);
color.G = (byte)(color.G * multiplier);
mData[i] = color;
}
}
#endif
internal static Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(Color[] pixelData, int textureWidth, int textureHeight)
{
return ToTexture2D(pixelData, textureWidth, textureHeight, true, FlatRedBallServices.GraphicsDevice);
}
internal static Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(Color[] pixelData, int textureWidth, int textureHeight, bool generateMipmaps, GraphicsDevice graphicsDevice)
{
#if FRB_XNA
// Justin Johnson - May 18, 2012 - Added XNA support for mipmap creation on generated textures
int mipLevelWidth;
int mipLevelHeight;
int mipTotalPixels;
int mipYCoordinate;
int mipXCoordinate;
int sourceXCoordinate;
int sourceYCoordinate;
int sourcePixelIndex;
Color[] mipLevelData;
#if XNA4
Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight, generateMipmaps, SurfaceFormat.Color);
#else
// Victor Chelaru
// May 22, 2011
// Not sure what the
// additional arguments
// should be here, but the
// code wasn't compiling with
// the code as written for XNA4.
// So I removed soem of the args to
// make it compile - we probably don't
// care as much for XNA 3.1 since 4.0 is
// the newest.
Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight);
#endif
// creates texture for each mipmap level (level count defined automatically)
if (generateMipmaps)
{
for (int i = 0; i < texture.LevelCount; i++)
{
if (i == 0)
{
mipLevelData = pixelData;
}
else
{
// Scale previous texture to 50% size
// Since mipmaps are usually blended, interpolation is not necessary: point sampling only for speed
mipLevelWidth = textureWidth / 2;
mipLevelWidth = System.Math.Max(mipLevelWidth, 1);
mipLevelHeight = textureHeight / 2;
mipLevelHeight = System.Math.Max(mipLevelHeight, 1);
mipTotalPixels = mipLevelWidth * mipLevelHeight;
mipLevelData = new Color[mipTotalPixels];
for (int mipPixelIndex = 0; mipPixelIndex < mipTotalPixels; mipPixelIndex++)
{
mipYCoordinate = (int)System.Math.Floor(mipPixelIndex / (double)mipLevelWidth);
mipXCoordinate = mipPixelIndex - (mipYCoordinate * mipLevelWidth);
sourceYCoordinate = mipYCoordinate * 2;
sourceXCoordinate = mipXCoordinate * 2;
sourcePixelIndex = System.Math.Min(sourceYCoordinate * textureWidth + sourceXCoordinate, pixelData.Length - 1);
mipLevelData[mipPixelIndex] = pixelData[sourcePixelIndex];
}
pixelData = mipLevelData;
textureWidth = mipLevelWidth;
textureHeight = mipLevelHeight;
}
#if (XNA4) || WINDOWS_8
texture.SetData<Color>(i, null, mipLevelData, 0, mipLevelData.Length);
#else
texture.SetData<Color>(i, null, mipLevelData, 0, mipLevelData.Length, SetDataOptions.Discard);
#endif
}
}
else
{
texture.SetData<Color>(pixelData);
}
#elif FRB_MDX
// Justin Johnson - May 18, 2012 - I did not change this at all when I updated this method
if (textureHeight > FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureHeight ||
textureWidth > FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureWidth)
{
throw new InvalidOperationException("The resolution of the to-be-created Texture2D " +
"is too large. The desired resolution is " + textureWidth + " by " + textureHeight + "." +
"The largest supported resolution is " +
FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureWidth + " by " +
FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureHeight + ".");
}
Microsoft.Xna.Framework.Graphics.Texture2D texture = new Microsoft.Xna.Framework.Graphics.Texture2D();
texture.texture = new Microsoft.DirectX.Direct3D.Texture(
FlatRedBallServices.GraphicsDevice,
textureWidth,
textureHeight,
0,
0,
Microsoft.DirectX.Direct3D.Format.A8R8G8B8,
Microsoft.DirectX.Direct3D.Pool.Managed);
texture.Width = textureWidth;
texture.Height = textureHeight;
uint[,] textureData = (uint[,])texture.texture.LockRectangle(
typeof(uint),
0,
Microsoft.DirectX.Direct3D.LockFlags.None,
textureWidth, textureHeight);
int pixelY = 0;
for (int pixelX = 0; pixelX < textureWidth; pixelX++)
{
for (pixelY = 0; pixelY < textureHeight; pixelY++)
{
// Vic says: I used to have the mData line say:
// mData[pixelY * width + pixelX]... but that didn't
// work I inverted it and it works fine now. Not sure
// why, but this works so oh well.
textureData[pixelX, pixelY] = (uint)
pixelData[pixelX * textureHeight + pixelY].ToArgb();
}
}
texture.texture.UnlockRectangle(0);
#else
// Justin Johnson - May 18, 2012 - not sure if any other devices support mipmapping and to what level. Fall back to no mipmaps
Texture2D texture = new Texture2D(FlatRedBallServices.GraphicsDevice, textureWidth, textureHeight);
texture.SetData<Color>(pixelData);
#endif
return texture;
}
#endregion
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Client;
namespace OpenSim.Tests.Common
{
public class TestClient : IClientAPI, IClientCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
private Scene m_scene;
// Properties so that we can get at received data for test purposes
public List<uint> ReceivedKills { get; private set; }
public List<UUID> ReceivedOfflineNotifications { get; private set; }
public List<UUID> ReceivedOnlineNotifications { get; private set; }
public List<UUID> ReceivedFriendshipTerminations { get; private set; }
public List<ImageDataPacket> SentImageDataPackets { get; private set; }
public List<ImagePacketPacket> SentImagePacketPackets { get; private set; }
public List<ImageNotInDatabasePacket> SentImageNotInDatabasePackets { get; private set; }
// Test client specific events - for use by tests to implement some IClientAPI behaviour.
public event Action<RegionInfo, Vector3, Vector3> OnReceivedMoveAgentIntoRegion;
public event Action<ulong, IPEndPoint> OnTestClientInformClientOfNeighbour;
public event TestClientOnSendRegionTeleportDelegate OnTestClientSendRegionTeleport;
public event Action<ISceneEntity, PrimUpdateFlags> OnReceivedEntityUpdate;
public event OnReceivedChatMessageDelegate OnReceivedChatMessage;
public event Action<GridInstantMessage> OnReceivedInstantMessage;
public event Action<UUID> OnReceivedSendRebakeAvatarTextures;
public delegate void TestClientOnSendRegionTeleportDelegate(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL);
public delegate void OnReceivedChatMessageDelegate(
string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, UUID ownerID, byte source, byte audible);
// disable warning: public events, part of the public API
#pragma warning disable 67
public event Action<IClientAPI> OnLogout;
public event ObjectPermissions OnObjectPermissions;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event ParcelBuy OnParcelBuy;
public event Action<IClientAPI> OnConnectionClosed;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event TeleportCancel OnTeleportCancel;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event SetAlwaysRun OnSetAlwaysRun;
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall1 OnRequestWearables;
public event Action<IClientAPI, bool> OnCompleteMovementToRegion;
public event UpdateAgent OnPreAgentUpdate;
public event UpdateAgent OnAgentUpdate;
public event UpdateAgent OnAgentCameraUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event ViewerEffectEventHandler OnViewerEffect;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event ObjectSelect OnObjectSelect;
public event ObjectRequest OnObjectRequest;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVector OnUpdatePrimGroupPosition;
public event UpdateVector OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<UUID> OnRemoveAvatar;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event GenericMessage OnGenericMessage;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event ObjectDeselect OnObjectDeselect;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event EstateChangeInfo OnEstateChangeInfo;
public event EstateManageTelehub OnEstateManageTelehub;
public event CachedTextureRequest OnCachedTextureRequest;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event Action<Vector3, bool, bool> OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event ActivateGesture OnActivateGesture;
public event DeactivateGesture OnDeactivateGesture;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event AvatarInterestUpdate OnAvatarInterestUpdate;
public event PlacesQuery OnPlacesQuery;
public event FindAgentUpdate OnFindAgent;
public event TrackAgentUpdate OnTrackAgent;
public event NewUserReport OnUserReport;
public event SaveStateHandler OnSaveState;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event ParcelBuyPass OnParcelBuyPass;
public event ParcelGodMark OnParcelGodMark;
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SendPostcard OnSendPostcard;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event GodlikeMessage onGodlikeMessage;
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
#pragma warning restore 67
/// <value>
/// This agent's UUID
/// </value>
private UUID m_agentId;
public ISceneAgent SceneAgent { get; set; }
/// <value>
/// The last caps seed url that this client was given.
/// </value>
public string CapsSeedUrl;
private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2);
public virtual Vector3 StartPos
{
get { return startPos; }
set { }
}
public virtual UUID AgentId
{
get { return m_agentId; }
}
public UUID SessionId { get; set; }
public UUID SecureSessionId { get; set; }
public virtual string FirstName
{
get { return m_firstName; }
}
private string m_firstName;
public virtual string LastName
{
get { return m_lastName; }
}
private string m_lastName;
public virtual String Name
{
get { return FirstName + " " + LastName; }
}
public bool IsActive
{
get { return true; }
set { }
}
public bool IsLoggingOut { get; set; }
public UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return String.Empty; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public bool IsGroupMember(UUID groupID)
{
return false;
}
public ulong GetGroupPowers(UUID groupID)
{
return 0;
}
public virtual int NextAnimationSequenceNumber
{
get { return 1; }
}
public IScene Scene
{
get { return m_scene; }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
private uint m_circuitCode;
public uint CircuitCode
{
get { return m_circuitCode; }
set { m_circuitCode = value; }
}
public IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="agentData"></param>
/// <param name="scene"></param>
/// <param name="sceneManager"></param>
public TestClient(AgentCircuitData agentData, Scene scene)
{
m_agentId = agentData.AgentID;
m_firstName = agentData.firstname;
m_lastName = agentData.lastname;
m_circuitCode = agentData.circuitcode;
m_scene = scene;
SessionId = agentData.SessionID;
SecureSessionId = agentData.SecureSessionID;
CapsSeedUrl = agentData.CapsPath;
ReceivedKills = new List<uint>();
ReceivedOfflineNotifications = new List<UUID>();
ReceivedOnlineNotifications = new List<UUID>();
ReceivedFriendshipTerminations = new List<UUID>();
SentImageDataPackets = new List<ImageDataPacket>();
SentImagePacketPackets = new List<ImagePacketPacket>();
SentImageNotInDatabasePackets = new List<ImageNotInDatabasePacket>();
}
/// <summary>
/// Trigger chat coming from this connection.
/// </summary>
/// <param name="channel"></param>
/// <param name="type"></param>
/// <param name="message"></param>
public bool Chat(int channel, ChatTypeEnum type, string message)
{
ChatMessage handlerChatFromClient = OnChatFromClient;
if (handlerChatFromClient != null)
{
OSChatMessage args = new OSChatMessage();
args.Channel = channel;
args.From = Name;
args.Message = message;
args.Type = type;
args.Scene = Scene;
args.Sender = this;
args.SenderUUID = AgentId;
handlerChatFromClient(this, args);
}
return true;
}
/// <summary>
/// Attempt a teleport to the given region.
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt)
{
OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16);
}
public void CompleteMovement()
{
if (OnCompleteMovementToRegion != null)
OnCompleteMovementToRegion(this, true);
}
/// <summary>
/// Emulate sending an IM from the viewer to the simulator.
/// </summary>
/// <param name='im'></param>
public void HandleImprovedInstantMessage(GridInstantMessage im)
{
ImprovedInstantMessage handlerInstantMessage = OnInstantMessage;
if (handlerInstantMessage != null)
handlerInstantMessage(this, im);
}
public virtual void ActivateGesture(UUID assetId, UUID gestureId)
{
}
public virtual void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List<CachedTextureResponseArg> cachedTextures)
{
}
public virtual void Kick(string message)
{
}
public virtual void SendStartPingCheck(byte seq)
{
}
public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public virtual void SendKillObject(List<uint> localID)
{
ReceivedKills.AddRange(localID);
}
public virtual void SetChildAgentThrottle(byte[] throttle)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
}
public virtual void SendChatMessage(
string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, UUID ownerID, byte source, byte audible)
{
// Console.WriteLine("mmm {0} {1} {2}", message, Name, AgentId);
if (OnReceivedChatMessage != null)
OnReceivedChatMessage(message, type, fromPos, fromName, fromAgentID, ownerID, source, audible);
}
public void SendInstantMessage(GridInstantMessage im)
{
if (OnReceivedInstantMessage != null)
OnReceivedInstantMessage(im);
}
public void SendGenericMessage(string method, UUID invoice, List<string> message)
{
}
public void SendGenericMessage(string method, UUID invoice, List<byte[]> message)
{
}
public virtual void SendLayerData(float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map, bool track)
{
}
public virtual void SendWindData(Vector2[] windSpeeds) { }
public virtual void SendCloudData(float[] cloudCover) { }
public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
if (OnReceivedMoveAgentIntoRegion != null)
OnReceivedMoveAgentIntoRegion(regInfo, pos, look);
}
public virtual AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
agentData.SessionID = SessionId;
agentData.SecureSessionID = UUID.Zero;
agentData.circuitcode = m_circuitCode;
agentData.child = false;
agentData.firstname = m_firstName;
agentData.lastname = m_lastName;
ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>();
if (capsModule != null)
{
agentData.CapsPath = capsModule.GetCapsPath(m_agentId);
agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId));
}
return agentData;
}
public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
if (OnTestClientInformClientOfNeighbour != null)
OnTestClientInformClientOfNeighbour(neighbourHandle, neighbourExternalEndPoint);
}
public virtual void SendRegionTeleport(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL)
{
m_log.DebugFormat(
"[TEST CLIENT]: Received SendRegionTeleport for {0} {1} on {2}", m_firstName, m_lastName, m_scene.Name);
CapsSeedUrl = capsURL;
if (OnTestClientSendRegionTeleport != null)
OnTestClientSendRegionTeleport(
regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL);
}
public virtual void SendTeleportFailed(string reason)
{
m_log.DebugFormat(
"[TEST CLIENT]: Teleport failed for {0} {1} on {2} with reason {3}",
m_firstName, m_lastName, m_scene.Name, reason);
}
public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint, string capsURL)
{
// This is supposed to send a packet to the client telling it's ready to start region crossing.
// Instead I will just signal I'm ready, mimicking the communication behavior.
// It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs.
// Arthur V.
wh.Set();
}
public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
}
public virtual void SendTeleportStart(uint flags)
{
}
public void SendTeleportProgress(uint flags, string message)
{
}
public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item)
{
}
public virtual void SendPayPrice(UUID objectID, int[] payPrice)
{
}
public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
}
public virtual void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendAvatarDataImmediate(ISceneEntity avatar)
{
}
public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
if (OnReceivedEntityUpdate != null)
OnReceivedEntityUpdate(entity, updateFlags);
}
public void ReprioritizeUpdates()
{
}
public void FlushPrimUpdates()
{
}
public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
int version,
bool fetchFolders,
bool fetchItems)
{
}
public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
}
public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID)
{
}
public virtual void SendRemoveInventoryItem(UUID itemID)
{
}
public virtual void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
}
public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
}
public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public virtual void SendAbortXferPacket(ulong xferID)
{
}
public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit,
int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor,
int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay,
int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public virtual void SendNameReply(UUID profileId, string firstname, string lastname)
{
}
public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
}
public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain,
byte flags)
{
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendSystemAlertMessage(string message)
{
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message,
string url)
{
}
public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
if (OnRegionHandShakeReply != null)
{
OnRegionHandShakeReply(this);
}
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false;
im.ImageID.Packets = numParts;
im.ImageID.ID = ImageUUID;
if (ImageSize > 0)
im.ImageID.Size = ImageSize;
im.ImageData.Data = ImageData;
im.ImageID.Codec = imageCodec;
im.Header.Zerocoded = true;
SentImageDataPackets.Add(im);
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
ImagePacketPacket im = new ImagePacketPacket();
im.Header.Reliable = false;
im.ImageID.Packet = partNumber;
im.ImageID.ID = imageUuid;
im.ImageData.Data = imageData;
SentImagePacketPackets.Add(im);
}
public void SendImageNotFound(UUID imageid)
{
ImageNotInDatabasePacket p = new ImageNotInDatabasePacket();
p.ImageID.ID = imageid;
SentImageNotInDatabasePackets.Add(p);
}
public void SendShutdownConnectionNotice()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
{
}
public void SendObjectPropertiesReply(ISceneEntity entity)
{
}
public void SendAgentOffline(UUID[] agentIDs)
{
ReceivedOfflineNotifications.AddRange(agentIDs);
}
public void SendAgentOnline(UUID[] agentIDs)
{
ReceivedOnlineNotifications.AddRange(agentIDs);
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot,
Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase)
{
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
UUID partnerID)
{
}
public int DebugPacketLevel { get; set; }
public void InPacket(object NewPack)
{
}
public void ProcessInPacket(Packet NewPack)
{
}
/// <summary>
/// This is a TestClient only method to do shutdown tasks that are normally carried out by LLUDPServer.RemoveClient()
/// </summary>
public void Logout()
{
// We must set this here so that the presence is removed from the PresenceService by the PresenceDetector
IsLoggingOut = true;
Close();
}
public void Close()
{
Close(false);
}
public void Close(bool force)
{
// Fire the callback for this connection closing
// This is necesary to get the presence detector to notice that a client has logged out.
if (OnConnectionClosed != null)
OnConnectionClosed(this);
m_scene.RemoveClient(AgentId, true);
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
}
public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message)
{
}
public void SendLogoutPacket()
{
}
public void Terminate()
{
}
public ClientInfo GetClientInfo()
{
return null;
}
public void SetClientInfo(ClientInfo info)
{
}
public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List<Vector3> SpawnPoint)
{
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(UUID covenant)
{
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<LandAccessEntry> accessList, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType,
string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
}
public void SendAsset(AssetRequestToClient req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties (UUID objectID)
{
}
public void SendRegionHandle (UUID regoinID, ulong handle)
{
}
public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return string.Empty;
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendEventInfoReply (EventData info)
{
}
public void SendOfferCallingCard (UUID destID, UUID transactionID)
{
}
public void SendAcceptCallingCard (UUID transactionID)
{
}
public void SendDeclineCallingCard (UUID transactionID)
{
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss)
{
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
}
public void SendTerminateFriend(UUID exFriendID)
{
ReceivedFriendshipTerminations.Add(exFriendID);
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
//throw new NotImplementedException();
return false;
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
}
public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(UUID groupID)
{
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
}
public void RefreshGroupMembership()
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public bool TryGet<T>(out T iface)
{
iface = default(T);
return false;
}
public T Get<T>()
{
return default(T);
}
public void Disconnect(string reason)
{
}
public void Disconnect()
{
}
public void SendRebakeAvatarTextures(UUID textureID)
{
if (OnReceivedSendRebakeAvatarTextures != null)
OnReceivedSendRebakeAvatarTextures(textureID);
}
public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
{
}
public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
{
}
public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
{
}
public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
{
}
public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
{
}
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
public void SendAgentTerseUpdate(ISceneEntity presence)
{
}
public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data)
{
}
public void SendPartPhysicsProprieties(ISceneEntity entity)
{
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Calls.Util;
using Ds3.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Ds3.Calls
{
public class PutBulkJobSpectraS3Request : Ds3Request
{
public string BucketName { get; private set; }
public IEnumerable<Ds3Object> Objects { get; private set; }
public long? MaxUploadSize { get; private set; }
public PutBulkJobSpectraS3Request WithMaxUploadSize(long maxUploadSize)
{
this.MaxUploadSize = maxUploadSize;
this.QueryParams["max_upload_size"] = maxUploadSize.ToString("D");
return this;
}
private bool? _aggregating;
public bool? Aggregating
{
get { return _aggregating; }
set { WithAggregating(value); }
}
private bool? _force;
public bool? Force
{
get { return _force; }
set { WithForce(value); }
}
private bool? _ignoreNamingConflicts;
public bool? IgnoreNamingConflicts
{
get { return _ignoreNamingConflicts; }
set { WithIgnoreNamingConflicts(value); }
}
private bool? _implicitJobIdResolution;
public bool? ImplicitJobIdResolution
{
get { return _implicitJobIdResolution; }
set { WithImplicitJobIdResolution(value); }
}
private bool? _minimizeSpanningAcrossMedia;
public bool? MinimizeSpanningAcrossMedia
{
get { return _minimizeSpanningAcrossMedia; }
set { WithMinimizeSpanningAcrossMedia(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private Priority? _priority;
public Priority? Priority
{
get { return _priority; }
set { WithPriority(value); }
}
private bool? _verifyAfterWrite;
public bool? VerifyAfterWrite
{
get { return _verifyAfterWrite; }
set { WithVerifyAfterWrite(value); }
}
public PutBulkJobSpectraS3Request WithAggregating(bool? aggregating)
{
this._aggregating = aggregating;
if (aggregating != null)
{
this.QueryParams.Add("aggregating", aggregating.ToString());
}
else
{
this.QueryParams.Remove("aggregating");
}
return this;
}
public PutBulkJobSpectraS3Request WithForce(bool? force)
{
this._force = force;
if (force != null)
{
this.QueryParams.Add("force", force.ToString());
}
else
{
this.QueryParams.Remove("force");
}
return this;
}
public PutBulkJobSpectraS3Request WithIgnoreNamingConflicts(bool? ignoreNamingConflicts)
{
this._ignoreNamingConflicts = ignoreNamingConflicts;
if (ignoreNamingConflicts != null)
{
this.QueryParams.Add("ignore_naming_conflicts", ignoreNamingConflicts.ToString());
}
else
{
this.QueryParams.Remove("ignore_naming_conflicts");
}
return this;
}
public PutBulkJobSpectraS3Request WithImplicitJobIdResolution(bool? implicitJobIdResolution)
{
this._implicitJobIdResolution = implicitJobIdResolution;
if (implicitJobIdResolution != null)
{
this.QueryParams.Add("implicit_job_id_resolution", implicitJobIdResolution.ToString());
}
else
{
this.QueryParams.Remove("implicit_job_id_resolution");
}
return this;
}
public PutBulkJobSpectraS3Request WithMinimizeSpanningAcrossMedia(bool? minimizeSpanningAcrossMedia)
{
this._minimizeSpanningAcrossMedia = minimizeSpanningAcrossMedia;
if (minimizeSpanningAcrossMedia != null)
{
this.QueryParams.Add("minimize_spanning_across_media", minimizeSpanningAcrossMedia.ToString());
}
else
{
this.QueryParams.Remove("minimize_spanning_across_media");
}
return this;
}
public PutBulkJobSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public PutBulkJobSpectraS3Request WithPriority(Priority? priority)
{
this._priority = priority;
if (priority != null)
{
this.QueryParams.Add("priority", priority.ToString());
}
else
{
this.QueryParams.Remove("priority");
}
return this;
}
public PutBulkJobSpectraS3Request WithVerifyAfterWrite(bool? verifyAfterWrite)
{
this._verifyAfterWrite = verifyAfterWrite;
if (verifyAfterWrite != null)
{
this.QueryParams.Add("verify_after_write", verifyAfterWrite.ToString());
}
else
{
this.QueryParams.Remove("verify_after_write");
}
return this;
}
public PutBulkJobSpectraS3Request(string bucketName, IEnumerable<Ds3Object> objects)
{
this.BucketName = bucketName;
this.Objects = objects.ToList();
this.QueryParams.Add("operation", "start_bulk_put");
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.PUT;
}
}
internal override string Path
{
get
{
return "/_rest_/bucket/" + BucketName;
}
}
internal override Stream GetContentStream()
{
return RequestPayloadUtil.MarshalDs3ObjectNameAndSize(this.Objects);
}
internal override long GetContentLength()
{
return GetContentStream().Length;
}
}
}
| |
/*******************************************************************************
* Copyright 2017 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
using System;
using System.Runtime.InteropServices;
namespace dynamixel_sdk
{
class dynamixel
{
const string dll_path = "../../../../../../../../c/build/win64/output/dxl_x64_c.dll";
#region PortHandler
[DllImport(dll_path)]
public static extern int portHandler (string port_name);
[DllImport(dll_path)]
public static extern bool openPort (int port_num);
[DllImport(dll_path)]
public static extern void closePort (int port_num);
[DllImport(dll_path)]
public static extern void clearPort (int port_num);
[DllImport(dll_path)]
public static extern void setPortName (int port_num, string port_name);
[DllImport(dll_path)]
public static extern string getPortName (int port_num);
[DllImport(dll_path)]
public static extern bool setBaudRate (int port_num, int baudrate);
[DllImport(dll_path)]
public static extern int getBaudRate (int port_num);
[DllImport(dll_path)]
public static extern int readPort (int port_num, byte[] packet, int length);
[DllImport(dll_path)]
public static extern int writePort (int port_num, byte[] packet, int length);
[DllImport(dll_path)]
public static extern void setPacketTimeout (int port_num, UInt16 packet_length);
[DllImport(dll_path)]
public static extern void setPacketTimeoutMSec(int port_num, double msec);
[DllImport(dll_path)]
public static extern bool isPacketTimeout (int port_num);
#endregion
#region PacketHandler
[DllImport(dll_path)]
public static extern void packetHandler ();
[DllImport(dll_path)]
public static extern IntPtr getTxRxResult (int protocol_version, int result);
[DllImport(dll_path)]
public static extern IntPtr getRxPacketError (int protocol_version, byte error);
[DllImport(dll_path)]
public static extern int getLastTxRxResult (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern byte getLastRxPacketError(int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void setDataWrite (int port_num, int protocol_version, UInt16 data_length, UInt16 data_pos, UInt32 data);
[DllImport(dll_path)]
public static extern UInt32 getDataRead (int port_num, int protocol_version, UInt16 data_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void txPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void rxPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void txRxPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void ping (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern UInt16 pingGetModelNum (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void broadcastPing (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool getBroadcastPingResult(int port_num, int protocol_version, int id);
[DllImport(dll_path)]
public static extern void clearMultiTurn (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void reboot (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void factoryReset (int port_num, int protocol_version, byte id, byte option);
[DllImport(dll_path)]
public static extern void readTx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void readRx (int port_num, int protocol_version, UInt16 length);
[DllImport(dll_path)]
public static extern void readTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void read1ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern byte read1ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern byte read1ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void read2ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern UInt16 read2ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern UInt16 read2ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void read4ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern UInt32 read4ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern UInt32 read4ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void writeTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void writeTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void write1ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, byte data);
[DllImport(dll_path)]
public static extern void write1ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, byte data);
[DllImport(dll_path)]
public static extern void write2ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 data);
[DllImport(dll_path)]
public static extern void write2ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 data);
[DllImport(dll_path)]
public static extern void write4ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt32 data);
[DllImport(dll_path)]
public static extern void write4ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt32 data);
[DllImport(dll_path)]
public static extern void regWriteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void regWriteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void syncReadTx (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length, UInt16 param_length);
// syncReadRx -> GroupSyncRead
// syncReadTxRx -> GroupSyncRead
[DllImport(dll_path)]
public static extern void syncWriteTxOnly (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length, UInt16 param_length);
[DllImport(dll_path)]
public static extern void bulkReadTx (int port_num, int protocol_version, UInt16 param_length);
// bulkReadRx -> GroupBulkRead
// bulkReadTxRx -> GroupBulkRead
[DllImport(dll_path)]
public static extern void bulkWriteTxOnly (int port_num, int protocol_version, UInt16 param_length);
#endregion
#region GroupBulkRead
[DllImport(dll_path)]
public static extern int groupBulkRead (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool groupBulkReadAddParam (int group_num, byte id, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern void groupBulkReadRemoveParam(int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupBulkReadClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadTxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadRxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadTxRxPacket (int group_num);
[DllImport(dll_path)]
public static extern bool groupBulkReadIsAvailable(int group_num, byte id, UInt16 address, UInt16 data_length);
[DllImport(dll_path)]
public static extern UInt32 groupBulkReadGetData (int group_num, byte id, UInt16 address, UInt16 data_length);
#endregion
#region GroupBulkWrite
[DllImport(dll_path)]
public static extern int groupBulkWrite (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool groupBulkWriteAddParam (int group_num, byte id, UInt16 start_address, UInt16 data_length, UInt32 data, UInt16 input_length);
[DllImport(dll_path)]
public static extern void groupBulkWriteRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern bool groupBulkWriteChangeParam (int group_num, byte id, UInt16 start_address, UInt16 data_length, UInt32 data, UInt16 input_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void groupBulkWriteClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkWriteTxPacket (int group_num);
#endregion
#region GroupSyncRead
[DllImport(dll_path)]
public static extern int groupSyncRead (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern bool groupSyncReadAddParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupSyncReadRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupSyncReadClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadTxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadRxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadTxRxPacket (int group_num);
[DllImport(dll_path)]
public static extern bool groupSyncReadIsAvailable (int group_num, byte id, UInt16 address, UInt16 data_length);
[DllImport(dll_path)]
public static extern UInt32 groupSyncReadGetData (int group_num, byte id, UInt16 address, UInt16 data_length);
#endregion
#region GroupSyncWrite
[DllImport(dll_path)]
public static extern int groupSyncWrite (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern bool groupSyncWriteAddParam (int group_num, byte id, UInt32 data, UInt16 data_length);
[DllImport(dll_path)]
public static extern void groupSyncWriteRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern bool groupSyncWriteChangeParam (int group_num, byte id, UInt32 data, UInt16 data_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void groupSyncWriteClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncWriteTxPacket (int group_num);
#endregion
}
}
| |
using System;
using Flunity.Utils;
using Flunity.Internal;
namespace Flunity
{
/// <summary>
/// Methods to run/stop animation on objects which implements IFrameAnimable interface
/// </summary>
public static class FrameAnimationExt
{
/// <summary>
/// Stop animation.
/// </summary>
public static void Stop(this IFrameAnimable target)
{
target.animation.Stop();
}
/// <summary>
/// Begin playing forward from current frame.
/// </summary>
public static void Play(this IFrameAnimable target)
{
target.animation.PlayLoop(1);
}
/// <summary>
/// Begin playing backward from current frame.
/// </summary>
public static void PlayReverse(this IFrameAnimable target)
{
target.animation.PlayLoop(-1);
}
/// <summary>
/// Begin playing backward from current frame and stop on the first frame.
/// PlayCompleted event will be dispatced.
/// </summary>
public static void PlayToBegin(this IFrameAnimable target)
{
target.animation.PlayTo(0);
}
/// <summary>
/// Begin playing forward from current frame and stop on the last frame.
/// PlayCompleted event will be dispatced.
/// </summary>
public static void PlayToEnd(this IFrameAnimable target)
{
target.animation.PlayTo(target.totalFrames - 1);
}
/// <summary>
/// Begin playing from the first frame to the last frame.
/// PlayCompleted event will be dispatced.
/// </summary>
public static void PlayFromBeginToEnd(this IFrameAnimable target)
{
target.currentFrame = 0;
target.PlayToEnd();
}
/// <summary>
/// Begin playing from the last frame to the first frame.
/// PlayCompleted event will be dispatced.
/// </summary>
public static void PlayFromEndToBegin(this IFrameAnimable target)
{
target.currentFrame = target.totalFrames - 1;
target.PlayToBegin();
}
/// <summary>
/// Begin playing from the current frame to the specified frame.
/// PlayCompleted event will be dispatced.
/// </summary>
public static void PlayTo(this IFrameAnimable target, int frameNum)
{
target.animation.PlayTo(frameNum);
}
/// <summary>
/// Returns true if currentFrame == 0
/// </summary>
public static bool IsFirstFrame(this IFrameAnimable target)
{
return target.currentFrame == 0;
}
/// <summary>
/// Returns true if currentFrame == totalFrames - 1
/// </summary>
public static bool IsLastFrame(this IFrameAnimable target)
{
return target.currentFrame == target.totalFrames - 1;
}
/// <summary>
/// Stops playing and goes to the specified frame.
/// </summary>
public static IFrameAnimable GotoAndStop(this IFrameAnimable target, int frameNum)
{
target.currentFrame = frameNum;
target.Stop();
return target;
}
/// <summary>
/// Goes to the specified frame and starts playing forward.
/// </summary>
public static IFrameAnimable GotoAndPlay(this IFrameAnimable target, int frameNum)
{
target.currentFrame = frameNum;
target.Play();
return target;
}
/// <summary>
/// Goes to the random frame. Does not stop playing if animation is active.
/// </summary>
public static IFrameAnimable GotoRandomFrame(this IFrameAnimable target)
{
target.currentFrame = RandomUtil.RandomInt(0, target.totalFrames - 1);
return target;
}
/// <summary>
/// Goes to the first frame. Does not stop playing if animation is active.
/// </summary>
public static IFrameAnimable GotoFirstFrame(this IFrameAnimable target)
{
target.currentFrame = 0;
return target;
}
/// <summary>
/// Goes to the last frame. Does not stop playing if animation is active.
/// </summary>
public static IFrameAnimable GotoLastFrame(this IFrameAnimable target)
{
target.currentFrame = target.totalFrames - 1;
return target;
}
/// <summary>
/// Goes to the next frame (does nothinf if it was last frame).
/// </summary>
public static IFrameAnimable GotoNextFrame(this IFrameAnimable target)
{
var currentFrame = target.currentFrame;
if (currentFrame + 1 < target.totalFrames)
target.currentFrame = currentFrame + 1;
return target;
}
/// <summary>
/// Goes to the previous frame (does nothinf if it was first frame).
/// </summary>
public static IFrameAnimable GotoPrevFrame(this IFrameAnimable target)
{
var currentFrame = target.currentFrame;
if (currentFrame > 0)
target.currentFrame = currentFrame - 1;
return target;
}
/// <summary>
/// Goes to the next frame (jumps to the first frame if it was last frame).
/// </summary>
public static IFrameAnimable StepForward(this IFrameAnimable target)
{
var currentFrame = target.currentFrame;
if (currentFrame + 1 < target.totalFrames)
target.currentFrame = currentFrame + 1;
else
target.currentFrame = 0;
return target;
}
/// <summary>
/// Goes to the previous frame (jumps to the last frame if it was first frame).
/// </summary>
public static IFrameAnimable StepBackward(this IFrameAnimable target)
{
var currentFrame = target.currentFrame;
if (currentFrame > 0)
target.currentFrame = currentFrame - 1;
else
target.currentFrame = target.totalFrames - 1;
return target;
}
}
}
| |
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
using System.Collections.Generic;
using erl.Oracle.TnsNames.Antlr4.Runtime;
using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen;
namespace erl.Oracle.TnsNames.Antlr4.Runtime
{
/// <summary>
/// Provides an implementation of
/// <see cref="ITokenSource"/>
/// as a wrapper around a list
/// of
/// <see cref="IToken"/>
/// objects.
/// <p>If the final token in the list is an
/// <see cref="TokenConstants.EOF"/>
/// token, it will be used
/// as the EOF token for every call to
/// <see cref="NextToken()"/>
/// after the end of the
/// list is reached. Otherwise, an EOF token will be created.</p>
/// </summary>
public class ListTokenSource : ITokenSource
{
/// <summary>
/// The wrapped collection of
/// <see cref="IToken"/>
/// objects to return.
/// </summary>
protected internal readonly IList<IToken> tokens;
/// <summary>The name of the input source.</summary>
/// <remarks>
/// The name of the input source. If this value is
/// <see langword="null"/>
/// , a call to
/// <see cref="SourceName()"/>
/// should return the source name used to create the
/// the next token in
/// <see cref="tokens"/>
/// (or the previous token if the end of
/// the input has been reached).
/// </remarks>
private readonly string sourceName;
/// <summary>
/// The index into
/// <see cref="tokens"/>
/// of token to return by the next call to
/// <see cref="NextToken()"/>
/// . The end of the input is indicated by this value
/// being greater than or equal to the number of items in
/// <see cref="tokens"/>
/// .
/// </summary>
protected internal int i;
/// <summary>This field caches the EOF token for the token source.</summary>
/// <remarks>This field caches the EOF token for the token source.</remarks>
protected internal IToken eofToken;
/// <summary>
/// This is the backing field for the <see cref="TokenFactory"/> property.
/// </summary>
private ITokenFactory _factory = CommonTokenFactory.Default;
/// <summary>
/// Constructs a new
/// <see cref="ListTokenSource"/>
/// instance from the specified
/// collection of
/// <see cref="IToken"/>
/// objects.
/// </summary>
/// <param name="tokens">
/// The collection of
/// <see cref="IToken"/>
/// objects to provide as a
/// <see cref="ITokenSource"/>
/// .
/// </param>
/// <exception>
/// NullPointerException
/// if
/// <paramref name="tokens"/>
/// is
/// <see langword="null"/>
/// </exception>
public ListTokenSource(IList<IToken> tokens)
: this(tokens, null)
{
}
/// <summary>
/// Constructs a new
/// <see cref="ListTokenSource"/>
/// instance from the specified
/// collection of
/// <see cref="IToken"/>
/// objects and source name.
/// </summary>
/// <param name="tokens">
/// The collection of
/// <see cref="IToken"/>
/// objects to provide as a
/// <see cref="ITokenSource"/>
/// .
/// </param>
/// <param name="sourceName">
/// The name of the
/// <see cref="ITokenSource"/>
/// . If this value is
/// <see langword="null"/>
/// ,
/// <see cref="SourceName()"/>
/// will attempt to infer the name from
/// the next
/// <see cref="IToken"/>
/// (or the previous token if the end of the input has
/// been reached).
/// </param>
/// <exception>
/// NullPointerException
/// if
/// <paramref name="tokens"/>
/// is
/// <see langword="null"/>
/// </exception>
public ListTokenSource(IList<IToken> tokens, string sourceName)
{
if (tokens == null)
{
throw new ArgumentNullException("tokens cannot be null");
}
this.tokens = tokens;
this.sourceName = sourceName;
}
/// <summary><inheritDoc/></summary>
public virtual int Column
{
get
{
if (i < tokens.Count)
{
return tokens[i].Column;
}
else
{
if (eofToken != null)
{
return eofToken.Column;
}
else
{
if (tokens.Count > 0)
{
// have to calculate the result from the line/column of the previous
// token, along with the text of the token.
IToken lastToken = tokens[tokens.Count - 1];
string tokenText = lastToken.Text;
if (tokenText != null)
{
int lastNewLine = tokenText.LastIndexOf('\n');
if (lastNewLine >= 0)
{
return tokenText.Length - lastNewLine - 1;
}
}
return lastToken.Column + lastToken.StopIndex - lastToken.StartIndex + 1;
}
}
}
// only reach this if tokens is empty, meaning EOF occurs at the first
// position in the input
return 0;
}
}
/// <summary><inheritDoc/></summary>
public virtual IToken NextToken()
{
if (i >= tokens.Count)
{
if (eofToken == null)
{
int start = -1;
if (tokens.Count > 0)
{
int previousStop = tokens[tokens.Count - 1].StopIndex;
if (previousStop != -1)
{
start = previousStop + 1;
}
}
int stop = Math.Max(-1, start - 1);
eofToken = _factory.Create(Tuple.Create((ITokenSource)this, InputStream), TokenConstants.EOF, "EOF", TokenConstants.DefaultChannel, start, stop, Line, Column);
}
return eofToken;
}
IToken t = tokens[i];
if (i == tokens.Count - 1 && t.Type == TokenConstants.EOF)
{
eofToken = t;
}
i++;
return t;
}
/// <summary><inheritDoc/></summary>
public virtual int Line
{
get
{
if (i < tokens.Count)
{
return tokens[i].Line;
}
else
{
if (eofToken != null)
{
return eofToken.Line;
}
else
{
if (tokens.Count > 0)
{
// have to calculate the result from the line/column of the previous
// token, along with the text of the token.
IToken lastToken = tokens[tokens.Count - 1];
int line = lastToken.Line;
string tokenText = lastToken.Text;
if (tokenText != null)
{
for (int j = 0; j < tokenText.Length; j++)
{
if (tokenText[j] == '\n')
{
line++;
}
}
}
// if no text is available, assume the token did not contain any newline characters.
return line;
}
}
}
// only reach this if tokens is empty, meaning EOF occurs at the first
// position in the input
return 1;
}
}
/// <summary><inheritDoc/></summary>
public virtual ICharStream InputStream
{
get
{
if (i < tokens.Count)
{
return tokens[i].InputStream;
}
else
{
if (eofToken != null)
{
return eofToken.InputStream;
}
else
{
if (tokens.Count > 0)
{
return tokens[tokens.Count - 1].InputStream;
}
}
}
// no input stream information is available
return null;
}
}
/// <summary><inheritDoc/></summary>
public virtual string SourceName
{
get
{
if (sourceName != null)
{
return sourceName;
}
ICharStream inputStream = InputStream;
if (inputStream != null)
{
return inputStream.SourceName;
}
return "List";
}
}
/// <summary><inheritDoc/></summary>
/// <summary><inheritDoc/></summary>
public virtual ITokenFactory TokenFactory
{
get
{
return _factory;
}
set
{
ITokenFactory factory = value;
this._factory = factory;
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.FileProperties;
using Windows.Storage.Streams;
using Windows.Storage;
namespace System.IO
{
/// <summary>
/// Contains extension methods that provide convenience helpers for WinRT IO.
/// </summary>
public static class WindowsRuntimeStorageExtensions
{
#region Extensions on IStorageFile for retreaving a managed Stream
[CLSCompliant(false)]
public static Task<Stream> OpenStreamForReadAsync(this IStorageFile windowsRuntimeFile)
{
if (windowsRuntimeFile == null)
throw new ArgumentNullException("windowsRuntimeFile");
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
return OpenStreamForReadAsyncCore(windowsRuntimeFile);
}
private static async Task<Stream> OpenStreamForReadAsyncCore(this IStorageFile windowsRuntimeFile)
{
Contract.Requires(windowsRuntimeFile != null);
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
try
{
IRandomAccessStream windowsRuntimeStream = await windowsRuntimeFile.OpenAsync(FileAccessMode.Read)
.AsTask().ConfigureAwait(continueOnCapturedContext: false);
Stream managedStream = windowsRuntimeStream.AsStreamForRead();
return managedStream;
}
catch (Exception ex)
{
// From this API, managed dev expect IO exceptions for "something wrong":
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
return null;
}
}
[CLSCompliant(false)]
public static Task<Stream> OpenStreamForWriteAsync(this IStorageFile windowsRuntimeFile)
{
if (windowsRuntimeFile == null)
throw new ArgumentNullException("windowsRuntimeFile");
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
return OpenStreamForWriteAsyncCore(windowsRuntimeFile, 0);
}
private static async Task<Stream> OpenStreamForWriteAsyncCore(this IStorageFile windowsRuntimeFile, Int64 offset)
{
Contract.Requires(windowsRuntimeFile != null);
Contract.Requires(offset >= 0);
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
try
{
IRandomAccessStream windowsRuntimeStream = await windowsRuntimeFile.OpenAsync(FileAccessMode.ReadWrite)
.AsTask().ConfigureAwait(continueOnCapturedContext: false);
Stream managedStream = windowsRuntimeStream.AsStreamForWrite();
managedStream.Position = offset;
return managedStream;
}
catch (Exception ex)
{
// From this API, managed dev expect IO exceptions for "something wrong":
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
return null;
}
}
#endregion Extensions on IStorageFile for retreaving a managed Stream
#region Extensions on IStorageFolder for retreaving a managed Stream
[CLSCompliant(false)]
public static Task<Stream> OpenStreamForReadAsync(this IStorageFolder rootDirectory, String relativePath)
{
if (rootDirectory == null)
throw new ArgumentNullException("rootDirectory");
if (relativePath == null)
throw new ArgumentNullException("relativePath");
if (String.IsNullOrWhiteSpace(relativePath))
throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, "relativePath");
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
return OpenStreamForReadAsyncCore(rootDirectory, relativePath);
}
private static async Task<Stream> OpenStreamForReadAsyncCore(this IStorageFolder rootDirectory, String relativePath)
{
Contract.Requires(rootDirectory != null);
Contract.Requires(!String.IsNullOrWhiteSpace(relativePath));
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
try
{
IStorageFile windowsRuntimeFile = await rootDirectory.GetFileAsync(relativePath)
.AsTask().ConfigureAwait(continueOnCapturedContext: false);
Stream managedStream = await windowsRuntimeFile.OpenStreamForReadAsync()
.ConfigureAwait(continueOnCapturedContext: false);
return managedStream;
}
catch (Exception ex)
{
// From this API, managed dev expect IO exceptions for "something wrong":
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
return null;
}
}
[CLSCompliant(false)]
public static Task<Stream> OpenStreamForWriteAsync(this IStorageFolder rootDirectory, String relativePath,
CreationCollisionOption creationCollisionOption)
{
if (rootDirectory == null)
throw new ArgumentNullException("rootDirectory");
if (relativePath == null)
throw new ArgumentNullException("relativePath");
if (String.IsNullOrWhiteSpace(relativePath))
throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, "relativePath");
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
return OpenStreamForWriteAsyncCore(rootDirectory, relativePath, creationCollisionOption);
}
private static async Task<Stream> OpenStreamForWriteAsyncCore(this IStorageFolder rootDirectory, String relativePath,
CreationCollisionOption creationCollisionOption)
{
Contract.Requires(rootDirectory != null);
Contract.Requires(!String.IsNullOrWhiteSpace(relativePath));
Contract.Requires(creationCollisionOption == CreationCollisionOption.FailIfExists
|| creationCollisionOption == CreationCollisionOption.GenerateUniqueName
|| creationCollisionOption == CreationCollisionOption.OpenIfExists
|| creationCollisionOption == CreationCollisionOption.ReplaceExisting,
"The specified creationCollisionOption has a value that is not a value we considered when devising the"
+ " policy about Append-On-OpenIfExists used in this method. Apparently a new enum value was added to the"
+ " CreationCollisionOption type and we need to make sure that the policy still makes sense.");
Contract.Ensures(Contract.Result<Task<Stream>>() != null);
Contract.EndContractBlock();
try
{
// Open file and set up default options for opening it:
IStorageFile windowsRuntimeFile = await rootDirectory.CreateFileAsync(relativePath, creationCollisionOption)
.AsTask().ConfigureAwait(continueOnCapturedContext: false);
Int64 offset = 0;
// If the specified creationCollisionOption was OpenIfExists, then we will try to APPEND, otherwise we will OVERWRITE:
if (creationCollisionOption == CreationCollisionOption.OpenIfExists)
{
BasicProperties fileProperties = await windowsRuntimeFile.GetBasicPropertiesAsync()
.AsTask().ConfigureAwait(continueOnCapturedContext: false);
UInt64 fileSize = fileProperties.Size;
Debug.Assert(fileSize <= Int64.MaxValue, ".NET streams assume that file sizes are not larger than Int64.MaxValue,"
+ " so we are not supporting the situation where this is not the case.");
offset = checked((Int64)fileSize);
}
// Now open a file with the correct options:
Stream managedStream = await OpenStreamForWriteAsyncCore(windowsRuntimeFile, offset).ConfigureAwait(continueOnCapturedContext: false);
return managedStream;
}
catch (Exception ex)
{
// From this API, managed dev expect IO exceptions for "something wrong":
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
return null;
}
}
#endregion Extensions on IStorageFolder for retreaving a managed Stream
} // class WindowsRuntimeStorageExtensions
} // namespace
// WindowsRuntimeStorageExtensions.cs
| |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
//
// 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.Linq;
using System.Collections.Generic;
using System.Text;
using Spark.Compiler.ChunkVisitors;
using Spark.Parser.Code;
namespace Spark.Compiler.VisualBasic.ChunkVisitors
{
public class GlobalMembersVisitor : ChunkVisitor
{
private readonly SourceWriter _source;
private readonly Dictionary<string, object> _globalSymbols;
private readonly NullBehaviour _nullBehaviour;
readonly Dictionary<string, string> _viewDataAdded = new Dictionary<string, string>();
readonly Dictionary<string, GlobalVariableChunk> _globalAdded = new Dictionary<string, GlobalVariableChunk>();
public GlobalMembersVisitor(SourceWriter output, Dictionary<string, object> globalSymbols, NullBehaviour nullBehaviour)
{
_source = output;
_globalSymbols = globalSymbols;
_nullBehaviour = nullBehaviour;
}
private SourceWriter CodeIndent(Chunk chunk)
{
if (_source.AdjustDebugSymbols)
{
if (chunk != null && chunk.Position != null)
{
_source.StartOfLine = false;
return _source
.WriteDirective("#ExternalSource(\"{1}\", {0})", chunk.Position.Line, chunk.Position.SourceContext.FileName)
.Indent(chunk.Position.Column - 1);
}
return _source.WriteDirective("#ExternalSource(\"\", 16707566)");
}
return _source;
}
private void CodeHidden()
{
if (_source.AdjustDebugSymbols)
_source.WriteLine("#ExternalSource(\"\", 16707566)");
}
private void CodeDefault()
{
if (_source.AdjustDebugSymbols)
_source.WriteLine("#End ExternalSource");
}
protected override void Visit(GlobalVariableChunk chunk)
{
if (!_globalSymbols.ContainsKey(chunk.Name))
_globalSymbols.Add(chunk.Name, null);
if (_globalAdded.ContainsKey(chunk.Name))
{
if (_globalAdded[chunk.Name].Type != chunk.Type ||
_globalAdded[chunk.Name].Value != chunk.Value)
{
throw new CompilerException(
string.Format(
"The global named {0} cannot be declared repeatedly with different types or values",
chunk.Name));
}
return;
}
var type = chunk.Type ?? "Object";
_source.WriteFormat(
"\r\n Private _{1} As {0} = {2}" +
"\r\n Public Property {1}() As {0}" +
"\r\n Get" +
"\r\n Return _{1}" +
"\r\n End Get" +
"\r\n Set(ByVal value as {0})" +
"\r\n _{1} = value" +
"\r\n End Set" +
"\r\n End Property",
type, chunk.Name, chunk.Value);
_source.WriteLine();
}
protected override void Visit(ViewDataModelChunk chunk)
{
if (Snippets.IsNullOrEmpty(chunk.TModelAlias))
return;
_source
.Write("Public ReadOnly Property ")
.WriteCode(chunk.TModelAlias)
.Write("() As ")
.WriteCode(chunk.TModel)
.WriteLine().AddIndent();
_source.WriteLine("Get").AddIndent();
_source.WriteLine("Return ViewData.Model");
_source.RemoveIndent().WriteLine("End Get");
_source.RemoveIndent().WriteLine("End Property");
CodeDefault();
}
protected override void Visit(ViewDataChunk chunk)
{
var key = chunk.Key;
var name = chunk.Name;
var type = chunk.Type ?? "object";
if (!_globalSymbols.ContainsKey(name))
_globalSymbols.Add(name, null);
if (_viewDataAdded.ContainsKey(name))
{
if (_viewDataAdded[name] != key + ":" + type)
{
throw new CompilerException(
string.Format("The view data named {0} cannot be declared with different types '{1}' and '{2}'",
name, type, _viewDataAdded[name]));
}
return;
}
_viewDataAdded.Add(name, key + ":" + type);
//_source.WriteCode(type).Write(" ").WriteLine(name);
_source
.Write("Public ReadOnly Property ")
.WriteCode(name)
.Write("() As ")
.WriteCode(type)
.WriteLine().AddIndent()
.WriteLine("Get").AddIndent();
if (Snippets.IsNullOrEmpty(chunk.Default))
{
CodeIndent(chunk)
.Write("Return CType(ViewData.Eval(\"")
.Write(key)
.Write("\"),")
.WriteCode(type)
.WriteLine(")");
}
else
{
CodeIndent(chunk)
.Write("Return CType(If(ViewData.Eval(\"")
.Write(key)
.Write("\"),")
.WriteCode(chunk.Default)
.Write("),")
.WriteCode(type)
.WriteLine(")");
}
_source
.RemoveIndent().WriteLine("End Get")
.RemoveIndent().WriteLine("End Property");
CodeDefault();
}
protected override void Visit(ExtensionChunk chunk)
{
chunk.Extension.VisitChunk(this, OutputLocation.ClassMembers, chunk.Body, _source.GetStringBuilder());
}
protected override void Visit(MacroChunk chunk)
{
_source
.Write("Public Function ")
.Write(chunk.Name)
.Write("(");
var delimiter = "";
foreach (var parameter in chunk.Parameters)
{
_source
.Write(delimiter)
.Write(parameter.Name)
.Write(" As ")
.WriteCode(parameter.Type);
delimiter = ", ";
}
_source
.WriteLine(") As String")
.AddIndent();
_source
.WriteLine("Using OutputScope(new Global.System.IO.StringWriter())")
.AddIndent();
var variables = new Dictionary<string, object>();
foreach (var param in chunk.Parameters)
{
variables.Add(param.Name, null);
}
var generator = new GeneratedCodeVisitor(_source, variables, _nullBehaviour);
generator.Accept(chunk.Body);
_source
.WriteLine("Return Output.ToString()")
.RemoveIndent().WriteLine("End Using")
.RemoveIndent().WriteLine("End Function");
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the GuardiaRegistrosEstado class.
/// </summary>
[Serializable]
public partial class GuardiaRegistrosEstadoCollection : ActiveList<GuardiaRegistrosEstado, GuardiaRegistrosEstadoCollection>
{
public GuardiaRegistrosEstadoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>GuardiaRegistrosEstadoCollection</returns>
public GuardiaRegistrosEstadoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
GuardiaRegistrosEstado o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Guardia_Registros_Estados table.
/// </summary>
[Serializable]
public partial class GuardiaRegistrosEstado : ActiveRecord<GuardiaRegistrosEstado>, IActiveRecord
{
#region .ctors and Default Settings
public GuardiaRegistrosEstado()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public GuardiaRegistrosEstado(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public GuardiaRegistrosEstado(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public GuardiaRegistrosEstado(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Guardia_Registros_Estados", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = true;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "Guardia_Registros_Estados";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Guardia_Registros_Estados",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.GuardiaRegistrosEstadoCollection colChildGuardiaRegistrosEstados;
public DalSic.GuardiaRegistrosEstadoCollection ChildGuardiaRegistrosEstados
{
get
{
if(colChildGuardiaRegistrosEstados == null)
{
colChildGuardiaRegistrosEstados = new DalSic.GuardiaRegistrosEstadoCollection().Where(GuardiaRegistrosEstado.Columns.Id, Id).Load();
colChildGuardiaRegistrosEstados.ListChanged += new ListChangedEventHandler(colChildGuardiaRegistrosEstados_ListChanged);
}
return colChildGuardiaRegistrosEstados;
}
set
{
colChildGuardiaRegistrosEstados = value;
colChildGuardiaRegistrosEstados.ListChanged += new ListChangedEventHandler(colChildGuardiaRegistrosEstados_ListChanged);
}
}
void colChildGuardiaRegistrosEstados_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colChildGuardiaRegistrosEstados[e.NewIndex].Id = Id;
}
}
private DalSic.GuardiaRegistroCollection colGuardiaRegistros;
public DalSic.GuardiaRegistroCollection GuardiaRegistros
{
get
{
if(colGuardiaRegistros == null)
{
colGuardiaRegistros = new DalSic.GuardiaRegistroCollection().Where(GuardiaRegistro.Columns.EstadoActual, Id).Load();
colGuardiaRegistros.ListChanged += new ListChangedEventHandler(colGuardiaRegistros_ListChanged);
}
return colGuardiaRegistros;
}
set
{
colGuardiaRegistros = value;
colGuardiaRegistros.ListChanged += new ListChangedEventHandler(colGuardiaRegistros_ListChanged);
}
}
void colGuardiaRegistros_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colGuardiaRegistros[e.NewIndex].EstadoActual = Id;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a GuardiaRegistrosEstado ActiveRecord object related to this GuardiaRegistrosEstado
///
/// </summary>
public DalSic.GuardiaRegistrosEstado ParentGuardiaRegistrosEstado
{
get { return DalSic.GuardiaRegistrosEstado.FetchByID(this.Id); }
set { SetColumnValue("id", value.Id); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
GuardiaRegistrosEstado item = new GuardiaRegistrosEstado();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,string varNombre)
{
GuardiaRegistrosEstado item = new GuardiaRegistrosEstado();
item.Id = varId;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colChildGuardiaRegistrosEstados != null)
{
foreach (DalSic.GuardiaRegistrosEstado item in colChildGuardiaRegistrosEstados)
{
if (item.Id != Id)
{
item.Id = Id;
}
}
}
if (colGuardiaRegistros != null)
{
foreach (DalSic.GuardiaRegistro item in colGuardiaRegistros)
{
if (item.EstadoActual != Id)
{
item.EstadoActual = Id;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colChildGuardiaRegistrosEstados != null)
{
colChildGuardiaRegistrosEstados.SaveAll();
}
if (colGuardiaRegistros != null)
{
colGuardiaRegistros.SaveAll();
}
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reactive.Linq;
using Avalonia.Data;
namespace Avalonia.Markup.Data
{
internal class IndexerNode : ExpressionNode, ISettableNode
{
public IndexerNode(IList<string> arguments)
{
Arguments = arguments;
}
public override string Description => "[" + string.Join(",", Arguments) + "]";
protected override IObservable<object> StartListeningCore(WeakReference reference)
{
var target = reference.Target;
var incc = target as INotifyCollectionChanged;
var inpc = target as INotifyPropertyChanged;
var inputs = new List<IObservable<object>>();
if (incc != null)
{
inputs.Add(WeakObservable.FromEventPattern<INotifyCollectionChanged, NotifyCollectionChangedEventArgs>(
incc,
nameof(incc.CollectionChanged))
.Where(x => ShouldUpdate(x.Sender, x.EventArgs))
.Select(_ => GetValue(target)));
}
if (inpc != null)
{
inputs.Add(WeakObservable.FromEventPattern<INotifyPropertyChanged, PropertyChangedEventArgs>(
inpc,
nameof(inpc.PropertyChanged))
.Where(x => ShouldUpdate(x.Sender, x.EventArgs))
.Select(_ => GetValue(target)));
}
return Observable.Merge(inputs).StartWith(GetValue(target));
}
public bool SetTargetValue(object value, BindingPriority priority)
{
var typeInfo = Target.Target.GetType().GetTypeInfo();
var list = Target.Target as IList;
var dictionary = Target.Target as IDictionary;
var indexerProperty = GetIndexer(typeInfo);
var indexerParameters = indexerProperty?.GetIndexParameters();
if (indexerProperty != null && indexerParameters.Length == Arguments.Count)
{
var convertedObjectArray = new object[indexerParameters.Length];
for (int i = 0; i < Arguments.Count; i++)
{
object temp = null;
if (!TypeUtilities.TryConvert(indexerParameters[i].ParameterType, Arguments[i], CultureInfo.InvariantCulture, out temp))
{
return false;
}
convertedObjectArray[i] = temp;
}
var intArgs = convertedObjectArray.OfType<int>().ToArray();
// Try special cases where we can validate indicies
if (typeInfo.IsArray)
{
return SetValueInArray((Array)Target.Target, intArgs, value);
}
else if (Arguments.Count == 1)
{
if (list != null)
{
if (intArgs.Length == Arguments.Count && intArgs[0] >= 0 && intArgs[0] < list.Count)
{
list[intArgs[0]] = value;
return true;
}
return false;
}
else if (dictionary != null)
{
if (dictionary.Contains(convertedObjectArray[0]))
{
dictionary[convertedObjectArray[0]] = value;
return true;
}
else
{
dictionary.Add(convertedObjectArray[0], value);
return true;
}
}
else
{
// Fallback to unchecked access
indexerProperty.SetValue(Target.Target, value, convertedObjectArray);
return true;
}
}
else
{
// Fallback to unchecked access
indexerProperty.SetValue(Target.Target, value, convertedObjectArray);
return true;
}
}
// Multidimensional arrays end up here because the indexer search picks up the IList indexer instead of the
// multidimensional indexer, which doesn't take the same number of arguments
else if (typeInfo.IsArray)
{
SetValueInArray((Array)Target.Target, value);
return true;
}
return false;
}
private bool SetValueInArray(Array array, object value)
{
int[] intArgs;
if (!ConvertArgumentsToInts(out intArgs))
return false;
return SetValueInArray(array, intArgs);
}
private bool SetValueInArray(Array array, int[] indicies, object value)
{
if (ValidBounds(indicies, array))
{
array.SetValue(value, indicies);
return true;
}
return false;
}
public IList<string> Arguments { get; }
public Type PropertyType => GetIndexer(Target.Target.GetType().GetTypeInfo())?.PropertyType;
private object GetValue(object target)
{
var typeInfo = target.GetType().GetTypeInfo();
var list = target as IList;
var dictionary = target as IDictionary;
var indexerProperty = GetIndexer(typeInfo);
var indexerParameters = indexerProperty?.GetIndexParameters();
if (indexerProperty != null && indexerParameters.Length == Arguments.Count)
{
var convertedObjectArray = new object[indexerParameters.Length];
for (int i = 0; i < Arguments.Count; i++)
{
object temp = null;
if (!TypeUtilities.TryConvert(indexerParameters[i].ParameterType, Arguments[i], CultureInfo.InvariantCulture, out temp))
{
return AvaloniaProperty.UnsetValue;
}
convertedObjectArray[i] = temp;
}
var intArgs = convertedObjectArray.OfType<int>().ToArray();
// Try special cases where we can validate indicies
if (typeInfo.IsArray)
{
return GetValueFromArray((Array)target, intArgs);
}
else if (Arguments.Count == 1)
{
if (list != null)
{
if (intArgs.Length == Arguments.Count && intArgs[0] >= 0 && intArgs[0] < list.Count)
{
return list[intArgs[0]];
}
return AvaloniaProperty.UnsetValue;
}
else if (dictionary != null)
{
if (dictionary.Contains(convertedObjectArray[0]))
{
return dictionary[convertedObjectArray[0]];
}
return AvaloniaProperty.UnsetValue;
}
else
{
// Fallback to unchecked access
return indexerProperty.GetValue(target, convertedObjectArray);
}
}
else
{
// Fallback to unchecked access
return indexerProperty.GetValue(target, convertedObjectArray);
}
}
// Multidimensional arrays end up here because the indexer search picks up the IList indexer instead of the
// multidimensional indexer, which doesn't take the same number of arguments
else if (typeInfo.IsArray)
{
return GetValueFromArray((Array)target);
}
return AvaloniaProperty.UnsetValue;
}
private object GetValueFromArray(Array array)
{
int[] intArgs;
if (!ConvertArgumentsToInts(out intArgs))
return AvaloniaProperty.UnsetValue;
return GetValueFromArray(array, intArgs);
}
private object GetValueFromArray(Array array, int[] indicies)
{
if (ValidBounds(indicies, array))
{
return array.GetValue(indicies);
}
return AvaloniaProperty.UnsetValue;
}
private bool ConvertArgumentsToInts(out int[] intArgs)
{
intArgs = new int[Arguments.Count];
for (int i = 0; i < Arguments.Count; ++i)
{
object value;
if (!TypeUtilities.TryConvert(typeof(int), Arguments[i], CultureInfo.InvariantCulture, out value))
{
return false;
}
intArgs[i] = (int)value;
}
return true;
}
private static PropertyInfo GetIndexer(TypeInfo typeInfo)
{
PropertyInfo indexer;
for (; typeInfo != null; typeInfo = typeInfo.BaseType?.GetTypeInfo())
{
// Check for the default indexer name first to make this faster.
// This will only be false when a class in VB has a custom indexer name.
if ((indexer = typeInfo.GetDeclaredProperty(CommonPropertyNames.IndexerName)) != null)
{
return indexer;
}
foreach (var property in typeInfo.DeclaredProperties)
{
if (property.GetIndexParameters().Any())
{
return property;
}
}
}
return null;
}
private bool ValidBounds(int[] indicies, Array array)
{
if (indicies.Length == array.Rank)
{
for (var i = 0; i < indicies.Length; ++i)
{
if (indicies[i] >= array.GetLength(i))
{
return false;
}
}
return true;
}
else
{
return false;
}
}
private bool ShouldUpdate(object sender, NotifyCollectionChangedEventArgs e)
{
if (sender is IList)
{
object indexObject;
if (!TypeUtilities.TryConvert(typeof(int), Arguments[0], CultureInfo.InvariantCulture, out indexObject))
{
return false;
}
var index = (int)indexObject;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
return index >= e.NewStartingIndex;
case NotifyCollectionChangedAction.Remove:
return index >= e.OldStartingIndex;
case NotifyCollectionChangedAction.Replace:
return index >= e.NewStartingIndex &&
index < e.NewStartingIndex + e.NewItems.Count;
case NotifyCollectionChangedAction.Move:
return (index >= e.NewStartingIndex &&
index < e.NewStartingIndex + e.NewItems.Count) ||
(index >= e.OldStartingIndex &&
index < e.OldStartingIndex + e.OldItems.Count);
case NotifyCollectionChangedAction.Reset:
return true;
}
}
return true; // Implementation defined meaning for the index, so just try to update anyway
}
private bool ShouldUpdate(object sender, PropertyChangedEventArgs e)
{
var typeInfo = sender.GetType().GetTypeInfo();
return typeInfo.GetDeclaredProperty(e.PropertyName)?.GetIndexParameters().Any() ?? false;
}
}
}
| |
// beanulator's code is licensed under the 4 clause BSD license:
//
// Copyright (c) 2013, beannaich
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. 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.
// 3. All advertising materials mentioning features or use of this software
// must display the following acknowledgement:
// This product includes software developed by beannaich.
// 4. Neither the name of beanulator 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 ''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 HOLDERS 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;
namespace Beanulator.Common.Processors.ARM
{
public class ARM7 : Processor
{
private Action[] code;
private Mode abt = new Mode(2);
private Mode fiq = new Mode(7);
private Mode irq = new Mode(2);
private Mode svc = new Mode(2);
private Mode und = new Mode(2);
private Mode usr = new Mode(7);
#region active state
private Flags cpsr;
private Flags spsr;
private Register lr;
private Register pc;
private Register[] registers;
#endregion
public ARM7()
{
cpsr = new Flags();
spsr = null;
registers = new Register[16];
registers.Initialize<Register>();
code = new Action[encode(~0u) + 1u];
#region initialize instruction table
#endregion
exception_res();
}
private void map(string pattern, Action code)
{
uint bitx = encode(Utility.Pattern(pattern, 0, 0, 1)); // pick out '-' bits
uint bit0 = encode(Utility.Pattern(pattern, 0, 1, 0)); // pick out '0' bits
uint bit1 = encode(Utility.Pattern(pattern, 1, 0, 0)); // pick out '1' bits
for (uint bits = bit1; bits <= (bitx | bit1); bits++) // binary search for instruction matches
{
if ((bits & (bit0 | bit1)) == bit1)
{
this.code[bits] = code;
}
}
}
private void change(uint mode)
{
var bank = (mode == Mode.FIQ) ? fiq : usr;
registers[ 8] = bank.registers[2];
registers[ 9] = bank.registers[3];
registers[10] = bank.registers[4];
registers[11] = bank.registers[5];
registers[12] = bank.registers[6];
switch (mode)
{
case Mode.USR: registers[13] = usr.registers[0]; registers[14] = usr.registers[1]; spsr = null; break;
case Mode.FIQ: registers[13] = fiq.registers[0]; registers[14] = fiq.registers[1]; spsr = fiq.spsr; break;
case Mode.IRQ: registers[13] = irq.registers[0]; registers[14] = irq.registers[1]; spsr = irq.spsr; break;
case Mode.SVC: registers[13] = svc.registers[0]; registers[14] = svc.registers[1]; spsr = svc.spsr; break;
case Mode.ABT: registers[13] = abt.registers[0]; registers[14] = abt.registers[1]; spsr = abt.spsr; break;
case Mode.UND: registers[13] = und.registers[0]; registers[14] = und.registers[1]; spsr = und.spsr; break;
case Mode.SYS: registers[13] = usr.registers[0]; registers[14] = usr.registers[1]; spsr = null; break;
}
lr = registers[14];
pc = registers[15];
}
private uint encode(uint code)
{
return ((code >> 16) & 0xff0) | ((code >> 4) & 0x00f);
}
private void vector(uint mode, uint address, uint i, uint f)
{
change(mode);
spsr.copy(cpsr);
cpsr.i = i;
cpsr.f = f;
cpsr.t = 0;
lr.set(pc.value); // todo: -4?
pc.set(address);
}
#region exceptions
private void exception_res() { vector(Mode.SVC, 0x00000000, 1, 1); }
private void exception_und() { vector(Mode.UND, 0x00000004, 1, cpsr.f); }
private void exception_swi() { vector(Mode.SVC, 0x00000008, 1, cpsr.f); }
private void exception_pab() { vector(Mode.ABT, 0x0000000c, 1, cpsr.f); }
private void exception_dab() { vector(Mode.ABT, 0x00000010, 1, cpsr.f); }
private void exception____() { }
private void exception_irq() { vector(Mode.IRQ, 0x00000018, 1, cpsr.f); }
private void exception_fiq() { vector(Mode.FIQ, 0x0000001c, 1, 1); }
#endregion
protected void step() { }
public class Flags
{
public uint n, z, c, v;
public uint r;
public uint i, f, t, m;
public void copy(Flags value)
{
this.n = value.n;
this.z = value.z;
this.c = value.c;
this.v = value.v;
this.r = value.r;
this.i = value.i;
this.f = value.f;
this.t = value.t;
this.m = value.m;
}
public void load(uint value)
{
this.n = (value >> 31) & 1;
this.z = (value >> 30) & 1;
this.c = (value >> 29) & 1;
this.v = (value >> 28) & 1;
this.r = (value >> 8) & 0xfffff;
this.i = (value >> 7) & 1;
this.f = (value >> 6) & 1;
this.t = (value >> 5) & 1;
this.m = (value >> 0) & 31;
}
public uint save()
{
return
(this.n << 31) |
(this.z << 30) |
(this.c << 29) |
(this.v << 28) |
(this.r << 8) |
(this.i << 7) |
(this.f << 6) |
(this.t << 5) |
(this.m << 0);
}
}
public class Mode
{
public const uint USR = 0x10;
public const uint FIQ = 0x11;
public const uint IRQ = 0x12;
public const uint SVC = 0x13;
public const uint ABT = 0x17;
public const uint UND = 0x1b;
public const uint SYS = 0x1f;
public Flags spsr;
public Register[] registers;
public Mode(int index)
{
this.spsr = new Flags();
this.registers = new Register[index];
}
}
public class Register
{
public event Action modified;
public uint value;
public void set(uint value)
{
this.value = value;
if (this.modified != null)
this.modified();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml.Schema;
using System.Xml.XPath;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_Misc", Desc = "")]
public class TC_SchemaSet_Misc : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_Misc(ITestOutputHelper output)
{
_output = output;
}
public bool bWarningCallback;
public bool bErrorCallback;
public int errorCount;
public int warningCount;
public bool WarningInnerExceptionSet = false;
public bool ErrorInnerExceptionSet = false;
public void Initialize()
{
bWarningCallback = bErrorCallback = false;
errorCount = warningCount = 0;
WarningInnerExceptionSet = ErrorInnerExceptionSet = false;
}
//hook up validaton callback
public void ValidationCallback(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
_output.WriteLine("WARNING: ");
bWarningCallback = true;
warningCount++;
WarningInnerExceptionSet = (args.Exception.InnerException != null);
_output.WriteLine("\nInnerExceptionSet : " + WarningInnerExceptionSet + "\n");
}
else if (args.Severity == XmlSeverityType.Error)
{
_output.WriteLine("ERROR: ");
bErrorCallback = true;
errorCount++;
ErrorInnerExceptionSet = (args.Exception.InnerException != null);
_output.WriteLine("\nInnerExceptionSet : " + ErrorInnerExceptionSet + "\n");
}
_output.WriteLine(args.Message); // Print the error to the screen.
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - Bug110823 - SchemaSet.Add is holding onto some of the schema files after adding", Priority = 1)]
[InlineData()]
[Theory]
public void v1()
{
XmlSchemaSet xss = new XmlSchemaSet();
xss.XmlResolver = new XmlUrlResolver();
using (XmlTextReader xtr = new XmlTextReader(Path.Combine(TestData._Root, "bug110823.xsd")))
{
xss.Add(XmlSchema.Read(xtr, null));
}
}
//[Variation(Desc = "v2 - Bug115049 - XSD: content model validation for an invalid root element should be abandoned", Priority = 2)]
[InlineData()]
[Theory]
public void v2()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(null, Path.Combine(TestData._Root, "bug115049.xsd"));
ss.Compile();
//create reader
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.Schemas.Add(ss);
XmlReader vr = XmlReader.Create(Path.Combine(TestData._Root, "bug115049.xml"), settings);
while (vr.Read()) ;
CError.Compare(errorCount, 1, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v4 - 243300 - We are not correctly handling xs:anyType as xsi:type in the instance", Priority = 2)]
[InlineData()]
[Theory]
public void v4()
{
string xml = @"<a xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xsi:type='xsd:anyType'>1242<b/></a>";
Initialize();
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlReader vr = XmlReader.Create(new StringReader(xml), settings, (string)null);
while (vr.Read()) ;
CError.Compare(errorCount, 0, "Error Count mismatch!");
CError.Compare(warningCount, 1, "Warning Count mismatch!");
return;
}
/* Parameters = file name , is custom xml namespace System.Xml.Tests */
//[Variation(Desc = "v20 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v10.xsd", 2, false })]
[InlineData("bug264908_v10.xsd", 2, false)]
//[Variation(Desc = "v19 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v9.xsd", 5, true })]
[InlineData("bug264908_v9.xsd", 5, true)]
//[Variation(Desc = "v18 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v8.xsd", 5, false })]
[InlineData("bug264908_v8.xsd", 5, false)]
//[Variation(Desc = "v17 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v7.xsd", 4, false })]
[InlineData("bug264908_v7.xsd", 4, false)]
//[Variation(Desc = "v16 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v6.xsd", 4, true })]
[InlineData("bug264908_v6.xsd", 4, true)]
//[Variation(Desc = "v15 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v5.xsd", 4, false })]
[InlineData("bug264908_v5.xsd", 4, false)]
//[Variation(Desc = "v14 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v4.xsd", 4, true })]
[InlineData("bug264908_v4.xsd", 4, true)]
//[Variation(Desc = "v13 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v3.xsd", 1, true })]
[InlineData("bug264908_v3.xsd", 1, true)]
//[Variation(Desc = "v12 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v2.xsd", 1, true })]
[InlineData("bug264908_v2.xsd", 1, true)]
//[Variation(Desc = "v11 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v1.xsd", 3, true })]
[InlineData("bug264908_v1.xsd", 3, true)]
[Theory]
public void v10(object param0, object param1, object param2)
{
string xmlFile = param0.ToString();
int count = (int)param1;
bool custom = (bool)param2;
string attName = "blah";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(null, Path.Combine(TestData._Root, xmlFile));
ss.Compile();
//test the count
CError.Compare(ss.Count, count, "Count of SchemaSet not matched!");
//make sure the correct schema is in the set
if (custom)
{
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
return;
}
Assert.True(false);
}
return;
}
//[Variation(Desc = "v21 - Bug 319346 - Chameleon add of a schema into the xml namespace", Priority = 1)]
[InlineData()]
[Theory]
public void v20()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
string attName = "blah";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(xmlns, Path.Combine(TestData._Root, "bug264908_v11.xsd"));
ss.Compile();
//test the count
CError.Compare(ss.Count, 3, "Count of SchemaSet not matched!");
//make sure the correct schema is in the set
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
return;
}
Assert.True(false);
}
//[Variation(Desc = "v22 - Bug 338038 - Component should be additive into the Xml namespace", Priority = 1)]
[InlineData()]
[Theory]
public void v21()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
string attName = "blah1";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v1.xsd"));
ss.Compile();
//test the count
CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!");
//make sure the correct schema is in the set
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
return;
}
Assert.True(false);
}
//[Variation(Desc = "v23 - Bug 338038 - Conflicting components in custome xml namespace System.Xml.Tests be caught", Priority = 1)]
[InlineData()]
[Theory]
public void v22()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v2.xsd"));
try
{
ss.Compile();
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!");
return;
}
Assert.True(false);
}
//[Variation(Desc = "v24 - Bug 338038 - Change type of xml:lang to decimal in custome xml namespace System.Xml.Tests", Priority = 1)]
[InlineData()]
[Theory]
public void v24()
{
string attName = "lang";
string newtype = "decimal";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd"));
ss.Compile();
CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!");
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, newtype, "Incorrect type for xml:lang");
return;
}
}
Assert.True(false);
}
//[Variation(Desc = "v25 - Bug 338038 - Conflicting definitions for xml attributes in two schemas", Priority = 1)]
[InlineData()]
[Theory]
public void v25()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd"));
ss.Compile();
try
{
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3b.xsd"));
ss.Compile();
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!");
return;
}
Assert.True(false);
}
//[Variation(Desc = "v26 - Bug 338038 - Change type of xml:lang to decimal and xml:base to short in two steps", Priority = 1)]
[InlineData()]
[Theory]
public void v26()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4b.xsd"));
ss.Compile();
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == "lang")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "decimal", "Incorrect type for xml:lang");
}
if (a.QualifiedName.Name == "base")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "short", "Incorrect type for xml:base");
}
}
CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!");
return;
}
//[Variation(Desc = "v27 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests", Priority = 1)]
[InlineData()]
[Theory]
public void v27()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd"));
ss.Compile();
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == "blah")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang");
}
}
CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!");
return;
}
//[Variation(Desc = "v28 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests, remove default ns schema", Priority = 1)]
[InlineData()]
[Theory]
public void v28()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
XmlSchema schema = null;
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
foreach (XmlSchema s in ss.Schemas(xmlns))
{
schema = s;
}
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd"));
ss.Compile();
ss.Remove(schema);
ss.Compile();
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == "blah")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang");
}
}
CError.Compare(ss.Count, 5, "Count of SchemaSet not matched!");
return;
}
//Regressions - Bug Fixes
public void Callback1(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
_output.WriteLine("WARNING Recieved");
bWarningCallback = true;
warningCount++;
CError.Compare(args.Exception.InnerException == null, false, "Inner Exception not set");
}
}
//[Variation(Desc = "v100 - Bug 320502 - XmlSchemaSet: while throwing a warning for invalid externals we do not set the inner exception", Priority = 1)]
[InlineData()]
[Theory]
public void v100()
{
string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:include schemaLocation='bogus'/></xs:schema>";
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(Callback1);
ss.Add(null, new XmlTextReader(new StringReader(xsd)));
ss.Compile();
CError.Compare(warningCount, 1, "Warning Count mismatch!");
return;
}
//[Variation(Desc = "v101 - Bug 339706 - XmlSchemaSet: Compile on the set fails when a compiled schema containing notation is already present", Priority = 1)]
[InlineData()]
[Theory]
public void v101()
{
string xsd1 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:notation name='a' public='a'/></xs:schema>";
string xsd2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='root'/></xs:schema>";
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(Callback1);
ss.Add(null, new XmlTextReader(new StringReader(xsd1)));
ss.Compile();
ss.Add(null, new XmlTextReader(new StringReader(xsd2)));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v102 - Bug 337850 - XmlSchemaSet: Type already declared error when redefined schema is added to the set before the redefining schema.", Priority = 1)]
[InlineData()]
[Theory]
public void v102()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(null, Path.Combine(TestData._Root, "schZ013c.xsd"));
ss.Add(null, Path.Combine(TestData._Root, "schZ013a.xsd"));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v104 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled SOM.", Priority = 1, Params = new object[] { false })]
[InlineData(false)]
//[Variation(Desc = "v103 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled set.", Priority = 1, Params = new object[] { true })]
[InlineData(true)]
[Theory]
public void v103(object param0)
{
bool addset = (bool)param0;
Initialize();
XmlSchemaSet ss1 = new XmlSchemaSet();
ss1.XmlResolver = new XmlUrlResolver();
ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss1.Add(null, Path.Combine(TestData._Root, "Misc103_x.xsd"));
ss1.Compile();
CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!");
XmlSchemaSet ss2 = new XmlSchemaSet();
ss2.XmlResolver = new XmlUrlResolver();
ss2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema s = ss2.Add(null, Path.Combine(TestData._Root, "Misc103_a.xsd"));
ss2.Compile();
CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!");
if (addset)
{
ss1.Add(ss2);
CError.Compare(ss1.GlobalElements.Count, 7, "Schema Set 1 GlobalElements Count mismatch!");
CError.Compare(ss1.GlobalAttributes.Count, 2, "Schema Set 1 GlobalAttributes Count mismatch!");
CError.Compare(ss1.GlobalTypes.Count, 6, "Schema Set 1 GlobalTypes Count mismatch!");
}
else
{
ss1.Add(s);
CError.Compare(ss1.GlobalElements.Count, 2, "Schema Set 1 GlobalElements Count mismatch!");
CError.Compare(ss1.GlobalAttributes.Count, 0, "Schema Set 1 GlobalAttributes Count mismatch!");
CError.Compare(ss1.GlobalTypes.Count, 2, "Schema Set 1 GlobalTypes Count mismatch!");
}
/***********************************************/
XmlSchemaSet ss3 = new XmlSchemaSet();
ss3.XmlResolver = new XmlUrlResolver();
ss3.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss3.Add(null, Path.Combine(TestData._Root, "Misc103_c.xsd"));
ss3.Compile();
ss1.Add(ss3);
CError.Compare(ss1.GlobalElements.Count, 8, "Schema Set 1 GlobalElements Count mismatch!");
return;
}
//[Variation(Desc = "v103 - Reference to a component from no namespace System.Xml.Tests an explicit import of no namespace System.Xml.Tests throw a validation warning", Priority = 1)]
[InlineData()]
[Theory]
public void v105()
{
Initialize();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(null, Path.Combine(TestData._Root, "Misc105.xsd"));
CError.Compare(warningCount, 1, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v106 - Adding a compiled SoS(schema for schema) to a set causes type collision error", Priority = 1)]
[InlineData()]
[Theory]
public void v106()
{
Initialize();
XmlSchemaSet ss1 = new XmlSchemaSet();
ss1.XmlResolver = new XmlUrlResolver();
ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlReaderSettings settings = new XmlReaderSettings();
#pragma warning disable 0618
settings.ProhibitDtd = false;
#pragma warning restore 0618
XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "XMLSchema.xsd"), settings);
ss1.Add(null, r);
ss1.Compile();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
foreach (XmlSchema s in ss1.Schemas())
{
ss.Add(s);
}
ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd"));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v107 - XsdValidatingReader: InnerException not set on validation warning of a schemaLocation not loaded.", Priority = 1)]
[InlineData()]
[Theory]
public void v107()
{
string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='a bug356711_a.xsd' xmlns:a='a'></root>";
Initialize();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd"));
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.Schemas.Add(schemaSet);
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.ValidationType = ValidationType.Schema;
XmlReader vr = XmlReader.Create(new StringReader(strXml), settings);
while (vr.Read()) ;
CError.Compare(warningCount, 1, "Warning Count mismatch!");
CError.Compare(WarningInnerExceptionSet, true, "Inner Exception not set!");
return;
}
//[Variation(Desc = "v108 - XmlSchemaSet.Add() should not trust compiled state of the schema being added", Priority = 1)]
[InlineData()]
[Theory]
public void v108()
{
string strSchema1 = @"
<xs:schema targetNamespace='http://bar'
xmlns='http://bar' xmlns:x='http://foo'
elementFormDefault='qualified'
attributeFormDefault='unqualified'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:import namespace='http://foo'/>
<xs:element name='bar'>
<xs:complexType>
<xs:sequence>
<xs:element ref='x:foo'/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
";
string strSchema2 = @"<xs:schema targetNamespace='http://foo'
xmlns='http://foo' xmlns:x='http://bar'
elementFormDefault='qualified'
attributeFormDefault='unqualified'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:import namespace='http://bar'/>
<xs:element name='foo'>
<xs:complexType>
<xs:sequence>
<xs:element ref='x:bar'/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
Initialize();
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
ValidationEventHandler handler = new ValidationEventHandler(ValidationCallback);
set.ValidationEventHandler += handler;
XmlSchema s1 = null;
using (XmlReader r = XmlReader.Create(new StringReader(strSchema1)))
{
s1 = XmlSchema.Read(r, handler);
set.Add(s1);
}
set.Compile();
// Now load set 2
set = new XmlSchemaSet();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema s2 = null;
using (XmlReader r = XmlReader.Create(new StringReader(strSchema2)))
{
s2 = XmlSchema.Read(r, handler);
}
XmlSchemaImport import = (XmlSchemaImport)s2.Includes[0];
import.Schema = s1;
import = (XmlSchemaImport)s1.Includes[0];
import.Schema = s2;
set.Add(s1);
set.Reprocess(s1);
set.Add(s2);
set.Reprocess(s2);
set.Compile();
s2 = null;
using (XmlReader r = XmlReader.Create(new StringReader(strSchema2)))
{
s2 = XmlSchema.Read(r, handler);
}
set = new XmlSchemaSet();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
import = (XmlSchemaImport)s2.Includes[0];
import.Schema = s1;
import = (XmlSchemaImport)s1.Includes[0];
import.Schema = s2;
set.Add(s1);
set.Reprocess(s1);
set.Add(s2);
set.Reprocess(s2);
set.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch");
return;
}
//[Variation(Desc = "v109 - 386243, Adding a chameleon schema agsinst to no namaespace throws unexpected warnings", Priority = 1)]
[InlineData()]
[Theory]
public void v109()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
ss.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v110 - 386246, ArgumentException 'item arleady added' error on a chameleon add done twice", Priority = 1)]
[InlineData()]
[Theory]
public void v110()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema s1 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
XmlSchema s2 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v111 - 380805, Chameleon include compiled in one set added to another", Priority = 1)]
[InlineData()]
[Theory]
public void v111()
{
Initialize();
XmlSchemaSet newSet = new XmlSchemaSet();
newSet.XmlResolver = new XmlUrlResolver();
newSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema chameleon = newSet.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
newSet.Compile();
CError.Compare(newSet.GlobalTypes.Count, 10, "GlobalTypes count mismatch!");
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
sc.Add(chameleon);
sc.Add(null, Path.Combine(TestData._Root, "baseEmployee.xsd"));
sc.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v112 - 382035, schema set tables not cleared as expected on reprocess", Priority = 1)]
[InlineData()]
[Theory]
public void v112()
{
Initialize();
XmlSchemaSet set2 = new XmlSchemaSet();
set2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema includedSchema = set2.Add(null, Path.Combine(TestData._Root, "bug382035a1.xsd"));
set2.Compile();
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema mainSchema = set.Add(null, Path.Combine(TestData._Root, "bug382035a.xsd"));
set.Compile();
XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "bug382035a1.xsd"));
XmlSchema reParsedInclude = XmlSchema.Read(r, new ValidationEventHandler(ValidationCallback));
((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude;
set.Reprocess(mainSchema);
set.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v113 - Set InnerException on XmlSchemaValidationException while parsing typed values", Priority = 1)]
[InlineData()]
[Theory]
public void v113()
{
string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema' xsi:type='xs:int'>a</root>";
Initialize();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.ValidationType = ValidationType.Schema;
XmlReader vr = XmlReader.Create(new StringReader(strXml), settings);
while (vr.Read()) ;
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch!");
CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!");
return;
}
//[Variation(Desc = "v114 - XmlSchemaSet: InnerException not set on parse errors during schema compilation", Priority = 1)]
[InlineData()]
[Theory]
public void v114()
{
string strXsd = @"<xs:schema elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='date' type='date'/>
<xs:simpleType name='date'>
<xs:restriction base='xs:int'>
<xs:enumeration value='a'/>
</xs:restriction>
</xs:simpleType>
</xs:schema>";
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(XmlSchema.Read(new StringReader(strXsd), new ValidationEventHandler(ValidationCallback)));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch!");
CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!");
return;
}
//[Variation(Desc = "v116 - 405327 NullReferenceExceptions while accessing obsolete properties in the SOM", Priority = 1)]
[InlineData()]
[Theory]
public void v116()
{
#pragma warning disable 0618
XmlSchemaAttribute attribute = new XmlSchemaAttribute();
object attributeType = attribute.AttributeType;
XmlSchemaElement element = new XmlSchemaElement();
object elementType = element.ElementType;
XmlSchemaType schemaType = new XmlSchemaType();
object BaseSchemaType = schemaType.BaseSchemaType;
#pragma warning restore 0618
}
//[Variation(Desc = "v117 - 398474 InnerException not set on XmlSchemaException, when xs:pattern has an invalid regular expression", Priority = 1)]
[InlineData()]
[Theory]
public void v117()
{
string strXsdv117 =
@"<?xml version='1.0' encoding='utf-8' ?>
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='doc'>
<xs:complexType>
<xs:sequence>
<xs:element name='value' maxOccurs='unbounded'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:pattern value='(?r:foo)'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
Initialize();
using (StringReader reader = new StringReader(strXsdv117))
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(XmlSchema.Read(reader, ValidationCallback));
ss.Compile();
CError.Compare(ErrorInnerExceptionSet, true, "\nInner Exception not set\n");
}
return;
}
//[Variation(Desc = "v118 - 424904 Not getting unhandled attributes on particle", Priority = 1)]
[InlineData()]
[Theory]
public void v118()
{
using (XmlReader r = new XmlTextReader(Path.Combine(TestData._Root, "Bug424904.xsd")))
{
XmlSchema s = XmlSchema.Read(r, null);
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.Add(s);
set.Compile();
XmlQualifiedName name = new XmlQualifiedName("test2", "http://foo");
XmlSchemaComplexType test2type = s.SchemaTypes[name] as XmlSchemaComplexType;
XmlSchemaParticle p = test2type.ContentTypeParticle;
XmlAttribute[] att = p.UnhandledAttributes;
Assert.False(att == null || att.Length < 1);
}
}
//[Variation(Desc = "v120 - 397633 line number and position not set on the validation error for an invalid xsi:type value", Priority = 1)]
[InlineData()]
[Theory]
public void v120()
{
using (XmlReader schemaReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xsd")))
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.Add("", schemaReader);
sc.Compile();
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = sc;
using (XmlReader docValidatingReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings))
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(docValidatingReader);
doc.Validate(null);
}
catch (XmlSchemaValidationException ex)
{
if (ex.LineNumber == 1 && ex.LinePosition == 2 && !string.IsNullOrEmpty(ex.SourceUri))
{
return;
}
}
}
}
Assert.True(false);
}
//[Variation(Desc = "v120a.XmlDocument.Load non-validating reader.Expect IOE.")]
[InlineData()]
[Theory]
public void v120a()
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
using (XmlReader reader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings))
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(reader);
doc.Validate(null);
}
catch (XmlSchemaValidationException ex)
{
_output.WriteLine(ex.Message);
return;
}
}
Assert.True(false);
}
//[Variation(Desc = "444196: XmlReader.MoveToNextAttribute returns incorrect results")]
[InlineData()]
[Theory]
public void v124()
{
Initialize();
string XamlPresentationNamespace =
"http://schemas.microsoft.com/winfx/2006/xaml/presentation";
string XamlToParse =
"<pfx0:DrawingBrush TileMode=\"Tile\" Viewbox=\"foobar\" />";
string xml =
" <xs:schema " +
" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
" targetNamespace=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
" elementFormDefault=\"qualified\" " +
" attributeFormDefault=\"unqualified\"" +
" >" +
"" +
" <xs:element name=\"DrawingBrush\" type=\"DrawingBrushType\" />" +
"" +
" <xs:complexType name=\"DrawingBrushType\">" +
" <xs:attribute name=\"Viewbox\" type=\"xs:string\" />" +
" <xs:attribute name=\"TileMode\" type=\"xs:string\" />" +
" </xs:complexType>" +
" </xs:schema>";
XmlSchema schema = XmlSchema.Read(new StringReader(xml), null);
schema.TargetNamespace = XamlPresentationNamespace;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.Add(schema);
schemaSet.Compile();
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = schemaSet;
NameTable nameTable = new NameTable();
XmlNamespaceManager namespaces = new XmlNamespaceManager(nameTable);
namespaces.AddNamespace("pfx0", XamlPresentationNamespace);
namespaces.AddNamespace(string.Empty, XamlPresentationNamespace);
XmlParserContext parserContext = new XmlParserContext(nameTable, namespaces, null, null, null, null, null, null, XmlSpace.None);
using (XmlReader xmlReader = XmlReader.Create(new StringReader(XamlToParse), readerSettings, parserContext))
{
xmlReader.Read();
xmlReader.MoveToAttribute(0);
xmlReader.MoveToNextAttribute();
xmlReader.MoveToNextAttribute();
xmlReader.MoveToNextAttribute();
xmlReader.MoveToAttribute(0);
if (xmlReader.MoveToNextAttribute())
return;
}
Assert.True(false);
}
//[Variation(Desc = "615444 XmlSchema.Write ((XmlWriter)null) throws InvalidOperationException instead of ArgumenNullException")]
[Fact]
public void v125()
{
XmlSchema xs = new XmlSchema();
try
{
xs.Write((XmlWriter)null);
}
catch (InvalidOperationException) { return; }
Assert.True(false);
}
//[Variation(Desc = "Dev10_40561 Redefine Chameleon: Unexpected qualified name on local particle")]
[InlineData()]
[Theory]
public void Dev10_40561()
{
Initialize();
string xml = @"<?xml version='1.0' encoding='utf-8'?><e1 xmlns='ns-a'> <c23 xmlns='ns-b'/></e1>";
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
string path = Path.Combine(TestData.StandardPath, "xsd10", "SCHEMA", "schN11_a.xsd");
set.Add(null, path);
set.Compile();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = set;
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
{
try
{
while (reader.Read()) ;
_output.WriteLine("XmlSchemaValidationException was not thrown");
Assert.True(false);
}
catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); }
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
// Test failure on ILC: Test depends on Xml Serialization and requires reflection on a LOT of types under System.Xml.Schema namespace.
// Rd.xml with "<Namespace Name="System.Xml.Schema" Dynamic="Required Public" />" lets this test pass but we should probably be
// fixing up XmlSerializer's own rd.xml rather than the test here.
[Fact]
public void GetBuiltinSimpleTypeWorksAsEcpected()
{
Initialize();
string xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine +
" <xs:simpleType>" + Environment.NewLine +
" <xs:restriction base=\"xs:anySimpleType\" />" + Environment.NewLine +
" </xs:simpleType>" + Environment.NewLine +
"</xs:schema>";
XmlSchema schema = new XmlSchema();
XmlSchemaSimpleType stringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String);
schema.Items.Add(stringType);
StringWriter sw = new StringWriter();
schema.Write(sw);
CError.Compare(sw.ToString(), xml, "Mismatch");
return;
}
//[Variation(Desc = "Dev10_40509 Assert and NRE when validate the XML against the XSD")]
[InlineData()]
[Theory]
public void Dev10_40509()
{
Initialize();
string xml = Path.Combine(TestData._Root, "bug511217.xml");
string xsd = Path.Combine(TestData._Root, "bug511217.xsd");
XmlSchemaSet s = new XmlSchemaSet();
s.XmlResolver = new XmlUrlResolver();
XmlReader r = XmlReader.Create(xsd);
s.Add(null, r);
s.Compile();
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
using (XmlReader docValidatingReader = XmlReader.Create(xml, rs))
{
XmlDocument doc = new XmlDocument();
doc.Load(docValidatingReader);
doc.Schemas = s;
doc.Validate(null);
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "Dev10_40511 XmlSchemaSet::Compile throws XmlSchemaException for valid schema")]
[InlineData()]
[Theory]
public void Dev10_40511()
{
Initialize();
string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:simpleType name='textType'>
<xs:restriction base='xs:string'>
<xs:minLength value='1' />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name='statusCodeType'>
<xs:restriction base='textType'>
<xs:length value='6' />
</xs:restriction>
</xs:simpleType>
</xs:schema>";
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.Add("xs", XmlReader.Create(new StringReader(xsd)));
sc.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "Dev10_40495 Undefined ComplexType error when loading schemas from in memory strings")]
[InlineData()]
[Theory]
public void Dev10_40495()
{
Initialize();
const string schema1Str = @"<xs:schema xmlns:tns=""http://BizTalk_Server_Project2.Schema1"" xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" targetNamespace=""http://BizTalk_Server_Project2.Schema1"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:include schemaLocation=""S3"" />
<xs:include schemaLocation=""S2"" />
<xs:element name=""Root"">
<xs:complexType>
<xs:sequence>
<xs:element name=""FxTypeElement"">
<xs:complexType>
<xs:complexContent mixed=""false"">
<xs:extension base=""tns:FxType"">
<xs:attribute name=""Field"" type=""xs:string"" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
const string schema2Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:complexType name=""FxType"">
<xs:attribute name=""Fx2"" type=""xs:string"" />
</xs:complexType>
</xs:schema>";
const string schema3Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:complexType name=""TestType"">
<xs:attribute name=""Fx2"" type=""xs:string"" />
</xs:complexType>
</xs:schema>";
XmlSchema schema1 = XmlSchema.Read(new StringReader(schema1Str), null);
XmlSchema schema2 = XmlSchema.Read(new StringReader(schema2Str), null);
XmlSchema schema3 = XmlSchema.Read(new StringReader(schema3Str), null);
//schema1 has some xs:includes in it. Since all schemas are string based, XmlSchema on its own cannot load automatically
//load these included schemas. We will resolve these schema locations schema1 and make them point to the correct
//in memory XmlSchema objects
((XmlSchemaExternal)schema1.Includes[0]).Schema = schema3;
((XmlSchemaExternal)schema1.Includes[1]).Schema = schema2;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
if (schemaSet.Add(schema1) != null)
{
//This compile will complain about Undefined complex Type tns:FxType and schemaSet_ValidationEventHandler will be
//called with this error.
schemaSet.Compile();
schemaSet.Reprocess(schema1);
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "Dev10_64765 XmlSchemaValidationException.SourceObject is always null when using XPathNavigator.CheckValidity method")]
[InlineData()]
[Theory]
public void Dev10_64765()
{
Initialize();
string xsd =
"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
"<xsd:element name='some'>" +
"</xsd:element>" +
"</xsd:schema>";
string xml = "<root/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
ValidateXPathNavigator(xml, CompileSchemaSet(xsd));
return;
}
private void ValidateXPathNavigator(string xml, XmlSchemaSet schemaSet)
{
XPathDocument doc = new XPathDocument(new StringReader(xml));
XPathNavigator nav = doc.CreateNavigator();
ValidateXPathNavigator(nav, schemaSet);
}
private void ValidateXPathNavigator(XPathNavigator nav, XmlSchemaSet schemaSet)
{
_output.WriteLine(nav.CheckValidity(schemaSet, OnValidationEvent) ? "Validation succeeded." : "Validation failed.");
}
private XmlSchemaSet CompileSchemaSet(string xsd)
{
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.Add(XmlSchema.Read(new StringReader(xsd), OnValidationEvent));
schemaSet.ValidationEventHandler += OnValidationEvent;
schemaSet.Compile();
return schemaSet;
}
private void OnValidationEvent(object sender, ValidationEventArgs e)
{
XmlSchemaValidationException exception = e.Exception as XmlSchemaValidationException;
if (exception == null || exception.SourceObject == null)
{
CError.Compare(exception != null, "exception == null");
CError.Compare(exception.SourceObject != null, "SourceObject == null");
return;
}
if (!PlatformDetection.IsNetNative) // Cannot get names of internal framework types
{
CError.Compare(exception.SourceObject.GetType().ToString(), "MS.Internal.Xml.Cache.XPathDocumentNavigator", "SourceObject.GetType");
}
_output.WriteLine("Exc: " + exception);
}
//[Variation(Desc = "Dev10_40563 XmlSchemaSet: Assert Failure with Chk Build.")]
[InlineData()]
[Theory]
public void Dev10_40563()
{
Initialize();
string xsd =
"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
"<xsd:element name='some'>" +
"</xsd:element>" +
"</xsd:schema>";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add("http://www.w3.org/2001/XMLSchema", XmlReader.Create(new StringReader(xsd)));
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.Schemas = ss;
string input = "<root xml:space='default'/>";
using (XmlReader r1 = XmlReader.Create(new StringReader(input), rs))
{
using (XmlReader r2 = XmlReader.Create(new StringReader(input), rs))
{
while (r1.Read()) ;
while (r2.Read()) ;
}
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "TFS_470020 Schema with substitution groups does not throw when content model is ambiguous")]
[InlineData()]
[Theory]
public void TFS_470020()
{
Initialize();
string xml = @"<?xml version='1.0' encoding='utf-8' ?>
<e3>
<e2>1</e2>
<e2>1</e2>
</e3>";
string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'>
<xs:element name='e1' type='xs:int'/>
<xs:element name='e2' type='xs:int' substitutionGroup='e1'/>
<xs:complexType name='t3'>
<xs:sequence>
<xs:element ref='e1' minOccurs='0' maxOccurs='1'/>
<xs:element name='e2' type='xs:int' minOccurs='0' maxOccurs='1'/>
</xs:sequence>
</xs:complexType>
<xs:element name='e3' type='t3'/>
</xs:schema>";
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.Add(null, XmlReader.Create(new StringReader(xsd)));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
doc.Schemas = set;
doc.Validate(ValidationCallback);
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch!");
return;
}
}
}
| |
//
// TreeViewBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
namespace Xwt.Mac
{
public class TreeViewBackend: TableViewBackend<NSOutlineView,ITreeViewEventSink>, ITreeViewBackend
{
ITreeDataSource source;
TreeSource tsource;
class TreeDelegate: NSOutlineViewDelegate
{
public TreeViewBackend Backend;
public override void ItemDidExpand (NSNotification notification)
{
Backend.EventSink.OnRowExpanded (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override void ItemWillExpand (NSNotification notification)
{
Backend.EventSink.OnRowExpanding (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override void ItemDidCollapse (NSNotification notification)
{
Backend.EventSink.OnRowCollapsed (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override void ItemWillCollapse (NSNotification notification)
{
Backend.EventSink.OnRowCollapsing (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override nfloat GetRowHeight (NSOutlineView outlineView, NSObject item)
{
nfloat height;
var treeItem = (TreeItem)item;
if (!Backend.RowHeights.TryGetValue (treeItem, out height) || height <= 0)
height = Backend.RowHeights [treeItem] = Backend.CalcRowHeight (treeItem, false);
return height;
}
public override NSTableRowView RowViewForItem (NSOutlineView outlineView, NSObject item)
{
return outlineView.GetRowView (outlineView.RowForItem (item), false) ?? new TableRowView ();
}
public override NSView GetView (NSOutlineView outlineView, NSTableColumn tableColumn, NSObject item)
{
var col = tableColumn as TableColumn;
var cell = outlineView.MakeView (tableColumn.Identifier, this) as CompositeCell;
if (cell == null)
cell = col.CreateNewView ();
if (cell.ObjectValue != item)
cell.ObjectValue = item;
return cell;
}
public override nfloat GetSizeToFitColumnWidth (NSOutlineView outlineView, nint column)
{
var tableColumn = Backend.Columns[(int)column] as TableColumn;
var width = tableColumn.HeaderCell.CellSize.Width;
CompositeCell templateCell = null;
for (int i = 0; i < outlineView.RowCount; i++) {
var cellView = outlineView.GetView (column, i, false) as CompositeCell;
if (cellView == null) { // use template for invisible rows
cellView = templateCell ?? (templateCell = (tableColumn as TableColumn)?.DataView?.Copy () as CompositeCell);
if (cellView != null)
cellView.ObjectValue = outlineView.ItemAtRow (i);
}
if (cellView != null) {
if (column == 0) // first column contains expanders
width = (nfloat)Math.Max (width, cellView.Frame.X + cellView.FittingSize.Width);
else
width = (nfloat)Math.Max (width, cellView.FittingSize.Width);
}
}
return width;
}
public override NSIndexSet GetSelectionIndexes(NSOutlineView outlineView, NSIndexSet proposedSelectionIndexes)
{
return Backend.SelectionMode != SelectionMode.None ? proposedSelectionIndexes : new NSIndexSet();
}
}
OutlineViewBackend Tree {
get { return (OutlineViewBackend) Table; }
}
protected override NSTableView CreateView ()
{
var t = new OutlineViewBackend (this);
t.Delegate = new TreeDelegate () { Backend = this };
return t;
}
public bool AnimationsEnabled {
get {
return Tree.AnimationsEnabled;
}
set {
Tree.AnimationsEnabled = value;
}
}
protected override string SelectionChangeEventName {
get { return "NSOutlineViewSelectionDidChangeNotification"; }
}
public TreePosition CurrentEventRow { get; internal set; }
public override NSTableColumn AddColumn (ListViewColumn col)
{
NSTableColumn tcol = base.AddColumn (col);
if (Tree.OutlineTableColumn == null)
Tree.OutlineTableColumn = tcol;
return tcol;
}
public void SetSource (ITreeDataSource source, IBackend sourceBackend)
{
this.source = source;
RowHeights.Clear ();
tsource = new TreeSource (source);
Tree.DataSource = tsource;
source.NodeInserted += (sender, e) => {
var parent = tsource.GetItem (source.GetParent (e.Node));
Tree.ReloadItem (parent, parent == null || Tree.IsItemExpanded (parent));
};
source.NodeDeleted += (sender, e) => {
var parent = tsource.GetItem (e.Node);
var item = tsource.GetItem(e.Child);
if (item != null)
RowHeights.Remove (null);
Tree.ReloadItem (parent, parent == null || Tree.IsItemExpanded (parent));
};
source.NodeChanged += (sender, e) => {
var item = tsource.GetItem (e.Node);
if (item != null) {
Tree.ReloadItem (item, false);
UpdateRowHeight (item);
}
};
source.NodesReordered += (sender, e) => {
var parent = tsource.GetItem (e.Node);
Tree.ReloadItem (parent, parent == null || Tree.IsItemExpanded (parent));
};
source.Cleared += (sender, e) =>
{
Tree.ReloadData ();
RowHeights.Clear ();
};
}
public override object GetValue (object pos, int nField)
{
return source.GetValue ((TreePosition)pos, nField);
}
public override void SetValue (object pos, int nField, object value)
{
source.SetValue ((TreePosition)pos, nField, value);
}
public override void InvalidateRowHeight (object pos)
{
UpdateRowHeight (tsource.GetItem((TreePosition)pos));
}
Dictionary<TreeItem, nfloat> RowHeights = new Dictionary<TreeItem, nfloat> ();
bool updatingRowHeight;
void UpdateRowHeight (TreeItem pos)
{
if (updatingRowHeight)
return;
var row = Tree.RowForItem (pos);
if (row >= 0) {
// calculate new height now by reusing the visible cell to avoid using the template cell with unnecessary data reloads
// NOTE: cell reusing is not supported in Delegate.GetRowHeight and would require an other data reload to the template cell
RowHeights[pos] = CalcRowHeight (pos);
Table.NoteHeightOfRowsWithIndexesChanged (NSIndexSet.FromIndex (row));
} else // Invalidate the height, to force recalculation in Delegate.GetRowHeight
RowHeights[pos] = -1;
}
nfloat CalcRowHeight (TreeItem pos, bool tryReuse = true)
{
updatingRowHeight = true;
var height = Table.RowHeight;
var row = Tree.RowForItem (pos);
for (int i = 0; i < Columns.Count; i++) {
CompositeCell cell = tryReuse && row >= 0 ? Tree.GetView (i, row, false) as CompositeCell : null;
if (cell == null) {
cell = (Columns [i] as TableColumn)?.DataView as CompositeCell;
cell.ObjectValue = pos;
height = (nfloat)Math.Max (height, cell.FittingSize.Height);
} else {
height = (nfloat)Math.Max (height, cell.GetRequiredHeightForWidth (cell.Frame.Width));
}
}
updatingRowHeight = false;
return height;
}
public TreePosition[] SelectedRows {
get {
TreePosition[] res = new TreePosition [Table.SelectedRowCount];
int n = 0;
if (Table.SelectedRowCount > 0) {
foreach (var i in Table.SelectedRows) {
res [n] = ((TreeItem)Tree.ItemAtRow ((int)i)).Position;
n++;
}
}
return res;
}
}
public TreePosition FocusedRow {
get {
if (Table.SelectedRowCount > 0)
return ((TreeItem)Tree.ItemAtRow ((int)Table.SelectedRows.FirstIndex)).Position;
return null;
}
set {
SelectRow (value);
ScrollToRow (value);
}
}
public override void SetCurrentEventRow (object pos)
{
CurrentEventRow = (TreePosition)pos;
}
public void SelectRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
Table.SelectRow ((int)Tree.RowForItem (it), Table.AllowsMultipleSelection);
}
public void UnselectRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
Table.DeselectRow (Tree.RowForItem (it));
}
public bool IsRowSelected (TreePosition pos)
{
var it = tsource.GetItem (pos);
return it != null && Table.IsRowSelected (Tree.RowForItem (it));
}
public bool IsRowExpanded (TreePosition pos)
{
var it = tsource.GetItem (pos);
return it != null && Tree.IsItemExpanded (it);
}
public void ExpandRow (TreePosition pos, bool expandChildren)
{
var it = tsource.GetItem (pos);
if (it != null)
Tree.ExpandItem (it, expandChildren);
}
public void CollapseRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
Tree.CollapseItem (it);
}
public void ScrollToRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
ScrollToRow ((int)Tree.RowForItem (it));
}
public void ExpandToRow (TreePosition pos)
{
var p = source.GetParent (pos);
if (p == null)
return;
var s = new Stack<TreePosition> ();
while (p != null) {
s.Push (p);
p = source.GetParent (p);
}
while (s.Count > 0) {
var it = tsource.GetItem (s.Pop ());
if (it == null)
break;
Tree.ExpandItem (it, false);
}
}
public TreePosition GetRowAtPosition (Point p)
{
var row = Table.GetRow (new CGPoint ((float)p.X, (float)p.Y));
return row >= 0 ? ((TreeItem)Tree.ItemAtRow (row)).Position : null;
}
public Rectangle GetCellBounds (TreePosition pos, CellView cell, bool includeMargin)
{
var it = tsource.GetItem (pos);
if (it == null)
return Rectangle.Zero;
var row = (int)Tree.RowForItem (it);
return GetCellBounds (row, cell, includeMargin);
}
public Rectangle GetRowBounds (TreePosition pos, bool includeMargin)
{
var it = tsource.GetItem (pos);
if (it == null)
return Rectangle.Zero;
var row = (int)Tree.RowForItem (it);
return GetRowBounds (row, includeMargin);
}
public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition)
{
// Get row
nint row = Tree.GetRow(new CGPoint ((nfloat)x, (nfloat)y));
pos = RowDropPosition.Into;
nodePosition = null;
if (row >= 0) {
nodePosition = ((TreeItem)Tree.ItemAtRow (row)).Position;
}
return nodePosition != null;
}
/* protected override void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args)
{
base.OnDragOverCheck (di, args);
var row = Tree.GetRow (new CGPoint (di.DraggingLocation.X, di.DraggingLocation.Y));
if (row != -1) {
var item = Tree.ItemAtRow (row);
Tree.SetDropItem (item, row);
}
}
protected override void OnDragOver (NSDraggingInfo di, DragOverEventArgs args)
{
base.OnDragOver (di, args);
var p = Tree.ConvertPointFromView (di.DraggingLocation, null);
var row = Tree.GetRow (p);
if (row != -1) {
Tree.SetDropRowDropOperation (row, NSTableViewDropOperation.On);
var item = Tree.ItemAtRow (row);
Tree.SetDropItem (item, 0);
}
}*/
}
class TreeItem: NSObject, ITablePosition
{
public TreePosition Position;
public TreeItem ()
{
}
public TreeItem (NativeHandle p): base (p)
{
}
object ITablePosition.Position {
get { return Position; }
}
public override NSObject Copy ()
{
return new TreeItem { Position = this.Position };
}
}
class TreeSource: NSOutlineViewDataSource
{
ITreeDataSource source;
Dictionary<TreePosition,TreeItem> items = new Dictionary<TreePosition, TreeItem> ();
public TreeSource (ITreeDataSource source)
{
this.source = source;
source.NodeInserted += (sender, e) => {
if (!items.ContainsKey (e.Node))
items.Add (e.Node, new TreeItem { Position = e.Node });
};
source.NodeDeleted += (sender, e) => {
items.Remove (e.Child);
};
source.Cleared += (sender, e) => {
items.Clear ();
};
}
public TreeItem GetItem (TreePosition pos)
{
if (pos == null)
return null;
TreeItem it;
items.TryGetValue (pos, out it);
return it;
}
[Export("tableView:acceptDrop:row:dropOperation:")]
public bool AcceptDrop (NSOutlineView outlineView, INSDraggingInfo info, NSObject item, nint index)
{
return false;
}
public override string[] FilesDropped (NSOutlineView outlineView, NSUrl dropDestination, NSArray items)
{
throw new NotImplementedException ();
}
public override NSObject GetChild (NSOutlineView outlineView, nint childIndex, NSObject item)
{
var treeItem = (TreeItem) item;
var pos = source.GetChild (treeItem != null ? treeItem.Position : null, (int) childIndex);
if (pos != null) {
TreeItem res;
if (!items.TryGetValue (pos, out res))
items [pos] = res = new TreeItem () { Position = pos };
return res;
}
else
return null;
}
public override nint GetChildrenCount (NSOutlineView outlineView, NSObject item)
{
var it = (TreeItem) item;
return source.GetChildrenCount (it != null ? it.Position : null);
}
public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn forTableColumn, NSObject byItem)
{
return byItem;
}
public override void SetObjectValue (NSOutlineView outlineView, NSObject theObject, NSTableColumn tableColumn, NSObject item)
{
}
public override bool ItemExpandable (NSOutlineView outlineView, NSObject item)
{
return GetChildrenCount (outlineView, item) > 0;
}
public override NSObject ItemForPersistentObject (NSOutlineView outlineView, NSObject theObject)
{
return null;
}
public override bool OutlineViewwriteItemstoPasteboard (NSOutlineView outlineView, NSArray items, NSPasteboard pboard)
{
return false;
}
public override NSObject PersistentObjectForItem (NSOutlineView outlineView, NSObject item)
{
return null;
}
public override void SortDescriptorsChanged (NSOutlineView outlineView, NSSortDescriptor[] oldDescriptors)
{
}
[Export("tableView:validateDrop:proposedRow:proposedDropOperation:")]
public NSDragOperation ValidateDrop (NSOutlineView outlineView, INSDraggingInfo info, NSObject item, nint index)
{
return NSDragOperation.None;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class AggregateTests
{
private const int ResultFuncModifier = 17;
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Sum(int count)
{
// The operation will overflow for long-running sizes, but that's okay:
// The helper is overflowing too!
Assert.Equal(Functions.SumRange(0, count), UnorderedSources.Default(count).Aggregate((x, y) => x + y));
}
[Fact]
[OuterLoop]
public static void Aggregate_Sum_Longrunning()
{
Aggregate_Sum(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Sum_Seed(int count)
{
Assert.Equal(Functions.SumRange(0, count), UnorderedSources.Default(count).Aggregate(0, (x, y) => x + y));
}
[Fact]
[OuterLoop]
public static void Aggregate_Sum_Seed_Longrunning()
{
Aggregate_Sum_Seed(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Product_Seed(int count)
{
// The operation will overflow for long-running sizes, but that's okay:
// The helper is overflowing too!
Assert.Equal(Functions.ProductRange(1, count), ParallelEnumerable.Range(1, count).Aggregate(1L, (x, y) => x * y));
}
[Fact]
[OuterLoop]
public static void Aggregate_Product_Seed_Longrunning()
{
Aggregate_Product_Seed(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Collection_Seed(int count)
{
Assert.Equal(Enumerable.Range(0, count), UnorderedSources.Default(count).Aggregate(ImmutableList<int>.Empty, (l, x) => l.Add(x)).OrderBy(x => x));
}
[Fact]
[OuterLoop]
public static void Aggregate_Collection_Seed_Longrunning()
{
// Given the cost of using an object, reduce count.
Aggregate_Collection_Seed(Sources.OuterLoopCount / 2);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Sum_Result(int count)
{
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, UnorderedSources.Default(count).Aggregate(0, (x, y) => x + y, result => result + ResultFuncModifier));
}
[Fact]
[OuterLoop]
public static void Aggregate_Sum_Result_Longrunning()
{
Aggregate_Sum_Result(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Product_Result(int count)
{
Assert.Equal(Functions.ProductRange(1, count) + ResultFuncModifier, ParallelEnumerable.Range(1, count).Aggregate(1L, (x, y) => x * y, result => result + ResultFuncModifier));
}
[Fact]
[OuterLoop]
public static void Aggregate_Product_Results_Longrunning()
{
Aggregate_Product_Result(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Collection_Results(int count)
{
Assert.Equal(Enumerable.Range(0, count), UnorderedSources.Default(count).Aggregate(ImmutableList<int>.Empty, (l, x) => l.Add(x), l => l.OrderBy(x => x)));
}
[Fact]
[OuterLoop]
public static void Aggregate_Collection_Results_Longrunning()
{
Aggregate_Collection_Results(Sources.OuterLoopCount / 2);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Sum_Accumulator(int count)
{
ParallelQuery<int> query = UnorderedSources.Default(count);
int actual = query.Aggregate(
0,
(accumulator, x) => accumulator + x,
(left, right) => left + right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual);
}
[Fact]
[OuterLoop]
public static void Aggregate_Sum_Accumulator_Longrunning()
{
Aggregate_Sum_Accumulator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Product_Accumulator(int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(1, count);
long actual = query.Aggregate(
1L,
(accumulator, x) => accumulator * x,
(left, right) => left * right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.ProductRange(1, count) + ResultFuncModifier, actual);
}
[Fact]
[OuterLoop]
public static void Aggregate_Product_Accumulator_Longrunning()
{
Aggregate_Product_Accumulator(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Collection_Accumulator(int count)
{
ParallelQuery<int> query = UnorderedSources.Default(count);
IList<int> actual = query.Aggregate(
ImmutableList<int>.Empty,
(accumulator, x) => accumulator.Add(x),
(left, right) => left.AddRange(right),
result => result.OrderBy(x => x).ToList());
Assert.Equal(Enumerable.Range(0, count), actual);
}
[Fact]
[OuterLoop]
public static void Aggregate_Collection_Accumulator_Longrunning()
{
Aggregate_Collection_Accumulator(Sources.OuterLoopCount / 2);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Sum_SeedFunction(int count)
{
ParallelQuery<int> query = UnorderedSources.Default(count);
int actual = query.Aggregate(
() => 0,
(accumulator, x) => accumulator + x,
(left, right) => left + right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual);
}
[Fact]
[OuterLoop]
public static void Aggregate_Sum_SeedFunction_Longrunning()
{
Aggregate_Sum_SeedFunction(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Product_SeedFunction(int count)
{
ParallelQuery<int> query = ParallelEnumerable.Range(1, count);
long actual = query.Aggregate(
() => 1L,
(accumulator, x) => accumulator * x,
(left, right) => left * right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.ProductRange(1, count) + ResultFuncModifier, actual);
}
[Fact]
[OuterLoop]
public static void Aggregate_Product_SeedFunction_Longrunning()
{
Aggregate_Product_SeedFunction(Sources.OuterLoopCount);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Aggregate_Collection_SeedFunction(int count)
{
ParallelQuery<int> query = UnorderedSources.Default(count);
IList<int> actual = query.Aggregate(
() => ImmutableList<int>.Empty,
(accumulator, x) => accumulator.Add(x),
(left, right) => left.AddRange(right),
result => result.OrderBy(x => x).ToList());
Assert.Equal(Enumerable.Range(0, count), actual);
}
[Fact]
[OuterLoop]
public static void Aggregate_Collection_SeedFunction_Longrunning()
{
Aggregate_Collection_SeedFunction(Sources.OuterLoopCount / 2);
}
[Fact]
public static void Aggregate_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Aggregate((i, j) => i));
// All other invocations return the seed value.
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, i => i));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, (i, j) => i + j, i => i));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(() => -1, (i, j) => i + j, (i, j) => i + j, i => i));
}
[Fact]
public static void Aggregate_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate((i, j) => { canceler(); return j; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, i => i));
AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, (i, j) => i, i => i));
AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(() => 0, (i, j) => { canceler(); ; return j; }, (i, j) => i, i => i));
}
[Fact]
public static void Aggregate_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate((i, j) => { canceler(); return j; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, i => i));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, (i, j) => i, i => i));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(() => 0, (i, j) => { canceler(); ; return j; }, (i, j) => i, i => i));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate((i, j) => { canceler(); return j; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, i => i));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, (i, j) => i, i => i));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(() => 0, (i, j) => { canceler(); ; return j; }, (i, j) => i, i => i));
}
[Fact]
public static void Aggregate_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.Aggregate((i, j) => i));
AssertThrows.AlreadyCanceled(source => source.Aggregate(0, (i, j) => i));
AssertThrows.AlreadyCanceled(source => source.Aggregate(0, (i, j) => i, i => i));
AssertThrows.AlreadyCanceled(source => source.Aggregate(0, (i, j) => i, (i, j) => i, i => i));
AssertThrows.AlreadyCanceled(source => source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i));
}
[Fact]
public static void Aggregate_AggregateException()
{
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate((i, j) => { throw new DeliberateTestException(); }));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => { throw new DeliberateTestException(); }));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, i => i));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(0, (i, j) => i, i => { throw new DeliberateTestException(); }));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); }));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(() => { throw new DeliberateTestException(); }, (i, j) => i, (i, j) => i, i => i));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(() => 0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); }));
if (Environment.ProcessorCount >= 2)
{
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(() => 0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i));
}
}
[Fact]
public static void Aggregate_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate((i, j) => i));
Assert.Throws<ArgumentNullException>("func", () => UnorderedSources.Default(1).Aggregate(null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i));
Assert.Throws<ArgumentNullException>("func", () => UnorderedSources.Default(1).Aggregate(0, null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>("func", () => UnorderedSources.Default(1).Aggregate(0, null, i => i));
Assert.Throws<ArgumentNullException>("resultSelector", () => UnorderedSources.Default(1).Aggregate<int, int, int>(0, (i, j) => i, null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>("updateAccumulatorFunc", () => UnorderedSources.Default(1).Aggregate(0, null, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>("combineAccumulatorsFunc", () => UnorderedSources.Default(1).Aggregate(0, (i, j) => i, null, i => i));
Assert.Throws<ArgumentNullException>("resultSelector", () => UnorderedSources.Default(1).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>("seedFactory", () => UnorderedSources.Default(1).Aggregate<int, int, int>(null, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>("updateAccumulatorFunc", () => UnorderedSources.Default(1).Aggregate(() => 0, null, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>("combineAccumulatorsFunc", () => UnorderedSources.Default(1).Aggregate(() => 0, (i, j) => i, null, i => i));
Assert.Throws<ArgumentNullException>("resultSelector", () => UnorderedSources.Default(1).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, null));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web.Routing;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.CheckMoneyOrder.Controllers;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
namespace Nop.Plugin.Payments.CheckMoneyOrder
{
/// <summary>
/// CheckMoneyOrder payment processor
/// </summary>
public class CheckMoneyOrderPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly CheckMoneyOrderPaymentSettings _checkMoneyOrderPaymentSettings;
private readonly ISettingService _settingService;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
#endregion
#region Ctor
public CheckMoneyOrderPaymentProcessor(CheckMoneyOrderPaymentSettings checkMoneyOrderPaymentSettings,
ISettingService settingService, IOrderTotalCalculationService orderTotalCalculationService)
{
this._checkMoneyOrderPaymentSettings = checkMoneyOrderPaymentSettings;
this._settingService = settingService;
this._orderTotalCalculationService = orderTotalCalculationService;
}
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.NewPaymentStatus = PaymentStatus.Pending;
return result;
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
//nothing
}
/// <summary>
/// Returns a value indicating whether payment method should be hidden during checkout
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>true - hide; false - display.</returns>
public bool HidePaymentMethod(IList<ShoppingCartItem> cart)
{
//you can put any logic here
//for example, hide this payment method if all products in the cart are downloadable
//or hide this payment method if current customer is from certain country
if (_checkMoneyOrderPaymentSettings.ShippableProductRequired && !cart.RequiresShipping())
return true;
return false;
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart,
_checkMoneyOrderPaymentSettings.AdditionalFee, _checkMoneyOrderPaymentSettings.AdditionalFeePercentage);
return result;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
result.AddError("Capture method not supported");
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
result.AddError("Refund method not supported");
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
result.AddError("Void method not supported");
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//it's not a redirection payment method. So we always return false
return false;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentCheckMoneyOrder";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.CheckMoneyOrder.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentCheckMoneyOrder";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.CheckMoneyOrder.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentCheckMoneyOrderController);
}
public override void Install()
{
//settings
var settings = new CheckMoneyOrderPaymentSettings
{
DescriptionText = "<p>Mail Personal or Business Check, Cashier's Check or money order to:</p><p><br /><b>NOP SOLUTIONS</b> <br /><b>your address here,</b> <br /><b>New York, NY 10001 </b> <br /><b>USA</b></p><p>Notice that if you pay by Personal or Business Check, your order may be held for up to 10 days after we receive your check to allow enough time for the check to clear. If you want us to ship faster upon receipt of your payment, then we recommend your send a money order or Cashier's check.</p><p>P.S. You can edit this text from admin panel.</p>"
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.DescriptionText", "Description");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.DescriptionText.Hint", "Enter info that will be shown to customers during checkout");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFee", "Additional fee");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFee.Hint", "The additional fee.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFeePercentage", "Additional fee. Use percentage");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.ShippableProductRequired", "Shippable product required");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.ShippableProductRequired.Hint", "An option indicating whether shippable products are required in order to display this payment method during checkout.");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<CheckMoneyOrderPaymentSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.DescriptionText");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.DescriptionText.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFee");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFee.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFeePercentage");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFeePercentage.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.ShippableProductRequired");
this.DeletePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.ShippableProductRequired.Hint");
base.Uninstall();
}
#endregion
#region Properies
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return false;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.NotSupported;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Standard;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return false;
}
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore;
using NetGore.Graphics;
using NetGore.World;
using SFML.Graphics;
namespace DemoGame.Client
{
/// <summary>
/// An item on the client. Used for representing any item, whether it is actually an Entity
/// on the map, or just an item in an inventory.
/// </summary>
public class ItemEntity : ItemEntityBase, IDrawable
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
readonly Grh _grh;
Color _color = Color.White;
bool _isVisible = true;
public ItemEntity() : base(Vector2.Zero, Vector2.Zero)
{
Amount = 1;
_grh = new Grh(null);
}
public ItemEntity(GrhIndex graphicIndex, byte amount, TickCount currentTime) : base(Vector2.Zero, Vector2.Zero)
{
Amount = amount;
_grh = new Grh(GrhInfo.GetData(graphicIndex), AnimType.Loop, currentTime);
}
public ItemEntity(MapEntityIndex mapEntityIndex, Vector2 pos, Vector2 size, GrhIndex graphicIndex, TickCount currentTime)
: base(pos, size)
{
Amount = 0;
((IDynamicEntitySetMapEntityIndex)this).SetMapEntityIndex(mapEntityIndex);
_grh = new Grh(GrhInfo.GetData(graphicIndex), AnimType.Loop, currentTime);
}
/// <summary>
/// Not used by the <see cref="ItemEntity"/> in the client.
/// </summary>
public override event TypedEventHandler<Entity, EventArgs<CharacterEntity>> PickedUp
{
add { }
remove { }
}
/// <summary>
/// Gets or sets the size of this item cluster (1 for a single item)
/// </summary>
public override byte Amount { get; set; }
/// <summary>
/// Gets or sets the index of the graphic that is used for this item
/// </summary>
public override GrhIndex GraphicIndex
{
get { return _grh.GrhData.GrhIndex; }
set { _grh.SetGrh(value); }
}
/// <summary>
/// Gets the Grh used to draw this ItemEntity
/// </summary>
public Grh Grh
{
get { return _grh; }
}
/// <summary>
/// Checks if this <see cref="Entity"/> can be picked up by the specified <paramref name="charEntity"/>, but does
/// not actually pick up this <see cref="Entity"/>.
/// </summary>
/// <param name="charEntity"><see cref="CharacterEntity"/> that is trying to use this <see cref="Entity"/></param>
/// <returns>True if this <see cref="Entity"/> can be picked up, else false.</returns>
public override bool CanPickup(CharacterEntity charEntity)
{
// Every character can try to pick up an item
return true;
}
/// <summary>
/// Checks if this item can be stacked with another item. To stack, both items must contain the same
/// stat modifiers, name, description, value, and graphic index.
/// </summary>
/// <param name="source">Item to check if can stack on this item</param>
/// <returns>
/// True if the two items can stack on each other, else false
/// </returns>
/// <exception cref="MethodAccessException">The client has no way to know if two ItemEntities can stack since
/// it doesn't always know everything about two items.</exception>
public override bool CanStack(ItemEntityBase source)
{
throw new MethodAccessException("The client has no way to know if two ItemEntities can stack since it doesn't" +
" always know everything about two items.");
}
/// <summary>
/// Creates a deep copy of the inheritor, which is a new class with the same values, and returns
/// the copy as an ItemEntityBase.
/// </summary>
/// <returns>A deep copy of the object.</returns>
public override ItemEntityBase DeepCopy()
{
return new ItemEntity(MapEntityIndex, Position, Size, GraphicIndex, _grh.LastUpdated);
}
/// <summary>
/// Draws the ItemEntity.
/// </summary>
/// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param>
/// <param name="pos">Position to draw at.</param>
/// <param name="color">The color to draw the item.</param>
/// <exception cref="ArgumentNullException"><paramref name="sb" /> is <c>null</c>.</exception>
public void Draw(ISpriteBatch sb, Vector2 pos, Color color)
{
if (sb == null)
throw new ArgumentNullException("sb");
if (BeforeDraw != null)
BeforeDraw.Raise(this, EventArgsHelper.Create(sb));
if (IsVisible)
{
if (_grh != null)
_grh.Draw(sb, pos, color);
}
if (AfterDraw != null)
AfterDraw.Raise(this, EventArgsHelper.Create(sb));
}
/// <summary>
/// Draws the ItemEntity.
/// </summary>
/// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param>
/// <param name="pos">Position to draw at.</param>
public void Draw(ISpriteBatch sb, Vector2 pos)
{
Draw(sb, pos, Color);
}
/// <summary>
/// When overridden in the derived class, handles destroying the <see cref="ItemEntityBase"/>.
/// </summary>
protected override void HandleDestroy()
{
Dispose();
}
/// <summary>
/// Picks up this <see cref="Entity"/>.
/// </summary>
/// <param name="charEntity"><see cref="CharacterEntity"/> that is trying to pick up this <see cref="Entity"/>.</param>
/// <returns>True if this <see cref="Entity"/> was successfully picked up, else false.</returns>
public override bool Pickup(CharacterEntity charEntity)
{
const string errmsg = "Client is not allowed to pick up items.";
Debug.Fail(errmsg);
if (log.IsErrorEnabled)
log.Error(errmsg);
return false;
}
#region IDrawable Members
/// <summary>
/// Notifies listeners immediately after this <see cref="IDrawable"/> is drawn.
/// This event will be raised even if <see cref="IDrawable.IsVisible"/> is false.
/// </summary>
public event TypedEventHandler<IDrawable, EventArgs<ISpriteBatch>> AfterDraw;
/// <summary>
/// Notifies listeners immediately before this <see cref="IDrawable"/> is drawn.
/// This event will be raised even if <see cref="IDrawable.IsVisible"/> is false.
/// </summary>
public event TypedEventHandler<IDrawable, EventArgs<ISpriteBatch>> BeforeDraw;
/// <summary>
/// Notifies listeners when the <see cref="IDrawable.Color"/> property has changed.
/// </summary>
public event TypedEventHandler<IDrawable> ColorChanged;
/// <summary>
/// Unused by the <see cref="ItemEntity"/> since the layer never changes.
/// </summary>
event TypedEventHandler<IDrawable, ValueChangedEventArgs<MapRenderLayer>> IDrawable.RenderLayerChanged
{
add { }
remove { }
}
/// <summary>
/// Notifies listeners when the <see cref="IDrawable.IsVisible"/> property has changed.
/// </summary>
public event TypedEventHandler<IDrawable> VisibleChanged;
/// <summary>
/// Gets or sets the <see cref="IDrawable.Color"/> to use when drawing this <see cref="IDrawable"/>. By default, this
/// value will be equal to white (ARGB: 255,255,255,255).
/// </summary>
public Color Color
{
get { return _color; }
set
{
if (_color == value)
return;
_color = value;
if (ColorChanged != null)
ColorChanged.Raise(this, EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets if this <see cref="IDrawable"/> will be drawn. All <see cref="IDrawable"/>s are initially
/// visible.
/// </summary>
[Browsable(false)]
public bool IsVisible
{
get { return _isVisible; }
set
{
if (_isVisible == value)
return;
_isVisible = value;
if (VisibleChanged != null)
VisibleChanged.Raise(this, EventArgs.Empty);
}
}
/// <summary>
/// Gets the depth of the object for the <see cref="IDrawable.MapRenderLayer"/> the object is on. A higher
/// layer depth results in the object being drawn on top of (in front of) objects with a lower value.
/// </summary>
[Browsable(false)]
public int LayerDepth
{
get { return -100; }
}
/// <summary>
/// Gets the MapRenderLayer for the ItemEntity
/// </summary>
public MapRenderLayer MapRenderLayer
{
get
{
// Items are always on the Dynamic layer
return MapRenderLayer.Dynamic;
}
}
/// <summary>
/// Draws the ItemEntity.
/// </summary>
/// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param>
public void Draw(ISpriteBatch sb)
{
Draw(sb, Position);
}
/// <summary>
/// Checks if in the object is in view of the specified <paramref name="camera"/>.
/// </summary>
/// <param name="camera">The <see cref="ICamera2D"/> to check if this object is in view of.</param>
/// <returns>
/// True if the object is in view of the camera, else False.
/// </returns>
public bool InView(ICamera2D camera)
{
return camera.InView(this);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orchard.ContentManagement.Handlers {
public abstract class ContentHandler : IContentHandler {
protected ContentHandler() {
Filters = new List<IContentFilter>();
}
public List<IContentFilter> Filters { get; set; }
protected void OnActivated<TPart>(Action<ActivatedContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnActivated = handler });
}
protected void OnInitializing<TPart>(Action<InitializingContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnInitializing = handler });
}
protected void OnInitialized<TPart>(Action<InitializingContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnInitialized = handler });
}
protected void OnCreating<TPart>(Action<CreateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnCreating = handler });
}
protected void OnCreated<TPart>(Action<CreateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnCreated = handler });
}
protected void OnLoading<TPart>(Action<LoadContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnLoading = handler });
}
protected void OnLoaded<TPart>(Action<LoadContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnLoaded = handler });
}
protected void OnUpdating<TPart>(Action<UpdateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUpdating = handler });
}
protected void OnUpdated<TPart>(Action<UpdateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUpdated = handler });
}
protected void OnVersioning<TPart>(Action<VersionContentContext, TPart, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnVersioning = handler });
}
protected void OnVersioned<TPart>(Action<VersionContentContext, TPart, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnVersioned = handler });
}
protected void OnPublishing<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnPublishing = handler });
}
protected void OnPublished<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnPublished = handler });
}
protected void OnUnpublishing<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUnpublishing = handler });
}
protected void OnUnpublished<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUnpublished = handler });
}
protected void OnRemoving<TPart>(Action<RemoveContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnRemoving = handler });
}
protected void OnRemoved<TPart>(Action<RemoveContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnRemoved = handler });
}
//protected void OnDestroying<TPart>(Action<DestroyContentContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineStorageFilter<TPart> { OnDestroying = handler });
//}
//protected void OnDestroyed<TPart>(Action<DestroyContentContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineStorageFilter<TPart> { OnDestroyed = handler });
//}
//protected void OnIndexing<TPart>(Action<IndexContentContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineStorageFilter<TPart> { OnIndexing = handler });
//}
//protected void OnIndexed<TPart>(Action<IndexContentContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineStorageFilter<TPart> { OnIndexed = handler });
//}
//protected void OnGetContentItemMetadata<TPart>(Action<GetContentItemMetadataContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineTemplateFilter<TPart> { OnGetItemMetadata = handler });
//}
//protected void OnGetDisplayShape<TPart>(Action<BuildDisplayContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineTemplateFilter<TPart> { OnGetDisplayShape = handler });
//}
//protected void OnGetEditorShape<TPart>(Action<BuildEditorContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineTemplateFilter<TPart> { OnGetEditorShape = handler });
//}
//protected void OnUpdateEditorShape<TPart>(Action<UpdateEditorContext, TPart> handler) where TPart : class, IContent {
// Filters.Add(new InlineTemplateFilter<TPart> { OnUpdateEditorShape = handler });
//}
class InlineStorageFilter<TPart> : StorageFilterBase<TPart> where TPart : class, IContent {
public Action<ActivatedContentContext, TPart> OnActivated { get; set; }
public Action<InitializingContentContext, TPart> OnInitializing { get; set; }
public Action<InitializingContentContext, TPart> OnInitialized { get; set; }
public Action<CreateContentContext, TPart> OnCreating { get; set; }
public Action<CreateContentContext, TPart> OnCreated { get; set; }
public Action<LoadContentContext, TPart> OnLoading { get; set; }
public Action<LoadContentContext, TPart> OnLoaded { get; set; }
public Action<UpdateContentContext, TPart> OnUpdating { get; set; }
public Action<UpdateContentContext, TPart> OnUpdated { get; set; }
public Action<VersionContentContext, TPart, TPart> OnVersioning { get; set; }
public Action<VersionContentContext, TPart, TPart> OnVersioned { get; set; }
public Action<PublishContentContext, TPart> OnPublishing { get; set; }
public Action<PublishContentContext, TPart> OnPublished { get; set; }
public Action<PublishContentContext, TPart> OnUnpublishing { get; set; }
public Action<PublishContentContext, TPart> OnUnpublished { get; set; }
public Action<RemoveContentContext, TPart> OnRemoving { get; set; }
public Action<RemoveContentContext, TPart> OnRemoved { get; set; }
//public Action<IndexContentContext, TPart> OnIndexing { get; set; }
//public Action<IndexContentContext, TPart> OnIndexed { get; set; }
//public Action<RestoreContentContext, TPart> OnRestoring { get; set; }
//public Action<RestoreContentContext, TPart> OnRestored { get; set; }
//public Action<DestroyContentContext, TPart> OnDestroying { get; set; }
//public Action<DestroyContentContext, TPart> OnDestroyed { get; set; }
protected override void Activated(ActivatedContentContext context, TPart instance) {
if (OnActivated != null) OnActivated(context, instance);
}
protected override void Initializing(InitializingContentContext context, TPart instance) {
if (OnInitializing != null) OnInitializing(context, instance);
}
protected override void Initialized(InitializingContentContext context, TPart instance) {
if (OnInitialized != null) OnInitialized(context, instance);
}
protected override void Creating(CreateContentContext context, TPart instance) {
if (OnCreating != null) OnCreating(context, instance);
}
protected override void Created(CreateContentContext context, TPart instance) {
if (OnCreated != null) OnCreated(context, instance);
}
protected override void Loading(LoadContentContext context, TPart instance) {
if (OnLoading != null) OnLoading(context, instance);
}
protected override void Loaded(LoadContentContext context, TPart instance) {
if (OnLoaded != null) OnLoaded(context, instance);
}
protected override void Updating(UpdateContentContext context, TPart instance) {
if (OnUpdating != null) OnUpdating(context, instance);
}
protected override void Updated(UpdateContentContext context, TPart instance) {
if (OnUpdated != null) OnUpdated(context, instance);
}
protected override void Versioning(VersionContentContext context, TPart existing, TPart building) {
if (OnVersioning != null) OnVersioning(context, existing, building);
}
protected override void Versioned(VersionContentContext context, TPart existing, TPart building) {
if (OnVersioned != null) OnVersioned(context, existing, building);
}
protected override void Publishing(PublishContentContext context, TPart instance) {
if (OnPublishing != null) OnPublishing(context, instance);
}
protected override void Published(PublishContentContext context, TPart instance) {
if (OnPublished != null) OnPublished(context, instance);
}
protected override void Unpublishing(PublishContentContext context, TPart instance) {
if (OnUnpublishing != null) OnUnpublishing(context, instance);
}
protected override void Unpublished(PublishContentContext context, TPart instance) {
if (OnUnpublished != null) OnUnpublished(context, instance);
}
protected override void Removing(RemoveContentContext context, TPart instance) {
if (OnRemoving != null) OnRemoving(context, instance);
}
protected override void Removed(RemoveContentContext context, TPart instance) {
if (OnRemoved != null) OnRemoved(context, instance);
}
//protected override void Indexing(IndexContentContext context, TPart instance) {
// if ( OnIndexing != null )
// OnIndexing(context, instance);
//}
//protected override void Indexed(IndexContentContext context, TPart instance) {
// if ( OnIndexed != null )
// OnIndexed(context, instance);
//}
//protected override void Restoring(RestoreContentContext context, TPart instance) {
// if (OnRestoring != null)
// OnRestoring(context, instance);
//}
//protected override void Restored(RestoreContentContext context, TPart instance) {
// if (OnRestored != null)
// OnRestored(context, instance);
//}
//protected override void Destroying(DestroyContentContext context, TPart instance) {
// if (OnDestroying != null)
// OnDestroying(context, instance);
//}
//protected override void Destroyed(DestroyContentContext context, TPart instance) {
// if (OnDestroyed != null)
// OnDestroyed(context, instance);
//}
}
void IContentHandler.Activating(ActivatingContentContext context) {
foreach (var filter in Filters.OfType<IContentActivatingFilter>())
filter.Activating(context);
Activating(context);
}
void IContentHandler.Activated(ActivatedContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Activated(context);
Activated(context);
}
void IContentHandler.Initializing(InitializingContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Initializing(context);
Initializing(context);
}
void IContentHandler.Initialized(InitializingContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Initialized(context);
Initialized(context);
}
void IContentHandler.Creating(CreateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Creating(context);
Creating(context);
}
void IContentHandler.Created(CreateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Created(context);
Created(context);
}
void IContentHandler.Loading(LoadContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Loading(context);
Loading(context);
}
void IContentHandler.Loaded(LoadContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Loaded(context);
Loaded(context);
}
void IContentHandler.Updating(UpdateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Updating(context);
Updating(context);
}
void IContentHandler.Updated(UpdateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Updated(context);
Updated(context);
}
void IContentHandler.Versioning(VersionContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Versioning(context);
Versioning(context);
}
void IContentHandler.Versioned(VersionContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Versioned(context);
Versioned(context);
}
void IContentHandler.Publishing(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Publishing(context);
Publishing(context);
}
void IContentHandler.Published(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Published(context);
Published(context);
}
void IContentHandler.Unpublishing(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Unpublishing(context);
Unpublishing(context);
}
void IContentHandler.Unpublished(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Unpublished(context);
Unpublished(context);
}
void IContentHandler.Removing(RemoveContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Removing(context);
Removing(context);
}
void IContentHandler.Removed(RemoveContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Removed(context);
Removed(context);
}
//void IContentHandler.Indexing(IndexContentContext context) {
// foreach ( var filter in Filters.OfType<IContentStorageFilter>() )
// filter.Indexing(context);
// Indexing(context);
//}
//void IContentHandler.Indexed(IndexContentContext context) {
// foreach ( var filter in Filters.OfType<IContentStorageFilter>() )
// filter.Indexed(context);
// Indexed(context);
//}
//void IContentHandler.Importing(ImportContentContext context) {
// Importing(context);
//}
//void IContentHandler.Imported(ImportContentContext context) {
// Imported(context);
//}
//void IContentHandler.Exporting(ExportContentContext context) {
// Exporting(context);
//}
//void IContentHandler.Exported(ExportContentContext context) {
// Exported(context);
//}
//void IContentHandler.Restoring(RestoreContentContext context) {
// foreach (var filter in Filters.OfType<IContentStorageFilter>())
// filter.Restoring(context);
// Restoring(context);
//}
//void IContentHandler.Restored(RestoreContentContext context) {
// foreach (var filter in Filters.OfType<IContentStorageFilter>())
// filter.Restored(context);
// Restored(context);
//}
//void IContentHandler.Destroying(DestroyContentContext context) {
// foreach (var filter in Filters.OfType<IContentStorageFilter>())
// filter.Destroying(context);
// Destroying(context);
//}
//void IContentHandler.Destroyed(DestroyContentContext context) {
// foreach (var filter in Filters.OfType<IContentStorageFilter>())
// filter.Destroyed(context);
// Destroyed(context);
//}
//void IContentHandler.GetContentItemMetadata(GetContentItemMetadataContext context) {
// foreach (var filter in Filters.OfType<IContentTemplateFilter>())
// filter.GetContentItemMetadata(context);
// GetItemMetadata(context);
//}
//void IContentHandler.BuildDisplay(BuildDisplayContext context) {
// foreach (var filter in Filters.OfType<IContentTemplateFilter>())
// filter.BuildDisplayShape(context);
// BuildDisplayShape(context);
//}
//void IContentHandler.BuildEditor(BuildEditorContext context) {
// foreach (var filter in Filters.OfType<IContentTemplateFilter>())
// filter.BuildEditorShape(context);
// BuildEditorShape(context);
//}
//void IContentHandler.UpdateEditor(UpdateEditorContext context) {
// foreach (var filter in Filters.OfType<IContentTemplateFilter>())
// filter.UpdateEditorShape(context);
// UpdateEditorShape(context);
//}
protected virtual void Activating(ActivatingContentContext context) { }
protected virtual void Activated(ActivatedContentContext context) { }
protected virtual void Initializing(InitializingContentContext context) { }
protected virtual void Initialized(InitializingContentContext context) { }
protected virtual void Creating(CreateContentContext context) { }
protected virtual void Created(CreateContentContext context) { }
protected virtual void Loading(LoadContentContext context) { }
protected virtual void Loaded(LoadContentContext context) { }
protected virtual void Updating(UpdateContentContext context) { }
protected virtual void Updated(UpdateContentContext context) { }
protected virtual void Versioning(VersionContentContext context) { }
protected virtual void Versioned(VersionContentContext context) { }
protected virtual void Publishing(PublishContentContext context) { }
protected virtual void Published(PublishContentContext context) { }
protected virtual void Unpublishing(PublishContentContext context) { }
protected virtual void Unpublished(PublishContentContext context) { }
protected virtual void Removing(RemoveContentContext context) { }
protected virtual void Removed(RemoveContentContext context) { }
//protected virtual void Indexing(IndexContentContext context) { }
//protected virtual void Indexed(IndexContentContext context) { }
//protected virtual void Importing(ImportContentContext context) { }
//protected virtual void Imported(ImportContentContext context) { }
//protected virtual void Exporting(ExportContentContext context) { }
//protected virtual void Exported(ExportContentContext context) { }
//protected virtual void Restoring(RestoreContentContext context) { }
//protected virtual void Restored(RestoreContentContext context) { }
//protected virtual void Destroying(DestroyContentContext context) { }
//protected virtual void Destroyed(DestroyContentContext context) { }
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Scripting;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
public class ForStatement : Statement, ILoopStatement {
private int _headerIndex;
private readonly Expression _left;
private Expression _list;
private Statement _body;
private readonly Statement _else;
private MSAst.LabelTarget _break, _continue;
public ForStatement(Expression left, Expression list, Statement body, Statement else_) {
_left = left;
_list = list;
_body = body;
_else = else_;
}
public int HeaderIndex {
set { _headerIndex = value; }
}
public Expression Left {
get { return _left; }
}
public Statement Body {
get { return _body; }
set { _body = value; }
}
public Expression List {
get { return _list; }
set { _list = value; }
}
public Statement Else {
get { return _else; }
}
MSAst.LabelTarget ILoopStatement.BreakLabel {
get {
return _break;
}
set {
_break = value;
}
}
MSAst.LabelTarget ILoopStatement.ContinueLabel {
get {
return _continue;
}
set {
_continue = value;
}
}
public override MSAst.Expression Reduce() {
// Temporary variable for the IEnumerator object
MSAst.ParameterExpression enumerator = Ast.Variable(typeof(KeyValuePair<IEnumerator, IDisposable>), "foreach_enumerator");
return Ast.Block(new[] { enumerator }, TransformFor(Parent, enumerator, _list, _left, _body, _else, Span, GlobalParent.IndexToLocation(_headerIndex), _break, _continue, true));
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_left != null) {
_left.Walk(walker);
}
if (_list != null) {
_list.Walk(walker);
}
if (_body != null) {
_body.Walk(walker);
}
if (_else != null) {
_else.Walk(walker);
}
}
walker.PostWalk(this);
}
internal static MSAst.Expression TransformFor(ScopeStatement parent, MSAst.ParameterExpression enumerator,
Expression list, Expression left, MSAst.Expression body,
Statement else_, SourceSpan span, SourceLocation header,
MSAst.LabelTarget breakLabel, MSAst.LabelTarget continueLabel, bool isStatement) {
// enumerator, isDisposable = Dynamic(GetEnumeratorBinder, list)
MSAst.Expression init = Ast.Assign(
enumerator,
new PythonDynamicExpression1<KeyValuePair<IEnumerator, IDisposable>>(
Binders.UnaryOperationBinder(
parent.GlobalParent.PyContext,
PythonOperationKind.GetEnumeratorForIteration
),
parent.GlobalParent.CompilationMode,
AstUtils.Convert(list, typeof(object))
)
);
// while enumerator.MoveNext():
// left = enumerator.Current
// body
// else:
// else
MSAst.Expression ls = AstUtils.Loop(
parent.GlobalParent.AddDebugInfo(
Ast.Call(
Ast.Property(
enumerator,
typeof(KeyValuePair<IEnumerator, IDisposable>).GetProperty("Key")
),
typeof(IEnumerator).GetMethod("MoveNext")
),
left.Span
),
null,
Ast.Block(
left.TransformSet(
SourceSpan.None,
Ast.Call(
Ast.Property(
enumerator,
typeof(KeyValuePair<IEnumerator, IDisposable>).GetProperty("Key")
),
typeof(IEnumerator).GetProperty("Current").GetGetMethod()
),
PythonOperationKind.None
),
body,
isStatement ? UpdateLineNumber(parent.GlobalParent.IndexToLocation(list.StartIndex).Line) : AstUtils.Empty(),
AstUtils.Empty()
),
else_,
breakLabel,
continueLabel
);
return Ast.Block(
init,
Ast.TryFinally(
ls,
Ast.Block(
Ast.Call(AstMethods.ForLoopDispose, enumerator),
Ast.Assign(enumerator, Ast.New(typeof(KeyValuePair<IEnumerator, IDisposable>)))
)
)
);
}
internal override bool CanThrow {
get {
if (_left.CanThrow) {
return true;
}
if (_list.CanThrow) {
return true;
}
// most constants (int, float, long, etc...) will throw here
ConstantExpression ce = _list as ConstantExpression;
if (ce != null) {
if (ce.Value is string) {
return false;
}
return true;
}
return false;
}
}
}
}
| |
#if DOTNET35 // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Security;
namespace System.Numerics
{
internal static partial class BigIntegerCalculator
{
public static uint[] Divide(uint[] left, uint right,
out uint remainder)
{
Debug.Assert(left != null);
Debug.Assert(left.Length >= 1);
// Executes the division for one big and one 32-bit integer.
// Thus, we've similar code than below, but there is no loop for
// processing the 32-bit integer, since it's a single element.
uint[] quotient = new uint[left.Length];
ulong carry = 0UL;
for (int i = left.Length - 1; i >= 0; i--)
{
ulong value = (carry << 32) | left[i];
ulong digit = value / right;
quotient[i] = (uint)digit;
carry = value - digit * right;
}
remainder = (uint)carry;
return quotient;
}
public static uint[] Divide(uint[] left, uint right)
{
Debug.Assert(left != null);
Debug.Assert(left.Length >= 1);
// Same as above, but only computing the quotient.
uint[] quotient = new uint[left.Length];
ulong carry = 0UL;
for (int i = left.Length - 1; i >= 0; i--)
{
ulong value = (carry << 32) | left[i];
ulong digit = value / right;
quotient[i] = (uint)digit;
carry = value - digit * right;
}
return quotient;
}
public static uint Remainder(uint[] left, uint right)
{
Debug.Assert(left != null);
Debug.Assert(left.Length >= 1);
// Same as above, but only computing the remainder.
ulong carry = 0UL;
for (int i = left.Length - 1; i >= 0; i--)
{
ulong value = (carry << 32) | left[i];
carry = value % right;
}
return (uint)carry;
}
[SecuritySafeCritical]
public static unsafe uint[] Divide(uint[] left, uint[] right,
out uint[] remainder)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(left.Length >= 1);
Debug.Assert(right.Length >= 1);
Debug.Assert(left.Length >= right.Length);
// Switching to unsafe pointers helps sparing
// some nasty index calculations...
// NOTE: left will get overwritten, we need a local copy
uint[] localLeft = CreateCopy(left);
uint[] bits = new uint[left.Length - right.Length + 1];
fixed (uint* l = &localLeft[0], r = &right[0], b = &bits[0])
{
Divide(l, localLeft.Length,
r, right.Length,
b, bits.Length);
}
remainder = localLeft;
return bits;
}
[SecuritySafeCritical]
public static unsafe uint[] Divide(uint[] left, uint[] right)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(left.Length >= 1);
Debug.Assert(right.Length >= 1);
Debug.Assert(left.Length >= right.Length);
// Same as above, but only returning the quotient.
// NOTE: left will get overwritten, we need a local copy
uint[] localLeft = CreateCopy(left);
uint[] bits = new uint[left.Length - right.Length + 1];
fixed (uint* l = &localLeft[0], r = &right[0], b = &bits[0])
{
Divide(l, localLeft.Length,
r, right.Length,
b, bits.Length);
}
return bits;
}
[SecuritySafeCritical]
public static unsafe uint[] Remainder(uint[] left, uint[] right)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(left.Length >= 1);
Debug.Assert(right.Length >= 1);
Debug.Assert(left.Length >= right.Length);
// Same as above, but only returning the remainder.
// NOTE: left will get overwritten, we need a local copy
uint[] localLeft = CreateCopy(left);
fixed (uint* l = &localLeft[0], r = &right[0])
{
Divide(l, localLeft.Length,
r, right.Length,
null, 0);
}
return localLeft;
}
[SecuritySafeCritical]
private static unsafe void Divide(uint* left, int leftLength,
uint* right, int rightLength,
uint* bits, int bitsLength)
{
Debug.Assert(leftLength >= 1);
Debug.Assert(rightLength >= 1);
Debug.Assert(leftLength >= rightLength);
Debug.Assert(bitsLength == leftLength - rightLength + 1
|| bitsLength == 0);
// Executes the "grammar-school" algorithm for computing q = a / b.
// Before calculating q_i, we get more bits into the highest bit
// block of the divisor. Thus, guessing digits of the quotient
// will be more precise. Additionally we'll get r = a % b.
uint divHi = right[rightLength - 1];
uint divLo = rightLength > 1 ? right[rightLength - 2] : 0;
// We measure the leading zeros of the divisor
int shift = LeadingZeros(divHi);
int backShift = 32 - shift;
// And, we make sure the most significant bit is set
if (shift > 0)
{
uint divNx = rightLength > 2 ? right[rightLength - 3] : 0;
divHi = (divHi << shift) | (divLo >> backShift);
divLo = (divLo << shift) | (divNx >> backShift);
}
// Then, we divide all of the bits as we would do it using
// pen and paper: guessing the next digit, subtracting, ...
for (int i = leftLength; i >= rightLength; i--)
{
int n = i - rightLength;
uint t = i < leftLength ? left[i] : 0;
ulong valHi = ((ulong)t << 32) | left[i - 1];
uint valLo = i > 1 ? left[i - 2] : 0;
// We shifted the divisor, we shift the dividend too
if (shift > 0)
{
uint valNx = i > 2 ? left[i - 3] : 0;
valHi = (valHi << shift) | (valLo >> backShift);
valLo = (valLo << shift) | (valNx >> backShift);
}
// First guess for the current digit of the quotient,
// which naturally must have only 32 bits...
ulong digit = valHi / divHi;
if (digit > 0xFFFFFFFF)
digit = 0xFFFFFFFF;
// Our first guess may be a little bit to big
while (DivideGuessTooBig(digit, valHi, valLo, divHi, divLo))
--digit;
if (digit > 0)
{
// Now it's time to subtract our current quotient
uint carry = SubtractDivisor(left + n, leftLength - n,
right, rightLength, digit);
if (carry != t)
{
Debug.Assert(carry == t + 1);
// Our guess was still exactly one too high
carry = AddDivisor(left + n, leftLength - n,
right, rightLength);
--digit;
Debug.Assert(carry == 1);
}
}
// We have the digit!
if (bitsLength != 0)
bits[n] = (uint)digit;
if (i < leftLength)
left[i] = 0;
}
}
[SecuritySafeCritical]
private static unsafe uint AddDivisor(uint* left, int leftLength,
uint* right, int rightLength)
{
Debug.Assert(leftLength >= 0);
Debug.Assert(rightLength >= 0);
Debug.Assert(leftLength >= rightLength);
// Repairs the dividend, if the last subtract was too much
ulong carry = 0UL;
for (int i = 0; i < rightLength; i++)
{
ulong digit = (left[i] + carry) + right[i];
left[i] = unchecked((uint)digit);
carry = digit >> 32;
}
return (uint)carry;
}
[SecuritySafeCritical]
private static unsafe uint SubtractDivisor(uint* left, int leftLength,
uint* right, int rightLength,
ulong q)
{
Debug.Assert(leftLength >= 0);
Debug.Assert(rightLength >= 0);
Debug.Assert(leftLength >= rightLength);
Debug.Assert(q <= 0xFFFFFFFF);
// Combines a subtract and a multiply operation, which is naturally
// more efficient than multiplying and then subtracting...
ulong carry = 0UL;
for (int i = 0; i < rightLength; i++)
{
carry += right[i] * q;
uint digit = unchecked((uint)carry);
carry = carry >> 32;
if (left[i] < digit)
++carry;
left[i] = unchecked(left[i] - digit);
}
return (uint)carry;
}
private static bool DivideGuessTooBig(ulong q, ulong valHi, uint valLo,
uint divHi, uint divLo)
{
Debug.Assert(q <= 0xFFFFFFFF);
// We multiply the two most significant limbs of the divisor
// with the current guess for the quotient. If those are bigger
// than the three most significant limbs of the current dividend
// we return true, which means the current guess is still too big.
ulong chkHi = divHi * q;
ulong chkLo = divLo * q;
chkHi = chkHi + (chkLo >> 32);
chkLo = chkLo & 0xFFFFFFFF;
if (chkHi < valHi)
return false;
if (chkHi > valHi)
return true;
if (chkLo < valLo)
return false;
if (chkLo > valLo)
return true;
return false;
}
private static uint[] CreateCopy(uint[] value)
{
Debug.Assert(value != null);
Debug.Assert(value.Length != 0);
uint[] bits = new uint[value.Length];
Array.Copy(value, 0, bits, 0, bits.Length);
return bits;
}
private static int LeadingZeros(uint value)
{
if (value == 0)
return 32;
int count = 0;
if ((value & 0xFFFF0000) == 0)
{
count += 16;
value = value << 16;
}
if ((value & 0xFF000000) == 0)
{
count += 8;
value = value << 8;
}
if ((value & 0xF0000000) == 0)
{
count += 4;
value = value << 4;
}
if ((value & 0xC0000000) == 0)
{
count += 2;
value = value << 2;
}
if ((value & 0x80000000) == 0)
{
count += 1;
}
return count;
}
}
}
#endif
| |
//
// 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.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Resources
{
/// <summary>
/// Operations for managing providers.
/// </summary>
internal partial class ProviderOperations : IServiceOperations<ResourceManagementClient>, IProviderOperations
{
/// <summary>
/// Initializes a new instance of the ProviderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProviderOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets a resource provider.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource provider information.
/// </returns>
public async Task<ProviderGetResult> GetAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-02-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
ProviderGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Provider providerInstance = new Provider();
result.Provider = providerInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = responseDoc["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = responseDoc["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = responseDoc["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
}
}
}
}
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>
/// Gets a list of resource providers.
/// </summary>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all
/// deployments.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public async Task<ProviderListResult> ListAsync(ProviderListParameters parameters, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers";
List<string> queryParameters = new List<string>();
if (parameters != null && parameters.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
}
queryParameters.Add("api-version=2016-02-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
ProviderListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Provider providerInstance = new Provider();
result.Providers.Add(providerInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = valueValue["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = valueValue["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = valueValue["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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>
/// Get a list of deployments.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public async Task<ProviderListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
ProviderListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Provider providerInstance = new Provider();
result.Providers.Add(providerInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = valueValue["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = valueValue["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = valueValue["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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>
/// Registers provider to be used with a subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource provider registration information.
/// </returns>
public async Task<ProviderRegistionResult> RegisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
url = url + "/register";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-02-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
ProviderRegistionResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderRegistionResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Provider providerInstance = new Provider();
result.Provider = providerInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = responseDoc["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = responseDoc["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = responseDoc["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
}
}
}
}
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>
/// Unregisters provider from a subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource provider registration information.
/// </returns>
public async Task<ProviderUnregistionResult> UnregisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
TracingAdapter.Enter(invocationId, this, "UnregisterAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
url = url + "/unregister";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-02-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
ProviderUnregistionResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderUnregistionResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Provider providerInstance = new Provider();
result.Provider = providerInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = responseDoc["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = responseDoc["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = responseDoc["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
JToken apiVersionsArray = resourceTypesValue["apiVersions"];
if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
{
foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
{
providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
}
}
JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
}
}
}
}
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 Lucene.Net.Attributes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Support
{
/*
* 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.
*/
[TestFixture]
public class TestWeakDictionaryBehavior
{
IDictionary<object, object> dictionary;
public static IDictionary<object, object> CreateDictionary()
{
return new WeakDictionary<object, object>();
}
private void CallGC()
{
for (int i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
[SetUp]
public void Setup()
{
dictionary = CreateDictionary();
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Add()
{
string key = "A";
dictionary.Add(key, "value");
Assert.IsTrue(dictionary.ContainsKey(key));
Assert.AreEqual("value", dictionary[key]);
Assert.AreEqual(1, dictionary.Count);
CollectionAssert.AreEquivalent(dictionary.Values, new object[] { "value" });
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Add_2()
{
string key = "A";
string key2 = "B";
dictionary.Add(key, "value");
dictionary.Add(key2, "value2");
Assert.IsTrue(dictionary.ContainsKey(key));
Assert.IsTrue(dictionary.ContainsKey(key2));
Assert.AreEqual("value", dictionary[key]);
Assert.AreEqual("value2", dictionary[key2]);
Assert.AreEqual(2, dictionary.Count);
CollectionAssert.AreEquivalent(dictionary.Values, new object[] { "value", "value2" });
}
[Test, LuceneNetSpecific]
public void Test_Keys()
{
string key = "A";
string key2 = "B";
dictionary.Add(key, "value");
CollectionAssert.AreEquivalent(dictionary.Keys, new object[] { key });
dictionary.Add(key2, "value2");
CollectionAssert.AreEquivalent(dictionary.Keys, new object[] { key, key2 });
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Add_Null()
{
Assert.Throws<ArgumentNullException>(() => dictionary.Add(null, "value"));
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Set_Null()
{
Assert.Throws<ArgumentNullException>(() => dictionary[null] = "value");
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_AddReplace()
{
string key = "A";
string key2 = "a".ToUpper();
dictionary.Add(key, "value");
dictionary[key2] = "value2";
Assert.AreEqual(1, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(key));
Assert.AreEqual("value2", dictionary[key]);
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_AddRemove()
{
string key = "A";
dictionary.Add(key, "value");
dictionary.Remove(key);
Assert.AreEqual(0, dictionary.Count);
Assert.IsFalse(dictionary.ContainsKey(key));
Assert.IsNull(dictionary[key]);
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Clear()
{
string key = "A";
dictionary.Add(key, "value");
dictionary.Clear();
Assert.AreEqual(0, dictionary.Count);
Assert.IsFalse(dictionary.ContainsKey(key));
Assert.IsNull(dictionary[key]);
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_AddRemove_2()
{
string key = "A";
dictionary.Add(key, "value");
dictionary.Remove(key);
dictionary.Remove(key);
Assert.AreEqual(0, dictionary.Count);
Assert.IsFalse(dictionary.ContainsKey(key));
Assert.IsNull(dictionary[key]);
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Get_Null()
{
object value;
Assert.Throws<ArgumentNullException>(() => value = dictionary[null]);
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_Remove_Null()
{
Assert.Throws<ArgumentNullException>(() => dictionary.Remove(null));
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_GetEnumerator()
{
string key = "A";
dictionary.Add(key, "value");
var de = dictionary.GetEnumerator();
Assert.IsTrue(de.MoveNext());
Assert.AreEqual(key, de.Current.Key);
Assert.AreEqual("value", de.Current.Value);
}
[Test, LuceneNetSpecific]
public void Test_Dictionary_ForEach()
{
string key = "A";
dictionary.Add(key, "value");
foreach (var de in dictionary)
{
Assert.AreEqual(key, de.Key);
Assert.AreEqual("value", de.Value);
}
}
[Test, LuceneNetSpecific]
public void Test_Collisions()
{
//Create 2 keys with same hashcode but that are not equal
CollisionTester key1 = new CollisionTester(1, 100);
CollisionTester key2 = new CollisionTester(2, 100);
dictionary.Add(key1, "value1");
dictionary.Add(key2, "value2");
Assert.AreEqual("value1", dictionary[key1]);
Assert.AreEqual("value2", dictionary[key2]);
dictionary.Remove(key1);
Assert.AreEqual(null, dictionary[key1]);
}
[Test, LuceneNetSpecific]
public void Test_Weak_1()
{
BigObject key = new BigObject(1);
BigObject key2 = new BigObject(2);
dictionary.Add(key, "value");
Assert.AreEqual("value", dictionary[key]);
key = null;
CallGC();
dictionary.Add(key2, "value2");
Assert.AreEqual(1, dictionary.Count);
}
[Test, LuceneNetSpecific]
public void Test_Weak_2()
{
BigObject key = new BigObject(1);
BigObject key2 = new BigObject(2);
BigObject key3 = new BigObject(3);
dictionary.Add(key, "value");
dictionary.Add(key2, "value2");
Assert.AreEqual("value", dictionary[key]);
key = null;
CallGC();
dictionary.Add(key3, "value3");
Assert.AreEqual(2, dictionary.Count);
Assert.IsNotNull(key2);
}
[Test, LuceneNetSpecific]
public void Test_Weak_ForEach()
{
BigObject[] keys1 = new BigObject[20];
BigObject[] keys2 = new BigObject[20];
for (int i = 0; i < keys1.Length; i++)
{
keys1[i] = new BigObject(i);
dictionary.Add(keys1[i], "value");
}
for (int i = 0; i < keys2.Length; i++)
{
keys2[i] = new BigObject(i);
dictionary.Add(keys2[i], "value");
}
Assert.AreEqual(40, dictionary.Count);
keys2 = null;
int count = 0;
foreach (var de in dictionary)
{
CallGC();
count++;
}
Assert.LessOrEqual(20, count);
Assert.Greater(40, count);
Assert.IsNotNull(keys1);
}
}
}
| |
#if UNITY_EDITOR || !UNITY_FLASH
/// <summary>
/// This class handles receiving data from the Game Analytics servers.
/// JSON data is sent using a MD5 hashed authorization header, containing the JSON data and private key. Data received must be in JSON format also.
/// </summary>
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System;
//using LitJson;
#if UNITY_METRO && !UNITY_EDITOR
using GA_Compatibility.Collections;
#endif
public class GA_Request
{
/// <summary>
/// Handlers for success and fail regarding requests sent to the GA server
/// </summary>
public delegate void SubmitSuccessHandler(RequestType requestType, Hashtable returnParam, SubmitErrorHandler errorEvent);
public delegate void SubmitErrorHandler(string message);
/// <summary>
/// Types of requests that can be made to the GA server
/// </summary>
public enum RequestType { GA_GetHeatmapGameInfo, GA_GetHeatmapData }
/// <summary>
/// All the different types of requests
/// </summary>
public Dictionary<RequestType, string> Requests = new Dictionary<RequestType, string>()
{
{ RequestType.GA_GetHeatmapGameInfo, "game" },
{ RequestType.GA_GetHeatmapData, "heatmap" }
};
#region private values
private string _baseURL = "http://data-api.gameanalytics.com";
#endregion
#region public methods
public WWW RequestGameInfo(SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
string game_key = GA.SettingsGA.GameKey;
string requestInfo = "game_key=" + game_key + "&keys=area%7Cevent_id%7Cbuild";
requestInfo = requestInfo.Replace(" ", "%20");
//Get the url with the request type
string url = GetURL(Requests[RequestType.GA_GetHeatmapGameInfo]);
url += "/?" + requestInfo;
WWW www = null;
#if !UNITY_WP8 && !UNITY_METRO
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Hashtable headers = new Hashtable();
headers.Add("Authorization", GA.API.Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#else
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", GA.API.Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#endif
GA.RunCoroutine(Request(www, RequestType.GA_GetHeatmapGameInfo, successEvent, errorEvent),()=>www.isDone);
return www;
}
public WWW RequestHeatmapData(List<string> events, string area, string build, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
return RequestHeatmapData(events, area, build, null, null, successEvent, errorEvent);
}
public WWW RequestHeatmapData(List<string> events, string area, string build, DateTime? startDate, DateTime? endDate, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
string game_key = GA.SettingsGA.GameKey;
string event_ids = "";
for (int i = 0; i < events.Count; i++)
{
if (i == events.Count - 1)
event_ids += events[i];
else
event_ids += events[i] + "|";
}
string requestInfo = "game_key=" + game_key + "&event_ids=" + event_ids + "&area=" + area;
if (!build.Equals(""))
requestInfo += "&build=" + build;
requestInfo = requestInfo.Replace(" ", "%20");
if (startDate.HasValue && endDate.HasValue)
{
DateTime startDT = new DateTime(startDate.Value.Year, startDate.Value.Month, startDate.Value.Day, 0, 0, 0);
DateTime endDT = new DateTime(endDate.Value.Year, endDate.Value.Month, endDate.Value.Day, 0, 0, 0);
requestInfo += "&start_ts=" + DateTimeToUnixTimestamp(startDT) + "&end_ts=" + DateTimeToUnixTimestamp(endDT);
}
//Get the url with the request type
string url = GetURL(Requests[RequestType.GA_GetHeatmapData]);
url += "/?" + requestInfo;
WWW www = null;
#if !UNITY_WP8 && !UNITY_METRO
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Hashtable headers = new Hashtable();
headers.Add("Authorization", GA.API.Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#else
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", GA.API.Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#endif
GA.RunCoroutine(Request(www, RequestType.GA_GetHeatmapData, successEvent, errorEvent),()=>www.isDone);
return www;
}
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (dateTime - new DateTime(1970, 1, 1)).TotalSeconds;
}
#endregion
#region private methods
private IEnumerator Request(WWW www, RequestType requestType, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
yield return www;
GA.Log("GameAnalytics: URL " + www.url);
try
{
if (!string.IsNullOrEmpty(www.error))
{
throw new Exception(www.error);
}
//Get the JSON object from the response
string text = www.text;
text = text.Replace("null","0");
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(text);
if (returnParam != null)
{
GA.Log("GameAnalytics: Result: " + text);
if (successEvent != null)
{
successEvent(requestType, returnParam, errorEvent);
}
}
else
{
throw new Exception(text);
}
}
catch (Exception e)
{
if (errorEvent != null)
{
errorEvent(e.Message);
}
}
}
/// <summary>
/// Gets the url on the GA server matching the specific service we are interested in
/// </summary>
/// <param name="category">
/// Determines the GA service/category <see cref="System.String"/>
/// </param>
/// <returns>
/// A string representing the url matching our service choice on the GA server <see cref="System.String"/>
/// </returns>
private string GetURL(string category)
{
return _baseURL + "/" + category;
}
#endregion
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using Orleans.Transactions.TestKit.Correctnesss;
namespace Orleans.Transactions.TestKit
{
public class TransactionRecoveryTestsRunner : TransactionTestRunnerBase
{
private static readonly TimeSpan RecoveryTimeout = TimeSpan.FromSeconds(60);
// reduce to or remove once we fix timeouts abort
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(1);
private readonly TestCluster testCluster;
private readonly ILogger logger;
protected void Log(string message)
{
this.testOutput($"[{DateTime.Now}] {message}");
this.logger.LogInformation(message);
}
private class ExpectedGrainActivity
{
public ExpectedGrainActivity(Guid grainId, ITransactionalBitArrayGrain grain)
{
this.GrainId = grainId;
this.Grain = grain;
}
public Guid GrainId { get; }
public ITransactionalBitArrayGrain Grain { get; }
public BitArrayState Expected { get; } = new BitArrayState();
public BitArrayState Unambiguous { get; } = new BitArrayState();
public List<BitArrayState> Actual { get; set; }
public async Task GetActual()
{
try
{
this.Actual = await this.Grain.Get();
} catch(Exception)
{
// allow a single retry
await Task.Delay(TimeSpan.FromSeconds(30));
this.Actual = await this.Grain.Get();
}
}
}
public TransactionRecoveryTestsRunner(TestCluster testCluster, Action<string> testOutput)
: base(testCluster.GrainFactory, testOutput)
{
this.testCluster = testCluster;
this.logger = this.testCluster.ServiceProvider.GetService<ILogger<TransactionRecoveryTestsRunner>>();
}
public virtual Task TransactionWillRecoverAfterRandomSiloGracefulShutdown(string transactionTestGrainClassName, int concurrent)
{
return TransactionWillRecoverAfterRandomSiloFailure(transactionTestGrainClassName, concurrent, true);
}
public virtual Task TransactionWillRecoverAfterRandomSiloUnGracefulShutdown(string transactionTestGrainClassName, int concurrent)
{
return TransactionWillRecoverAfterRandomSiloFailure(transactionTestGrainClassName, concurrent, false);
}
protected virtual async Task TransactionWillRecoverAfterRandomSiloFailure(string transactionTestGrainClassName, int concurrent, bool gracefulShutdown)
{
var endOnCommand = new[] { false };
var index = new[] { 0 };
Func<int> getIndex = () => index[0]++;
List<ExpectedGrainActivity> txGrains = Enumerable.Range(0, concurrent * 2)
.Select(i => Guid.NewGuid())
.Select(grainId => new ExpectedGrainActivity(grainId, TestGrain<ITransactionalBitArrayGrain>(transactionTestGrainClassName, grainId)))
.ToList();
//ping all grains to activate them
await WakeupGrains(txGrains.Select(g=>g.Grain).ToList());
List<ExpectedGrainActivity>[] transactionGroups = txGrains
.Select((txGrain, i) => new { index = i, value = txGrain })
.GroupBy(v => v.index / 2)
.Select(g => g.Select(i => i.value).ToList())
.ToArray();
var txSucceedBeforeInterruption = await AllTxSucceed(transactionGroups, getIndex());
txSucceedBeforeInterruption.Should().BeTrue();
await ValidateResults(txGrains, transactionGroups);
// have transactions in flight when silo goes down
Task<bool> succeeding = RunWhileSucceeding(transactionGroups, getIndex, endOnCommand);
await Task.Delay(TimeSpan.FromSeconds(2));
var siloToTerminate = this.testCluster.Silos[ThreadSafeRandom.Next(this.testCluster.Silos.Count)];
this.Log($"Warmup transaction succeeded. {(gracefulShutdown ? "Stopping" : "Killing")} silo {siloToTerminate.SiloAddress} ({siloToTerminate.Name}) and continuing");
if (gracefulShutdown)
await this.testCluster.StopSiloAsync(siloToTerminate);
else
await this.testCluster.KillSiloAsync(siloToTerminate);
this.Log("Waiting for transactions to stop completing successfully");
var complete = await Task.WhenAny(succeeding, Task.Delay(TimeSpan.FromSeconds(30)));
endOnCommand[0] = true;
bool endedOnCommand = await succeeding;
if (endedOnCommand) this.Log($"No transactions failed due to silo death. Test may not be valid");
this.Log($"Waiting for system to recover. Performed {index[0]} transactions on each group.");
var transactionGroupsRef = new[] { transactionGroups };
await TestingUtils.WaitUntilAsync(lastTry => CheckTxResult(transactionGroupsRef, getIndex, lastTry), RecoveryTimeout, RetryDelay);
this.Log($"Recovery completed. Performed {index[0]} transactions on each group. Validating results.");
await ValidateResults(txGrains, transactionGroups);
}
private Task WakeupGrains(List<ITransactionalBitArrayGrain> grains)
{
var tasks = new List<Task>();
foreach (var grain in grains)
{
tasks.Add(grain.Ping());
}
return Task.WhenAll(tasks);
}
private async Task<bool> RunWhileSucceeding(List<ExpectedGrainActivity>[] transactionGroups, Func<int> getIndex, bool[] end)
{
// Loop until failure, or getTime changes
while (await AllTxSucceed(transactionGroups, getIndex()) && !end[0])
{
}
return end[0];
}
private async Task<bool> CheckTxResult(List<ExpectedGrainActivity>[][] transactionGroupsRef, Func<int> getIndex, bool assertIsTrue)
{
// only retry failed transactions
transactionGroupsRef[0] = await RunAllTxReportFailed(transactionGroupsRef[0], getIndex());
bool succeed = transactionGroupsRef[0] == null;
this.Log($"All transactions succeed after interruption : {succeed}");
if (assertIsTrue)
{
//consider it recovered if all tx succeed
this.Log($"Final check : {succeed}");
succeed.Should().BeTrue();
return succeed;
}
else
{
return succeed;
}
}
// Runs all transactions and returns failed;
private async Task<List<ExpectedGrainActivity>[]> RunAllTxReportFailed(List<ExpectedGrainActivity>[] transactionGroups, int index)
{
List<Task> tasks = transactionGroups
.Select(p => SetBit(p, index))
.ToList();
try
{
await Task.WhenAll(tasks);
return null;
}
catch (Exception)
{
// Collect the indices of the transaction groups which failed their transactions for diagnostics.
List<ExpectedGrainActivity>[] failedGroups = tasks.Select((task, i) => new { task, i }).Where(t => t.task.IsFaulted).Select(t => transactionGroups[t.i]).ToArray();
this.Log($"Some transactions failed. Index: {index}. {failedGroups.Length} out of {tasks.Count} failed. Failed groups: {string.Join(", ", failedGroups.Select(transactionGroup => string.Join(":", transactionGroup.Select(a => a.GrainId))))}");
return failedGroups;
}
}
private async Task<bool> AllTxSucceed(List<ExpectedGrainActivity>[] transactionGroups, int index)
{
// null return indicates none failed
return (await RunAllTxReportFailed(transactionGroups, index) == null);
}
private async Task SetBit(List<ExpectedGrainActivity> grains, int index)
{
try
{
await this.grainFactory.GetGrain<ITransactionCoordinatorGrain>(Guid.NewGuid()).MultiGrainSetBit(grains.Select(v => v.Grain).ToList(), index);
grains.ForEach(g =>
{
g.Expected.Set(index, true);
g.Unambiguous.Set(index, true);
});
}
catch (OrleansTransactionAbortedException e)
{
this.Log($"Some transactions failed. Index: {index}: Exception: {e.GetType().Name}");
grains.ForEach(g =>
{
g.Expected.Set(index, false);
g.Unambiguous.Set(index, true);
});
throw;
}
catch (Exception e)
{
this.Log($"Ambiguous transaction failure. Index: {index}: Exception: {e.GetType().Name}");
grains.ForEach(g =>
{
g.Expected.Set(index, false);
g.Unambiguous.Set(index, false);
});
throw;
}
}
private async Task ValidateResults(List<ExpectedGrainActivity> txGrains, List<ExpectedGrainActivity>[] transactionGroups)
{
await Task.WhenAll(txGrains.Select(a => a.GetActual()));
this.Log($"Got all {txGrains.Count} actual values");
bool pass = true;
foreach (List<ExpectedGrainActivity> transactionGroup in transactionGroups)
{
if (transactionGroup.Count == 0) continue;
BitArrayState first = transactionGroup[0].Actual.FirstOrDefault();
foreach (ExpectedGrainActivity activity in transactionGroup.Skip(1))
{
BitArrayState actual = activity.Actual.FirstOrDefault();
BitArrayState difference = first ^ actual;
if (difference.Value.Any(v => v != 0))
{
this.Log($"Activity on grain {activity.GrainId} did not match activity on {transactionGroup[0].GrainId}:\n"
+ $"{first} ^\n"
+ $"{actual} = \n"
+ $"{difference}\n"
+ $"Activation: {activity.GrainId}");
pass = false;
}
}
}
int i = 0;
foreach (ExpectedGrainActivity activity in txGrains)
{
BitArrayState expected = activity.Expected;
BitArrayState unambiguous = activity.Unambiguous;
BitArrayState unambuguousExpected = expected & unambiguous;
List<BitArrayState> actual = activity.Actual;
BitArrayState first = actual.FirstOrDefault();
if (first == null)
{
this.Log($"No activity for {i} ({activity.GrainId})");
pass = false;
continue;
}
int j = 0;
foreach (BitArrayState result in actual)
{
// skip comparing first to first.
if (ReferenceEquals(first, result)) continue;
// Check if each state is identical to the first state.
var difference = result ^ first;
if (difference.Value.Any(v => v != 0))
{
this.Log($"Activity on grain {i}, state {j} did not match 'first':\n"
+ $" {first}\n"
+ $"^ {result}\n"
+ $"= {difference}\n"
+ $"Activation: {activity.GrainId}");
pass = false;
}
j++;
}
// Check if the unambiguous portions of the first match.
var unambiguousFirst = first & unambiguous;
var unambiguousDifference = unambuguousExpected ^ unambiguousFirst;
if (unambiguousDifference.Value.Any(v => v != 0))
{
this.Log(
$"First state on grain {i} did not match 'expected':\n"
+ $" {unambuguousExpected}\n"
+ $"^ {unambiguousFirst}\n"
+ $"= {unambiguousDifference}\n"
+ $"Activation: {activity.GrainId}");
pass = false;
}
i++;
}
this.Log($"Report complete : {pass}");
pass.Should().BeTrue();
}
}
}
| |
//
// GtkNotificationAreaBox.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, 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 Mono.Unix;
using Gtk;
using Banshee.Gui;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Banshee.NotificationArea
{
public class GtkNotificationAreaBox : StatusIcon, INotificationAreaBox
{
#pragma warning disable 0067
public event EventHandler Disconnected;
#pragma warning restore 0067
public event EventHandler Activated;
public event PopupMenuHandler PopupMenuEvent;
private TrackInfoPopup _popup;
private bool _canShowPopup;
private bool _cursorOverTrayicon;
private bool _hideDelayStarted;
public Widget Widget => null;
public GtkNotificationAreaBox (BaseClientWindow window)
{
Visible = false;
IconName = (IconThemeUtils.HasIcon ("banshee-panel")) ?
"banshee-panel" : ServiceStack.Application.IconName;
HasTooltip = true;
Activate += delegate {OnActivated ();};
PopupMenu += delegate {OnPopupMenuEvent ();};
_popup = new TrackInfoPopup ();
}
public void PositionMenu (Menu menu, out int x, out int y, out bool push_in)
{
StatusIcon.PositionMenu (menu, out x, out y, out push_in, Handle);
}
private void HidePopup ()
{
if (_popup == null) {
return;
}
_popup.Hide ();
_popup.EnterNotifyEvent -= OnPopupEnterNotify;
_popup.LeaveNotifyEvent -= OnPopupLeaveNotify;
_popup.Destroy ();
_popup.Dispose ();
_popup = null;
}
private void ShowPopup ()
{
if (_popup != null) {
return;
}
_popup = new TrackInfoPopup ();
_popup.EnterNotifyEvent += OnPopupEnterNotify;
_popup.LeaveNotifyEvent += OnPopupLeaveNotify;
PositionPopup ();
_popup.Show ();
}
private void OnPopupEnterNotify (object o, EnterNotifyEventArgs args)
{
_hideDelayStarted = false;
}
private void OnPopupLeaveNotify (object o, LeaveNotifyEventArgs args)
{
Gdk.Rectangle rect;
if (!_popup.Intersect (new Gdk.Rectangle ((int)args.Event.X, (int)args.Event.Y, 1, 1), out rect)) {
OnLeaveNotifyEvent (o, args);
}
}
private void PositionPopup ()
{
int x, y;
Gdk.Screen screen;
Gdk.Rectangle area;
Orientation orientation;
GetGeometry (out screen, out area, out orientation);
Requisition popupMinSize, popupNaturalSize;
_popup.GetPreferredSize (out popupMinSize, out popupNaturalSize);
bool onBottom = area.Bottom + popupNaturalSize.Height >= screen.Height;
y = onBottom
? area.Top - popupNaturalSize.Height - 5
: area.Bottom + 5;
int monitor = screen.GetMonitorAtPoint (area.Left, y);
var monitorRect = screen.GetMonitorGeometry(monitor);
x = area.Left - (popupNaturalSize.Width / 2) + (area.Width / 2);
if (x + popupNaturalSize.Width >= monitorRect.Right - 5) {
x = monitorRect.Right - popupNaturalSize.Width - 5;
} else if (x < monitorRect.Left + 5) {
x = monitorRect.Left + 5;
}
_popup.Move (x, y);
}
private void OnEnterNotifyEvent (object o, EnterNotifyEventArgs args)
{
_hideDelayStarted = false;
_cursorOverTrayicon = true;
if (_canShowPopup) {
// only show the popup when the cursor is still over the
// tray icon after 500ms
GLib.Timeout.Add (500, delegate {
if (_cursorOverTrayicon && _canShowPopup) {
ShowPopup ();
}
return false;
});
}
}
private void OnLeaveNotifyEvent (object o, LeaveNotifyEventArgs args)
{
// Give the user half a second to move the mouse cursor to the popup.
if (!_hideDelayStarted) {
_hideDelayStarted = true;
_cursorOverTrayicon = false;
GLib.Timeout.Add (500, delegate {
if (_hideDelayStarted) {
_hideDelayStarted = false;
HidePopup ();
}
return false;
});
}
}
public void OnPlayerEvent (PlayerEventArgs args)
{
switch (args.Event) {
case PlayerEvent.StartOfStream:
_canShowPopup = false;
break;
case PlayerEvent.EndOfStream:
// only hide the popup when we don't play again after 250ms
GLib.Timeout.Add (250, delegate {
if (ServiceManager.PlayerEngine.CurrentState != PlayerState.Playing) {
_canShowPopup = false;
HidePopup ();
}
return false;
});
break;
}
}
protected override bool OnScrollEvent (Gdk.EventScroll evnt)
{
switch (evnt.Direction) {
case Gdk.ScrollDirection.Up:
if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) {
ServiceManager.PlayerEngine.Volume += PlayerEngine.VolumeDelta;
} else if((evnt.State & Gdk.ModifierType.ShiftMask) != 0) {
ServiceManager.PlayerEngine.Position += PlayerEngine.SkipDelta;
} else {
ServiceManager.PlaybackController.Next ();
}
break;
case Gdk.ScrollDirection.Down:
if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) {
if (ServiceManager.PlayerEngine.Volume < PlayerEngine.VolumeDelta) {
ServiceManager.PlayerEngine.Volume = 0;
} else {
ServiceManager.PlayerEngine.Volume -= PlayerEngine.VolumeDelta;
}
} else if((evnt.State & Gdk.ModifierType.ShiftMask) != 0) {
ServiceManager.PlayerEngine.Position -= PlayerEngine.SkipDelta;
} else {
ServiceManager.PlaybackController.Previous ();
}
break;
}
return true;
}
protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
{
if (evnt.Type != Gdk.EventType.ButtonPress) {
return false;
}
switch (evnt.Button) {
case 1:
if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) {
ServiceManager.PlaybackController.Next ();
} else {
OnActivated ();
}
break;
case 2:
ServiceManager.PlayerEngine.TogglePlaying ();
break;
case 3:
if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) {
ServiceManager.PlaybackController.Next ();
} else {
OnPopupMenuEvent ();
}
break;
}
return true;
}
protected override bool OnQueryTooltip (int x, int y, bool keyboardMode, Tooltip tooltip)
{
tooltip.Custom = _popup;
return true;
}
public void Show ()
{
Visible = true;
}
public void Hide ()
{
Visible = false;
}
protected virtual void OnActivated ()
{
EventHandler handler = Activated;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnPopupMenuEvent ()
{
PopupMenuHandler handler = PopupMenuEvent;
if (handler != null) {
handler (this, new PopupMenuArgs ());
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace PlayFab.UUnit
{
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
internal class JsonPropertyAttrTestClass
{
[PlayFab.Json.JsonProperty(PropertyName = "GoodField")]
public string InvalidField;
[PlayFab.Json.JsonProperty(PropertyName = "GoodProperty")]
public string InvalidProperty { get; set; }
[PlayFab.Json.JsonProperty(NullValueHandling = PlayFab.Json.NullValueHandling.Ignore)]
public object HideNull = null;
public object ShowNull = null;
}
internal class NullableTestClass
{
public bool? BoolField = null;
public bool? BoolProperty { get; set; }
public int? IntField = null;
public int? IntProperty { get; set; }
public DateTime? TimeField = null;
public DateTime? TimeProperty { get; set; }
public Region? EnumField = null;
public Region? EnumProperty { get; set; }
}
internal class ObjNumFieldTest
{
public sbyte SbyteValue; public byte ByteValue;
public short ShortValue; public ushort UshortValue;
public int IntValue; public uint UintValue;
public long LongValue; public ulong UlongValue;
public float FloatValue; public double DoubleValue;
public static ObjNumFieldTest Max = new ObjNumFieldTest { SbyteValue = sbyte.MaxValue-1, ByteValue = byte.MaxValue-1, ShortValue = short.MaxValue-1, UshortValue = ushort.MaxValue-1, IntValue = int.MaxValue-1, UintValue = uint.MaxValue-1, LongValue = long.MaxValue-1, UlongValue = ulong.MaxValue-1, FloatValue = float.MaxValue-float.Epsilon, DoubleValue = double.MaxValue-double.Epsilon };
public static ObjNumFieldTest Min = new ObjNumFieldTest { SbyteValue = sbyte.MinValue+1, ByteValue = byte.MinValue+1, ShortValue = short.MinValue+1, UshortValue = ushort.MinValue+1, IntValue = int.MinValue+1, UintValue = uint.MinValue+1, LongValue = long.MinValue+1, UlongValue = ulong.MinValue+1, FloatValue = float.MinValue+float.Epsilon, DoubleValue = double.MinValue+double.Epsilon };
public static ObjNumFieldTest Zero = new ObjNumFieldTest();
}
internal class ObjNumPropTest
{
public sbyte SbyteValue { get; set; }
public byte ByteValue { get; set; }
public short ShortValue { get; set; }
public ushort UshortValue { get; set; }
public int IntValue { get; set; }
public uint UintValue { get; set; }
public long LongValue { get; set; }
public ulong UlongValue { get; set; }
public float FloatValue { get; set; }
public double DoubleValue { get; set; }
public static ObjNumPropTest Max = new ObjNumPropTest { SbyteValue = sbyte.MaxValue-1, ByteValue = byte.MaxValue-1, ShortValue = short.MaxValue-1, UshortValue = ushort.MaxValue-1, IntValue = int.MaxValue-1, UintValue = uint.MaxValue-1, LongValue = long.MaxValue-1, UlongValue = ulong.MaxValue-1, FloatValue = float.MaxValue-float.Epsilon, DoubleValue = double.MaxValue-double.Epsilon };
public static ObjNumPropTest Min = new ObjNumPropTest { SbyteValue = sbyte.MinValue+1, ByteValue = byte.MinValue+1, ShortValue = short.MinValue+1, UshortValue = ushort.MinValue+1, IntValue = int.MinValue+1, UintValue = uint.MinValue+1, LongValue = long.MinValue+1, UlongValue = ulong.MinValue+1, FloatValue = float.MinValue+float.Epsilon, DoubleValue = double.MinValue+double.Epsilon };
public static ObjNumPropTest Zero = new ObjNumPropTest();
}
internal struct StructNumFieldTest
{
public sbyte SbyteValue; public byte ByteValue;
public short ShortValue; public ushort UshortValue;
public int IntValue; public uint UintValue;
public long LongValue; public ulong UlongValue;
public float FloatValue; public double DoubleValue;
public static StructNumFieldTest Max = new StructNumFieldTest { SbyteValue = sbyte.MaxValue-1, ByteValue = byte.MaxValue-1, ShortValue = short.MaxValue-1, UshortValue = ushort.MaxValue-1, IntValue = int.MaxValue-1, UintValue = uint.MaxValue-1, LongValue = long.MaxValue-1, UlongValue = ulong.MaxValue-1, FloatValue = float.MaxValue-float.Epsilon, DoubleValue = double.MaxValue-double.Epsilon };
public static StructNumFieldTest Min = new StructNumFieldTest { SbyteValue = sbyte.MinValue+1, ByteValue = byte.MinValue+1, ShortValue = short.MinValue+1, UshortValue = ushort.MinValue+1, IntValue = int.MinValue+1, UintValue = uint.MinValue+1, LongValue = long.MinValue+1, UlongValue = ulong.MinValue+1, FloatValue = float.MinValue+float.Epsilon, DoubleValue = double.MinValue+double.Epsilon };
public static StructNumFieldTest Zero = new StructNumFieldTest();
}
internal class ObjOptNumFieldTest
{
public sbyte? SbyteValue { get; set; }
public byte? ByteValue { get; set; }
public short? ShortValue { get; set; }
public ushort? UshortValue { get; set; }
public int? IntValue { get; set; }
public uint? UintValue { get; set; }
public long? LongValue { get; set; }
public ulong? UlongValue { get; set; }
public float? FloatValue { get; set; }
public double? DoubleValue { get; set; }
public static ObjOptNumFieldTest Max = new ObjOptNumFieldTest { SbyteValue = sbyte.MaxValue-1, ByteValue = byte.MaxValue-1, ShortValue = short.MaxValue-1, UshortValue = ushort.MaxValue-1, IntValue = int.MaxValue-1, UintValue = uint.MaxValue-1, LongValue = long.MaxValue-1, UlongValue = ulong.MaxValue-1, FloatValue = float.MaxValue-float.Epsilon, DoubleValue = double.MaxValue-double.Epsilon };
public static ObjOptNumFieldTest Min = new ObjOptNumFieldTest { SbyteValue = sbyte.MinValue+1, ByteValue = byte.MinValue+1, ShortValue = short.MinValue+1, UshortValue = ushort.MinValue+1, IntValue = int.MinValue+1, UintValue = uint.MinValue+1, LongValue = long.MinValue+1, UlongValue = ulong.MinValue+1, FloatValue = float.MinValue+float.Epsilon, DoubleValue = double.MinValue+double.Epsilon };
public static ObjOptNumFieldTest Zero = new ObjOptNumFieldTest { SbyteValue = 0, ByteValue = 0, ShortValue = 0, UshortValue = 0, IntValue = 0, UintValue = 0, LongValue = 0, UlongValue = 0, FloatValue = 0, DoubleValue = 0 };
public static ObjOptNumFieldTest Null = new ObjOptNumFieldTest { SbyteValue = null, ByteValue = null, ShortValue = null, UshortValue = null, IntValue = null, UintValue = null, LongValue = null, UlongValue = null, FloatValue = null, DoubleValue = null };
}
internal class OtherSpecificDatatypes
{
public Dictionary<string, string> StringDict { get; set; }
public Dictionary<string, int> IntDict { get; set; }
public Dictionary<string, uint> UintDict { get; set; }
public Dictionary<string, Region> EnumDict { get; set; }
public string TestString { get; set; }
}
internal class SerializeJsonSubOjbect
{
public object SubObject;
}
public class JsonFeatureTests : UUnitTestCase
{
//[UUnitTest]
public void JsonPropertyTest(UUnitTestContext testContext)
{
var expectedObject = new JsonPropertyAttrTestClass { InvalidField = "asdf", InvalidProperty = "fdsa" };
var json = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObject);
// Verify that the field names have been transformed by the JsonProperty attribute
testContext.False(json.ToLowerInvariant().Contains("invalid"), json);
testContext.False(json.ToLowerInvariant().Contains("hidenull"), json);
testContext.True(json.ToLowerInvariant().Contains("shownull"), json);
// Verify that the fields are re-serialized into the proper locations by the JsonProperty attribute
var actualObject = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<JsonPropertyAttrTestClass>(json);
testContext.StringEquals(expectedObject.InvalidField, actualObject.InvalidField, actualObject.InvalidField);
testContext.StringEquals(expectedObject.InvalidProperty, actualObject.InvalidProperty, actualObject.InvalidProperty);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void TestObjNumField(UUnitTestContext testContext)
{
var expectedObjects = new[] { ObjNumFieldTest.Max, ObjNumFieldTest.Min, ObjNumFieldTest.Zero };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<ObjNumFieldTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, 0.001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, 0.001);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void TestObjNumProp(UUnitTestContext testContext)
{
var expectedObjects = new[] { ObjNumPropTest.Max, ObjNumPropTest.Min, ObjNumPropTest.Zero };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<ObjNumPropTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, float.MaxValue * 0.000000001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, double.MaxValue * 0.000000001f);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void TestStructNumField(UUnitTestContext testContext)
{
var expectedObjects = new[] { StructNumFieldTest.Max, StructNumFieldTest.Min, StructNumFieldTest.Zero };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<ObjNumPropTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, float.MaxValue * 0.000000001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, double.MaxValue * 0.000000001f);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void TestObjOptNumField(UUnitTestContext testContext)
{
var expectedObjects = new[] { ObjOptNumFieldTest.Max, ObjOptNumFieldTest.Min, ObjOptNumFieldTest.Zero, ObjOptNumFieldTest.Null };
for (var i = 0; i < expectedObjects.Length; i++)
{
// Convert the object to json and back, and verify that everything is the same
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObjects[i]).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<ObjOptNumFieldTest>(actualJson);
testContext.SbyteEquals(expectedObjects[i].SbyteValue, actualObject.SbyteValue);
testContext.ByteEquals(expectedObjects[i].ByteValue, actualObject.ByteValue);
testContext.ShortEquals(expectedObjects[i].ShortValue, actualObject.ShortValue);
testContext.UshortEquals(expectedObjects[i].UshortValue, actualObject.UshortValue);
testContext.IntEquals(expectedObjects[i].IntValue, actualObject.IntValue);
testContext.UintEquals(expectedObjects[i].UintValue, actualObject.UintValue);
testContext.LongEquals(expectedObjects[i].LongValue, actualObject.LongValue);
testContext.ULongEquals(expectedObjects[i].UlongValue, actualObject.UlongValue);
testContext.FloatEquals(expectedObjects[i].FloatValue, actualObject.FloatValue, float.MaxValue * 0.000000001f);
testContext.DoubleEquals(expectedObjects[i].DoubleValue, actualObject.DoubleValue, double.MaxValue * 0.000000001f);
}
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void OtherSpecificDatatypes(UUnitTestContext testContext)
{
var expectedObj = new OtherSpecificDatatypes
{
StringDict = new Dictionary<string, string> { { "stringKey", "stringValue" } },
EnumDict = new Dictionary<string, Region> { { "enumKey", Region.Japan } },
IntDict = new Dictionary<string, int> { { "intKey", int.MinValue } },
UintDict = new Dictionary<string, uint> { { "uintKey", uint.MaxValue } },
TestString = "yup",
};
// Convert the object to json and back, and verify that everything is the same
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObj).Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
var actualObject = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<OtherSpecificDatatypes>(actualJson);
testContext.ObjEquals(expectedObj.TestString, actualObject.TestString);
testContext.SequenceEquals(expectedObj.IntDict, actualObject.IntDict);
testContext.SequenceEquals(expectedObj.UintDict, actualObject.UintDict);
testContext.SequenceEquals(expectedObj.StringDict, actualObject.StringDict);
testContext.SequenceEquals(expectedObj.EnumDict, actualObject.EnumDict);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void ArrayAsObject(UUnitTestContext testContext)
{
var json = "{\"Version\": \"2016-06-21_23-57-16\", \"ObjectArray\": [{\"Id\": 2, \"Name\": \"Stunned\", \"Type\": \"Condition\", \"ShowNumber\": true, \"EN_text\": \"Stunned\", \"EN_reminder\": \"Can\'t attack, block, or activate\"}, {\"Id\": 3, \"Name\": \"Poisoned\", \"Type\": \"Condition\", \"ShowNumber\": true, \"EN_text\": \"Poisoned\", \"EN_reminder\": \"Takes {N} damage at the start of each turn. Wears off over time.\" }], \"StringArray\": [\"NoSubtype\", \"Aircraft\"]}";
var result = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<Dictionary<string, object>>(json);
var version = result["Version"] as string;
var objArray = result["ObjectArray"] as List<object>;
var strArray = result["StringArray"] as List<object>;
testContext.NotNull(result);
testContext.True(!string.IsNullOrEmpty(version));
testContext.True(objArray != null && objArray.Count > 0);
testContext.True(strArray != null && strArray.Count > 0);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void TimeSpanJson(UUnitTestContext testContext)
{
var span = TimeSpan.FromSeconds(5);
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(span);
var expectedJson = "5";
testContext.StringEquals(expectedJson, actualJson, actualJson);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void ArrayOfObjects(UUnitTestContext testContext)
{
var actualJson = "[{\"a\":\"aValue\"}, {\"b\":\"bValue\"}]";
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var actualObjectList = serializer.DeserializeObject<List<Dictionary<string, object>>>(actualJson);
var actualObjectArray = serializer.DeserializeObject<Dictionary<string, object>[]>(actualJson);
testContext.IntEquals(actualObjectList.Count, 2);
testContext.IntEquals(actualObjectArray.Length, 2);
testContext.StringEquals(actualObjectList[0]["a"] as string, "aValue");
testContext.StringEquals(actualObjectList[1]["b"] as string, "bValue");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void NullableJson(UUnitTestContext testContext)
{
var testObjNull = new NullableTestClass();
var testObjInt = new NullableTestClass { IntField = 42, IntProperty = 42 };
var testObjTime = new NullableTestClass { TimeField = DateTime.UtcNow, TimeProperty = DateTime.UtcNow };
var testObjEnum = new NullableTestClass { EnumField = Region.Japan, EnumProperty = Region.Japan };
var testObjBool = new NullableTestClass { BoolField = true, BoolProperty = true };
var testObjs = new[] { testObjNull, testObjEnum, testObjBool, testObjInt, testObjTime };
List<string> failures = new List<string>();
foreach (var testObj in testObjs)
{
NullableTestClass actualObj = null;
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(testObj);
try
{
actualObj = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<NullableTestClass>(actualJson);
}
catch (Exception)
{
failures.Add(actualJson + " Cannot be deserialized as NullableTestClass");
continue;
}
if (NullableNotEquals(testObj.BoolField,actualObj.BoolField)) failures.Add("Nullable bool field does not serialize properly: " + testObj.BoolField + ", from " + actualJson);
if (NullableNotEquals(testObj.BoolProperty, actualObj.BoolProperty)) failures.Add("Nullable bool property does not serialize properly: " + testObj.BoolProperty + ", from " + actualJson);
if (NullableNotEquals(testObj.IntField, actualObj.IntField)) failures.Add("Nullable integer field does not serialize properly: " + testObj.IntField + ", from " + actualJson);
if (NullableNotEquals(testObj.IntProperty, actualObj.IntProperty)) failures.Add("Nullable integer property does not serialize properly: " + testObj.IntProperty + ", from " + actualJson);
if (NullableNotEquals(testObj.EnumField, actualObj.EnumField)) failures.Add("Nullable enum field does not serialize properly: " + testObj.EnumField + ", from " + actualJson);
if (NullableNotEquals(testObj.EnumProperty, actualObj.EnumProperty)) failures.Add("Nullable enum property does not serialize properly: " + testObj.EnumProperty + ", from " + actualJson);
if (testObj.TimeField.HasValue != actualObj.TimeField.HasValue)
failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeField + ", from " + actualJson);
if (testObj.TimeField.HasValue && Math.Abs((testObj.TimeField - actualObj.TimeField).Value.TotalSeconds) > 1)
failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeField + ", from " + actualJson);
if (testObj.TimeProperty.HasValue != actualObj.TimeProperty.HasValue)
failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeProperty + ", from " + actualJson);
if (testObj.TimeProperty.HasValue && Math.Abs((testObj.TimeProperty - actualObj.TimeProperty).Value.TotalSeconds) > 1)
failures.Add("Nullable struct property does not serialize properly: " + testObj.TimeProperty + ", from " + actualJson);
}
if (failures.Count == 0)
testContext.EndTest(UUnitFinishState.PASSED, null);
else
testContext.EndTest(UUnitFinishState.FAILED, string.Join("\n", failures.ToArray()));
}
//[UUnitTest]
public void TestDeserializeToObject(UUnitTestContext testContext)
{
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var testInt = serializer.DeserializeObject<object>("1");
var testString = serializer.DeserializeObject<object>("\"a string\"");
testContext.IntEquals((int)(ulong)testInt, 1);
testContext.StringEquals((string)testString, "a string");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
//[UUnitTest]
public void TestJsonSubObject(UUnitTestContext testContext)
{
// actualObj contains a real ObjNumFieldTest within subObject
var expectedObj = new SerializeJsonSubOjbect { SubObject = new ObjNumFieldTest { ByteValue = 1, DoubleValue = 1, FloatValue = 1, IntValue = 1, LongValue = 1, SbyteValue = 1, ShortValue = 1, UintValue = 1, UlongValue = 1, UshortValue = 1 } };
var expectedJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObj);
// Convert back to SerializeJsonSubOjbect which will serialize the original ObjNumFieldTest to a SimpleJson.JsonObject (or equivalent in another serializer)
var actualObj = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<SerializeJsonSubOjbect>(expectedJson);
testContext.False(actualObj.SubObject is ObjNumFieldTest, "ObjNumFieldTest should have deserialized as a generic JsonObject");
var actualJson = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(actualObj);
// The real test is that reserializing actualObj should produce identical json
testContext.StringEquals(expectedJson, actualJson, actualJson);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
private static bool NullableEquals<T>(T? left, T? right) where T : struct
{
// If both have a value, return whether the values match.
if (left.HasValue && right.HasValue)
return left.Value.Equals(right.Value);
// If neither has a value, return true. If only one does, return false.
return !left.HasValue && !right.HasValue;
}
private static bool NullableNotEquals<T>(T? left, T? right) where T : struct
{
return !NullableEquals(left, right);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace SliceEm
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainWnd : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu _mainMenu;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItemNew;
private System.Windows.Forms.MenuItem menuItemOpen;
private System.Windows.Forms.MenuItem menuItemExit;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItemDefaultLR;
private System.Windows.Forms.MenuItem menuItemDefaultLL;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public MainWnd()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this._mainMenu = new System.Windows.Forms.MainMenu();
this.menuItemFile = new System.Windows.Forms.MenuItem();
this.menuItemNew = new System.Windows.Forms.MenuItem();
this.menuItemOpen = new System.Windows.Forms.MenuItem();
this.menuItemExit = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItemDefaultLR = new System.Windows.Forms.MenuItem();
this.menuItemDefaultLL = new System.Windows.Forms.MenuItem();
//
// _mainMenu
//
this._mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFile,
this.menuItem1});
//
// menuItemFile
//
this.menuItemFile.Index = 0;
this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemNew,
this.menuItemOpen,
this.menuItemExit});
this.menuItemFile.MergeType = System.Windows.Forms.MenuMerge.MergeItems;
this.menuItemFile.ShowShortcut = false;
this.menuItemFile.Text = "File";
//
// menuItemNew
//
this.menuItemNew.Index = 0;
this.menuItemNew.Text = "New";
this.menuItemNew.Click += new System.EventHandler(this.menuItemNew_Click);
//
// menuItemOpen
//
this.menuItemOpen.Index = 1;
this.menuItemOpen.Text = "Open";
this.menuItemOpen.Click += new System.EventHandler(this.menuItemOpen_Click);
//
// menuItemExit
//
this.menuItemExit.Index = 2;
this.menuItemExit.MergeOrder = 10;
this.menuItemExit.Text = "Exit";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// menuItem1
//
this.menuItem1.Index = 1;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemDefaultLR,
this.menuItemDefaultLL});
this.menuItem1.MergeOrder = 3;
this.menuItem1.Text = "Window";
//
// menuItemDefaultLR
//
this.menuItemDefaultLR.Index = 0;
this.menuItemDefaultLR.Text = "Default Layout Right";
this.menuItemDefaultLR.Click += new System.EventHandler(this.menuItemDefaultLR_Click);
//
// menuItemDefaultLL
//
this.menuItemDefaultLL.Index = 1;
this.menuItemDefaultLL.Text = "Default Layout Left";
this.menuItemDefaultLL.Click += new System.EventHandler(this.menuItemDefaultLL_Click);
//
// MainWnd
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(688, 477);
this.IsMdiContainer = true;
this.Menu = this._mainMenu;
this.Name = "MainWnd";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "SliceEm";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainWnd_Closing);
this.Load += new System.EventHandler(this.MainWnd_Load);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainWnd());
}
private void MainWnd_Load(object sender, System.EventArgs e)
{
__OpenGLWindow = new OpenGLForm();
__OpenGLWindow.MdiParent = this;
__OpenGLWindow.Show();
}
private SliceEditor __SingleSliceWindow = null;
private CharEdit __AllSliceWindow = null;
private OpenGLForm __OpenGLWindow = null;
private void menuItemNew_Click(object sender, System.EventArgs e)
{
try
{
__SingleSliceWindow.Close();
}
catch
{
}
try
{
__AllSliceWindow.Close();
}
catch
{
}
SliceEmFile SEF = new SliceEmFile();
__OpenGLWindow.Setup(SEF);
SliceEditor SingleSliceEditor = new SliceEditor();
__SingleSliceWindow = SingleSliceEditor;
SingleSliceEditor.MdiParent = this;
Size Szz = new Size();
Szz.Width = 400;
Szz.Height = 400;
SingleSliceEditor.Size = Szz;
CharEdit CE = new CharEdit(SEF, SingleSliceEditor , __OpenGLWindow);
__AllSliceWindow = CE;
CE.UpdateNotifySetup(__OpenGLWindow.OGLC);
Size Sz = new Size();
Sz.Width = 200;
Sz.Height = 400;
CE.Size = Sz;
CE.MdiParent = this;
CE.Show();
menuItemDefaultLR_Click(null, null);
}
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
try
{
if(__AllSliceWindow!=null)
{
__AllSliceWindow.MapClose();
}
}
catch
{
}
SliceEditor SingleSliceEditor = new SliceEditor();
__SingleSliceWindow = SingleSliceEditor;
SingleSliceEditor.MdiParent = this;
Size Szz = new Size();
Szz.Width = 400;
Szz.Height = 400;
SingleSliceEditor.Size = Szz;
CharEdit CE = new CharEdit( SingleSliceEditor , __OpenGLWindow);
__OpenGLWindow.Setup(CE._data);
__AllSliceWindow = CE;
CE.UpdateNotifySetup(__OpenGLWindow.OGLC);
Size Sz = new Size();
Sz.Width = 200;
Sz.Height = 400;
CE.Size = Sz;
CE.MdiParent = this;
CE.Show();
menuItemDefaultLR_Click(null, null);
}
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Close();
}
private void menuItemDefaultLR_Click(object sender, System.EventArgs e)
{
// place all slice window
Size sOne = new Size();
Size sTwo = new Size();
Size sThree = new Size();
int dX = 5;
int dY = 5;
sOne.Width = (this.ClientSize.Width - dX) * 4 / 10;
sTwo.Width = (this.ClientSize.Width - dX) * 4 / 10;
sThree.Width = (this.ClientSize.Width - dX) * 6 / 10;
sOne.Height =(this.ClientSize.Height - dY) * 5 / 10;
sTwo.Height =(this.ClientSize.Height - dY) * 5 / 10;
sThree.Height =(this.ClientSize.Height - dY);
__AllSliceWindow.Size = sOne;
__OpenGLWindow.Size = sTwo;
__SingleSliceWindow.Size = sThree;
__AllSliceWindow.Location = new Point(0,0);
__OpenGLWindow.Location = new Point(0,sOne.Height);
__SingleSliceWindow.Location = new Point(sOne.Width,0);
}
private void menuItemDefaultLL_Click(object sender, System.EventArgs e)
{
// place all slice window
Size sOne = new Size();
Size sTwo = new Size();
Size sThree = new Size();
int dX = 5;
int dY = 5;
sOne.Width = (this.ClientSize.Width - dX) * 4 / 10;
sTwo.Width = (this.ClientSize.Width - dX) * 4 / 10;
sThree.Width = (this.ClientSize.Width - dX) * 6 / 10;
sOne.Height =(this.ClientSize.Height - dY) * 5 / 10;
sTwo.Height =(this.ClientSize.Height - dY) * 5 / 10;
sThree.Height =(this.ClientSize.Height - dY);
__AllSliceWindow.Size = sOne;
__OpenGLWindow.Size = sTwo;
__SingleSliceWindow.Size = sThree;
__AllSliceWindow.Location = new Point(sThree.Width ,0);
__OpenGLWindow.Location = new Point(sThree.Width ,sOne.Height);
__SingleSliceWindow.Location = new Point(0,0);
}
private void MainWnd_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Com.Aspose.Cells.Model;
namespace Com.Aspose.Cells
{
public struct FileInfo
{
public string Name;
public string MimeType;
public byte[] file;
}
public class ApiInvoker
{
private static readonly ApiInvoker _instance = new ApiInvoker();
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public string appSid { set; get; }
public string apiKey { set; get; }
public static ApiInvoker GetInstance()
{
return _instance;
}
public void addDefaultHeader(string key, string value)
{
defaultHeaderMap.Add(key, value);
}
public string escapeString(string str)
{
return str;
}
public static object deserialize(string json, Type type)
{
try
{
if (json.StartsWith("{") || json.StartsWith("["))
return JsonConvert.DeserializeObject(json, type);
else
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(json);
return JsonConvert.SerializeXmlNode(xmlDoc);
}
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
catch (JsonSerializationException jse)
{
throw new ApiException(500, jse.Message);
}
catch (System.Xml.XmlException xmle)
{
throw new ApiException(500, xmle.Message);
}
}
public static object deserialize(byte[] BinaryData, Type type)
{
try
{
return new ResponseMessage(BinaryData);
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
}
private static string Sign(string url, string appKey)
{
UriBuilder uriBuilder = new UriBuilder(url);
// Remove final slash here as it can be added automatically.
uriBuilder.Path = uriBuilder.Path.TrimEnd('/');
// Compute the hash.
byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
HMACSHA1 algorithm = new HMACSHA1(privateKey);
byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
byte[] hash = algorithm.ComputeHash(sequence);
string signature = Convert.ToBase64String(hash);
// Remove invalid symbols.
signature = signature.TrimEnd('=');
signature = HttpUtility.UrlEncode(signature);
// Convert codes to upper case as they can be updated automatically.
signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
// Add the signature to query string.
return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
}
public static string serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
}
public static void CopyTo(Stream source, Stream destination, int bufferSize = 81920)
{
byte[] array = new byte[bufferSize];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
path = path.Replace("{appSid}", this.appSid);
path = Regex.Replace(path, @"{.+?}", "");
//var b = new StringBuilder();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
path = Sign(host + path, this.apiKey);
var client = WebRequest.Create(path);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
if (formParams.Count > 1)
{
string formDataBoundary = String.Format("Somthing");
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
}
else
{
client.ContentType = "multipart/form-data";
formData = GetMultipartFormData(formParams, "");
}
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
if (body != null)
{
var swRequestWriter = new StreamWriter(requestStream);
System.Diagnostics.Debug.WriteLine("*********");
System.Diagnostics.Debug.WriteLine("Object:" + serialize(body));
swRequestWriter.Write(serialize(body));
swRequestWriter.Close();
}
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
CopyTo(webResponse.GetResponseStream(), memoryStream);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch (WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
if (postParameters.Count > 1)
{
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
needsCLRF = true;
var fileInfo = (FileInfo)param.Value;
if (param.Value is FileInfo)
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
fileInfo.MimeType);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
fileInfo.file);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
}
else
{
foreach (var param in postParameters)
{
var fileInfo = (FileInfo)param.Value;
if (param.Value is FileInfo)
{
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
}
else
{
string postData = (string)param.Value;
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
}
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
/**
* Overloaded method for returning the path value
* For a string value an empty value is returned if the value is null
* @param value
* @return
*/
public String ToPathValue(String value)
{
return (value == null) ? "" : value;
}
public String ToPathValue(int value)
{
return value.ToString();
}
public String ToPathValue(int? value)
{
return value.ToString();
}
public String ToPathValue(float value)
{
return value.ToString();
}
public String ToPathValue(float? value)
{
return value.ToString();
}
public String ToPathValue(long value)
{
return value.ToString();
}
public String ToPathValue(long? value)
{
return value.ToString();
}
public String ToPathValue(bool value)
{
return value.ToString();
}
public String ToPathValue(bool? value)
{
return value.ToString();
}
public String ToPathValue(double value)
{
return value.ToString();
}
public String ToPathValue(double? value)
{
return value.ToString();
}
//public String ToPathValue(Com.Aspose.Cells.Model.DateTime value)
//{
// //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// //return format.format(value);
// return value.ToString();
//}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet;
using NuGet.Frameworks;
using NuGet.Packaging.Core;
using NuGet.Packaging;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class GenerateNuSpec : Task
{
private const string NuSpecXmlNamespace = @"http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd";
public string InputFileName { get; set; }
[Required]
public string OutputFileName { get; set; }
public string MinClientVersion { get; set; }
[Required]
public string Id { get; set; }
[Required]
public string Version { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Authors { get; set; }
[Required]
public string Owners { get; set; }
[Required]
public string Description { get; set; }
public string ReleaseNotes { get; set; }
public string Summary { get; set; }
public string Language { get; set; }
public string ProjectUrl { get; set; }
public string IconUrl { get; set; }
public string LicenseUrl { get; set; }
public string Copyright { get; set; }
public bool RequireLicenseAcceptance { get; set; }
public bool DevelopmentDependency { get; set; }
public string Tags { get; set; }
public ITaskItem[] Dependencies { get; set; }
public ITaskItem[] References { get; set; }
public ITaskItem[] FrameworkReferences { get; set; }
public ITaskItem[] Files { get; set; }
public override bool Execute()
{
try
{
WriteNuSpecFile();
}
catch (Exception ex)
{
Log.LogError(ex.ToString());
Log.LogErrorFromException(ex);
}
return !Log.HasLoggedErrors;
}
private void WriteNuSpecFile()
{
var manifest = CreateManifest();
if (!IsDifferent(manifest))
{
Log.LogMessage("Skipping generation of .nuspec because contents are identical.");
return;
}
var directory = Path.GetDirectoryName(OutputFileName);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (var file = File.Create(OutputFileName))
{
manifest.Save(file, false);
}
}
private bool IsDifferent(Manifest newManifest)
{
if (!File.Exists(OutputFileName))
return true;
var oldSource = File.ReadAllText(OutputFileName);
var newSource = "";
using (var stream = new MemoryStream())
{
newManifest.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
newSource = Encoding.UTF8.GetString(stream.ToArray());
}
return oldSource != newSource;
}
private Manifest CreateManifest()
{
Manifest manifest;
ManifestMetadata manifestMetadata;
if (!string.IsNullOrEmpty(InputFileName))
{
using (var stream = File.OpenRead(InputFileName))
{
manifest = Manifest.ReadFrom(stream, false);
}
if (manifest.Metadata == null)
{
manifest = new Manifest(new ManifestMetadata(), manifest.Files);
}
}
else
{
manifest = new Manifest(new ManifestMetadata());
}
manifestMetadata = manifest.Metadata;
manifestMetadata.UpdateMember(x => x.Authors, Authors?.Split(';'));
manifestMetadata.UpdateMember(x => x.Copyright, Copyright);
manifestMetadata.UpdateMember(x => x.DependencyGroups, GetDependencySets());
manifestMetadata.UpdateMember(x => x.Description, Description);
manifestMetadata.DevelopmentDependency |= DevelopmentDependency;
manifestMetadata.UpdateMember(x => x.FrameworkReferences, GetFrameworkAssemblies());
if (IconUrl != null)
{
manifestMetadata.SetIconUrl(IconUrl);
}
manifestMetadata.UpdateMember(x => x.Id, Id);
manifestMetadata.UpdateMember(x => x.Language, Language);
if (LicenseUrl != null)
{
manifestMetadata.SetLicenseUrl(LicenseUrl);
}
manifestMetadata.UpdateMember(x => x.MinClientVersionString, MinClientVersion);
manifestMetadata.UpdateMember(x => x.Owners, Owners?.Split(';'));
if (ProjectUrl != null)
{
manifestMetadata.SetProjectUrl(ProjectUrl);
}
manifestMetadata.UpdateMember(x => x.PackageAssemblyReferences, GetReferenceSets());
manifestMetadata.UpdateMember(x => x.ReleaseNotes, ReleaseNotes);
manifestMetadata.RequireLicenseAcceptance |= RequireLicenseAcceptance;
manifestMetadata.UpdateMember(x => x.Summary, Summary);
manifestMetadata.UpdateMember(x => x.Tags, Tags);
manifestMetadata.UpdateMember(x => x.Title, Title);
manifestMetadata.UpdateMember(x => x.Version, Version != null ? new NuGetVersion(Version) : null);
manifest.AddRangeToMember(x => x.Files, GetManifestFiles());
return manifest;
}
private List<ManifestFile> GetManifestFiles()
{
return (from f in Files.NullAsEmpty()
select new ManifestFile()
{
Source = f.GetMetadata(Metadata.FileSource),
Target = f.GetMetadata(Metadata.FileTarget),
Exclude = f.GetMetadata(Metadata.FileExclude)
}).OrderBy(f => f.Target, StringComparer.OrdinalIgnoreCase).ToList();
}
private List<FrameworkAssemblyReference> GetFrameworkAssemblies()
{
return (from fr in FrameworkReferences.NullAsEmpty()
orderby fr.ItemSpec, StringComparer.Ordinal
select new FrameworkAssemblyReference(fr.ItemSpec, new[] { fr.GetTargetFramework() })
).ToList();
}
private List<PackageDependencyGroup> GetDependencySets()
{
var dependencies = from d in Dependencies.NullAsEmpty()
select new Dependency
{
Id = d.ItemSpec,
Version = d.GetVersion(),
TargetFramework = d.GetTargetFramework() ?? NuGetFramework.AnyFramework,
Include = d.GetValueList("Include"),
Exclude = d.GetValueList("Exclude")
};
return (from dependency in dependencies
group dependency by dependency.TargetFramework into dependenciesByFramework
select new PackageDependencyGroup(
dependenciesByFramework.Key,
from dependency in dependenciesByFramework
where dependency.Id != "_._"
orderby dependency.Id, StringComparer.Ordinal
group dependency by dependency.Id into dependenciesById
select new PackageDependency(
dependenciesById.Key,
VersionRange.Parse(
dependenciesById.Select(x => x.Version)
.Aggregate(AggregateVersions)
.ToStringSafe()),
dependenciesById.Select(x => x.Include).Aggregate(AggregateInclude),
dependenciesById.Select(x => x.Exclude).Aggregate(AggregateExclude)
))).OrderBy(s => s?.TargetFramework?.GetShortFolderName(), StringComparer.Ordinal)
.ToList();
}
private IEnumerable<PackageReferenceSet> GetReferenceSets()
{
var references = from r in References.NullAsEmpty()
select new
{
File = r.ItemSpec,
TargetFramework = r.GetTargetFramework(),
};
return (from reference in references
group reference by reference.TargetFramework into referencesByFramework
select new PackageReferenceSet(
referencesByFramework.Key,
from reference in referencesByFramework
orderby reference.File, StringComparer.Ordinal
select reference.File
)
).ToList();
}
private static VersionRange AggregateVersions(VersionRange aggregate, VersionRange next)
{
var versionRange = new VersionRange();
SetMinVersion(ref versionRange, aggregate);
SetMinVersion(ref versionRange, next);
SetMaxVersion(ref versionRange, aggregate);
SetMaxVersion(ref versionRange, next);
if (versionRange.MinVersion == null && versionRange.MaxVersion == null)
{
versionRange = null;
}
return versionRange;
}
private static IReadOnlyList<string> AggregateInclude(IReadOnlyList<string> aggregate, IReadOnlyList<string> next)
{
// include is a union
if (aggregate == null)
{
return next;
}
if (next == null)
{
return aggregate;
}
return aggregate.Union(next).ToArray();
}
private static IReadOnlyList<string> AggregateExclude(IReadOnlyList<string> aggregate, IReadOnlyList<string> next)
{
// exclude is an intersection
if (aggregate == null || next == null)
{
return null;
}
return aggregate.Intersect(next).ToArray();
}
private static void SetMinVersion(ref VersionRange target, VersionRange source)
{
if (source == null || source.MinVersion == null)
{
return;
}
bool update = false;
NuGetVersion minVersion = target.MinVersion;
bool includeMinVersion = target.IsMinInclusive;
if (target.MinVersion == null)
{
update = true;
minVersion = source.MinVersion;
includeMinVersion = source.IsMinInclusive;
}
if (target.MinVersion < source.MinVersion)
{
update = true;
minVersion = source.MinVersion;
includeMinVersion = source.IsMinInclusive;
}
if (target.MinVersion == source.MinVersion)
{
update = true;
includeMinVersion = target.IsMinInclusive && source.IsMinInclusive;
}
if (update)
{
target = new VersionRange(minVersion, includeMinVersion, target.MaxVersion, target.IsMaxInclusive, target.IncludePrerelease, target.Float, target.OriginalString);
}
}
private static void SetMaxVersion(ref VersionRange target, VersionRange source)
{
if (source == null || source.MaxVersion == null)
{
return;
}
bool update = false;
NuGetVersion maxVersion = target.MaxVersion;
bool includeMaxVersion = target.IsMaxInclusive;
if (target.MaxVersion == null)
{
update = true;
maxVersion = source.MaxVersion;
includeMaxVersion = source.IsMaxInclusive;
}
if (target.MaxVersion > source.MaxVersion)
{
update = true;
maxVersion = source.MaxVersion;
includeMaxVersion = source.IsMaxInclusive;
}
if (target.MaxVersion == source.MaxVersion)
{
update = true;
includeMaxVersion = target.IsMaxInclusive && source.IsMaxInclusive;
}
if (update)
{
target = new VersionRange(target.MinVersion, target.IsMinInclusive, maxVersion, includeMaxVersion, target.IncludePrerelease, target.Float, target.OriginalString);
}
}
private class Dependency
{
public string Id { get; set; }
public NuGetFramework TargetFramework { get; set; }
public VersionRange Version { get; set; }
public IReadOnlyList<string> Exclude { get; set; }
public IReadOnlyList<string> Include { get; set; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.