context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Concurrent; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime.Scheduler { internal class OrleansTaskScheduler { private static readonly Action<IWorkItem> ExecuteWorkItemAction = workItem => workItem.Execute(); private static readonly WaitCallback ExecuteWorkItemCallback = obj => ((IWorkItem)obj).Execute(); private readonly ILogger logger; private readonly SchedulerStatisticsGroup schedulerStatistics; private readonly IOptions<StatisticsOptions> statisticsOptions; private readonly ConcurrentDictionary<IGrainContext, WorkItemGroup> workgroupDirectory; private readonly ILogger<WorkItemGroup> workItemGroupLogger; private readonly ILogger<ActivationTaskScheduler> activationTaskSchedulerLogger; private readonly CancellationTokenSource cancellationTokenSource; private bool applicationTurnsStopped; internal static TimeSpan TurnWarningLengthThreshold { get; set; } // This is the maximum number of pending work items for a single activation before we write a warning log. internal int MaxPendingItemsSoftLimit { get; private set; } public OrleansTaskScheduler( IOptions<SchedulingOptions> options, ILoggerFactory loggerFactory, SchedulerStatisticsGroup schedulerStatistics, IOptions<StatisticsOptions> statisticsOptions) { this.schedulerStatistics = schedulerStatistics; this.statisticsOptions = statisticsOptions; this.logger = loggerFactory.CreateLogger<OrleansTaskScheduler>(); this.workItemGroupLogger = loggerFactory.CreateLogger<WorkItemGroup>(); this.activationTaskSchedulerLogger = loggerFactory.CreateLogger<ActivationTaskScheduler>(); this.cancellationTokenSource = new CancellationTokenSource(); this.SchedulingOptions = options.Value; applicationTurnsStopped = false; TurnWarningLengthThreshold = options.Value.TurnWarningLengthThreshold; this.MaxPendingItemsSoftLimit = options.Value.MaxPendingWorkItemsSoftLimit; this.StoppedWorkItemGroupWarningInterval = options.Value.StoppedActivationWarningInterval; workgroupDirectory = new ConcurrentDictionary<IGrainContext, WorkItemGroup>(); IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount); if (!schedulerStatistics.CollectShedulerQueuesStats) return; FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo); } public int WorkItemGroupCount => workgroupDirectory.Count; public TimeSpan StoppedWorkItemGroupWarningInterval { get; } public SchedulingOptions SchedulingOptions { get; } private float AverageRunQueueLengthLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLength) / (float)workgroupDirectory.Values.Count; } } private float AverageEnqueuedLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count; } } private float AverageArrivalRateLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count; } } private float SumRunQueueLengthLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLength); } } private float SumEnqueuedLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests); } } private float SumArrivalRateLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate); } } public void StopApplicationTurns() { #if DEBUG logger.Debug("StopApplicationTurns"); #endif // Do not RunDown the application run queue, since it is still used by low priority system targets. applicationTurnsStopped = true; foreach (var group in workgroupDirectory.Values) { if (!group.IsSystemGroup) { group.Stop(); } } } public void Stop() { // Stop system work groups. var stopAll = !this.applicationTurnsStopped; foreach (var group in workgroupDirectory.Values) { if (stopAll || group.IsSystemGroup) { group.Stop(); } } cancellationTokenSource.Cancel(); } private static readonly Action<Action> ExecuteActionCallback = obj => obj.Invoke(); private static readonly WaitCallback ExecuteAction = obj => ((Action)obj).Invoke(); public void QueueAction(Action action, IGrainContext context) { #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("ScheduleTask on {Context}", context); #endif var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped logger.LogWarning((int)ErrorCode.SchedulerAppTurnsStopped_1, "Dropping task item {Task} on context {Context} because application turns are stopped", action, context); return; } if (workItemGroup?.TaskScheduler is TaskScheduler scheduler) { // This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem. // We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start. Task t = new Task(action); t.Start(scheduler); } else { // Note that we do not use UnsafeQueueUserWorkItem here because we typically want to propagate execution context, // which includes async locals. #if NETCOREAPP ThreadPool.QueueUserWorkItem(ExecuteActionCallback, action, preferLocal: true); #else ThreadPool.QueueUserWorkItem(ExecuteAction, action); #endif } } // Enqueue a work item to a given context public void QueueWorkItem(IWorkItem workItem) { #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("QueueWorkItem " + workItem); #endif var workItemGroup = GetWorkItemGroup(workItem.GrainContext); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped var msg = string.Format("Dropping work item {0} because application turns are stopped", workItem); logger.Warn(ErrorCode.SchedulerAppTurnsStopped_1, msg); return; } if (workItemGroup?.TaskScheduler is TaskScheduler scheduler) { // This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem. // We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start. Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem); t.Start(scheduler); } else { // Note that we do not use UnsafeQueueUserWorkItem here because we typically want to propagate execution context, // which includes async locals. #if NETCOREAPP ThreadPool.QueueUserWorkItem(ExecuteWorkItemAction, workItem, preferLocal: true); #else ThreadPool.QueueUserWorkItem(ExecuteWorkItemCallback, workItem); #endif } } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public WorkItemGroup RegisterWorkContext(IGrainContext context) { if (context is null) { return null; } var wg = new WorkItemGroup( this, context, this.workItemGroupLogger, this.activationTaskSchedulerLogger, this.cancellationTokenSource.Token, this.schedulerStatistics, this.statisticsOptions); if (context is SystemTarget systemTarget) { systemTarget.WorkItemGroup = wg; } if (context is ActivationData activation) { activation.WorkItemGroup = wg; } workgroupDirectory.TryAdd(context, wg); return wg; } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public void UnregisterWorkContext(IGrainContext context) { if (context is null) { return; } WorkItemGroup workGroup; if (workgroupDirectory.TryRemove(context, out workGroup)) { workGroup.Stop(); } if (context is SystemTarget systemTarget) { systemTarget.WorkItemGroup = null; } if (context is ActivationData activation) { activation.WorkItemGroup = null; } } // public for testing only -- should be private, otherwise [MethodImpl(MethodImplOptions.AggressiveInlining)] public WorkItemGroup GetWorkItemGroup(IGrainContext context) { switch (context) { case null: return null; case SystemTarget systemTarget when systemTarget.WorkItemGroup is WorkItemGroup wg: return wg; case ActivationData activation when activation.WorkItemGroup is WorkItemGroup wg: return wg; default: { if (this.workgroupDirectory.TryGetValue(context, out var workGroup)) return workGroup; this.ThrowNoWorkItemGroup(context); return null; } } } [MethodImpl(MethodImplOptions.NoInlining)] private void ThrowNoWorkItemGroup(IGrainContext context) { var error = string.Format("QueueWorkItem was called on a non-null context {0} but there is no valid WorkItemGroup for it.", context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongContext, error); throw new InvalidSchedulingContextException(error); } [MethodImpl(MethodImplOptions.NoInlining)] internal void CheckSchedulingContextValidity(IGrainContext context) { if (context is null) { throw new InvalidSchedulingContextException( "CheckSchedulingContextValidity was called on a null SchedulingContext." + "Please make sure you are not trying to create a Timer from outside Orleans Task Scheduler, " + "which will be the case if you create it inside Task.Run."); } GetWorkItemGroup(context); // GetWorkItemGroup throws for Invalid context } internal void PrintStatistics() { if (!logger.IsEnabled(LogLevel.Information)) return; var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), Environment.NewLine); if (stats.Length > 0) logger.Info(ErrorCode.SchedulerStatistics, "OrleansTaskScheduler.PrintStatistics(): WorkItems={0}, Directory:" + Environment.NewLine + "{1}", WorkItemGroupCount, stats); } internal void DumpSchedulerStatus(bool alwaysOutput = true) { if (!logger.IsEnabled(LogLevel.Debug) && !alwaysOutput) return; PrintStatistics(); var sb = new StringBuilder(); sb.AppendLine("Dump of current OrleansTaskScheduler status:"); sb.AppendFormat("CPUs={0} WorkItems={1} {2}", Environment.ProcessorCount, workgroupDirectory.Count, applicationTurnsStopped ? "STOPPING" : "").AppendLine(); // todo: either remove or support. At the time of writting is being used only in tests // sb.AppendLine("RunQueue:"); // RunQueue.DumpStatus(sb); - woun't work without additional costs // Pool.DumpStatus(sb); foreach (var workgroup in workgroupDirectory.Values) sb.AppendLine(workgroup.DumpStatus()); logger.Info(ErrorCode.SchedulerStatus, sb.ToString()); } } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Cms { /** * Parsing class for an CMS Signed Data object from an input stream. * <p> * Note: that because we are in a streaming mode only one signer can be tried and it is important * that the methods on the parser are called in the appropriate order. * </p> * <p> * A simple example of usage for an encapsulated signature. * </p> * <p> * Two notes: first, in the example below the validity of * the certificate isn't verified, just the fact that one of the certs * matches the given signer, and, second, because we are in a streaming * mode the order of the operations is important. * </p> * <pre> * CmsSignedDataParser sp = new CmsSignedDataParser(encapSigData); * * sp.GetSignedContent().Drain(); * * IX509Store certs = sp.GetCertificates(); * SignerInformationStore signers = sp.GetSignerInfos(); * * foreach (SignerInformation signer in signers.GetSigners()) * { * ArrayList certList = new ArrayList(certs.GetMatches(signer.SignerID)); * X509Certificate cert = (X509Certificate) certList[0]; * * Console.WriteLine("verify returns: " + signer.Verify(cert)); * } * </pre> * Note also: this class does not introduce buffering - if you are processing large files you should create * the parser with: * <pre> * CmsSignedDataParser ep = new CmsSignedDataParser(new BufferedInputStream(encapSigData, bufSize)); * </pre> * where bufSize is a suitably large buffer size. */ public class CmsSignedDataParser : CmsContentInfoParser { private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance; private SignedDataParser _signedData; private DerObjectIdentifier _signedContentType; private CmsTypedStream _signedContent; private IDictionary _digests; private ISet _digestOids; private SignerInformationStore _signerInfoStore; private Asn1Set _certSet, _crlSet; private bool _isCertCrlParsed; private IX509Store _attributeStore; private IX509Store _certificateStore; private IX509Store _crlStore; public CmsSignedDataParser( byte[] sigBlock) : this(new MemoryStream(sigBlock, false)) { } public CmsSignedDataParser( CmsTypedStream signedContent, byte[] sigBlock) : this(signedContent, new MemoryStream(sigBlock, false)) { } /** * base constructor - with encapsulated content */ public CmsSignedDataParser( Stream sigData) : this(null, sigData) { } /** * base constructor * * @param signedContent the content that was signed. * @param sigData the signature object. */ public CmsSignedDataParser( CmsTypedStream signedContent, Stream sigData) : base(sigData) { try { this._signedContent = signedContent; this._signedData = SignedDataParser.GetInstance(this.contentInfo.GetContent(Asn1Tags.Sequence)); this._digests = new Hashtable(); this._digestOids = new HashSet(); Asn1SetParser digAlgs = _signedData.GetDigestAlgorithms(); IAsn1Convertible o; while ((o = digAlgs.ReadObject()) != null) { AlgorithmIdentifier id = AlgorithmIdentifier.GetInstance(o.ToAsn1Object()); try { string digestOid = id.ObjectID.Id; string digestName = Helper.GetDigestAlgName(digestOid); if (!this._digests.Contains(digestName)) { this._digests[digestName] = Helper.GetDigestInstance(digestName); this._digestOids.Add(digestOid); } } catch (SecurityUtilityException) { // TODO Should do something other than ignore it } } // // If the message is simply a certificate chain message GetContent() may return null. // ContentInfoParser cont = _signedData.GetEncapContentInfo(); Asn1OctetStringParser octs = (Asn1OctetStringParser) cont.GetContent(Asn1Tags.OctetString); if (octs != null) { CmsTypedStream ctStr = new CmsTypedStream( cont.ContentType.Id, octs.GetOctetStream()); if (_signedContent == null) { this._signedContent = ctStr; } else { // // content passed in, need to read past empty encapsulated content info object if present // ctStr.Drain(); } } _signedContentType = _signedContent == null ? cont.ContentType : new DerObjectIdentifier(_signedContent.ContentType); } catch (IOException e) { throw new CmsException("io exception: " + e.Message, e); } if (_digests.Count < 1) { throw new CmsException("no digests could be created for message."); } } /** * Return the version number for the SignedData object * * @return the version number */ public int Version { get { return _signedData.Version.Value.IntValue; } } public ISet DigestOids { get { return new HashSet(_digestOids); } } /** * return the collection of signers that are associated with the * signatures for the message. * @throws CmsException */ public SignerInformationStore GetSignerInfos() { if (_signerInfoStore == null) { PopulateCertCrlSets(); IList signerInfos = new ArrayList(); IDictionary hashes = new Hashtable(); foreach (object digestKey in _digests.Keys) { hashes[digestKey] = DigestUtilities.DoFinal( (IDigest)_digests[digestKey]); } try { Asn1SetParser s = _signedData.GetSignerInfos(); IAsn1Convertible o; while ((o = s.ReadObject()) != null) { SignerInfo info = SignerInfo.GetInstance(o.ToAsn1Object()); string digestName = Helper.GetDigestAlgName( info.DigestAlgorithm.ObjectID.Id); byte[] hash = (byte[]) hashes[digestName]; signerInfos.Add(new SignerInformation(info, _signedContentType, null, new BaseDigestCalculator(hash))); } } catch (IOException e) { throw new CmsException("io exception: " + e.Message, e); } _signerInfoStore = new SignerInformationStore(signerInfos); } return _signerInfoStore; } /** * return a X509Store containing the attribute certificates, if any, contained * in this message. * * @param type type of store to create * @return a store of attribute certificates * @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available. * @exception CmsException if a general exception prevents creation of the X509Store */ public IX509Store GetAttributeCertificates( string type) { if (_attributeStore == null) { PopulateCertCrlSets(); _attributeStore = Helper.CreateAttributeStore(type, _certSet); } return _attributeStore; } /** * return a X509Store containing the public key certificates, if any, contained * in this message. * * @param type type of store to create * @return a store of public key certificates * @exception NoSuchStoreException if the store type isn't available. * @exception CmsException if a general exception prevents creation of the X509Store */ public IX509Store GetCertificates( string type) { if (_certificateStore == null) { PopulateCertCrlSets(); _certificateStore = Helper.CreateCertificateStore(type, _certSet); } return _certificateStore; } /** * return a X509Store containing CRLs, if any, contained * in this message. * * @param type type of store to create * @return a store of CRLs * @exception NoSuchStoreException if the store type isn't available. * @exception CmsException if a general exception prevents creation of the X509Store */ public IX509Store GetCrls( string type) { if (_crlStore == null) { PopulateCertCrlSets(); _crlStore = Helper.CreateCrlStore(type, _crlSet); } return _crlStore; } private void PopulateCertCrlSets() { if (_isCertCrlParsed) return; _isCertCrlParsed = true; try { // care! Streaming - Must process the GetCertificates() result before calling GetCrls() _certSet = GetAsn1Set(_signedData.GetCertificates()); _crlSet = GetAsn1Set(_signedData.GetCrls()); } catch (IOException e) { throw new CmsException("problem parsing cert/crl sets", e); } } /// <summary> /// Return the <c>DerObjectIdentifier</c> associated with the encapsulated /// content info structure carried in the signed data. /// </summary> public DerObjectIdentifier SignedContentType { get { return _signedContentType; } } public CmsTypedStream GetSignedContent() { if (_signedContent == null) { return null; } Stream digStream = _signedContent.ContentStream; foreach (IDigest digest in _digests.Values) { digStream = new DigestStream(digStream, digest, null); } return new CmsTypedStream(_signedContent.ContentType, digStream); } /** * Replace the signerinformation store associated with the passed * in message contained in the stream original with the new one passed in. * You would probably only want to do this if you wanted to change the unsigned * attributes associated with a signer, or perhaps delete one. * <p> * The output stream is returned unclosed. * </p> * @param original the signed data stream to be used as a base. * @param signerInformationStore the new signer information store to use. * @param out the stream to Write the new signed data object to. * @return out. */ public static Stream ReplaceSigners( Stream original, SignerInformationStore signerInformationStore, Stream outStr) { // NB: SecureRandom would be ignored since using existing signatures only CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); CmsSignedDataParser parser = new CmsSignedDataParser(original); // gen.AddDigests(parser.DigestOids); gen.AddSigners(signerInformationStore); CmsTypedStream signedContent = parser.GetSignedContent(); bool encapsulate = (signedContent != null); Stream contentOut = gen.Open(outStr, parser.SignedContentType.Id, encapsulate); if (encapsulate) { Streams.PipeAll(signedContent.ContentStream, contentOut); } gen.AddAttributeCertificates(parser.GetAttributeCertificates("Collection")); gen.AddCertificates(parser.GetCertificates("Collection")); gen.AddCrls(parser.GetCrls("Collection")); // gen.AddSigners(parser.GetSignerInfos()); contentOut.Close(); return outStr; } /** * Replace the certificate and CRL information associated with this * CMSSignedData object with the new one passed in. * <p> * The output stream is returned unclosed. * </p> * @param original the signed data stream to be used as a base. * @param certsAndCrls the new certificates and CRLs to be used. * @param out the stream to Write the new signed data object to. * @return out. * @exception CmsException if there is an error processing the CertStore */ public static Stream ReplaceCertificatesAndCrls( Stream original, IX509Store x509Certs, IX509Store x509Crls, IX509Store x509AttrCerts, Stream outStr) { // NB: SecureRandom would be ignored since using existing signatures only CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); CmsSignedDataParser parser = new CmsSignedDataParser(original); gen.AddDigests(parser.DigestOids); CmsTypedStream signedContent = parser.GetSignedContent(); bool encapsulate = (signedContent != null); Stream contentOut = gen.Open(outStr, parser.SignedContentType.Id, encapsulate); if (encapsulate) { Streams.PipeAll(signedContent.ContentStream, contentOut); } // gen.AddAttributeCertificates(parser.GetAttributeCertificates("Collection")); // gen.AddCertificates(parser.GetCertificates("Collection")); // gen.AddCrls(parser.GetCrls("Collection")); if (x509AttrCerts != null) gen.AddAttributeCertificates(x509AttrCerts); if (x509Certs != null) gen.AddCertificates(x509Certs); if (x509Crls != null) gen.AddCrls(x509Crls); gen.AddSigners(parser.GetSignerInfos()); contentOut.Close(); return outStr; } private static Asn1Set GetAsn1Set( Asn1SetParser asn1SetParser) { return asn1SetParser == null ? null : Asn1Set.GetInstance(asn1SetParser.ToAsn1Object()); } } }
// ************************** // *** INIFile class V1.0 *** // ************************** // *** (C)2009 S.T.A. snc *** // ************************** // This code is under "The Code Project Open License (CPOL)" // http://www.codeproject.com/Articles/646296/A-Cross-platform-Csharp-Class-for-Using-INI-Files using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace abanu.core { public class INIFile { #region "Declarations" // *** Lock for thread-safe access to file and local cache *** private object m_Lock = new object(); // *** File name *** private string m_FileName = null; public string FileName { get { return m_FileName; } } // *** Lazy loading flag *** private bool m_Lazy = false; // *** Local cache *** private Dictionary<string, Dictionary<string, string>> m_Sections = new Dictionary<string,Dictionary<string, string>>(); // *** Local cache modified flag *** private bool m_CacheModified = false; #endregion #region "Methods" // *** Constructor *** public INIFile(string FileName) { Initialize(FileName, false); } public INIFile(string FileName, bool Lazy) { Initialize(FileName, Lazy); } // *** Initialization *** private void Initialize(string FileName, bool Lazy) { m_FileName = FileName; m_Lazy = Lazy; if (!m_Lazy) Refresh(); } // *** Read file contents into local cache *** public void Refresh() { lock (m_Lock) { StreamReader sr = null; try { // *** Clear local cache *** m_Sections.Clear(); // *** Open the INI file *** try { sr = new StreamReader(m_FileName); } catch (FileNotFoundException) { return; } // *** Read up the file content *** Dictionary<string, string> CurrentSection = null; string s; while ((s = sr.ReadLine()) != null) { s = s.Trim(); // *** Check for section names *** if (s.StartsWith("[") && s.EndsWith("]")) { if (s.Length > 2) { string SectionName = s.Substring(1, s.Length - 2); // *** Only first occurrence of a section is loaded *** if (m_Sections.ContainsKey(SectionName)) { CurrentSection = null; } else { CurrentSection = new Dictionary<string, string>(); m_Sections.Add(SectionName, CurrentSection); } } } else if (CurrentSection != null) { // *** Check for key+value pair *** int i; if ((i = s.IndexOf('=')) > 0) { int j = s.Length - i - 1; string Key = s.Substring(0, i).Trim(); if (Key.Length > 0) { // *** Only first occurrence of a key is loaded *** if (!CurrentSection.ContainsKey(Key)) { string Value = (j > 0) ? (s.Substring(i + 1, j).Trim()) : (""); CurrentSection.Add(Key, Value); } } } } } } finally { // *** Cleanup: close file *** if (sr != null) sr.Close(); sr = null; } } } // *** Flush local cache content *** public void Flush() { lock (m_Lock) { // *** If local cache was not modified, exit *** if (!m_CacheModified) return; m_CacheModified = false; // *** Open the file *** StreamWriter sw = new StreamWriter(m_FileName); try { // *** Cycle on all sections *** bool First = false; foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Sections) { Dictionary<string, string> Section = SectionPair.Value; if (First) sw.WriteLine(); First = true; // *** Write the section name *** sw.Write('['); sw.Write(SectionPair.Key); sw.WriteLine(']'); // *** Cycle on all key+value pairs in the section *** foreach (KeyValuePair<string, string> ValuePair in Section) { // *** Write the key+value pair *** sw.Write(ValuePair.Key); sw.Write('='); sw.WriteLine(ValuePair.Value); } } } finally { // *** Cleanup: close file *** if (sw != null) sw.Close(); sw = null; } } } // *** Read a value from local cache *** public string GetValue(string SectionName, string Key, string DefaultValue) { // *** Lazy loading *** if (m_Lazy) { m_Lazy = false; Refresh(); } lock (m_Lock) { // *** Check if the section exists *** Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) return DefaultValue; // *** Check if the key exists *** string Value; if (!Section.TryGetValue(Key, out Value)) return DefaultValue; // *** Return the found value *** return Value; } } // *** Insert or modify a value in local cache *** public void SetValue(string SectionName, string Key, string Value) { // *** Lazy loading *** if (m_Lazy) { m_Lazy = false; Refresh(); } lock (m_Lock) { // *** Flag local cache modification *** m_CacheModified = true; // *** Check if the section exists *** Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) { // *** If it doesn't, add it *** Section = new Dictionary<string, string>(); m_Sections.Add(SectionName, Section); } // *** Modify the value *** if (Section.ContainsKey(Key)) Section.Remove(Key); Section.Add(Key, Value); } } // *** Encode byte array *** private string EncodeByteArray(byte[] Value) { if (Value == null) return null; StringBuilder sb = new StringBuilder(); foreach (byte b in Value) { string hex = Convert.ToString(b, 16); int l = hex.Length; if (l > 2) { sb.Append(hex.Substring(l - 2, 2)); } else { if (l < 2) sb.Append("0"); sb.Append(hex); } } return sb.ToString(); } // *** Decode byte array *** private byte[] DecodeByteArray(string Value) { if (Value == null) return null; int l = Value.Length; if (l < 2) return new byte[] { }; l /= 2; byte[] Result = new byte[l]; for (int i = 0; i < l; i++) Result[i] = Convert.ToByte(Value.Substring(i * 2, 2), 16); return Result; } // *** Getters for various types *** public bool GetValue(string SectionName, string Key, bool DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(System.Globalization.CultureInfo.InvariantCulture)); int Value; if (int.TryParse(StringValue, out Value)) return (Value != 0); return DefaultValue; } public int GetValue(string SectionName, string Key, int DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); int Value; if (int.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } public byte GetValue(string SectionName, string Key, byte DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); byte Value; if (byte.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } public double GetValue(string SectionName, string Key, double DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); double Value; if (double.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } public byte[] GetValue(string SectionName, string Key, byte[] DefaultValue) { string StringValue = GetValue(SectionName, Key, EncodeByteArray(DefaultValue)); try { return DecodeByteArray(StringValue); } catch (FormatException) { return DefaultValue; } } // *** Setters for various types *** public void SetValue(string SectionName, string Key, bool Value) { SetValue(SectionName, Key, (Value) ? ("1") : ("0")); } public void SetValue(string SectionName, string Key, int Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } public void SetValue(string SectionName, string Key, byte Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } public void SetValue(string SectionName, string Key, double Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } public void SetValue(string SectionName, string Key, byte[] Value) { SetValue(SectionName, Key, EncodeByteArray(Value)); } #endregion } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: DocumentGridPage.cs // // Description: DocumentGridPage displays a graphical representation of an // DocumentPaginator page including drop-shadow // and is used by DocumentGrid. // // History: // 10/29/2004 : jdersch - created // //--------------------------------------------------------------------------- using MS.Internal.Annotations.Anchoring; using MS.Win32; using System.Threading; using System.Windows; using System.Windows.Annotations; using System.Windows.Annotations.Storage; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Shapes; using System.Windows.Input; using System.Windows.Media; using System; using System.Collections; using System.Diagnostics; namespace MS.Internal.Documents { /// <summary> /// /// </summary> internal class DocumentGridPage : FrameworkElement, IDisposable { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Standard constructor. /// </summary> public DocumentGridPage(DocumentPaginator paginator) : base() { _paginator = paginator; //Attach the GetPageCompleted event handler to the paginator so we can //use it to keep track of whether our page has been loaded yet. _paginator.GetPageCompleted += new GetPageCompletedEventHandler(OnGetPageCompleted); //Set up the static elements of our Visual Tree. Init(); } #endregion //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// The DocumentPage for the displayed page. /// </summary> public DocumentPage DocumentPage { get { CheckDisposed(); return _documentPageView.DocumentPage; } } /// <summary> /// The page number displayed. /// </summary> public int PageNumber { get { CheckDisposed(); return _documentPageView.PageNumber; } set { CheckDisposed(); if (_documentPageView.PageNumber != value) { _documentPageView.PageNumber = value; } } } /// <summary> /// The DocumentPageView displayed by this DocumentGridPage /// </summary> public DocumentPageView DocumentPageView { get { CheckDisposed(); return _documentPageView; } } /// <summary> /// Whether to show the border and drop shadow around the page. /// </summary> /// <value></value> public bool ShowPageBorders { get { CheckDisposed(); return _showPageBorders; } set { CheckDisposed(); if (_showPageBorders != value) { _showPageBorders = value; InvalidateMeasure(); } } } /// <summary> /// Whether the requested page is loaded. /// </summary> public bool IsPageLoaded { get { CheckDisposed(); return _loaded; } } //------------------------------------------------------------------- // // Public Events // //------------------------------------------------------------------- #region Public Events /// <summary> /// Fired when the document is finished paginating. /// </summary> public event EventHandler PageLoaded; #endregion Public Events #endregion Public Properties //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods /// <summary> /// Derived class must implement to support Visual children. The method must return /// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1. /// /// By default a Visual does not have any children. /// /// Remark: /// During this virtual call it is not valid to modify the Visual tree. /// </summary> protected override Visual GetVisualChild(int index) { CheckDisposed(); // count is either 0 or 3 if(VisualChildrenCount != 0) { switch(index) { case 0: return _dropShadowRight; case 1: return _dropShadowBottom; case 2: return _pageBorder; default: throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } } throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// /// By default a Visual does not have any children. /// /// Remark: During this virtual method the Visual tree must not be modified. /// </summary> protected override int VisualChildrenCount { get { if(!_disposed && hasAddedChildren) return 3; else return 0; } } /// <summary> /// Content measurement. /// </summary> /// <param name="availableSize">Available size that parent can give to the child. This is soft constraint.</param> /// <returns>The DocumentGridPage's desired size.</returns> protected override sealed Size MeasureOverride(Size availableSize) { CheckDisposed(); if(!hasAddedChildren) { //Add the drop shadow this.AddVisualChild(_dropShadowRight); this.AddVisualChild(_dropShadowBottom); //Add the page (inside the pageBorder) this.AddVisualChild(_pageBorder); hasAddedChildren = true; } //Show / hide the border and drop shadow based on the current //state of the ShowPageBorders property. if (ShowPageBorders) { _pageBorder.BorderThickness = _pageBorderVisibleThickness; _pageBorder.Background = Brushes.White; _dropShadowRight.Opacity = _dropShadowOpacity; _dropShadowBottom.Opacity = _dropShadowOpacity; } else { _pageBorder.BorderThickness = _pageBorderInvisibleThickness; _pageBorder.Background = Brushes.Transparent; _dropShadowRight.Opacity = 0.0; _dropShadowBottom.Opacity = 0.0; } //Measure our children. _dropShadowRight.Measure(availableSize); _dropShadowBottom.Measure(availableSize); _pageBorder.Measure(availableSize); //Set the Page Zoom on the DocumentPageView to the ratio between our measure constraint //and the actual size of the page; this will cause the DPV to scale our page appropriately. if (DocumentPage.Size != Size.Empty && DocumentPage.Size.Width != 0.0 ) { _documentPageView.SetPageZoom(availableSize.Width / DocumentPage.Size.Width); } return availableSize; } /// <summary> /// Content arrangement. /// </summary> /// <param name="arrangeSize">The final size that element should use to arrange itself and its children.</param> protected override sealed Size ArrangeOverride(Size arrangeSize) { CheckDisposed(); //Arrange the page, no offset. _pageBorder.Arrange(new Rect(new Point(0.0,0.0), arrangeSize)); //Arrange the drop shadow parts along the right //and bottom edges of the page. //Right edge - as tall as the page (minus the shadow width so we don't overlap //with the bottom edge), 5px wide. Offset vertically by 5px. _dropShadowRight.Arrange( new Rect( new Point(arrangeSize.Width, _dropShadowWidth), new Size(_dropShadowWidth, Math.Max( 0.0, arrangeSize.Height - _dropShadowWidth)) )); //Bottom edge - 5px tall, and as wide as the page. Offset horizontally by 5px. _dropShadowBottom.Arrange( new Rect( new Point(_dropShadowWidth, arrangeSize.Height), new Size(arrangeSize.Width, _dropShadowWidth) )); base.ArrangeOverride(arrangeSize); return arrangeSize; } #endregion Protected Methods //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods /// <summary> /// Creates the static members of DocumentGridPage's Visual Tree. /// </summary> private void Init() { //Create the DocumentPageView, which will display our //content. _documentPageView = new DocumentPageView(); _documentPageView.ClipToBounds = true; _documentPageView.StretchDirection = StretchDirection.Both; _documentPageView.PageNumber = int.MaxValue; //Create the border that goes around the page content. _pageBorder = new Border(); _pageBorder.BorderBrush = Brushes.Black; _pageBorder.Child = _documentPageView; //Create the drop shadow that goes behind the page, made //of two rectangles in an "L" shape. _dropShadowRight = new Rectangle(); _dropShadowRight.Fill = Brushes.Black; _dropShadowRight.Opacity = _dropShadowOpacity; _dropShadowBottom = new Rectangle(); _dropShadowBottom.Fill = Brushes.Black; _dropShadowBottom.Opacity = _dropShadowOpacity; _loaded = false; } /// <summary> /// Handles the GetPageCompleted event raised by the DocumentPaginator. /// At this point, we'll set the _loaded flag to indicate the page is loaded /// and fire the PageLoaded event. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Details about this event.</param> private void OnGetPageCompleted(object sender, GetPageCompletedEventArgs e) { //If the GetPageCompleted action completed successfully //and is our page then we'll set the flag and fire the event. if (!_disposed && e != null && !e.Cancelled && e.Error == null && e.PageNumber != int.MaxValue && e.PageNumber == this.PageNumber && e.DocumentPage != null && e.DocumentPage != DocumentPage.Missing) { _loaded = true; if (PageLoaded != null) { PageLoaded(this, EventArgs.Empty); } } } /// <summary> /// Dispose the object. /// </summary> protected void Dispose() { if (!_disposed) { _disposed = true; //Detach the GetPageCompleted event from the content. if (_paginator != null) { _paginator.GetPageCompleted -= new GetPageCompletedEventHandler(OnGetPageCompleted); _paginator = null; } //Dispose our DocumentPageView. IDisposable dpv = _documentPageView as IDisposable; if (dpv != null ) { dpv.Dispose(); } } } /// <summary> /// Checks if the instance is already disposed, throws if so. /// </summary> private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(typeof(DocumentPageView).ToString()); } } #endregion Private Methods #region IDisposable Members /// <summary> /// Dispose the object. /// </summary> void IDisposable.Dispose() { GC.SuppressFinalize(this); this.Dispose(); } #endregion IDisposable Members //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields private bool hasAddedChildren; private DocumentPaginator _paginator; private DocumentPageView _documentPageView; private Rectangle _dropShadowRight; private Rectangle _dropShadowBottom; private Border _pageBorder; private bool _showPageBorders; private bool _loaded; //Constants private const double _dropShadowOpacity = 0.35; private const double _dropShadowWidth = 5.0; private readonly Thickness _pageBorderVisibleThickness = new Thickness(1, 1, 1, 1); private readonly Thickness _pageBorderInvisibleThickness = new Thickness(0, 0, 0, 0); private bool _disposed; #endregion Private Fields } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Linq; namespace Test { public class AverageMaxMinTests { // // Average // [Fact] public static void RunAvgTests() { int count1 = 1, count2 = 2, count3 = 4, count4 = 13, count5 = 1024 * 8, count6 = 1024 * 16; Action<int>[] testActions = new Action<int>[] { (count) => RunAvgTest1<int>(count), (count) => RunAvgTest1<int?>(count), (count) => RunAvgTest1<long>(count), (count) => RunAvgTest1<long?>(count), (count) => RunAvgTest1<float>(count), (count) => RunAvgTest1<float?>(count), (count) => RunAvgTest1<double>(count), (count) => RunAvgTest1<double?>(count), (count) => RunAvgTest1<decimal>(count), (count) => RunAvgTest1<decimal?>(count) }; for (int i = 0; i < testActions.Length; i++) { bool isFloat = i == 4 || i == 5; testActions[i](count1); testActions[i](count2); testActions[i](count3); testActions[i](count4); testActions[i](count5); if (!isFloat) testActions[i](count6); Assert.Throws<InvalidOperationException>( () => { testActions[i](0); }); } } [Fact] public static void RunAvgTests_Negative() { Action<int>[] testActions = new Action<int>[] { (count) => RunAvgTest1<int>(count), (count) => RunAvgTest1<int?>(count), (count) => RunAvgTest1<long>(count), (count) => RunAvgTest1<long?>(count), (count) => RunAvgTest1<float>(count), (count) => RunAvgTest1<float?>(count), (count) => RunAvgTest1<double>(count), (count) => RunAvgTest1<double?>(count), (count) => RunAvgTest1<decimal>(count), (count) => RunAvgTest1<decimal?>(count) }; for (int i = 0; i < testActions.Length; i++) { Assert.Throws<InvalidOperationException>( () => { testActions[i](0); }); } } private static void RunAvgTest1<T>(int count) { string testMethodFail = string.Format("RunAvgTest1<{0}>(count={1}): FAILED.", typeof(T), count); if (typeof(T) == typeof(int)) { int[] ints = new int[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < ints.Length; i++) ints[i] = i; double realAvg = ints.AsParallel().Average(); if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(ints), expectAvg, realAvg)); } else if (typeof(T) == typeof(int?)) { int?[] ints = new int?[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < ints.Length; i++) ints[i] = i; double realAvg = ints.AsParallel().Average().Value; if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(ints), expectAvg, realAvg)); } if (typeof(T) == typeof(long)) { long[] longs = new long[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < longs.Length; i++) longs[i] = i; double realAvg = longs.AsParallel().Average(); if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(longs), expectAvg, realAvg)); } else if (typeof(T) == typeof(long?)) { long?[] longs = new long?[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < longs.Length; i++) longs[i] = i; double realAvg = longs.AsParallel().Average().Value; if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(longs), expectAvg, realAvg)); } else if (typeof(T) == typeof(float)) { float[] floats = new float[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < floats.Length; i++) floats[i] = i; double realAvg = floats.AsParallel().Average(); if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(floats), expectAvg, realAvg)); } else if (typeof(T) == typeof(float?)) { float?[] floats = new float?[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < floats.Length; i++) floats[i] = i; double realAvg = floats.AsParallel().Average().Value; if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(floats), expectAvg, realAvg)); } else if (typeof(T) == typeof(double)) { double[] doubles = new double[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < doubles.Length; i++) doubles[i] = i; double realAvg = doubles.AsParallel().Average(); if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(doubles), expectAvg, realAvg)); } else if (typeof(T) == typeof(double?)) { double?[] doubles = new double?[count]; double expectAvg = ((double)count - 1) / 2; for (int i = 0; i < doubles.Length; i++) doubles[i] = i; double realAvg = doubles.AsParallel().Average().Value; if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(doubles), expectAvg, realAvg)); } else if (typeof(T) == typeof(decimal)) { decimal[] decimals = new decimal[count]; decimal expectAvg = ((decimal)count - 1) / 2; for (int i = 0; i < decimals.Length; i++) decimals[i] = i; decimal realAvg = decimals.AsParallel().Average(); if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(decimals), expectAvg, realAvg)); } else if (typeof(T) == typeof(decimal?)) { decimal?[] decimals = new decimal?[count]; decimal expectAvg = ((decimal)count - 1) / 2; for (int i = 0; i < decimals.Length; i++) decimals[i] = i; decimal realAvg = decimals.AsParallel().Average().Value; if (!expectAvg.Equals(realAvg)) Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(decimals), expectAvg, realAvg)); } } // // Min // [Fact] public static void RunMinTests() { Action<int, int>[] testActions = new Action<int, int>[] { (dataSize, minSlot) => RunMinTest1<int>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<int?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<long>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<long?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<float>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<float?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<double>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<double?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<decimal>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<decimal?>(dataSize, minSlot) }; for (int i = 0; i < testActions.Length; i++) { if (i % 2 != 0) testActions[i](0, 0); testActions[i](1, 0); testActions[i](2, 0); testActions[i](2, 1); testActions[i](1024 * 4, 1024 * 2 - 1); } } [Fact] public static void RunMinTests_Negative() { Action<int, int>[] testActions = new Action<int, int>[] { (dataSize, minSlot) => RunMinTest1<int>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<int?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<long>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<long?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<float>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<float?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<double>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<double?>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<decimal>(dataSize, minSlot), (dataSize, minSlot) => RunMinTest1<decimal?>(dataSize, minSlot) }; for (int i = 0; i < testActions.Length; i++) { if (i % 2 == 0) Assert.Throws<InvalidOperationException>(() => testActions[i](0, 0)); } } private static void RunMinTest1<T>(int dataSize, int minSlot) { string methodFailed = string.Format("RunMinTest1<{0}>(dataSize={1}, minSlot={2}): FAILED.", typeof(T), dataSize, minSlot); if (typeof(T) == typeof(int)) { const int minNum = -100; int[] ints = new int[dataSize]; for (int i = 0; i < ints.Length; i++) ints[i] = i; if (dataSize > 0) ints[minSlot] = minNum; int min = ints.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } else if (typeof(T) == typeof(int?)) { int? minNum = dataSize == 0 ? (int?)null : -100; int?[] ints = new int?[dataSize]; for (int i = 0; i < ints.Length; i++) ints[i] = i; if (dataSize > 0) ints[minSlot] = minNum; int? min = ints.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } if (typeof(T) == typeof(long)) { const long minNum = -100; long[] longs = new long[dataSize]; for (int i = 0; i < longs.Length; i++) longs[i] = i; if (dataSize > 0) longs[minSlot] = minNum; long min = longs.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } else if (typeof(T) == typeof(long?)) { long? minNum = dataSize == 0 ? (long?)null : -100; long?[] longs = new long?[dataSize]; for (int i = 0; i < longs.Length; i++) longs[i] = i; if (dataSize > 0) longs[minSlot] = minNum; long? min = longs.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } if (typeof(T) == typeof(float)) { const float minNum = -100; float[] floats = new float[dataSize]; for (int i = 0; i < floats.Length; i++) floats[i] = i; if (dataSize > 0) floats[minSlot] = minNum; float min = floats.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } else if (typeof(T) == typeof(float?)) { float? minNum = dataSize == 0 ? (float?)null : -100; float?[] floats = new float?[dataSize]; for (int i = 0; i < floats.Length; i++) floats[i] = i; if (dataSize > 0) floats[minSlot] = minNum; float? min = floats.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } if (typeof(T) == typeof(double)) { const double minNum = -100; double[] doubles = new double[dataSize]; for (int i = 0; i < doubles.Length; i++) doubles[i] = i; if (dataSize > 0) doubles[minSlot] = minNum; double min = doubles.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } else if (typeof(T) == typeof(double?)) { double? minNum = dataSize == 0 ? (double?)null : -100; double?[] doubles = new double?[dataSize]; for (int i = 0; i < doubles.Length; i++) doubles[i] = i; if (dataSize > 0) doubles[minSlot] = minNum; double? min = doubles.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } if (typeof(T) == typeof(decimal)) { const decimal minNum = -100; decimal[] decimals = new decimal[dataSize]; for (int i = 0; i < decimals.Length; i++) decimals[i] = i; if (dataSize > 0) decimals[minSlot] = minNum; decimal min = decimals.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } else if (typeof(T) == typeof(decimal?)) { decimal? minNum = dataSize == 0 ? (decimal?)null : -100; decimal?[] decimals = new decimal?[dataSize]; for (int i = 0; i < decimals.Length; i++) decimals[i] = i; if (dataSize > 0) decimals[minSlot] = minNum; decimal? min = decimals.AsParallel().Min(); if (!minNum.Equals(min)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", minNum, min)); } } // // Max // [Fact] public static void RunMaxTests() { Action<int, int>[] testActions = new Action<int, int>[] { (dataSize, maxSlot) => RunMaxTest1<int>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<int?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<long>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<long?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<float>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<float?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<double>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<double?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<decimal>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<decimal?>(dataSize, maxSlot) }; for (int i = 0; i < testActions.Length; i++) { if (i % 2 != 0) testActions[i](0, 0); testActions[i](1, 0); testActions[i](2, 0); testActions[i](2, 1); testActions[i](1024 * 4, 1024 * 2 - 1); } } [Fact] public static void RunMaxTests_Negative() { Action<int, int>[] testActions = new Action<int, int>[] { (dataSize, maxSlot) => RunMaxTest1<int>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<int?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<long>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<long?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<float>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<float?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<double>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<double?>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<decimal>(dataSize, maxSlot), (dataSize, maxSlot) => RunMaxTest1<decimal?>(dataSize, maxSlot) }; for (int i = 0; i < testActions.Length; i++) { if (i % 2 == 0) Assert.Throws<InvalidOperationException>(() => testActions[i](0, 0)); } } private static void RunMaxTest1<T>(int dataSize, int maxSlot) { string methodFailed = string.Format("RunMaxTest1<{0}>(dataSize={1}, maxSlot={2}): FAILED.", typeof(T), dataSize, maxSlot); if (typeof(T) == typeof(int)) { int maxNum = dataSize + 100; int[] ints = new int[dataSize]; for (int i = 0; i < ints.Length; i++) ints[i] = i; if (dataSize > 0) ints[maxSlot] = maxNum; int max = ints.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(int?)) { int? maxNum = dataSize == 0 ? (int?)null : dataSize + 100; int?[] ints = new int?[dataSize]; for (int i = 0; i < ints.Length; i++) ints[i] = i; if (dataSize > 0) ints[maxSlot] = maxNum; int? max = ints.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(long)) { long maxNum = dataSize + 100; long[] longs = new long[dataSize]; for (int i = 0; i < longs.Length; i++) longs[i] = i; if (dataSize > 0) longs[maxSlot] = maxNum; long max = longs.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(long?)) { long? maxNum = dataSize == 0 ? (long?)null : dataSize + 100; long?[] longs = new long?[dataSize]; for (int i = 0; i < longs.Length; i++) longs[i] = i; if (dataSize > 0) longs[maxSlot] = maxNum; long? max = longs.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(float)) { float maxNum = dataSize + 100; float[] floats = new float[dataSize]; for (int i = 0; i < floats.Length; i++) floats[i] = i; if (dataSize > 0) floats[maxSlot] = maxNum; float max = floats.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(float?)) { float? maxNum = dataSize == 0 ? (float?)null : dataSize + 100; float?[] floats = new float?[dataSize]; for (int i = 0; i < floats.Length; i++) floats[i] = i; if (dataSize > 0) floats[maxSlot] = maxNum; float? max = floats.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(double)) { double maxNum = dataSize + 100; double[] doubles = new double[dataSize]; for (int i = 0; i < doubles.Length; i++) doubles[i] = i; if (dataSize > 0) doubles[maxSlot] = maxNum; double max = doubles.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(double?)) { double? maxNum = dataSize == 0 ? (double?)null : dataSize + 100; double?[] doubles = new double?[dataSize]; for (int i = 0; i < doubles.Length; i++) doubles[i] = i; if (dataSize > 0) doubles[maxSlot] = maxNum; double? max = doubles.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(decimal)) { decimal maxNum = dataSize + 100; decimal[] decimals = new decimal[dataSize]; for (int i = 0; i < decimals.Length; i++) decimals[i] = i; if (dataSize > 0) decimals[maxSlot] = maxNum; decimal max = decimals.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } if (typeof(T) == typeof(decimal?)) { decimal? maxNum = dataSize == 0 ? (decimal?)null : dataSize + 100; decimal?[] decimals = new decimal?[dataSize]; for (int i = 0; i < decimals.Length; i++) decimals[i] = i; if (dataSize > 0) decimals[maxSlot] = maxNum; decimal? max = decimals.AsParallel().Max(); if (!maxNum.Equals(max)) Assert.True(false, string.Format(methodFailed + " > Expect: {0}, real: {1}", maxNum, max)); } } } }
/* * Copyright (c) 2007-2009, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Threading; using OpenMetaverse.Packets; using OpenMetaverse.Messages.Linden; using OpenMetaverse.Interfaces; #if (COGBOT_LIBOMV || USE_STHREADS) using ThreadPoolUtil; using Thread = ThreadPoolUtil.Thread; using ThreadPool = ThreadPoolUtil.ThreadPool; using Monitor = ThreadPoolUtil.Monitor; #endif namespace OpenMetaverse { /// <summary> /// Registers, unregisters, and fires events generated by incoming packets /// </summary> public class PacketEventDictionary { private sealed class PacketCallback { public EventHandler<PacketReceivedEventArgs> Callback; public bool IsAsync; public PacketCallback(EventHandler<PacketReceivedEventArgs> callback, bool isAsync) { Callback = callback; IsAsync = isAsync; } } /// <summary> /// Object that is passed to worker threads in the ThreadPool for /// firing packet callbacks /// </summary> private struct PacketCallbackWrapper { /// <summary>Callback to fire for this packet</summary> public EventHandler<PacketReceivedEventArgs> Callback; /// <summary>Reference to the simulator that this packet came from</summary> public Simulator Simulator; /// <summary>The packet that needs to be processed</summary> public Packet Packet; } /// <summary>Reference to the GridClient object</summary> public GridClient Client; private Dictionary<PacketType, PacketCallback> _EventTable = new Dictionary<PacketType, PacketCallback>(); /// <summary> /// Default constructor /// </summary> /// <param name="client"></param> public PacketEventDictionary(GridClient client) { Client = client; } /// <summary> /// Register an event handler /// </summary> /// <remarks>Use PacketType.Default to fire this event on every /// incoming packet</remarks> /// <param name="packetType">Packet type to register the handler for</param> /// <param name="eventHandler">Callback to be fired</param> /// <param name="isAsync">True if this callback should be ran /// asynchronously, false to run it synchronous</param> public void RegisterEvent(PacketType packetType, EventHandler<PacketReceivedEventArgs> eventHandler, bool isAsync) { lock (_EventTable) { PacketCallback callback; if (_EventTable.TryGetValue(packetType, out callback)) { callback.Callback += eventHandler; callback.IsAsync = callback.IsAsync || isAsync; } else { callback = new PacketCallback(eventHandler, isAsync); _EventTable[packetType] = callback; } } } /// <summary> /// Unregister an event handler /// </summary> /// <param name="packetType">Packet type to unregister the handler for</param> /// <param name="eventHandler">Callback to be unregistered</param> public void UnregisterEvent(PacketType packetType, EventHandler<PacketReceivedEventArgs> eventHandler) { lock (_EventTable) { PacketCallback callback; if (_EventTable.TryGetValue(packetType, out callback)) { callback.Callback -= eventHandler; if (callback.Callback == null || callback.Callback.GetInvocationList().Length == 0) _EventTable.Remove(packetType); } } } /// <summary> /// Fire the events registered for this packet type /// </summary> /// <param name="packetType">Incoming packet type</param> /// <param name="packet">Incoming packet</param> /// <param name="simulator">Simulator this packet was received from</param> internal void RaiseEvent(PacketType packetType, Packet packet, Simulator simulator) { PacketCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(PacketType.Default, out callback) && callback.Callback != null) { if (callback.IsAsync) { PacketCallbackWrapper wrapper; wrapper.Callback = callback.Callback; wrapper.Packet = packet; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(ThreadPoolDelegate, wrapper); } else { try { callback.Callback(this, new PacketReceivedEventArgs(packet, simulator)); } catch (Exception ex) { Logger.Log("Default packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } if (_EventTable.TryGetValue(packetType, out callback) && callback.Callback != null) { if (callback.IsAsync) { PacketCallbackWrapper wrapper; wrapper.Callback = callback.Callback; wrapper.Packet = packet; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(ThreadPoolDelegate, wrapper); } else { try { callback.Callback(this, new PacketReceivedEventArgs(packet, simulator)); } catch (Exception ex) { Logger.Log("Packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } return; } if (packetType != PacketType.Default && packetType != PacketType.PacketAck) { Logger.DebugLog("No handler registered for packet event " + packetType, Client); } } private void ThreadPoolDelegate(Object state) { PacketCallbackWrapper wrapper = (PacketCallbackWrapper)state; try { wrapper.Callback(this, new PacketReceivedEventArgs(wrapper.Packet, wrapper.Simulator)); } catch (Exception ex) { Logger.Log("Async Packet Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } /// <summary> /// Registers, unregisters, and fires events generated by the Capabilities /// event queue /// </summary> public class CapsEventDictionary { /// <summary> /// Object that is passed to worker threads in the ThreadPool for /// firing CAPS callbacks /// </summary> private struct CapsCallbackWrapper { /// <summary>Callback to fire for this packet</summary> public Caps.EventQueueCallback Callback; /// <summary>Name of the CAPS event</summary> public string CapsEvent; /// <summary>Strongly typed decoded data</summary> public IMessage Message; /// <summary>Reference to the simulator that generated this event</summary> public Simulator Simulator; } /// <summary>Reference to the GridClient object</summary> public GridClient Client; private Dictionary<string, Caps.EventQueueCallback> _EventTable = new Dictionary<string, Caps.EventQueueCallback>(); private WaitCallback _ThreadPoolCallback; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the GridClient object</param> public CapsEventDictionary(GridClient client) { Client = client; _ThreadPoolCallback = new WaitCallback(ThreadPoolDelegate); } /// <summary> /// Register an new event handler for a capabilities event sent via the EventQueue /// </summary> /// <remarks>Use String.Empty to fire this event on every CAPS event</remarks> /// <param name="capsEvent">Capability event name to register the /// handler for</param> /// <param name="eventHandler">Callback to fire</param> public void RegisterEvent(string capsEvent, Caps.EventQueueCallback eventHandler) { // TODO: Should we add support for synchronous CAPS handlers? lock (_EventTable) { if (_EventTable.ContainsKey(capsEvent)) _EventTable[capsEvent] += eventHandler; else _EventTable[capsEvent] = eventHandler; } } /// <summary> /// Unregister a previously registered capabilities handler /// </summary> /// <param name="capsEvent">Capability event name unregister the /// handler for</param> /// <param name="eventHandler">Callback to unregister</param> public void UnregisterEvent(string capsEvent, Caps.EventQueueCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(capsEvent) && _EventTable[capsEvent] != null) _EventTable[capsEvent] -= eventHandler; } } /// <summary> /// Fire the events registered for this event type synchronously /// </summary> /// <param name="capsEvent">Capability name</param> /// <param name="message">Decoded event body</param> /// <param name="simulator">Reference to the simulator that /// generated this event</param> internal void RaiseEvent(string capsEvent, IMessage message, Simulator simulator) { bool specialHandler = false; Caps.EventQueueCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(capsEvent, out callback)) { if (callback != null) { try { callback(capsEvent, message, simulator); } catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } // Explicit handler next if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null) { try { callback(capsEvent, message, simulator); } catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } specialHandler = true; } if (!specialHandler) Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client); } /// <summary> /// Fire the events registered for this event type asynchronously /// </summary> /// <param name="capsEvent">Capability name</param> /// <param name="message">Decoded event body</param> /// <param name="simulator">Reference to the simulator that /// generated this event</param> internal void BeginRaiseEvent(string capsEvent, IMessage message, Simulator simulator) { bool specialHandler = false; Caps.EventQueueCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(String.Empty, out callback)) { if (callback != null) { CapsCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.CapsEvent = capsEvent; wrapper.Message = message; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); } } // Explicit handler next if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null) { CapsCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.CapsEvent = capsEvent; wrapper.Message = message; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); specialHandler = true; } if (!specialHandler) Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client); } private void ThreadPoolDelegate(Object state) { CapsCallbackWrapper wrapper = (CapsCallbackWrapper)state; try { wrapper.Callback(wrapper.CapsEvent, wrapper.Message, wrapper.Simulator); } catch (Exception ex) { Logger.Log("Async CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Testing; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class RazorPagesTest : IClassFixture<MvcTestFixture<RazorPagesWebSite.StartupWithoutEndpointRouting>> { private static readonly Assembly _resourcesAssembly = typeof(RazorPagesTest).GetTypeInfo().Assembly; public RazorPagesTest(MvcTestFixture<RazorPagesWebSite.StartupWithoutEndpointRouting> fixture) { var factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(ConfigureWebHostBuilder); Client = factory.CreateDefaultClient(); } private static void ConfigureWebHostBuilder(IWebHostBuilder builder) => builder.UseStartup<RazorPagesWebSite.StartupWithoutEndpointRouting>(); public HttpClient Client { get; } [Fact] public async Task Page_SimpleForms_RenderAntiforgery() { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/RazorPagesWebSite.SimpleForms.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync("http://localhost/SimpleForms"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "SimpleForms"); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, forgeryToken); } [Fact] public async Task Page_Handler_HandlerFromQueryString() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/HandlerTestPage?handler=Customer"); // Assert Assert.StartsWith("Method: OnGetCustomer", content.Trim()); } [Fact] public async Task Page_Handler_HandlerRouteDataChosenOverQueryString() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/HandlerTestPage/Customer?handler=ViewCustomer"); // Assert Assert.StartsWith("Method: OnGetCustomer", content.Trim()); } [Fact] public async Task Page_Handler_Handler() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/HandlerTestPage/Customer"); // Assert Assert.StartsWith("Method: OnGetCustomer", content.Trim()); } [Fact] public async Task Page_Handler_Async() { // Arrange var getResponse = await Client.GetAsync("http://localhost/HandlerTestPage"); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/ModelHandlerTestPage"); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/HandlerTestPage"); postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); postRequest.Headers.Add("RequestVerificationToken", formToken); // Act var response = await Client.SendAsync(postRequest); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Method: OnPostAsync", content.Trim()); } [Fact] public async Task Page_Handler_AsyncHandler() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/HandlerTestPage/ViewCustomer"); // Assert Assert.StartsWith("Method: OnGetViewCustomerAsync", content.Trim()); } [Fact] public async Task Page_Handler_ReturnTypeImplementsIActionResult() { // Arrange var getResponse = await Client.GetAsync("http://localhost/HandlerTestPage"); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/ModelHandlerTestPage"); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/HandlerTestPage/CustomActionResult"); postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); postRequest.Headers.Add("RequestVerificationToken", formToken); // Act var response = await Client.SendAsync(postRequest); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("CustomActionResult", content); } [Fact] public async Task PageWithoutModel_ReturnPartial() { // Act using var document = await Client.GetHtmlDocumentAsync("PageWithoutModelRenderPartial"); var element = document.RequiredQuerySelector("#content"); Assert.Equal("Hello from Razor Page", element.TextContent); } [Fact] public async Task PageWithModel_Works() { // Act using var document = await Client.GetHtmlDocumentAsync("RenderPartial"); var element = document.RequiredQuerySelector("#content"); Assert.Equal("Hello from RenderPartialModel", element.TextContent); } [Fact] public async Task PageWithModel_PartialUsingPageModelWorks() { // Act using var document = await Client.GetHtmlDocumentAsync("RenderPartial/UsePageModelAsPartialModel"); var element = document.RequiredQuerySelector("#content"); Assert.Equal("Hello from RenderPartialWithModel", element.TextContent); } [Fact] public async Task PageWithModel_PartialWithNoModel() { // Act using var document = await Client.GetHtmlDocumentAsync("RenderPartial/NoPartialModel"); var element = document.RequiredQuerySelector("#content"); Assert.Equal("Hello default", element.TextContent); } [Fact] public async Task Page_Handler_AsyncReturnTypeImplementsIActionResult() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/HandlerTestPage/CustomActionResult"); // Assert Assert.Equal("CustomActionResult", content); } [Fact] public async Task PageModel_Handler_Handler() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/ModelHandlerTestPage/Customer"); // Assert Assert.StartsWith("Method: OnGetCustomer", content.Trim()); } [Fact] public async Task PageModel_Handler_Async() { // Arrange var getResponse = await Client.GetAsync("http://localhost/ModelHandlerTestPage"); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/ModelHandlerTestPage"); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ModelHandlerTestPage"); postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); postRequest.Headers.Add("RequestVerificationToken", formToken); // Act var response = await Client.SendAsync(postRequest); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Method: OnPostAsync", content.Trim()); } [Fact] public async Task PageModel_Handler_AsyncHandler() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/ModelHandlerTestPage/ViewCustomer"); // Assert Assert.StartsWith("Method: OnGetViewCustomerAsync", content.Trim()); } [Fact] public async Task PageModel_Handler_ReturnTypeImplementsIActionResult() { // Arrange var getResponse = await Client.GetAsync("http://localhost/ModelHandlerTestPage"); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/ModelHandlerTestPage"); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ModelHandlerTestPage/CustomActionResult"); postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); postRequest.Headers.Add("RequestVerificationToken", formToken); // Act var response = await Client.SendAsync(postRequest); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("CustomActionResult", content); } [Fact] public async Task PageModel_Handler_AsyncReturnTypeImplementsIActionResult() { // Arrange & Act var content = await Client.GetStringAsync("http://localhost/ModelHandlerTestPage/CustomActionResult"); // Assert Assert.Equal("CustomActionResult", content); } [Fact] public async Task RouteData_StringValueOnIntProp_ExpectsNotFound() { // Arrange var routeRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/RouteData/pizza"); // Act var routeResponse = await Client.SendAsync(routeRequest); // Assert Assert.Equal(HttpStatusCode.NotFound, routeResponse.StatusCode); } [Fact] public async Task RouteData_IntProperty_IsCoerced() { // Arrange var routeRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/RouteData/5"); // Act var routeResponse = await Client.SendAsync(routeRequest); // Assert Assert.Equal(HttpStatusCode.OK, routeResponse.StatusCode); var content = await routeResponse.Content.ReadAsStringAsync(); Assert.Equal("From RouteData: 5", content.Trim()); } [Fact] public async Task Page_SetsPath() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/PathSet"); // Act var response = await Client.SendAsync(request); // Assert var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Path: /PathSet.cshtml", content.Trim()); } // Tests that RazorPage includes InvalidTagHelperIndexerAssignment which is called when the page has an indexer // Issue https://github.com/aspnet/Mvc/issues/5920 [Fact] public async Task TagHelper_InvalidIndexerDoesNotFail() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TagHelpers"); // Act var response = await Client.SendAsync(request); // Assert var content = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.StartsWith("<a href=\"/Show?id=2\">Post title</a>", content.Trim()); } [Fact] public async Task NoPage_NotFound() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/NoPage"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } [Fact] public async Task PageHandlerCanReturnBadRequest() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Pages/HandlerWithParameter"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal("Parameter cannot be null.", await response.Content.ReadAsStringAsync()); } [Fact] public async Task HelloWorld_CanGetContent() { // Arrange // Note: If the route in this test case ever changes, the negative test case // RazorPagesWithBasePathTest.PageOutsideBasePath_IsNotRouteable needs to be updated too. var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/HelloWorld"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hello, World!", content.Trim()); } [Fact] public async Task HelloWorldWithRoute_CanGetContent() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/HelloWorldWithRoute/Some/Path/route"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hello, route!", content.Trim()); } [Fact] public async Task HelloWorldWithHandler_CanGetContent() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/HelloWorldWithHandler?message=handler"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hello, handler!", content.Trim()); } [Fact] public async Task HelloWorldWithPageModelHandler_CanPostContent() { // Arrange var getRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/HelloWorldWithPageModelHandler?message=message"); var getResponse = await Client.SendAsync(getRequest); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/HelloWorlWithPageModelHandler"); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/HelloWorldWithPageModelHandler"); postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); postRequest.Headers.Add("RequestVerificationToken", formToken); // Act var response = await Client.SendAsync(postRequest); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Hello, You posted!", content.Trim()); } [Theory] [InlineData("GET")] [InlineData("HEAD")] public async Task HelloWorldWithPageModelHandler_CanGetContent(string httpMethod) { // Arrange var url = "http://localhost/HelloWorldWithPageModelHandler?message=pagemodel"; var request = new HttpRequestMessage(new HttpMethod(httpMethod), url); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Hello, pagemodel!", content.Trim()); } [Fact] public async Task HelloWorldWithPageModelAttributeHandler() { // Arrange var url = "HelloWorldWithPageModelAttributeModel?message=DecoratedModel"; // Act var content = await Client.GetStringAsync(url); // Assert Assert.Equal("Hello, DecoratedModel!", content.Trim()); } [Fact] public async Task PageWithoutContent() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/PageWithoutContent/No/Content/Path"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("", content); } [Fact] public async Task ViewReturnsPage() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/OnGetView"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("The message: From OnGet", content.Trim()); } [Fact] public async Task TempData_SetTempDataInPage_CanReadValue() { // Arrange 1 var url = "http://localhost/TempData/SetTempDataOnPageAndRedirect?message=Hi1"; var request = new HttpRequestMessage(HttpMethod.Get, url); // Act 1 var response = await Client.SendAsync(request); // Assert 1 Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); // Arrange 2 request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location); request.Headers.Add("Cookie", GetCookie(response)); // Act2 response = await Client.SendAsync(request); // Assert 2 var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hi1", content.Trim()); } [Fact] public async Task TempData_SetTempDataInPageModel_CanReadValue() { // Arrange 1 var url = "http://localhost/TempData/SetTempDataOnPageModelAndRedirect?message=Hi2"; var request = new HttpRequestMessage(HttpMethod.Get, url); // Act 1 var response = await Client.SendAsync(request); // Assert 1 Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); // Arrange 2 request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location); request.Headers.Add("Cookie", GetCookie(response)); // Act 2 response = await Client.SendAsync(request); // Assert 2 var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hi2", content.Trim()); } [Fact] public async Task TempData_TempDataPropertyOnPageModel_IsPopulatedFromTempData() { // Arrange 1 var url = "http://localhost/TempData/SetMessageAndRedirect"; var request = new HttpRequestMessage(HttpMethod.Get, url); // Act 1 var response = await Client.SendAsync(request); // Assert 1 Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); // Act 2 request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location); request.Headers.Add("Cookie", GetCookie(response)); response = await Client.SendAsync(request); // Assert 2 Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Message: Secret Message", content.Trim()); Assert.EndsWith("TempData: Secret Message", content.Trim()); } [Fact] public async Task TempData_TempDataPropertyOnPageModel_PopulatesTempData() { // Arrange 1 var getRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TempData/TempDataPageModelProperty"); var getResponse = await Client.SendAsync(getRequest); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/TempData/TempDataPageModelProperty"); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var url = "http://localhost/TempData/TempDataPageModelProperty"; var request = new HttpRequestMessage(HttpMethod.Post, url); request.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); request.Headers.Add("RequestVerificationToken", formToken); // Act 1 var response = await Client.SendAsync(request); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Message: Secret post", content.Trim()); Assert.EndsWith("TempData:", content.Trim()); // Arrange 2 request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TempData/TempDataPageModelProperty"); request.Headers.Add("Cookie", GetCookie(response)); // Act 2 response = await Client.SendAsync(request); // Assert 2 Assert.Equal(HttpStatusCode.OK, response.StatusCode); content = await response.Content.ReadAsStringAsync(); Assert.StartsWith("Message: Secret post", content.Trim()); Assert.EndsWith("TempData: Secret post", content.Trim()); } [Fact] public async Task AuthorizePage_AddsAuthorizationForSpecificPages() { // Arrange var url = "/HelloWorldWithAuth"; // Act var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("/Login?ReturnUrl=%2FHelloWorldWithAuth", response.Headers.Location.PathAndQuery); } [Fact] public async Task AuthorizePage_AllowAnonymousForSpecificPages() { // Arrange var url = "/Pages/Admin/Login"; // Act var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Login Page", content); } [Fact] public async Task ViewStart_IsDiscoveredWhenRootDirectoryIsNotSpecified() { // Test for https://github.com/aspnet/Mvc/issues/5915 //Arrange var expected = @"Hello from _ViewStart Hello from /Pages/WithViewStart/Index.cshtml!"; // Act var response = await Client.GetStringAsync("/Pages/WithViewStart"); // Assert Assert.Equal(expected, response, ignoreLineEndingDifferences: true); } [Fact] public async Task ViewImport_IsDiscoveredWhenRootDirectoryIsNotSpecified() { // Test for https://github.com/aspnet/Mvc/issues/5915 // Arrange var expected = "Hello from CustomService!"; // Act var response = await Client.GetStringAsync("/Pages/WithViewImport"); // Assert Assert.Equal(expected, response.Trim()); } [Fact] public async Task PropertiesOnPageAreBound() { // Arrange var expected = "Id = 10, Name = Foo, Age = 25"; var request = new HttpRequestMessage(HttpMethod.Post, "Pages/PropertyBinding/PagePropertyBinding/10") { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("Name", "Foo"), new KeyValuePair<string, string>("Age", "25"), }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, content.Trim()); } [Fact] public async Task PropertiesOnPageAreValidated() { // Arrange var expected = new[] { "Id = 27, Name = , Age = 325", "The Name field is required.", "The field Age must be between 0 and 99.", }; var request = new HttpRequestMessage(HttpMethod.Post, "Pages/PropertyBinding/PagePropertyBinding/27") { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("Age", "325"), }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); foreach (var item in expected) { Assert.Contains(item, content); } } [Fact] public async Task PropertiesOnPageModelAreBound() { // Arrange var expected = "Id = 10, Name = Foo, Age = 25, PropertyWithSupportGetsTrue = foo"; var request = new HttpRequestMessage(HttpMethod.Post, "Pages/PropertyBinding/PageModelWithPropertyBinding/10?PropertyWithSupportGetsTrue=foo") { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("Name", "Foo"), new KeyValuePair<string, string>("Age", "25"), }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, content.Trim()); } [Fact] public async Task PropertiesOnPageModelAreValidated() { // Arrange var url = "Pages/PropertyBinding/PageModelWithPropertyBinding/27"; var expected = new[] { "Id = 27, Name = , Age = 325, PropertyWithSupportGetsTrue =", "The Name field is required.", "The field Age must be between 0 and 99.", }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("Age", "325"), }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); foreach (var item in expected) { Assert.Contains(item, content); } } [Fact] public async Task PolymorphicPropertiesOnPageModelsAreBound() { // Arrange var name = "TestName"; var age = 23; var expected = $"Name = {name}, Age = {age}"; var request = new HttpRequestMessage(HttpMethod.Post, "Pages/PropertyBinding/PolymorphicBinding") { Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "Name", name }, { "Age", age.ToString(CultureInfo.InvariantCulture) }, }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert await response.AssertStatusCodeAsync(HttpStatusCode.OK); var content = await response.Content.ReadAsStringAsync(); Assert.Equal(expected, content); } [Fact(Skip = "https://github.com/dotnet/corefx/issues/36024")] public async Task PolymorphicPropertiesOnPageModelsAreValidated() { // Arrange var name = "TestName"; var age = 123; var request = new HttpRequestMessage(HttpMethod.Post, "Pages/PropertyBinding/PolymorphicBinding") { Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "Name", name }, { "Age", age.ToString(CultureInfo.InvariantCulture) }, }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert await response.AssertStatusCodeAsync(HttpStatusCode.BadRequest); var result = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Collection( result.Properties(), p => { Assert.Equal("Age", p.Name); var value = Assert.IsType<JArray>(p.Value); Assert.Equal("The field Age must be between 0 and 99.", value.First.ToString()); }); } [Fact] public async Task HandlerMethodArgumentsAndPropertiesAreModelBound() { // Arrange var expected = "Id = 11, Name = Test-Name, Age = 32"; var request = new HttpRequestMessage(HttpMethod.Post, "Pages/PropertyBinding/PageWithPropertyAndArgumentBinding?id=11") { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("Name", "Test-Name"), new KeyValuePair<string, string>("Age", "32"), }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, content.Trim()); } [Fact] public async Task PagePropertiesAreNotBoundInGetRequests() { // Arrange var expected = "Id = 11, Name = Test-Name, Age ="; var validationError = "The Name field is required."; var request = new HttpRequestMessage(HttpMethod.Get, "Pages/PropertyBinding/PageWithPropertyAndArgumentBinding?id=11") { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("Name", "Test-Name"), new KeyValuePair<string, string>("Age", "32"), }), }; // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, content.Trim()); Assert.DoesNotContain(validationError, content); } [Fact] public async Task PageProperty_WithSupportsGetTrue_OnPageWithHandler_FuzzyMatchesHeadRequest() { // Arrange var request = new HttpRequestMessage(HttpMethod.Head, "Pages/PropertyBinding/PageModelWithPropertyBinding/10?PropertyWithSupportGetsTrue=foo"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Content); Assert.NotNull(response.Content.Headers.ContentType); Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType); } [Fact] public async Task PageProperty_WithSupportsGetTrue_OnPageWithNoHandler_FuzzyMatchesHeadRequest() { // Arrange var request = new HttpRequestMessage(HttpMethod.Head, "Pages/PropertyBinding/BindPropertyWithGet?value=11"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Content); Assert.NotNull(response.Content.Headers.ContentType); Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType); } [Fact] public async Task PageProperty_WithSupportsGet_BoundInGet() { // Arrange var expected = "<p>11</p>"; var request = new HttpRequestMessage(HttpMethod.Get, "Pages/PropertyBinding/BindPropertyWithGet?value=11"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, content.Trim()); } [Fact] public async Task PagePropertiesAreInjected() { // Arrange var expected = @"Microsoft.AspNetCore.Mvc.Routing.UrlHelper Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper`1[AspNetCoreGeneratedDocument.InjectedPageProperties] Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary`1[AspNetCoreGeneratedDocument.InjectedPageProperties]"; // Act var response = await Client.GetStringAsync("InjectedPageProperties"); // Assert Assert.Equal(expected, response.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task RedirectFromPageWorks() { // Arrange var expected = "/Pages/Redirects/Redirect/10"; // Act var response = await Client.GetAsync("/Pages/Redirects/RedirectFromPage"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectFromPageModelWorks() { // Arrange var expected = "/Pages/Redirects/Redirect/12"; // Act var response = await Client.GetAsync("/Pages/Redirects/RedirectFromModel"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToSelfWorks() { // Arrange var expected = "/Pages/Redirects/RedirectToSelf?user=37"; var request = new HttpRequestMessage(HttpMethod.Post, "/Pages/Redirects/RedirectToSelf") { Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("value", "37"), }), }; // Act await AddAntiforgeryHeaders(request); var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectDoesNotIncludeHandlerByDefault() { // Arrange var expected = "/Pages/Redirects/RedirectFromHandler"; // Act var response = await Client.GetAsync("/Pages/Redirects/RedirectFromHandler/RedirectToPage/10"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToOtherHandlersWorks() { // Arrange var expected = "/Pages/Redirects/RedirectFromHandler/RedirectToPage/11"; // Act var response = await Client.GetAsync("/Pages/Redirects/RedirectFromHandler/RedirectToAnotherHandler/11"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task Controller_RedirectToPage() { // Arrange var expected = "/RedirectToController?param=17"; // Act var response = await Client.GetAsync("/RedirectToPage"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task Page_RedirectToController() { // Arrange var expected = "/RedirectToPage?param=92"; // Act var response = await Client.GetAsync("/RedirectToController"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToSibling_Works() { // Arrange var expected = "/Pages/Redirects/Redirect/10"; var response = await Client.GetAsync("/Pages/Redirects/RedirectToSibling/RedirectToRedirect"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToSibling_RedirectsToIndexPage_WithoutIndexSegment() { // Arrange var expected = "/Pages/Redirects"; var response = await Client.GetAsync("/Pages/Redirects/RedirectToSibling/RedirectToIndex"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToSibling_RedirectsToSubDirectory() { // Arrange var expected = "/Pages/Redirects/SubDir/SubDirPage"; var response = await Client.GetAsync("/Pages/Redirects/RedirectToSibling/RedirectToSubDir"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToSibling_RedirectsToDotSlash() { // Arrange var expected = "/Pages/Redirects/SubDir/SubDirPage"; // Act var response = await Client.GetAsync("/Pages/Redirects/RedirectToSibling/RedirectToDotSlash"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task RedirectToSibling_RedirectsToParentDirectory() { // Arrange var expected = "/Pages/Conventions/AuthFolder"; var response = await Client.GetAsync("/Pages/Redirects/RedirectToSibling/RedirectToParent"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(expected, response.Headers.Location.ToString()); } [Fact] public async Task TagHelpers_SupportSiblingRoutes() { // Arrange var expected = @"<form method=""post"" action=""/Pages/TagHelper/CrossPost""></form> <a href=""/Pages/TagHelper/SelfPost/12"" /> <input type=""image"" formaction=""/Pages/TagHelper/CrossPost#my-fragment"" />"; // Act var response = await Client.GetStringAsync("/Pages/TagHelper/SiblingLinks"); // Assert Assert.Equal(expected, response.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task TagHelpers_SupportSubDirectoryRoutes() { // Arrange var expected = @"<form method=""post"" action=""/Pages/TagHelper/SubDir/SubDirPage""></form> <a href=""/Pages/TagHelper/SubDir/SubDirPage/12"" /> <input type=""image"" formaction=""/Pages/TagHelper/SubDir/SubDirPage#my-fragment"" />"; // Act var response = await Client.GetStringAsync("/Pages/TagHelper/SubDirectoryLinks"); // Assert Assert.Equal(expected, response.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task TagHelpers_SupportsPathNavigation() { // Arrange var expected = @"<form method=""post"" action=""/Pages/TagHelper/SubDirectoryLinks""></form> <form method=""post"" action=""/HelloWorld""></form> <a href=""/Pages/Redirects/RedirectToIndex"" /> <input type=""image"" formaction=""/Pages/Admin#my-fragment"" />"; // Act var response = await Client.GetStringAsync("/Pages/TagHelper/PathTraversalLinks"); // Assert Assert.Equal(expected, response.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task Page_WithSection_CanAccessModel() { // Arrange var expected = "Value is 17"; // Act var response = await Client.GetStringAsync("/Pages/Section"); // Assert Assert.StartsWith(expected, response.Trim()); } [Fact] public async Task PagesCanByRoutedViaRoute_AddedViaAddPageRoute() { // Arrange var expected = "Hello, test!"; // Act var response = await Client.GetStringAsync("/Different-Route/test"); // Assert Assert.StartsWith(expected, response.Trim()); } [Fact] public async Task PagesCanByRoutedToApplicationRoot_ViaAddPageRoute() { // Arrange var expected = "Hello from NotTheRoot"; // Act var response = await Client.GetStringAsync(""); // Assert Assert.StartsWith(expected, response.Trim()); } [Fact] public async Task AuthFiltersAppliedToPageModel_AreExecuted() { // Act var response = await Client.GetAsync("/Pages/ModelWithAuthFilter"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("/Login?ReturnUrl=%2FPages%2FModelWithAuthFilter", response.Headers.Location.PathAndQuery); } [Fact] public async Task AuthorizeAttributeIsExecutedPriorToAutoAntiforgeryFilter() { // Act var response = await Client.PostAsync("/Pages/Admin/Edit", new StringContent("")); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("/Login?ReturnUrl=%2FPages%2FAdmin%2FEdit", response.Headers.Location.PathAndQuery); } [Fact] public async Task PageFiltersAppliedToPageModel_AreExecuted() { // Arrange var expected = "Hello from OnGetEdit"; // Act var response = await Client.GetStringAsync("/ModelWithPageFilter"); // Assert Assert.Equal(expected, response.Trim()); } [Fact] public async Task ResponseCacheAttributes_AreApplied() { // Arrange var expected = "Hello from ModelWithResponseCache.OnGet"; // Act var response = await Client.GetAsync("/ModelWithResponseCache"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var cacheControl = response.Headers.CacheControl; Assert.Equal(TimeSpan.FromSeconds(10), cacheControl.MaxAge.Value); Assert.True(cacheControl.Private); Assert.Equal(expected, (await response.Content.ReadAsStringAsync()).Trim()); } [Fact] public async Task ViewLocalizer_WorksForPagesWithoutModel() { // Arrange var expected = "Bon Jour from Page"; // Act var response = await Client.GetStringAsync("/Pages/Localized/Page?culture=fr-FR"); Assert.Equal(expected, response.Trim()); } [Fact] public async Task ViewLocalizer_WorksForPagesWithModel() { // Arrange var expected = "Bon Jour from PageWithModel"; // Act var response = await Client.GetStringAsync("/Pages/Localized/PageWithModel?culture=fr-FR"); // Assert Assert.Equal(expected, response.Trim()); } [Fact] public async Task BindPropertiesAttribute_CanBeAppliedToModelType() { // Arrange var expected = "Property1 = 123, Property2 = 25,"; var request = new HttpRequestMessage(HttpMethod.Post, "/Pages/PropertyBinding/BindPropertiesOnModel?Property1=123") { Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "Property2", "25" }, }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, responseContent.Trim()); } [Fact] public async Task BindPropertiesAttribute_CanBeAppliedToModelType_AllowsBindingOnGet() { // Arrange var url = "/Pages/PropertyBinding/BindPropertiesWithSupportsGetOnModel?Property=Property-Value"; // Act var response = await Client.GetAsync(url); // Assert await response.AssertStatusCodeAsync(HttpStatusCode.OK); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Property-Value", content.Trim()); } [Fact] public async Task BindingInfoOnPropertiesIsPreferredToBindingInfoOnType() { // Arrange var expected = "Property1 = 123, Property2 = 25,"; var request = new HttpRequestMessage(HttpMethod.Post, "/Pages/PropertyBinding/BindPropertiesOnModel?Property1=123") { Content = new FormUrlEncodedContent(new[] { // FormValueProvider appears before QueryStringValueProvider. However, the FromQuery explicitly listed // on the property should cause it to use the latter. new KeyValuePair<string, string>("Property1", "345"), new KeyValuePair<string, string>("Property2", "25"), }), }; await AddAntiforgeryHeaders(request); // Act var response = await Client.SendAsync(request); // Assert response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); Assert.StartsWith(expected, responseContent.Trim()); } [Fact] public Task InheritsOnViewImportsWorksForPagesWithoutModel() => InheritsOnViewImportsWorks("Pages/CustomBaseType/Page"); [Fact] public Task InheritsOnViewImportsWorksForPagesWithModel() => InheritsOnViewImportsWorks("Pages/CustomBaseType/PageWithModel"); private async Task InheritsOnViewImportsWorks(string path) { // Arrange var expected = "<custom-base-type-layout>RazorPagesWebSite.CustomPageBase</custom-base-type-layout>"; // Act var response = await Client.GetStringAsync(path); // Assert Assert.Equal(expected, response.Trim()); } [Fact] public async Task PageHandlerFilterOnPageModelIsExecuted() { // Arrange var expected = "Hello from OnPageHandlerExecuting"; // Act var response = await Client.GetStringAsync("/ModelAsFilter?message=Hello+world"); // Assert Assert.Equal(expected, response.Trim()); } [Fact] public async Task ResultFilterOnPageModelIsExecuted() { // Act var response = await Client.GetAsync("/ModelAsFilter/TestResultFilter"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } [Fact] public async Task Page_CanOverrideRouteTemplate() { // Arrange & Act var content = await Client.GetStringAsync("like-totally-custom"); // Assert Assert.Equal("<p>Hey, it's Mr. totally custom here!</p>", content.Trim()); } [Fact] public async Task Page_Handler_BindsToDefaultValues() { // Arrange string expected; using (new CultureReplacer(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture)) { expected = $"id: 10, guid: {default(Guid)}, boolean: {default(bool)}, dateTime: {default(DateTime)}"; } // Act var content = await Client.GetStringAsync("http://localhost/ModelHandlerTestPage/DefaultValues"); // Assert Assert.Equal(expected, content); } [Theory] [InlineData(nameof(IAuthorizationFilter.OnAuthorization))] [InlineData(nameof(IAsyncAuthorizationFilter.OnAuthorizationAsync))] public async Task PageResultSetAt_AuthorizationFilter_Works(string targetName) { // Act var content = await Client.GetStringAsync("http://localhost/Pages/ShortCircuitPageAtAuthFilter?target=" + targetName); // Assert Assert.Equal("From ShortCircuitPageAtAuthFilter.cshtml", content); } [Theory] [InlineData(nameof(IPageFilter.OnPageHandlerExecuting))] [InlineData(nameof(IAsyncPageFilter.OnPageHandlerExecutionAsync))] public async Task PageResultSetAt_PageFilter_Works(string targetName) { // Act var content = await Client.GetStringAsync("http://localhost/Pages/ShortCircuitPageAtPageFilter?target=" + targetName); // Assert Assert.Equal("From ShortCircuitPageAtPageFilter.cshtml", content); } [Fact] public async Task ViewDataAwaitableInPageFilter_AfterHandlerMethod_ReturnsPageResult() { // Act var content = await Client.GetStringAsync("http://localhost/Pages/ViewDataAvailableAfterHandlerExecuted"); // Assert Assert.Equal("ViewData: Bar", content); } [Fact] public async Task OptionsRequest_WithoutHandler_Returns200_WithoutExecutingPage() { // Arrange var request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/HelloWorld"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Empty(content.Trim()); } [Fact] public async Task PageWithOptionsHandler_ExecutesGetRequest() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/HelloWorldWithOptionsHandler"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hello from OnGet!", content.Trim()); } [Fact] public async Task PageWithOptionsHandler_ExecutesOptionsRequest() { // Arrange var request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/HelloWorldWithOptionsHandler"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hello from OnOptions!", content.Trim()); } private async Task AddAntiforgeryHeaders(HttpRequestMessage request) { var getResponse = await Client.GetAsync(request.RequestUri); Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, ""); var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); request.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value); request.Headers.Add("RequestVerificationToken", formToken); } private static string GetCookie(HttpResponseMessage response) { var setCookie = response.Headers.GetValues("Set-Cookie").ToArray(); return setCookie[0].Split(';').First(); } public class CookieMetadata { public string Key { get; set; } public string Value { get; set; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="VideoServiceClient"/> instances.</summary> public sealed partial class VideoServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="VideoServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="VideoServiceSettings"/>.</returns> public static VideoServiceSettings GetDefault() => new VideoServiceSettings(); /// <summary>Constructs a new <see cref="VideoServiceSettings"/> object with default settings.</summary> public VideoServiceSettings() { } private VideoServiceSettings(VideoServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetVideoSettings = existing.GetVideoSettings; OnCopy(existing); } partial void OnCopy(VideoServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>VideoServiceClient.GetVideo</c> /// and <c>VideoServiceClient.GetVideoAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetVideoSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="VideoServiceSettings"/> object.</returns> public VideoServiceSettings Clone() => new VideoServiceSettings(this); } /// <summary> /// Builder class for <see cref="VideoServiceClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> internal sealed partial class VideoServiceClientBuilder : gaxgrpc::ClientBuilderBase<VideoServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public VideoServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public VideoServiceClientBuilder() { UseJwtAccessWithScopes = VideoServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref VideoServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<VideoServiceClient> task); /// <summary>Builds the resulting client.</summary> public override VideoServiceClient Build() { VideoServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<VideoServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<VideoServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private VideoServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return VideoServiceClient.Create(callInvoker, Settings); } private async stt::Task<VideoServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return VideoServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => VideoServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => VideoServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => VideoServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>VideoService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage videos. /// </remarks> public abstract partial class VideoServiceClient { /// <summary> /// The default endpoint for the VideoService service, which is a host of "googleads.googleapis.com" and a port /// of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default VideoService scopes.</summary> /// <remarks> /// The default VideoService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="VideoServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="VideoServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="VideoServiceClient"/>.</returns> public static stt::Task<VideoServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new VideoServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="VideoServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="VideoServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="VideoServiceClient"/>.</returns> public static VideoServiceClient Create() => new VideoServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="VideoServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="VideoServiceSettings"/>.</param> /// <returns>The created <see cref="VideoServiceClient"/>.</returns> internal static VideoServiceClient Create(grpccore::CallInvoker callInvoker, VideoServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } VideoService.VideoServiceClient grpcClient = new VideoService.VideoServiceClient(callInvoker); return new VideoServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC VideoService client</summary> public virtual VideoService.VideoServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::Video GetVideo(GetVideoRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Video> GetVideoAsync(GetVideoRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Video> GetVideoAsync(GetVideoRequest request, st::CancellationToken cancellationToken) => GetVideoAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the video to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::Video GetVideo(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetVideo(new GetVideoRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the video to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Video> GetVideoAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetVideoAsync(new GetVideoRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the video to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Video> GetVideoAsync(string resourceName, st::CancellationToken cancellationToken) => GetVideoAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the video to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::Video GetVideo(gagvr::VideoName resourceName, gaxgrpc::CallSettings callSettings = null) => GetVideo(new GetVideoRequest { ResourceNameAsVideoName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the video to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Video> GetVideoAsync(gagvr::VideoName resourceName, gaxgrpc::CallSettings callSettings = null) => GetVideoAsync(new GetVideoRequest { ResourceNameAsVideoName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the video to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Video> GetVideoAsync(gagvr::VideoName resourceName, st::CancellationToken cancellationToken) => GetVideoAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>VideoService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage videos. /// </remarks> public sealed partial class VideoServiceClientImpl : VideoServiceClient { private readonly gaxgrpc::ApiCall<GetVideoRequest, gagvr::Video> _callGetVideo; /// <summary> /// Constructs a client wrapper for the VideoService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="VideoServiceSettings"/> used within this client.</param> public VideoServiceClientImpl(VideoService.VideoServiceClient grpcClient, VideoServiceSettings settings) { GrpcClient = grpcClient; VideoServiceSettings effectiveSettings = settings ?? VideoServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetVideo = clientHelper.BuildApiCall<GetVideoRequest, gagvr::Video>(grpcClient.GetVideoAsync, grpcClient.GetVideo, effectiveSettings.GetVideoSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetVideo); Modify_GetVideoApiCall(ref _callGetVideo); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetVideoApiCall(ref gaxgrpc::ApiCall<GetVideoRequest, gagvr::Video> call); partial void OnConstruction(VideoService.VideoServiceClient grpcClient, VideoServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC VideoService client</summary> public override VideoService.VideoServiceClient GrpcClient { get; } partial void Modify_GetVideoRequest(ref GetVideoRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::Video GetVideo(GetVideoRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetVideoRequest(ref request, ref callSettings); return _callGetVideo.Sync(request, callSettings); } /// <summary> /// Returns the requested video in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::Video> GetVideoAsync(GetVideoRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetVideoRequest(ref request, ref callSettings); return _callGetVideo.Async(request, callSettings); } } }
using System; using NUnit.Framework; using Whois.Parsers; namespace Whois.Parsing.Whois.Nic.Uk.Uk { [TestFixture] public class UkParsingTests : ParsingTests { private WhoisParser parser; [SetUp] public void SetUp() { SerilogConfig.Init(); parser = new WhoisParser(); } [Test] public void Test_found() { var sample = SampleReader.Read("whois.nic.uk", "uk", "found.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("netbenefit.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Ascio Technologies Inc t/a Ascio Technologies inc [Tag = ASCIO]", response.Registrar.Name); Assert.AreEqual("http://www.ascio.com", response.Registrar.Url); Assert.AreEqual(new DateTime(2011, 07, 28, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 08, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 08, 20, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Netbenefit (UK) Ltd", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("3rd Floor Prospero House", response.Registrant.Address[0]); Assert.AreEqual("241 Borough High Street", response.Registrant.Address[1]); Assert.AreEqual("London", response.Registrant.Address[2]); Assert.AreEqual("SE1 1GB", response.Registrant.Address[3]); Assert.AreEqual("United Kingdom", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns0.netbenefit.co.uk", response.NameServers[0]); Assert.AreEqual("ns1.netbenefit.co.uk", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until expiry date.", response.DomainStatus[0]); Assert.AreEqual(16, response.FieldsParsed); } [Test] public void Test_found_registrant_type_individual() { var sample = SampleReader.Read("whois.nic.uk", "uk", "found_registrant_type_individual.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("bedandbreakfastsearcher.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Webfusion Ltd t/a 123-reg [Tag = 123-REG]", response.Registrar.Name); Assert.AreEqual("http://www.123-reg.co.uk", response.Registrar.Url); Assert.AreEqual(new DateTime(2012, 04, 11, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2006, 04, 16, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2014, 04, 16, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Mike Peacock", response.Registrant.Name); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns1.rapidswitch.com", response.NameServers[0]); Assert.AreEqual("ns2.rapidswitch.com", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until expiry date.", response.DomainStatus[0]); Assert.AreEqual(11, response.FieldsParsed); } [Test] public void Test_found_registrant_type_unknown() { var sample = SampleReader.Read("whois.nic.uk", "uk", "found_registrant_type_unknown.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("google.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Markmonitor Inc. t/a Markmonitor [Tag = MARKMONITOR]", response.Registrar.Name); Assert.AreEqual("http://www.markmonitor.com", response.Registrar.Url); Assert.AreEqual(new DateTime(2011, 02, 10, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1999, 02, 14, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 02, 14, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Google Inc.", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("1600 Amphitheatre Parkway", response.Registrant.Address[0]); Assert.AreEqual("Mountain View", response.Registrant.Address[1]); Assert.AreEqual("CA", response.Registrant.Address[2]); Assert.AreEqual("94043", response.Registrant.Address[3]); Assert.AreEqual("United States", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("ns1.google.com", response.NameServers[0]); Assert.AreEqual("ns2.google.com", response.NameServers[1]); Assert.AreEqual("ns3.google.com", response.NameServers[2]); Assert.AreEqual("ns4.google.com", response.NameServers[3]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until expiry date.", response.DomainStatus[0]); Assert.AreEqual(18, response.FieldsParsed); } [Test] public void Test_found_registrar_godaddy() { var sample = SampleReader.Read("whois.nic.uk", "uk", "found_registrar_godaddy.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("ecigsbrand.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("GoDaddy.com, LLP. [Tag = GODADDY]", response.Registrar.Name); Assert.AreEqual(new DateTime(2012, 08, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2010, 09, 16, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 09, 16, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Vitality & Wellness Ltd.", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("72 High Street", response.Registrant.Address[0]); Assert.AreEqual("Haslemere", response.Registrant.Address[1]); Assert.AreEqual("Surrey", response.Registrant.Address[2]); Assert.AreEqual("GU27 2LA", response.Registrant.Address[3]); Assert.AreEqual("United Kingdom", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("pdns01.domaincontrol.com", response.NameServers[0]); Assert.AreEqual("pdns02.domaincontrol.com", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until expiry date.", response.DomainStatus[0]); Assert.AreEqual(15, response.FieldsParsed); } [Test] public void Test_found_registrar_without_trading_name() { var sample = SampleReader.Read("whois.nic.uk", "uk", "found_registrar_without_trading_name.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("netbenefit.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("NetNames Limited [Tag = NETNAMES]", response.Registrar.Name); Assert.AreEqual("http://www.netnames.co.uk", response.Registrar.Url); Assert.AreEqual(new DateTime(2010, 07, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 08, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); // Registrant Details Assert.AreEqual("Netbenefit (UK) Ltd", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("3rd Floor Prospero House", response.Registrant.Address[0]); Assert.AreEqual("241 Borough High Street", response.Registrant.Address[1]); Assert.AreEqual("London", response.Registrant.Address[2]); Assert.AreEqual("SE1 1GB", response.Registrant.Address[3]); Assert.AreEqual("United Kingdom", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns0.netbenefit.co.uk", response.NameServers[0]); Assert.AreEqual("ns1.netbenefit.co.uk", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until renewal date.", response.DomainStatus[0]); Assert.AreEqual(15, response.FieldsParsed); } [Test] public void Test_not_found() { var sample = SampleReader.Read("whois.nic.uk", "uk", "not_found.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/NotFound", response.TemplateName); Assert.AreEqual("u34jedzcq.co.uk", response.DomainName.ToString()); Assert.AreEqual(2, response.FieldsParsed); } [Test] public void Test_other_status_no_longer_required() { var sample = SampleReader.Read("whois.nic.uk", "uk", "other_status_no_longer_required.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Other, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("atlasholidays.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Print Copy Systems Limited t/a Lan Systems [Tag = LANSYSTEMS]", response.Registrar.Name); Assert.AreEqual("http://www.lansystems.co.uk", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 05, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1999, 04, 16, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 04, 16, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Atlas Associates", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("The PC Clinic (UK) Ltd., 1 Hinckley Road,", response.Registrant.Address[0]); Assert.AreEqual("Sapcote", response.Registrant.Address[1]); Assert.AreEqual("Leicestershire", response.Registrant.Address[2]); Assert.AreEqual("LE9 4FS", response.Registrant.Address[3]); Assert.AreEqual("United Kingdom", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns1.thenameservers.co.uk", response.NameServers[0]); Assert.AreEqual("ns2.thenameservers.co.uk", response.NameServers[1]); Assert.AreEqual("ns3.thenameservers.co.uk", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("No longer required", response.DomainStatus[0]); Assert.AreEqual(17, response.FieldsParsed); } [Test] public void Test_other_status_no_status_listed() { var sample = SampleReader.Read("whois.nic.uk", "uk", "other_status_no_status_listed.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Reserved, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("internet.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("No registrar listed. This domain is registered directly with Nominet.", response.Registrar.Name); Assert.AreEqual(new DateTime(2012, 03, 23, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 08, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); // Registrant Details Assert.AreEqual("Nominet UK", response.Registrant.Name); // Registrant Address Assert.AreEqual(6, response.Registrant.Address.Count); Assert.AreEqual("Minerva House, Edmund Halley Road", response.Registrant.Address[0]); Assert.AreEqual("Oxford Science Park", response.Registrant.Address[1]); Assert.AreEqual("Oxford", response.Registrant.Address[2]); Assert.AreEqual("Oxon", response.Registrant.Address[3]); Assert.AreEqual("OX4 4DQ", response.Registrant.Address[4]); Assert.AreEqual("United Kingdom", response.Registrant.Address[5]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("nom-ns1.nominet.org.uk", response.NameServers[0]); Assert.AreEqual("nom-ns2.nominet.org.uk", response.NameServers[1]); Assert.AreEqual("nom-ns3.nominet.org.uk", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("No registration status listed.", response.DomainStatus[0]); Assert.AreEqual(16, response.FieldsParsed); } [Test] public void Test_other_status_processing_registration() { var sample = SampleReader.Read("whois.nic.uk", "uk", "other_status_processing_registration.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Other, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("reachingyoungmales.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Webfusion Ltd t/a 123-Reg.co.uk [Tag = 123-REG]", response.Registrar.Name); Assert.AreEqual("http://www.123-reg.co.uk", response.Registrar.Url); Assert.AreEqual(new DateTime(2010, 09, 17, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2010, 09, 17, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); // Registrant Details Assert.AreEqual("VCCP digital", response.Registrant.Name); // Registrant Address Assert.AreEqual(6, response.Registrant.Address.Count); Assert.AreEqual("Greencoat House", response.Registrant.Address[0]); Assert.AreEqual("Francis Street Victoria", response.Registrant.Address[1]); Assert.AreEqual("London", response.Registrant.Address[2]); Assert.AreEqual("London", response.Registrant.Address[3]); Assert.AreEqual("SW1P 1DH", response.Registrant.Address[4]); Assert.AreEqual("United Kingdom", response.Registrant.Address[5]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns.123-reg.co.uk", response.NameServers[0]); Assert.AreEqual("ns2.123-reg.co.uk", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registration request being processed.", response.DomainStatus[0]); Assert.AreEqual(16, response.FieldsParsed); } [Test] public void Test_other_status_processing_renewal() { var sample = SampleReader.Read("whois.nic.uk", "uk", "other_status_processing_renewal.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Other, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("creatinghomeowners.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Webfusion Ltd t/a 123-Reg.co.uk [Tag = 123-REG]", response.Registrar.Name); Assert.AreEqual("http://www.123-reg.co.uk", response.Registrar.Url); Assert.AreEqual(new DateTime(2010, 09, 22, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2008, 09, 22, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); // Registrant Details Assert.AreEqual("VCCP digital", response.Registrant.Name); // Registrant Address Assert.AreEqual(6, response.Registrant.Address.Count); Assert.AreEqual("Greencoat House", response.Registrant.Address[0]); Assert.AreEqual("Francis Street Victoria", response.Registrant.Address[1]); Assert.AreEqual("London", response.Registrant.Address[2]); Assert.AreEqual("London", response.Registrant.Address[3]); Assert.AreEqual("SW1P 1DH", response.Registrant.Address[4]); Assert.AreEqual("United Kingdom", response.Registrant.Address[5]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns.123-reg.co.uk", response.NameServers[0]); Assert.AreEqual("ns2.123-reg.co.uk", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Renewal request being processed.", response.DomainStatus[0]); Assert.AreEqual(16, response.FieldsParsed); } [Test] public void Test_other_status_registered_until_expiry_date() { var sample = SampleReader.Read("whois.nic.uk", "uk", "other_status_registered_until_expiry_date.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("google.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Markmonitor Inc. t/a Markmonitor [Tag = MARKMONITOR]", response.Registrar.Name); Assert.AreEqual("http://www.markmonitor.com", response.Registrar.Url); Assert.AreEqual(new DateTime(2011, 02, 10, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1999, 02, 14, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 02, 14, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Google Inc.", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("1600 Amphitheatre Parkway", response.Registrant.Address[0]); Assert.AreEqual("Mountain View", response.Registrant.Address[1]); Assert.AreEqual("CA", response.Registrant.Address[2]); Assert.AreEqual("94043", response.Registrant.Address[3]); Assert.AreEqual("United States", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("ns1.google.com", response.NameServers[0]); Assert.AreEqual("ns2.google.com", response.NameServers[1]); Assert.AreEqual("ns3.google.com", response.NameServers[2]); Assert.AreEqual("ns4.google.com", response.NameServers[3]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until expiry date.", response.DomainStatus[0]); Assert.AreEqual(18, response.FieldsParsed); } [Test] public void Test_suspended() { var sample = SampleReader.Read("whois.nic.uk", "uk", "suspended.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Suspended, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("allofshoes.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Key-Systems GmbH [Tag = KEY-SYSTEMS-DE]", response.Registrar.Name); Assert.AreEqual("http://www.key-systems.net", response.Registrar.Url); Assert.AreEqual(new DateTime(2012, 02, 09, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2008, 08, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2010, 08, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Yuan Chen", response.Registrant.Name); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("Meiyuan Road", response.Registrant.Address[0]); Assert.AreEqual("Putian", response.Registrant.Address[1]); Assert.AreEqual("351100", response.Registrant.Address[2]); Assert.AreEqual("China", response.Registrant.Address[3]); // Domain Status Assert.AreEqual(2, response.DomainStatus.Count); Assert.AreEqual("Renewal required.", response.DomainStatus[0]); Assert.AreEqual("*** This registration has been SUSPENDED. ***", response.DomainStatus[1]); Assert.AreEqual(14, response.FieldsParsed); } [Test] public void Test_throttled() { var sample = SampleReader.Read("whois.nic.uk", "uk", "throttled.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Throttled, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Throttled", response.TemplateName); Assert.AreEqual("google.co.uk", response.DomainName.ToString()); Assert.AreEqual(2, response.FieldsParsed); } [Test] public void Test_not_found_status_available() { var sample = SampleReader.Read("whois.nic.uk", "uk", "not_found_status_available.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/NotFound", response.TemplateName); Assert.AreEqual("u34jedzcq.co.uk", response.DomainName.ToString()); Assert.AreEqual(2, response.FieldsParsed); } [Test] public void Test_invalid() { var sample = SampleReader.Read("whois.nic.uk", "uk", "invalid.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Invalid, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Invalid", response.TemplateName); Assert.AreEqual("u34jedzcq.uk", response.DomainName.ToString()); Assert.AreEqual(2, response.FieldsParsed); } [Test] public void Test_found_status_registered() { var sample = SampleReader.Read("whois.nic.uk", "uk", "found_status_registered.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("google.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Markmonitor Inc. t/a Markmonitor [Tag = MARKMONITOR]", response.Registrar.Name); Assert.AreEqual("http://www.markmonitor.com", response.Registrar.Url); Assert.AreEqual(new DateTime(2014, 01, 13, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1999, 02, 14, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2015, 02, 14, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Google Inc.", response.Registrant.Name); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("1600 Amphitheatre Parkway", response.Registrant.Address[0]); Assert.AreEqual("Mountain View", response.Registrant.Address[1]); Assert.AreEqual("CA", response.Registrant.Address[2]); Assert.AreEqual("94043", response.Registrant.Address[3]); Assert.AreEqual("United States", response.Registrant.Address[4]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("ns1.google.com", response.NameServers[0]); Assert.AreEqual("ns2.google.com", response.NameServers[1]); Assert.AreEqual("ns3.google.com", response.NameServers[2]); Assert.AreEqual("ns4.google.com", response.NameServers[3]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("Registered until expiry date.", response.DomainStatus[0]); Assert.AreEqual(18, response.FieldsParsed); } [Test] public void Test_reserved() { var sample = SampleReader.Read("whois.nic.uk", "uk", "reserved.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Reserved, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("internet.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("No registrar listed. This domain is registered directly with Nominet.", response.Registrar.Name); Assert.AreEqual(new DateTime(2012, 03, 23, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(1996, 08, 01, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); // Registrant Details Assert.AreEqual("Nominet UK", response.Registrant.Name); // Registrant Address Assert.AreEqual(6, response.Registrant.Address.Count); Assert.AreEqual("Minerva House, Edmund Halley Road", response.Registrant.Address[0]); Assert.AreEqual("Oxford Science Park", response.Registrant.Address[1]); Assert.AreEqual("Oxford", response.Registrant.Address[2]); Assert.AreEqual("Oxon", response.Registrant.Address[3]); Assert.AreEqual("OX4 4DQ", response.Registrant.Address[4]); Assert.AreEqual("United Kingdom", response.Registrant.Address[5]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("nom-ns1.nominet.org.uk", response.NameServers[0]); Assert.AreEqual("nom-ns2.nominet.org.uk", response.NameServers[1]); Assert.AreEqual("nom-ns3.nominet.org.uk", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("No registration status listed.", response.DomainStatus[0]); Assert.AreEqual(16, response.FieldsParsed); } [Test] public void Test_suspended_status_suspended() { var sample = SampleReader.Read("whois.nic.uk", "uk", "suspended_status_suspended.txt"); var response = parser.Parse("whois.nic.uk", sample); Assert.AreEqual(WhoisStatus.Suspended, response.Status); AssertWriter.Write(response); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.uk/uk/Found", response.TemplateName); Assert.AreEqual("allofshoes.co.uk", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("Key-Systems GmbH [Tag = KEY-SYSTEMS-DE]", response.Registrar.Name); Assert.AreEqual("http://www.key-systems.net", response.Registrar.Url); Assert.AreEqual(new DateTime(2012, 02, 09, 00, 00, 00, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2008, 08, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2010, 08, 30, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("Yuan Chen", response.Registrant.Name); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("Meiyuan Road", response.Registrant.Address[0]); Assert.AreEqual("Putian", response.Registrant.Address[1]); Assert.AreEqual("351100", response.Registrant.Address[2]); Assert.AreEqual("China", response.Registrant.Address[3]); // Domain Status Assert.AreEqual(2, response.DomainStatus.Count); Assert.AreEqual("Renewal required.", response.DomainStatus[0]); Assert.AreEqual("*** This registration has been SUSPENDED. ***", response.DomainStatus[1]); Assert.AreEqual(14, response.FieldsParsed); } } }
using NUnit.Framework; using System.Linq; namespace LinUnit.Tests { public class ExpressionTests { [Test] public void Equal() { 1.Should(x => x == 1); } [Test, ExpectedException(ExpectedMessage = "2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Equal_fails() { 1.Should(x => x == 2); } [Test] public void Not_equal() { 1.Should(x => x != 2); } [Test, ExpectedException(ExpectedMessage = "not 1\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Not_equal_fails() { 1.Should(x => x != 1); } [Test] public void And() { 1.Should(x => x == 1 && x != 2); } [Test, ExpectedException(ExpectedMessage = "1 and 2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void And_fails() { 1.Should(x => x == 1 && x == 2); } [Test] public void Or() { 1.Should(x => x == 1 || x == 2); } [Test, ExpectedException(ExpectedMessage = "2 or 3\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Or_fails() { 1.Should(x => x == 2 || x == 3); } [Test] public void Greater() { 1.Should(x => x > 0); } [Test, ExpectedException(ExpectedMessage = "greater than 2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Greater_fails() { 1.Should(x => x > 2); } [Test] public void Greater_or_equal() { 1.Should(x => x >= 1); } [Test, ExpectedException(ExpectedMessage = "greater than or equal to 2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Greater_or_equal_fails() { 1.Should(x => x >= 2); } [Test] public void Less() { 1.Should(x => x < 2); } [Test, ExpectedException(ExpectedMessage = "less than 1\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Less_fails() { 1.Should(x => x < 1); } [Test] public void Less_or_equal() { 1.Should(x => x <= 1); } [Test, ExpectedException(ExpectedMessage = "less than or equal to 0\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Less_or_equal_fails() { 1.Should(x => x <= 0); } [Test] public void Not() { "abc".Should(x => !x.Contains("d")); } [Test, ExpectedException(ExpectedMessage = "not \"x.Contains(\"a\")\"\r\n But was: \"abc\"", MatchType = MessageMatch.Contains)] public void Notfails() { "abc".Should(x => !x.Contains("a")); } [Test] public void Operations_on_right_side() { var y = 2; var z = 4; 4.Should(x => x == y*y); 2.Should(x => x == z/y); 4.Should(x => x == y+y); 2.Should(x => x == z-y); } [Test] public void Static_method_called_on_parameter_with_no_arguments() { "a".Should(x => x.Any()); } [Test, ExpectedException(ExpectedMessage = "\"x.Any()\"\r\n But was: <string.Empty>", MatchType = MessageMatch.Contains)] public void Static_method_called_on_parameter_with_no_arguments_fails() { "".Should(x => x.Any()); } [Test] public void Static_method_called_on_parameter_with_simple_arguments() { new[] {1, 2}.Should(x => x.Contains(1)); } [Test, ExpectedException(ExpectedMessage = "\"x.Contains(3)\"\r\n But was: < 1, 2 >", MatchType = MessageMatch.Contains)] public void Static_method_called_on_parameter_with_simple_arguments_fails() { new[] {1, 2}.Should(x => x.Contains(3)); } [Test] public void Static_method_called_on_parameter_with_lambda_argument() { new[] {1, 2, 3}.Should(x => x.All(y => y > 0)); } [Test, ExpectedException(ExpectedMessage = "\"x.All(y => (y > 1))\"\r\n But was: < 1, 2, 3 >", MatchType = MessageMatch.Contains)] public void Static_method_called_on_parameter_with_lambda_argument_fails() { new[] {1, 2, 3}.Should(x => x.All(y => y > 1)); } [Test] public void Instance_method_called_on_parameter_with_simple_arguments() { "abc".Should(x => x.Contains("a")); } [Test, ExpectedException(ExpectedMessage = "\"x.Contains(\"d\")\"\r\n But was: \"abc\"", MatchType = MessageMatch.Contains)] public void Instance_method_called_on_parameter_with_simple_arguments_fails() { "abc".Should(x => x.Contains("d")); } [Test] public void Static_method_call_on_right_side() { 1.Should(x => x == int.Parse("1")); } [Test, ExpectedException(ExpectedMessage = "2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Static_method_call_on_right_side_fails() { 1.Should(x => x == int.Parse("2")); } [Test] public void Instance_method_call_on_right_side() { "1".Should(x => x == 1.ToString()); } [Test, ExpectedException(ExpectedMessage = "\"2\"\r\n But was: \"1\"", MatchType = MessageMatch.Contains)] public void Instance_method_call_on_right_side_fails() { "1".Should(x => x == 2.ToString()); } [Test] public void Parameter_on_right_side() { 1.Should(x => x == x); } [Test, ExpectedException(ExpectedMessage = "not 1\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Parameter_on_right_side_fails() { 1.Should(x => x != x); } [Test] public void Method_call_on_parameter_on_right_side() { 1.Should(x => x == int.Parse(x.ToString())); } [Test, ExpectedException(ExpectedMessage = "11\r\n But was: 1", MatchType = MessageMatch.Contains)] public void Method_call_on_parameter_on_right_side_fails() { 1.Should(x => x == int.Parse(x.ToString() + 1)); } [Test, ExpectedException(ExpectedMessage = "Expression 1 invalid on left side of binary expression")] public void Invalid_left_side_operand_1() { 1.Should(x => 1 == x); } [Test, ExpectedException(ExpectedMessage = "Expression x.ToString() invalid on left side of binary expression")] public void Invalid_left_side_operand_2() { 1.Should(x => x.ToString() == "1"); } [Test, ExpectedException(ExpectedMessage = "y invalid on left side of binary expression", MatchType = MessageMatch.Contains)] public void Invalid_left_side_operand_3() { var y = 1; 1.Should(x => y == x); } [Test, ExpectedException(ExpectedMessage = "Expression x.Length invalid on left side of binary expression")] public void Invalid_left_side_operand_4() { "".Should(x => x.Length == 0); } [Test, ExpectedException(ExpectedMessage = "invalid on left side of binary expression", MatchType = MessageMatch.Contains)] public void Invalid_left_side_operand_5() { "".Should(x => x[0] == 0); } [Test] public void CaptureExternalVariable() { var y = 1; 1.Should(x => x == y); } [Test, ExpectedException(ExpectedMessage = "2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void CaptureExternalVariableFails() { var y = 2; 1.Should(x => x == y); } [Test] public void CaptureExternalVariableArray() { var y = new[]{1, 2}; var z = new[]{2, 1}; 1.Should(x => x == y[0] && x == z[1]); } [Test, ExpectedException(ExpectedMessage = "1 and 2\r\n But was: 1", MatchType = MessageMatch.Contains)] public void CaptureExternalVariableArrayFails() { var y = new[]{1, 2}; var z = new[]{2, 1}; 1.Should(x => x == y[0] && x == z[0]); } [Test] public void MethodCallWithCapturedVariableArgument() { var y = 2; new[] {1, 2}.Should(x => x.Contains(y)); } [Test, ExpectedException(ExpectedMessage = "y)\"\r\n But was: < 1, 2 >", MatchType = MessageMatch.Contains)] public void MethodCallWithCapturedVariableArgumentFails() { var y = 3; new[]{1, 2}.Should(x => x.Contains(y)); } } }
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 AldursLab.WurmAssistantWebService.Areas.HelpPage.SampleGeneration { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.IO; using System.Collections; using System.Windows.Forms; /* ScpTo.cs * ==================================================================== * The following example was posted with the original JSch java library, * and is translated to C# to show the usage of SharpSSH JSch API * ==================================================================== * */ namespace Tamir.SharpSsh.jsch.examples { /// <summary> /// This program will demonstrate the sftp protocol support. /// You will be asked username, host and passwd. /// If everything works fine, you will get a prompt 'sftp>'. /// 'help' command will show available command. /// In current implementation, the destination path for 'get' and 'put' /// commands must be a file, not a directory. /// </summary> public class Sftp { public static void Main(String[] arg) { try { JSch jsch=new JSch(); InputForm inForm = new InputForm(); inForm.Text = "Enter username@hostname"; inForm.textBox1.Text = Environment.UserName+"@localhost"; if (!inForm.PromptForInput()) { Console.WriteLine("Cancelled"); return; } String host = inForm.textBox1.Text; String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); Channel channel=session.openChannel("sftp"); channel.connect(); ChannelSftp c=(ChannelSftp)channel; Stream ins=Console.OpenStandardInput(); TextWriter outs=Console.Out; ArrayList cmds=new ArrayList(); byte[] buf=new byte[1024]; int i; String str; int level=0; while(true) { outs.Write("sftp> "); cmds.Clear(); i=ins.Read(buf, 0, 1024); if(i<=0)break; i--; if(i>0 && buf[i-1]==0x0d)i--; //str=Util.getString(buf, 0, i); //Console.WriteLine("|"+str+"|"); int s=0; for(int ii=0; ii<i; ii++) { if(buf[ii]==' ') { if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); } while(ii<i){if(buf[ii]!=' ')break; ii++;} s=ii; } } if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); } if(cmds.Count==0)continue; String cmd=(String)cmds[0]; if(cmd.Equals("quit")) { c.quit(); break; } if(cmd.Equals("exit")) { c.exit(); break; } if(cmd.Equals("rekey")) { session.rekey(); continue; } if(cmd.Equals("compression")) { if(cmds.Count<2) { outs.WriteLine("compression level: "+level); continue; } try { level=int.Parse((String)cmds[1]); Hashtable config=new Hashtable(); if(level==0) { config.Add("compression.s2c", "none"); config.Add("compression.c2s", "none"); } else { config.Add("compression.s2c", "zlib,none"); config.Add("compression.c2s", "zlib,none"); } session.setConfig(config); } catch{}//(Exception e){} continue; } if(cmd.Equals("cd") || cmd.Equals("lcd")) { if(cmds.Count<2) continue; String path=(String)cmds[1]; try { if(cmd.Equals("cd")) c.cd(path); else c.lcd(path); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir")) { if(cmds.Count<2) continue; String path=(String)cmds[1]; try { if(cmd.Equals("rm")) c.rm(path); else if(cmd.Equals("rmdir")) c.rmdir(path); else c.mkdir(path); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod")) { if(cmds.Count!=3) continue; String path=(String)cmds[2]; int foo=0; if(cmd.Equals("chmod")) { byte[] bar=Util.getBytes((String)cmds[1]); int k; for(int j=0; j<bar.Length; j++) { k=bar[j]; if(k<'0'||k>'7'){foo=-1; break;} foo<<=3; foo|=(k-'0'); } if(foo==-1)continue; } else { try{foo=int.Parse((String)cmds[1]);} catch{}//(Exception e){continue;} } try { if(cmd.Equals("chgrp")){ c.chgrp(foo, path); } else if(cmd.Equals("chown")){ c.chown(foo, path); } else if(cmd.Equals("chmod")){ c.chmod(foo, path); } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("pwd") || cmd.Equals("lpwd")) { str=(cmd.Equals("pwd")?"Remote":"Local"); str+=" working directory: "; if(cmd.Equals("pwd")) str+=c.pwd(); else str+=c.lpwd(); outs.WriteLine(str); continue; } if(cmd.Equals("ls") || cmd.Equals("dir")) { String path="."; if(cmds.Count==2) path=(String)cmds[1]; try { ArrayList vv=c.ls(path); if(vv!=null) { for(int ii=0; ii<vv.Count; ii++) { object obj = vv[ii]; if(obj is ChannelSftp.LsEntry) outs.WriteLine(vv[ii]); } } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("lls") || cmd.Equals("ldir")) { String path="."; if(cmds.Count==2) path=(String)cmds[1]; try { //java.io.File file=new java.io.File(path); if(!File.Exists(path)) { outs.WriteLine(path+": No such file or directory"); continue; } if(Directory.Exists(path)) { String[] list=Directory.GetDirectories(path); for(int ii=0; ii<list.Length; ii++) { outs.WriteLine(list[ii]); } continue; } outs.WriteLine(path); } catch(Exception e) { Console.WriteLine(e); } continue; } if(cmd.Equals("get") || cmd.Equals("get-resume") || cmd.Equals("get-append") || cmd.Equals("put") || cmd.Equals("put-resume") || cmd.Equals("put-append") ) { if(cmds.Count!=2 && cmds.Count!=3) continue; String p1=(String)cmds[1]; // String p2=p1; String p2="."; if(cmds.Count==3)p2=(String)cmds[2]; try { SftpProgressMonitor monitor=new MyProgressMonitor(); if(cmd.StartsWith("get")) { int mode=ChannelSftp.OVERWRITE; if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; } else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; } c.get(p1, p2, monitor, mode); } else { int mode=ChannelSftp.OVERWRITE; if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; } else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; } c.put(p1, p2, monitor, mode); } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename")) { if(cmds.Count!=3) continue; String p1=(String)cmds[1]; String p2=(String)cmds[2]; try { if(cmd.Equals("rename")) c.rename(p1, p2); else c.symlink(p1, p2); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("stat") || cmd.Equals("lstat")) { if(cmds.Count!=2) continue; String p1=(String)cmds[1]; SftpATTRS attrs=null; try { if(cmd.Equals("stat")) attrs=c.stat(p1); else attrs=c.lstat(p1); } catch(SftpException e) { Console.WriteLine(e.message); } if(attrs!=null) { outs.WriteLine(attrs); } else { } continue; } if(cmd.Equals("version")) { outs.WriteLine("SFTP protocol version "+c.version()); continue; } if(cmd.Equals("help") || cmd.Equals("?")) { outs.WriteLine(help); continue; } outs.WriteLine("unimplemented command: "+cmd); } session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } } public class MyUserInfo : UserInfo { public String getPassword(){ return passwd; } public bool promptYesNo(String str) { DialogResult returnVal = MessageBox.Show( str, "SharpSSH", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); return (returnVal==DialogResult.Yes); } String passwd; InputForm passwordField=new InputForm(); public String getPassphrase(){ return null; } public bool promptPassphrase(String message){ return true; } public bool promptPassword(String message) { InputForm inForm = new InputForm(); inForm.Text = message; inForm.PasswordField = true; if ( inForm.PromptForInput() ) { passwd=inForm.getText(); return true; } else{ return false; } } public void showMessage(String message) { MessageBox.Show( message, "SharpSSH", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } public class MyProgressMonitor : SftpProgressMonitor { private ConsoleProgressBar bar; private long c = 0; private long max = 0; private long percent=-1; int elapsed=-1; System.Timers.Timer timer; public override void init(int op, String src, String dest, long max) { bar = new ConsoleProgressBar(); this.max=max; elapsed=0; timer=new System.Timers.Timer(1000); timer.Start(); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); } public override bool count(long c) { this.c += c; if(percent>=this.c*100/max){ return true; } percent=this.c*100/max; string note = ("Transfering... [Elapsed time: "+elapsed+"]"); bar.Update((int)this.c, (int)max, note); return true; } public override void end() { if (timer != null) { timer.Stop(); timer.Dispose(); } string note = ("Done in " + elapsed + " seconds!"); if (bar!=null) { bar.Update((int) this.c, (int) max, note); bar = null; } } private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.elapsed++; } } private static String help = " Available commands:\n"+ " * means unimplemented command.\n"+ "cd path Change remote directory to 'path'\n"+ "lcd path Change local directory to 'path'\n"+ "chgrp grp path Change group of file 'path' to 'grp'\n"+ "chmod mode path Change permissions of file 'path' to 'mode'\n"+ "chown own path Change owner of file 'path' to 'own'\n"+ "help Display this help text\n"+ "get remote-path [local-path] Download file\n"+ "get-resume remote-path [local-path] Resume to download file.\n"+ "get-append remote-path [local-path] Append remote file to local file\n"+ "*lls [ls-options [path]] Display local directory listing\n"+ "ln oldpath newpath Symlink remote file\n"+ "*lmkdir path Create local directory\n"+ "lpwd Print local working directory\n"+ "ls [path] Display remote directory listing\n"+ "*lumask umask Set local umask to 'umask'\n"+ "mkdir path Create remote directory\n"+ "put local-path [remote-path] Upload file\n"+ "put-resume local-path [remote-path] Resume to upload file\n"+ "put-append local-path [remote-path] Append local file to remote file.\n"+ "pwd Display remote working directory\n"+ "stat path Display info about path\n"+ "exit Quit sftp\n"+ "quit Quit sftp\n"+ "rename oldpath newpath Rename remote file\n"+ "rmdir path Remove remote directory\n"+ "rm path Delete remote file\n"+ "symlink oldpath newpath Symlink remote file\n"+ "rekey Key re-exchanging\n"+ "compression level Packet compression will be enabled\n"+ "version Show SFTP version\n"+ "? Synonym for help"; } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { internal static class StringUtils { public const string CarriageReturnLineFeed = "\r\n"; public const string Empty = ""; public const char CarriageReturn = '\r'; public const char LineFeed = '\n'; public const char Tab = '\t'; public static string FormatWith(this string format, IFormatProvider provider, object arg0) { return format.FormatWith(provider, new[] { arg0 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1) { return format.FormatWith(provider, new[] { arg0, arg1 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2) { return format.FormatWith(provider, new[] { arg0, arg1, arg2 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) { return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 }); } private static string FormatWith(this string format, IFormatProvider provider, params object[] args) { // leave this a private to force code to use an explicit overload // avoids stack memory being reserved for the object array ValidationUtils.ArgumentNotNull(format, nameof(format)); return string.Format(provider, format, args); } /// <summary> /// Determines whether the string is all white space. Empty string will return false. /// </summary> /// <param name="s">The string to test whether it is all white space.</param> /// <returns> /// <c>true</c> if the string is all white space; otherwise, <c>false</c>. /// </returns> public static bool IsWhiteSpace(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (s.Length == 0) { return false; } for (int i = 0; i < s.Length; i++) { if (!char.IsWhiteSpace(s[i])) { return false; } } return true; } /// <summary> /// Nulls an empty string. /// </summary> /// <param name="s">The string.</param> /// <returns>Null if the string was null, otherwise the string unchanged.</returns> public static string NullEmptyString(string s) { return (string.IsNullOrEmpty(s)) ? null : s; } public static StringWriter CreateStringWriter(int capacity) { StringBuilder sb = new StringBuilder(capacity); StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); return sw; } public static int? GetLength(string value) { if (value == null) { return null; } else { return value.Length; } } public static void ToCharAsUnicode(char c, char[] buffer) { buffer[0] = '\\'; buffer[1] = 'u'; buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f'); buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f'); buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f'); buffer[5] = MathUtils.IntToHex(c & '\x000f'); } public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (valueSelector == null) { throw new ArgumentNullException(nameof(valueSelector)); } var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) { return caseInsensitiveResults.SingleOrDefault(); } else { // multiple results returned. now filter using case sensitivity var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); return caseSensitiveResults.SingleOrDefault(); } } public static string ToCamelCase(string s) { if (string.IsNullOrEmpty(s)) { return s; } if (!char.IsUpper(s[0])) { return s; } char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) { bool hasNext = (i + 1 < chars.Length); if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { break; } #if !(DOTNET || PORTABLE) chars[i] = char.ToLower(chars[i], CultureInfo.InvariantCulture); #else chars[i] = char.ToLowerInvariant(chars[i]); #endif } return new string(chars); } public static bool IsHighSurrogate(char c) { #if !(PORTABLE40 || PORTABLE) return char.IsHighSurrogate(c); #else return (c >= 55296 && c <= 56319); #endif } public static bool IsLowSurrogate(char c) { #if !(PORTABLE40 || PORTABLE) return char.IsLowSurrogate(c); #else return (c >= 56320 && c <= 57343); #endif } public static bool StartsWith(this string source, char value) { return (source.Length > 0 && source[0] == value); } public static bool EndsWith(this string source, char value) { return (source.Length > 0 && source[source.Length - 1] == value); } } }
// 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.Contracts; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal class ProducerConsumerStream : Stream { private TaskCompletionSource<WriteBufferWrapper> _buffer; private TaskCompletionSource<int> _dataAvail; private WriteBufferWrapper _currentBuffer; private bool _disposed; public ProducerConsumerStream() { _buffer = new TaskCompletionSource<WriteBufferWrapper>(); _dataAvail = new TaskCompletionSource<int>(); _currentBuffer = WriteBufferWrapper.EmptyContainer; } public override bool CanRead { get { return !_disposed; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override void Flush() { _dataAvail.TrySetResult(0); } public override int Read(byte[] buffer, int offset, int count) { try { return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } catch (OperationCanceledException oce) { // If WriteAsync is canceled, an OperationCanceledException might get thrown on the Read path. // The stream is no longer usable so converting to an ObjectDisposedException. throw new ObjectDisposedException("ProducerConsumerStream", oce); } } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count <= 0 || count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count"); } cancellationToken.ThrowIfCancellationRequested(); if (_disposed) { return 0; } using (cancellationToken.Register(CancelAndDispose, this)) { _buffer.TrySetResult(new WriteBufferWrapper(buffer, offset, count)); int totalBytesRead = 0; while (count > 0) { int bytesRead = await _dataAvail.Task; _dataAvail = new TaskCompletionSource<int>(); if (bytesRead == 0) { break; } totalBytesRead += bytesRead; count -= bytesRead; } return totalBytesRead; } } public override void Write(byte[] buffer, int offset, int count) { try { WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } catch (OperationCanceledException oce) { // If ReadAsync is canceled, an OperationCanceledException might get thrown on the write path. // The stream is no longer usable so converting to an ObjectDisposedException. throw new ObjectDisposedException("ProducerConsumerStream", oce); } } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count"); } cancellationToken.ThrowIfCancellationRequested(); if (_disposed) { throw new ObjectDisposedException("ProducerConsumerStream"); } using (cancellationToken.Register(CancelAndDispose, this)) { while (count > 0) { if (_currentBuffer == WriteBufferWrapper.EmptyContainer) { _currentBuffer = await _buffer.Task; _buffer = new TaskCompletionSource<WriteBufferWrapper>(); } int bytesWritten = _currentBuffer.Write(buffer, offset, count); count -= bytesWritten; offset += bytesWritten; if (_currentBuffer.Count == 0) { _currentBuffer = WriteBufferWrapper.EmptyContainer; } _dataAvail.TrySetResult(bytesWritten); } } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; _dataAvail.TrySetResult(0); } base.Dispose(disposing); } private static void CancelAndDispose(object state) { var thisPtr = state as ProducerConsumerStream; if (thisPtr != null) { thisPtr._dataAvail.TrySetCanceled(); thisPtr._buffer.TrySetCanceled(); thisPtr.Dispose(); } } #pragma warning disable 659,661 // Hashcode not needed, Equals overriden for fast path comparison of EmptyContainer private struct WriteBufferWrapper : IEquatable<WriteBufferWrapper> #pragma warning restore 659,661 { public static readonly WriteBufferWrapper EmptyContainer = new WriteBufferWrapper(null, -1, -1, true); private byte[] _buffer; private int _offset; private int _count; private readonly bool _readOnly; public WriteBufferWrapper(byte[] buffer, int offset, int count) : this(buffer, offset, count, false) { } private WriteBufferWrapper(byte[] buffer, int offset, int count, bool isReadOnly) : this() { _buffer = buffer; _offset = offset; _count = count; _readOnly = isReadOnly; } public byte[] ByteBuffer { get { return _buffer; } } public int Offset { get { return _offset; } } public int Count { get { return _count; } } public override bool Equals(object obj) { if (obj is WriteBufferWrapper) return this.Equals((WriteBufferWrapper)obj); return false; } public bool Equals(WriteBufferWrapper other) { // Doing _readOnly comparison first as main use case is comparing against // BufferContainer.EmptyContainer which is the only readonly instance of BufferContainer. // If either instance is the read only, then this field is sufficient for comparison. if (_readOnly || other._readOnly) { return _readOnly == other._readOnly; } if (other._buffer == _buffer && other._offset == _offset) { return other._count == _count; } return false; } public static bool operator ==(WriteBufferWrapper a, WriteBufferWrapper b) { return a.Equals(b); } public static bool operator !=(WriteBufferWrapper a, WriteBufferWrapper b) { return !(a == b); } internal int Write(byte[] srcBuffer, int srcOffset, int srcCount) { if (_readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly)); } int bytesToCopy = Math.Min(_count, srcCount); Buffer.BlockCopy(srcBuffer, srcOffset, _buffer, _offset, bytesToCopy); _offset += bytesToCopy; _count -= bytesToCopy; return bytesToCopy; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WK.Orion.Applications.DPM.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Siren.IO; namespace Siren.Protocol.Binary { public class CompactBinaryReader : BaseBinaryReader { public CompactBinaryReader() { } public override void OnVersion() { } public override void OnStructBegin() { } public override void OnStructEnd() { } public override void OnListBegin(out SirenFieldType dataType,out int count) { dataType = (SirenFieldType)Stream.ReadUInt8(); count = (int)Stream.ReadVarUInt32(); } public override void OnListEnd() { } public override void OnDictionaryBegin(out SirenFieldType keyDataType, out SirenFieldType valueDataType,out int count) { keyDataType = (SirenFieldType)Stream.ReadUInt8(); valueDataType = (SirenFieldType)Stream.ReadUInt8(); count = (int)Stream.ReadVarUInt32(); } public override void OnDictionaryEnd() { } public override int OnPropertyBegin(string name, ushort id, SirenFieldType dataType, out ushort outId, out SirenFieldType outDataType) { if (!mIsPropertyWaiting) { ushort tempId; uint raw = Stream.ReadUInt8(); var type = (SirenFieldType)(raw & 0x1f); raw >>= 5; if (raw < 6) { tempId = (ushort)raw; } else if (raw == 6) { tempId = Stream.ReadUInt8(); } else { tempId = Stream.ReadUInt16(); } mCurrentPropertyId = tempId; mCurrentPropertyType = type; mIsPropertyWaiting = true; } outId = mCurrentPropertyId; outDataType = mCurrentPropertyType; if (id == mCurrentPropertyId) { mIsPropertyWaiting = false; return 0; } else if (id < mCurrentPropertyId) { return -1; } mIsPropertyWaiting = false; return 1; } public override void OnPropertyEnd() { } public override void OnPropertySkip(SirenFieldType dataType) { SkipPropertyHelper(dataType); } public override object OnValue(Type type) { if (type == typeof(bool)) { return Stream.ReadUInt8() == 1; } else if (type == typeof(char)) { return (char)Stream.ReadUInt8(); } else if (type == typeof(short)) { return IntegerHelper.DecodeZigzag(Stream.ReadVarUInt16()); } else if (type == typeof(int)) { return IntegerHelper.DecodeZigzag(Stream.ReadVarUInt32()); } else if (type == typeof(Int64)) { return IntegerHelper.DecodeZigzag(Stream.ReadVarUInt64()); } else if (type == typeof(byte)) { return Stream.ReadUInt8(); } else if (type == typeof(ushort)) { return Stream.ReadVarUInt16(); } else if (type == typeof(uint)) { return Stream.ReadVarUInt32(); } else if (type == typeof(UInt64)) { return Stream.ReadVarUInt64(); } else if (type == typeof(float)) { return Stream.ReadFloat(); } else if (type == typeof(double)) { return Stream.ReadDouble(); } else { if (type.IsEnum) { return Stream.ReadVarUInt32(); } else { Console.WriteLine("Invalid value type:{0}", type); } } return null; } public override string OnString() { uint length = Stream.ReadVarUInt32(); return Stream.ReadString((int)length); } public override byte[] OnMemoryData() { uint length = Stream.ReadVarUInt32(); return Stream.ReadBytes((int)length); } public override void OnError() { } void SkipProperty() { uint raw = Stream.ReadUInt8(); var type = (SirenFieldType)(raw & 0x1f); raw >>= 5; if (raw < 6) { } else if (raw == 6) { Stream.ReadUInt8(); } else { Stream.ReadUInt16(); } SkipPropertyHelper(type); } void SkipPropertyHelper(SirenFieldType type) { switch (type) { case SirenFieldType.Bool: Stream.SkipBytes(sizeof(byte)); break; case SirenFieldType.Int8: case SirenFieldType.UInt8: Stream.SkipBytes(sizeof(byte)); break; case SirenFieldType.Int16: case SirenFieldType.UInt16: Stream.ReadVarUInt16(); break; case SirenFieldType.Int32: case SirenFieldType.UInt32: Stream.ReadVarUInt32(); break; case SirenFieldType.Int64: case SirenFieldType.UInt64: Stream.ReadVarUInt64(); break; case SirenFieldType.Float: Stream.SkipBytes(sizeof(float)); break; case SirenFieldType.Double: Stream.SkipBytes(sizeof(double)); break; case SirenFieldType.String: { uint length= Stream.ReadVarUInt32(); Stream.SkipBytes((int)length); } break; case SirenFieldType.Blob: { uint length= Stream.ReadVarUInt32(); Stream.SkipBytes((int)length); } break; case SirenFieldType.Struct: SkipProperty(); break; case SirenFieldType.List: { SirenFieldType valueType=(SirenFieldType)Stream.ReadUInt8(); uint count= Stream.ReadVarUInt32(); for (int i = 0; i < count; i++) { SkipPropertyHelper(valueType); } } break; case SirenFieldType.Dictionary: { SirenFieldType keyType=(SirenFieldType)Stream.ReadUInt8(); SirenFieldType valueType=(SirenFieldType)Stream.ReadUInt8(); uint count= Stream.ReadVarUInt32(); for (int i = 0; i < count; i++) { SkipPropertyHelper(keyType); SkipPropertyHelper(valueType); } } break; } } } }
// // UserCommentIFDEntry.cs: // // Author: // Ruben Vermeersch (ruben@savanne.be) // Mike Gemuende (mike@gemuende.de) // // Copyright (C) 2009 Ruben Vermeersch // Copyright (C) 2009 Mike Gemuende // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; namespace TagLib.IFD.Entries { /// <summary> /// Contains an ASCII STRING value. /// </summary> public class UserCommentIFDEntry : IFDEntry { #region Constant Values /// <summary> /// Marker for an ASCII-encoded UserComment tag. /// </summary> public static readonly ByteVector COMMENT_ASCII_CODE = new byte[] {0x41, 0x53, 0x43, 0x49, 0x49, 0x00, 0x00, 0x00}; /// <summary> /// Marker for a JIS-encoded UserComment tag. /// </summary> public static readonly ByteVector COMMENT_JIS_CODE = new byte[] {0x4A, 0x49, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00}; /// <summary> /// Marker for a UNICODE-encoded UserComment tag. /// </summary> public static readonly ByteVector COMMENT_UNICODE_CODE = new byte[] {0x55, 0x4E, 0x49, 0x43, 0x4F, 0x44, 0x45, 0x00}; /// <summary> /// Corrupt marker that seems to be resembling unicode. /// </summary> public static readonly ByteVector COMMENT_BAD_UNICODE_CODE = new byte[] {0x55, 0x6E, 0x69, 0x63, 0x6F, 0x64, 0x65, 0x00}; /// <summary> /// Marker for a UserComment tag with undefined encoding. /// </summary> public static readonly ByteVector COMMENT_UNDEFINED_CODE = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; #endregion #region Properties /// <value> /// The ID of the tag, the current instance belongs to /// </value> public ushort Tag { get; private set; } /// <value> /// The value which is stored by the current instance /// </value> public string Value { get; private set; } #endregion #region Constructors /// <summary> /// Construcor. /// </summary> /// <param name="tag"> /// A <see cref="System.UInt16"/> with the tag ID of the entry this instance /// represents /// </param> /// <param name="value"> /// A <see cref="string"/> to be stored /// </param> public UserCommentIFDEntry (ushort tag, string value) { Tag = tag; Value = value; } /// <summary> /// Construcor. /// </summary> /// <param name="tag"> /// A <see cref="System.UInt16"/> with the tag ID of the entry this instance /// represents /// </param> /// <param name="data"> /// A <see cref="ByteVector"/> to be stored /// </param> /// <param name="file"> /// The file that's currently being parsed, used for reporting corruptions. /// </param> public UserCommentIFDEntry (ushort tag, ByteVector data, TagLib.File file) { Tag = tag; if (data.StartsWith (COMMENT_ASCII_CODE)) { Value = TrimNull (data.ToString (StringType.Latin1, COMMENT_ASCII_CODE.Count, data.Count - COMMENT_ASCII_CODE.Count)); return; } if (data.StartsWith (COMMENT_UNICODE_CODE)) { Value = TrimNull (data.ToString (StringType.UTF8, COMMENT_UNICODE_CODE.Count, data.Count - COMMENT_UNICODE_CODE.Count)); return; } var trimmed = data.ToString ().Trim (); if (trimmed.Length == 0 || trimmed == "\0") { Value = String.Empty; return; } // Some programs like e.g. CanonZoomBrowser inserts just the first 0x00-byte // followed by 7-bytes of trash. if (data.StartsWith ((byte) 0x00) && data.Count >= 8) { // And CanonZoomBrowser fills some trailing bytes of the comment field // with '\0'. So we return only the characters before the first '\0'. int term = data.Find ("\0", 8); if (term != -1) { Value = data.ToString (StringType.Latin1, 8, term - 8); } else { Value = data.ToString (StringType.Latin1, 8, data.Count - 8); } return; } if (data.Data.Length == 0) { Value = String.Empty; return; } // Try to parse anyway int offset = 0; int length = data.Count - offset; // Corruption that starts with a Unicode header and a count byte. if (data.StartsWith (COMMENT_BAD_UNICODE_CODE)) { offset = COMMENT_BAD_UNICODE_CODE.Count; length = data.Count - offset; } file.MarkAsCorrupt ("UserComment with other encoding than Latin1 or Unicode"); Value = TrimNull (data.ToString (StringType.UTF8, offset, length)); } private string TrimNull (string value) { int term = value.IndexOf ('\0'); if (term > -1) value = value.Substring (0, term); return value; } #endregion #region Public Methods /// <summary> /// Renders the current instance to a <see cref="ByteVector"/> /// </summary> /// <param name="is_bigendian"> /// A <see cref="System.Boolean"/> indicating the endianess for rendering. /// </param> /// <param name="offset"> /// A <see cref="System.UInt32"/> with the offset, the data is stored. /// </param> /// <param name="type"> /// A <see cref="System.UInt16"/> the ID of the type, which is rendered /// </param> /// <param name="count"> /// A <see cref="System.UInt32"/> with the count of the values which are /// rendered. /// </param> /// <returns> /// A <see cref="ByteVector"/> with the rendered data. /// </returns> public ByteVector Render (bool is_bigendian, uint offset, out ushort type, out uint count) { type = (ushort) IFDEntryType.Undefined; ByteVector data = new ByteVector (); data.Add (COMMENT_UNICODE_CODE); data.Add (ByteVector.FromString (Value, StringType.UTF8)); count = (uint) data.Count; return data; } #endregion } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. using Burrows.Configuration.Configuration; using Burrows.Configuration.SubscriptionConnectors; using Burrows.Endpoints; namespace Burrows.Pipeline { using System; using System.IO; using Configuration; using Context; using Burrows.Configuration; using Sinks; /// <summary> /// Extensions for the message pipeline. /// </summary> public static class MessagePipelineExtensions { /// <summary> /// Dispatch a message through the pipeline /// </summary> /// <param name="pipeline">The pipeline instance</param> /// <param name="message">The message to dispatch</param> public static bool Dispatch<T>(this IInboundMessagePipeline pipeline, T message) where T : class { return pipeline.Dispatch(message, x => true); } public static bool Dispatch<T>(this IOutboundMessagePipeline pipeline, T message) where T : class { return pipeline.Dispatch(message, x => true); } /// <summary> /// Dispatch a message through the pipeline. If the message will be consumed, the accept function /// is called to allow the endpoint to acknowledge the message reception if applicable /// </summary> /// <param name="pipeline">The pipeline instance</param> /// <param name="message">The message to dispatch</param> /// <param name="acknowledge">The function to call if the message will be consumed by the pipeline</param> /// <returns>whether the message was consumed</returns> public static bool Dispatch<T>(this IInboundMessagePipeline pipeline, T message, Func<T, bool> acknowledge) where T : class { bool consumed = false; using (var bodyStream = new MemoryStream()) { ReceiveContext receiveContext = ReceiveContext.FromBodyStream(bodyStream); pipeline.Configure(x => receiveContext.SetBus(x.Bus)); var context = new ConsumeContext<T>(receiveContext, message); using (context.CreateScope()) { foreach (var consumer in pipeline.Enumerate(context)) { if (!acknowledge(message)) return false; acknowledge = x => true; consumed = true; consumer(context); } } } return consumed; } /// <summary> /// <see cref="Dispatch{T}(Burrows.Pipeline.IInboundMessagePipeline,T)"/>: this one is for the outbound pipeline. /// </summary> public static bool Dispatch<T>(this IOutboundMessagePipeline pipeline, T message, Func<T, bool> acknowledge) where T : class { bool consumed = false; var context = new SendContext<T>(message); foreach (var consumer in pipeline.Enumerate(context)) { if (!acknowledge(message)) return false; acknowledge = x => true; consumed = true; consumer(context); } return consumed; } /// <summary> /// Subscribe a component type to the pipeline that is resolved from the container for each message /// </summary> /// <typeparam name="TComponent"></typeparam> /// <param name="pipeline">The pipeline to configure</param> /// <returns></returns> public static UnsubscribeAction ConnectConsumer<TComponent>(this IInboundMessagePipeline pipeline) where TComponent : class, new() { return pipeline.Configure(x => { var consumerFactory = new DelegateConsumerFactory<TComponent>(() => new TComponent()); IConsumerConnector connector = ConsumerConnectorCache.GetConsumerConnector<TComponent>(); return connector.Connect(x, consumerFactory); }); } /// <summary> /// Subscribe a component type to the pipeline that is resolved from the container for each message /// </summary> /// <typeparam name="TConsumer"></typeparam> /// <param name="pipeline">The pipeline to configure</param> /// <param name="consumerFactory"></param> /// <returns></returns> public static UnsubscribeAction ConnectConsumer<TConsumer>(this IInboundMessagePipeline pipeline, Func<TConsumer> consumerFactory) where TConsumer : class { return pipeline.Configure(x => { var factory = new DelegateConsumerFactory<TConsumer>(consumerFactory); IConsumerConnector connector = ConsumerConnectorCache.GetConsumerConnector<TConsumer>(); return connector.Connect(x, factory); }); } /// <summary> /// Subscribe a component to the pipeline that handles every message /// </summary> /// <typeparam name="TComponent"></typeparam> /// <param name="pipeline">The pipeline to configure</param> /// <param name="instance">The instance that will handle the messages</param> /// <returns></returns> public static UnsubscribeAction ConnectInstance<TComponent>(this IInboundMessagePipeline pipeline, TComponent instance) where TComponent : class { return pipeline.Configure(x => { IInstanceConnector connector = InstanceConnectorCache.GetInstanceConnector<TComponent>(); return connector.Connect(x, instance); }); } public static UnsubscribeAction ConnectHandler<TMessage>(this IInboundMessagePipeline pipeline, Action<TMessage> handler, Predicate<TMessage> condition) where TMessage : class { return pipeline.Configure(x => { var connector = new HandlerSubscriptionConnector<TMessage>(); return connector.Connect(x, HandlerSelector.ForSelectiveHandler(condition, handler)); }); } /// <summary> /// Connects an endpoint to the outbound pipeline by message type. /// </summary> /// <typeparam name="TMessage">The type of the message to route</typeparam> /// <param name="pipeline">The outbound pipeline</param> /// <param name="endpoint">The endpoint to route to</param> /// <returns></returns> public static UnsubscribeAction ConnectEndpoint<TMessage>(this IOutboundMessagePipeline pipeline, IEndpoint endpoint) where TMessage : class { var sink = new EndpointMessageSink<TMessage>(endpoint); return pipeline.ConnectToRouter(sink); } public static UnsubscribeAction ConnectEndpoint<TMessage, TKey>(this IOutboundMessagePipeline pipeline, TKey correlationId, IEndpoint endpoint) where TMessage : class, ICorrelatedBy<TKey> { var correlatedConfigurator = new OutboundCorrelatedMessageRouterConfigurator(pipeline); CorrelatedMessageRouter<IBusPublishContext<TMessage>, TMessage, TKey> router = correlatedConfigurator.FindOrCreate<TMessage, TKey>(); UnsubscribeAction result = router.Connect(correlationId, new EndpointMessageSink<TMessage>(endpoint)); return result; } } }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERLevel; namespace ParentLoad.Business.ERLevel { /// <summary> /// A03_Continent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="A03_Continent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A02_Continent"/> collection. /// </remarks> [Serializable] public partial class A03_Continent_ReChild : BusinessBase<A03_Continent_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "Continent Child Name"); /// <summary> /// Gets or sets the Continent Child Name. /// </summary> /// <value>The Continent Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A03_Continent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="A03_Continent_ReChild"/> object.</returns> internal static A03_Continent_ReChild NewA03_Continent_ReChild() { return DataPortal.CreateChild<A03_Continent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="A03_Continent_ReChild"/> object from the given A03_Continent_ReChildDto. /// </summary> /// <param name="data">The <see cref="A03_Continent_ReChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="A03_Continent_ReChild"/> object.</returns> internal static A03_Continent_ReChild GetA03_Continent_ReChild(A03_Continent_ReChildDto data) { A03_Continent_ReChild obj = new A03_Continent_ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A03_Continent_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public A03_Continent_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A03_Continent_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A03_Continent_ReChild"/> object from the given <see cref="A03_Continent_ReChildDto"/>. /// </summary> /// <param name="data">The A03_Continent_ReChildDto to use.</param> private void Fetch(A03_Continent_ReChildDto data) { // Value properties LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A03_Continent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A02_Continent parent) { var dto = new A03_Continent_ReChildDto(); dto.Parent_Continent_ID = parent.Continent_ID; dto.Continent_Child_Name = Continent_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IA03_Continent_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="A03_Continent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A02_Continent parent) { if (!IsDirty) return; var dto = new A03_Continent_ReChildDto(); dto.Parent_Continent_ID = parent.Continent_ID; dto.Continent_Child_Name = Continent_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IA03_Continent_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="A03_Continent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A02_Continent parent) { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IA03_Continent_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Continent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using ClosedXML.Excel; using ClosedXML.Excel.Drawings; using ClosedXML_Tests.Utils; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ClosedXML_Tests.Excel { // Tests in this fixture test only the successful loading of existing Excel files, // i.e. we test that ClosedXML doesn't choke on a given input file // These tests DO NOT test that ClosedXML successfully recognises all the Excel parts or that it can successfully save those parts again. [TestFixture] public class LoadingTests { [Test] public void CanSuccessfullyLoadFiles() { var files = new List<string>() { @"Misc\TableWithCustomTheme.xlsx", @"Misc\EmptyTable.xlsx", @"Misc\LoadPivotTables.xlsx", @"Misc\LoadFileWithCustomSheetViews.xlsx", @"Misc\LoadSheetsWithCommas.xlsx", @"Misc\ExcelProducedWorkbookWithImages.xlsx", @"Misc\InvalidPrintTitles.xlsx", @"Misc\ExcelProducedWorkbookWithImages.xlsx", @"Misc\EmptyCellValue.xlsx", @"Misc\AllShapes.xlsx", @"Misc\TableHeadersWithLineBreaks.xlsx", @"Misc\TableWithNameNull.xlsx", @"Misc\DuplicateImageNames.xlsx", @"Misc\InvalidPrintArea.xlsx", @"Misc\Date1904System.xlsx", @"Misc\LoadImageWithoutTransform2D.xlsx" }; foreach (var file in files) { TestHelper.LoadFile(file); } } [Test] public void CanSuccessfullyLoadLOFiles() { // TODO: unpark all files var parkedForLater = new[] { "Misc.LO.xlsx.formats.xlsx", "Misc.LO.xlsx.pivot_table.shared-group-field.xlsx", "Misc.LO.xlsx.pivot_table.shared-nested-dategroup.xlsx", "Misc.LO.xlsx.pivottable_bool_field_filter.xlsx", "Misc.LO.xlsx.pivottable_date_field_filter.xlsx", "Misc.LO.xlsx.pivottable_double_field_filter.xlsx", "Misc.LO.xlsx.pivottable_duplicated_member_filter.xlsx", "Misc.LO.xlsx.pivottable_rowcolpage_field_filter.xlsx", "Misc.LO.xlsx.pivottable_string_field_filter.xlsx", "Misc.LO.xlsx.pivottable_tabular_mode.xlsx", "Misc.LO.xlsx.pivot_table_first_header_row.xlsx", "Misc.LO.xlsx.tdf100709.xlsx", "Misc.LO.xlsx.tdf89139_pivot_table.xlsx", "Misc.LO.xlsx.universal-content-strict.xlsx", "Misc.LO.xlsx.universal-content.xlsx", "Misc.LO.xlsx.xf_default_values.xlsx" }; var files = TestHelper.ListResourceFiles(s => s.Contains(".LO.") && !parkedForLater.Any(i => s.Contains(i))).ToArray(); foreach (var file in files) { TestHelper.LoadFile(file); } } [Test] public void CanLoadAndManipulateFileWithEmptyTable() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\EmptyTable.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); var table = ws.Tables.First(); table.DataRange.InsertRowsBelow(5); } } [Test] public void CanLoadDate1904SystemCorrectly() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\Date1904System.xlsx"))) using (var ms = new MemoryStream()) { using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); var c = ws.Cell("A2"); Assert.AreEqual(XLDataType.DateTime, c.DataType); Assert.AreEqual(new DateTime(2017, 10, 27, 21, 0, 0), c.GetDateTime()); wb.SaveAs(ms); } ms.Seek(0, SeekOrigin.Begin); using (var wb = new XLWorkbook(ms)) { var ws = wb.Worksheets.First(); var c = ws.Cell("A2"); Assert.AreEqual(XLDataType.DateTime, c.DataType); Assert.AreEqual(new DateTime(2017, 10, 27, 21, 0, 0), c.GetDateTime()); wb.SaveAs(ms); } } } [Test] public void CanLoadAndSaveFileWithMismatchingSheetIdAndRelId() { // This file's workbook.xml contains: // <x:sheet name="Data" sheetId="13" r:id="rId1" /> // and the mismatch between the sheetId and r:id can create problems. using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\FileWithMismatchSheetIdAndRelId.xlsx"))) using (var wb = new XLWorkbook(stream)) { using (var ms = new MemoryStream()) { wb.SaveAs(ms, true); } } } [Test] public void CanLoadBasicPivotTable() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LoadPivotTables.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("PivotTable1"); var pt = ws.PivotTable("PivotTable1"); Assert.AreEqual("PivotTable1", pt.Name); Assert.AreEqual(1, pt.RowLabels.Count()); Assert.AreEqual("Name", pt.RowLabels.Single().SourceName); Assert.AreEqual(1, pt.ColumnLabels.Count()); Assert.AreEqual("Month", pt.ColumnLabels.Single().SourceName); var pv = pt.Values.Single(); Assert.AreEqual("Sum of NumberOfOrders", pv.CustomName); Assert.AreEqual("NumberOfOrders", pv.SourceName); } } [Test] public void CanLoadOrderedPivotTable() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LoadPivotTables.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("OrderedPivotTable"); var pt = ws.PivotTable("OrderedPivotTable"); Assert.AreEqual(XLPivotSortType.Ascending, pt.RowLabels.Single().SortType); Assert.AreEqual(XLPivotSortType.Descending, pt.ColumnLabels.Single().SortType); } } [Test] public void CanLoadPivotTableSubtotals() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LoadPivotTables.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("PivotTableSubtotals"); var pt = ws.PivotTable("PivotTableSubtotals"); var subtotals = pt.RowLabels.Get("Group").Subtotals.ToArray(); Assert.AreEqual(3, subtotals.Length); Assert.AreEqual(XLSubtotalFunction.Average, subtotals[0]); Assert.AreEqual(XLSubtotalFunction.Count, subtotals[1]); Assert.AreEqual(XLSubtotalFunction.Sum, subtotals[2]); } } /// <summary> /// For non-English locales, the default style ("Normal" in English) can be /// another piece of text (e.g. ??????? in Russian). /// This test ensures that the default style is correctly detected and /// no style conflicts occur on save. /// </summary> [Test] public void CanSaveFileWithDefaultStyleNameNotInEnglish() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\FileWithDefaultStyleNameNotInEnglish.xlsx"))) using (var wb = new XLWorkbook(stream)) { using (var ms = new MemoryStream()) { wb.SaveAs(ms, true); } } } /// <summary> /// As per https://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.cellvalues(v=office.15).aspx /// the 'Date' DataType is available only in files saved with Microsoft Office /// In other files, the data type will be saved as numeric /// ClosedXML then deduces the data type by inspecting the number format string /// </summary> [Test] public void CanLoadLibreOfficeFileWithDates() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LibreOfficeFileWithDates.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); foreach (var cell in ws.CellsUsed()) { Assert.AreEqual(XLDataType.DateTime, cell.DataType); } } } [Test] public void CanLoadFileWithImagesWithCorrectAnchorTypes() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(2, ws.Pictures.Count); Assert.AreEqual(XLPicturePlacement.FreeFloating, ws.Pictures.First().Placement); Assert.AreEqual(XLPicturePlacement.Move, ws.Pictures.Skip(1).First().Placement); var ws2 = wb.Worksheets.Skip(1).First(); Assert.AreEqual(1, ws2.Pictures.Count); Assert.AreEqual(XLPicturePlacement.MoveAndSize, ws2.Pictures.First().Placement); } } [Test] public void CanLoadFileWithImagesWithCorrectImageType() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageFormats.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(1, ws.Pictures.Count); Assert.AreEqual(XLPictureFormat.Jpeg, ws.Pictures.First().Format); var ws2 = wb.Worksheets.Skip(1).First(); Assert.AreEqual(1, ws2.Pictures.Count); Assert.AreEqual(XLPictureFormat.Png, ws2.Pictures.First().Format); } } [Test] public void CanLoadAndDeduceAnchorsFromExcelGeneratedFile() { // This file was produced by Excel. It contains 3 images, but the latter 2 were copied from the first. // There is actually only 1 embedded image if you inspect the file's internals. // Additionally, Excel saves all image anchors as TwoCellAnchor, but uses the EditAs attribute to distinguish the types using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\ExcelProducedWorkbookWithImages.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(3, ws.Pictures.Count); Assert.AreEqual(XLPicturePlacement.MoveAndSize, ws.Picture("Picture 1").Placement); Assert.AreEqual(XLPicturePlacement.Move, ws.Picture("Picture 2").Placement); Assert.AreEqual(XLPicturePlacement.FreeFloating, ws.Picture("Picture 3").Placement); using (var ms = new MemoryStream()) wb.SaveAs(ms, true); } } [Test] public void CanLoadFromTemplate() { using (var tf1 = new TemporaryFile()) using (var tf2 = new TemporaryFile()) { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\AllShapes.xlsx"))) using (var wb = new XLWorkbook(stream)) { // Save as temporary file wb.SaveAs(tf1.Path); } var workbook = XLWorkbook.OpenFromTemplate(tf1.Path); Assert.True(workbook.Worksheets.Any()); Assert.Throws<InvalidOperationException>(() => workbook.Save()); workbook.SaveAs(tf2.Path); } } /// <summary> /// Excel escapes symbol ' in worksheet title so we have to process this correctly. /// </summary> [Test] public void CanOpenWorksheetWithEscapedApostrophe() { string title = ""; TestDelegate openWorkbook = () => { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\EscapedApostrophe.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); title = ws.Name; } }; Assert.DoesNotThrow(openWorkbook); Assert.AreEqual("L'E", title); } [Test] public void CanRoundTripSheetProtectionForObjects() { using (var book = new XLWorkbook()) { var sheet = book.AddWorksheet("TestSheet"); sheet.Protect() .SetObjects(true) .SetScenarios(true); using (var xlStream = new MemoryStream()) { book.SaveAs(xlStream); using (var persistedBook = new XLWorkbook(xlStream)) { var persistedSheet = persistedBook.Worksheets.Worksheet(1); Assert.AreEqual(sheet.Protection.Objects, persistedSheet.Protection.Objects); } } } } [Test] [TestCase("A1*10", "1230", 1230)] [TestCase("A1/10", "12.3", 12.3)] [TestCase("A1&\" cells\"", "123 cells", "123 cells")] [TestCase("A1&\"000\"", "123000", "123000")] [TestCase("ISNUMBER(A1)", "True", true)] [TestCase("ISBLANK(A1)", "False", false)] [TestCase("DATE(2018,1,28)", "43128", null)] public void LoadFormulaCachedValue(string formula, object expectedValueCached, object expectedCachedValue) { using (var ms = new MemoryStream()) { using (XLWorkbook book1 = new XLWorkbook()) { var sheet = book1.AddWorksheet("sheet1"); sheet.Cell("A1").Value = 123; sheet.Cell("A2").FormulaA1 = formula; var options = new SaveOptions { EvaluateFormulasBeforeSaving = true }; book1.SaveAs(ms, options); } ms.Position = 0; using (XLWorkbook book2 = new XLWorkbook(ms)) { var ws = book2.Worksheet(1); Assert.IsTrue(ws.Cell("A2").NeedsRecalculation); Assert.AreEqual(expectedValueCached, ws.Cell("A2").ValueCached); if (expectedCachedValue != null) Assert.AreEqual(expectedCachedValue, ws.Cell("A2").CachedValue); } } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sqs-2012-11-05.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SQS.Model { /// <summary> /// Container for the parameters to the ReceiveMessage operation. /// Retrieves one or more messages, with a maximum limit of 10 messages, from the /// specified queue. Long poll support is enabled by using the <code>WaitTimeSeconds</code> /// parameter. For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html">Amazon /// SQS Long Poll</a> in the <i>Amazon SQS Developer Guide</i>. /// /// /// <para> /// Short poll is the default behavior where a weighted random set of machines is /// sampled on a <code>ReceiveMessage</code> call. This means only the messages /// on the sampled machines are returned. If the number of messages in the queue is small /// (less than 1000), it is likely you will get fewer messages than you requested /// per <code>ReceiveMessage</code> call. If the number of messages in the queue /// is extremely small, you might not receive any messages in a particular <code>ReceiveMessage</code> /// response; in which case you should repeat the request. /// </para> /// /// <para> /// For each message returned, the response includes the following: /// </para> /// <ul> <li> /// <para> /// Message body /// </para> /// </li> <li> /// <para> /// MD5 digest of the message body. For information about MD5, go to /// <a href="http://www.faqs.org/rfcs/rfc1321.html">http://www.faqs.org/rfcs/rfc1321.html</a>. /// /// </para> /// </li> <li> /// <para> /// Message ID you received when you sent the message to the queue. /// </para> /// </li> <li> /// <para> /// Receipt handle. /// </para> /// </li> <li> /// <para> /// Message attributes. /// </para> /// </li> <li> /// <para> /// MD5 digest of the message attributes. /// </para> /// </li> </ul> /// <para> /// The receipt handle is the identifier you must provide when deleting the message. /// For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html">Queue /// and Message Identifiers</a> in the <i>Amazon SQS Developer Guide</i>. /// </para> /// /// <para> /// You can provide the <code>VisibilityTimeout</code> parameter in your request, /// which will be applied to the messages that Amazon SQS returns in the response. /// If you do not include the parameter, the overall visibility timeout for the queue /// is used for the returned messages. For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html">Visibility /// Timeout</a> in the <i>Amazon SQS Developer Guide</i>. /// </para> /// <note> /// <para> /// Going forward, new attributes might be added. If you are writing code that /// calls this action, we recommend that you structure your code so that it can /// handle new attributes gracefully. /// </para> /// </note> /// </summary> public partial class ReceiveMessageRequest : AmazonSQSRequest { private List<string> _attributeNames = new List<string>(); private int? _maxNumberOfMessages; private List<string> _messageAttributeNames = new List<string>(); private string _queueUrl; private int? _visibilityTimeout; private int? _waitTimeSeconds; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public ReceiveMessageRequest() { } /// <summary> /// Instantiates ReceiveMessageRequest with the parameterized properties /// </summary> /// <param name="queueUrl">The URL of the Amazon SQS queue to take action on.</param> public ReceiveMessageRequest(string queueUrl) { _queueUrl = queueUrl; } /// <summary> /// Gets and sets the property AttributeNames. /// <para> /// A list of attributes that need to be returned along with each message. /// </para> /// /// <para> /// The following lists the names and descriptions of the attributes that can be /// returned: /// </para> /// <ul> <li><code>All</code> - returns all values.</li> <li><code>ApproximateFirstReceiveTimestamp</code> /// - returns the time when the message was first received (epoch time in milliseconds).</li> /// <li><code>ApproximateReceiveCount</code> - returns the number of times /// a message has been received but not deleted.</li> <li><code>SenderId</code> - /// returns the AWS account number (or the IP address, if anonymous access is allowed) /// of the sender.</li> <li><code>SentTimestamp</code> - returns the time /// when the message was sent (epoch time in milliseconds).</li> </ul> /// </summary> public List<string> AttributeNames { get { return this._attributeNames; } set { this._attributeNames = value; } } // Check to see if AttributeNames property is set internal bool IsSetAttributeNames() { return this._attributeNames != null && this._attributeNames.Count > 0; } /// <summary> /// Gets and sets the property MaxNumberOfMessages. /// <para> /// The maximum number of messages to return. Amazon SQS never returns more messages /// than this value but may return fewer. Values can be from 1 to 10. Default is 1. /// </para> /// /// <para> /// All of the messages are not necessarily returned. /// </para> /// </summary> public int MaxNumberOfMessages { get { return this._maxNumberOfMessages.GetValueOrDefault(); } set { this._maxNumberOfMessages = value; } } // Check to see if MaxNumberOfMessages property is set internal bool IsSetMaxNumberOfMessages() { return this._maxNumberOfMessages.HasValue; } /// <summary> /// Gets and sets the property MessageAttributeNames. /// <para> /// The message attribute Name can contain the following characters: A-Z, a-z, 0-9, underscore(_), /// hyphen(-), and period (.). The message attribute name must not start or end /// with a period, and it should not have successive periods. The message attribute name /// is case sensitive and must be unique among all attribute names for the message. /// The message attribute name can be up to 256 characters long. Attribute names cannot /// start with "AWS." or "Amazon." because these prefixes are reserved for use by Amazon /// Web Services. /// </para> /// </summary> public List<string> MessageAttributeNames { get { return this._messageAttributeNames; } set { this._messageAttributeNames = value; } } // Check to see if MessageAttributeNames property is set internal bool IsSetMessageAttributeNames() { return this._messageAttributeNames != null && this._messageAttributeNames.Count > 0; } /// <summary> /// Gets and sets the property QueueUrl. /// <para> /// The URL of the Amazon SQS queue to take action on. /// </para> /// </summary> public string QueueUrl { get { return this._queueUrl; } set { this._queueUrl = value; } } // Check to see if QueueUrl property is set internal bool IsSetQueueUrl() { return this._queueUrl != null; } /// <summary> /// Gets and sets the property VisibilityTimeout. /// <para> /// The duration (in seconds) that the received messages are hidden from subsequent /// retrieve requests after being retrieved by a <code>ReceiveMessage</code> request. /// </para> /// </summary> public int VisibilityTimeout { get { return this._visibilityTimeout.GetValueOrDefault(); } set { this._visibilityTimeout = value; } } // Check to see if VisibilityTimeout property is set internal bool IsSetVisibilityTimeout() { return this._visibilityTimeout.HasValue; } /// <summary> /// Gets and sets the property WaitTimeSeconds. /// <para> /// The duration (in seconds) for which the call will wait for a message to arrive /// in the queue before returning. If a message is available, the call will return /// sooner than WaitTimeSeconds. /// </para> /// </summary> public int WaitTimeSeconds { get { return this._waitTimeSeconds.GetValueOrDefault(); } set { this._waitTimeSeconds = value; } } // Check to see if WaitTimeSeconds property is set internal bool IsSetWaitTimeSeconds() { return this._waitTimeSeconds.HasValue; } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace DocuSign.eSign.Model { /// <summary> /// /// </summary> [DataContract] public class Text : IEquatable<Text> { /// <summary> /// Height of the tab in pixels. /// </summary> /// <value>Height of the tab in pixels.</value> [DataMember(Name="height", EmitDefaultValue=false)] public int? Height { get; set; } /// <summary> /// When set to **true**, sets this as a payment tab. Can only be used with Text, Number, Formula, or List tabs. The value of the tab must be a number. /// </summary> /// <value>When set to **true**, sets this as a payment tab. Can only be used with Text, Number, Formula, or List tabs. The value of the tab must be a number.</value> [DataMember(Name="isPaymentAmount", EmitDefaultValue=false)] public string IsPaymentAmount { get; set; } /// <summary> /// The Formula string contains the TabLabel for the reference tabs used in the formula and calculation operators. Each TabLabel must be contained in brackets. \nMaximum Length: 2000 characters.\n\n*Example*: Three tabs (TabLabels: Line1, Line2, and Tax) need to be added together. The formula string would be: \n\n[Line1]+[Line2]+[Tax] /// </summary> /// <value>The Formula string contains the TabLabel for the reference tabs used in the formula and calculation operators. Each TabLabel must be contained in brackets. \nMaximum Length: 2000 characters.\n\n*Example*: Three tabs (TabLabels: Line1, Line2, and Tax) need to be added together. The formula string would be: \n\n[Line1]+[Line2]+[Tax]</value> [DataMember(Name="formula", EmitDefaultValue=false)] public string Formula { get; set; } /// <summary> /// A regular expressionn used to validate input for the tab. /// </summary> /// <value>A regular expressionn used to validate input for the tab.</value> [DataMember(Name="validationPattern", EmitDefaultValue=false)] public string ValidationPattern { get; set; } /// <summary> /// The message displayed if the custom tab fails input validation (either custom of embedded). /// </summary> /// <value>The message displayed if the custom tab fails input validation (either custom of embedded).</value> [DataMember(Name="validationMessage", EmitDefaultValue=false)] public string ValidationMessage { get; set; } /// <summary> /// When set to **true**, this custom tab is shared. /// </summary> /// <value>When set to **true**, this custom tab is shared.</value> [DataMember(Name="shared", EmitDefaultValue=false)] public string Shared { get; set; } /// <summary> /// Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field. /// </summary> /// <value>Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.</value> [DataMember(Name="requireInitialOnSharedChange", EmitDefaultValue=false)] public string RequireInitialOnSharedChange { get; set; } /// <summary> /// When set to **true**, the sender must populate the tab before an envelope can be sent using the template. \n\nThis value tab can only be changed by modifying (PUT) the template. \n\nTabs with a `senderRequired` value of true cannot be deleted from an envelope. /// </summary> /// <value>When set to **true**, the sender must populate the tab before an envelope can be sent using the template. \n\nThis value tab can only be changed by modifying (PUT) the template. \n\nTabs with a `senderRequired` value of true cannot be deleted from an envelope.</value> [DataMember(Name="senderRequired", EmitDefaultValue=false)] public string SenderRequired { get; set; } /// <summary> /// When set to **true** and shared is true, information must be entered in this field to complete the envelope. /// </summary> /// <value>When set to **true** and shared is true, information must be entered in this field to complete the envelope.</value> [DataMember(Name="requireAll", EmitDefaultValue=false)] public string RequireAll { get; set; } /// <summary> /// Specifies the tool tip text for the tab. /// </summary> /// <value>Specifies the tool tip text for the tab.</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Specifies the value of the tab. /// </summary> /// <value>Specifies the value of the tab.</value> [DataMember(Name="value", EmitDefaultValue=false)] public string Value { get; set; } /// <summary> /// The initial value of the tab when it was sent to the recipient. /// </summary> /// <value>The initial value of the tab when it was sent to the recipient.</value> [DataMember(Name="originalValue", EmitDefaultValue=false)] public string OriginalValue { get; set; } /// <summary> /// Width of the tab in pixels. /// </summary> /// <value>Width of the tab in pixels.</value> [DataMember(Name="width", EmitDefaultValue=false)] public int? Width { get; set; } /// <summary> /// When set to **true**, the signer is required to fill out this tab /// </summary> /// <value>When set to **true**, the signer is required to fill out this tab</value> [DataMember(Name="required", EmitDefaultValue=false)] public string Required { get; set; } /// <summary> /// When set to **true**, the signer cannot change the data of the custom tab. /// </summary> /// <value>When set to **true**, the signer cannot change the data of the custom tab.</value> [DataMember(Name="locked", EmitDefaultValue=false)] public string Locked { get; set; } /// <summary> /// When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender.\n\nWhen an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console.\n\nThis setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes. /// </summary> /// <value>When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender.\n\nWhen an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console.\n\nThis setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes.</value> [DataMember(Name="concealValueOnDocument", EmitDefaultValue=false)] public string ConcealValueOnDocument { get; set; } /// <summary> /// When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes. /// </summary> /// <value>When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes.</value> [DataMember(Name="disableAutoSize", EmitDefaultValue=false)] public string DisableAutoSize { get; set; } /// <summary> /// An optional value that describes the maximum length of the property when the property is a string. /// </summary> /// <value>An optional value that describes the maximum length of the property when the property is a string.</value> [DataMember(Name="maxLength", EmitDefaultValue=false)] public int? MaxLength { get; set; } /// <summary> /// The label string associated with the tab. /// </summary> /// <value>The label string associated with the tab.</value> [DataMember(Name="tabLabel", EmitDefaultValue=false)] public string TabLabel { get; set; } /// <summary> /// The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default. /// </summary> /// <value>The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.</value> [DataMember(Name="font", EmitDefaultValue=false)] public string Font { get; set; } /// <summary> /// When set to **true**, the information in the tab is bold. /// </summary> /// <value>When set to **true**, the information in the tab is bold.</value> [DataMember(Name="bold", EmitDefaultValue=false)] public string Bold { get; set; } /// <summary> /// When set to **true**, the information in the tab is italic. /// </summary> /// <value>When set to **true**, the information in the tab is italic.</value> [DataMember(Name="italic", EmitDefaultValue=false)] public string Italic { get; set; } /// <summary> /// When set to **true**, the information in the tab is underlined. /// </summary> /// <value>When set to **true**, the information in the tab is underlined.</value> [DataMember(Name="underline", EmitDefaultValue=false)] public string Underline { get; set; } /// <summary> /// The font color used for the information in the tab.\n\nPossible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White. /// </summary> /// <value>The font color used for the information in the tab.\n\nPossible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.</value> [DataMember(Name="fontColor", EmitDefaultValue=false)] public string FontColor { get; set; } /// <summary> /// The font size used for the information in the tab.\n\nPossible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72. /// </summary> /// <value>The font size used for the information in the tab.\n\nPossible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.</value> [DataMember(Name="fontSize", EmitDefaultValue=false)] public string FontSize { get; set; } /// <summary> /// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute. /// </summary> /// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value> [DataMember(Name="documentId", EmitDefaultValue=false)] public string DocumentId { get; set; } /// <summary> /// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document. /// </summary> /// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value> [DataMember(Name="recipientId", EmitDefaultValue=false)] public string RecipientId { get; set; } /// <summary> /// Specifies the page number on which the tab is located. /// </summary> /// <value>Specifies the page number on which the tab is located.</value> [DataMember(Name="pageNumber", EmitDefaultValue=false)] public string PageNumber { get; set; } /// <summary> /// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position. /// </summary> /// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value> [DataMember(Name="xPosition", EmitDefaultValue=false)] public string XPosition { get; set; } /// <summary> /// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position. /// </summary> /// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value> [DataMember(Name="yPosition", EmitDefaultValue=false)] public string YPosition { get; set; } /// <summary> /// Anchor text information for a radio button. /// </summary> /// <value>Anchor text information for a radio button.</value> [DataMember(Name="anchorString", EmitDefaultValue=false)] public string AnchorString { get; set; } /// <summary> /// Specifies the X axis location of the tab, in achorUnits, relative to the anchorString. /// </summary> /// <value>Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.</value> [DataMember(Name="anchorXOffset", EmitDefaultValue=false)] public string AnchorXOffset { get; set; } /// <summary> /// Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString. /// </summary> /// <value>Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.</value> [DataMember(Name="anchorYOffset", EmitDefaultValue=false)] public string AnchorYOffset { get; set; } /// <summary> /// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches. /// </summary> /// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value> [DataMember(Name="anchorUnits", EmitDefaultValue=false)] public string AnchorUnits { get; set; } /// <summary> /// When set to **true**, this tab is ignored if anchorString is not found in the document. /// </summary> /// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value> [DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)] public string AnchorIgnoreIfNotPresent { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)] public string AnchorCaseSensitive { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)] public string AnchorMatchWholeWord { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)] public string AnchorHorizontalAlignment { get; set; } /// <summary> /// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. /// </summary> /// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].</value> [DataMember(Name="tabId", EmitDefaultValue=false)] public string TabId { get; set; } /// <summary> /// When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. /// </summary> /// <value>When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.</value> [DataMember(Name="templateLocked", EmitDefaultValue=false)] public string TemplateLocked { get; set; } /// <summary> /// When set to **true**, the sender may not remove the recipient. Used only when working with template recipients. /// </summary> /// <value>When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.</value> [DataMember(Name="templateRequired", EmitDefaultValue=false)] public string TemplateRequired { get; set; } /// <summary> /// For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility. /// </summary> /// <value>For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.</value> [DataMember(Name="conditionalParentLabel", EmitDefaultValue=false)] public string ConditionalParentLabel { get; set; } /// <summary> /// For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. /// </summary> /// <value>For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.</value> [DataMember(Name="conditionalParentValue", EmitDefaultValue=false)] public string ConditionalParentValue { get; set; } /// <summary> /// The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties. /// </summary> /// <value>The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.</value> [DataMember(Name="customTabId", EmitDefaultValue=false)] public string CustomTabId { get; set; } /// <summary> /// Gets or Sets MergeField /// </summary> [DataMember(Name="mergeField", EmitDefaultValue=false)] public MergeField MergeField { get; set; } /// <summary> /// Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later. /// </summary> /// <value>Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.</value> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Text {\n"); sb.Append(" Height: ").Append(Height).Append("\n"); sb.Append(" IsPaymentAmount: ").Append(IsPaymentAmount).Append("\n"); sb.Append(" Formula: ").Append(Formula).Append("\n"); sb.Append(" ValidationPattern: ").Append(ValidationPattern).Append("\n"); sb.Append(" ValidationMessage: ").Append(ValidationMessage).Append("\n"); sb.Append(" Shared: ").Append(Shared).Append("\n"); sb.Append(" RequireInitialOnSharedChange: ").Append(RequireInitialOnSharedChange).Append("\n"); sb.Append(" SenderRequired: ").Append(SenderRequired).Append("\n"); sb.Append(" RequireAll: ").Append(RequireAll).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" OriginalValue: ").Append(OriginalValue).Append("\n"); sb.Append(" Width: ").Append(Width).Append("\n"); sb.Append(" Required: ").Append(Required).Append("\n"); sb.Append(" Locked: ").Append(Locked).Append("\n"); sb.Append(" ConcealValueOnDocument: ").Append(ConcealValueOnDocument).Append("\n"); sb.Append(" DisableAutoSize: ").Append(DisableAutoSize).Append("\n"); sb.Append(" MaxLength: ").Append(MaxLength).Append("\n"); sb.Append(" TabLabel: ").Append(TabLabel).Append("\n"); sb.Append(" Font: ").Append(Font).Append("\n"); sb.Append(" Bold: ").Append(Bold).Append("\n"); sb.Append(" Italic: ").Append(Italic).Append("\n"); sb.Append(" Underline: ").Append(Underline).Append("\n"); sb.Append(" FontColor: ").Append(FontColor).Append("\n"); sb.Append(" FontSize: ").Append(FontSize).Append("\n"); sb.Append(" DocumentId: ").Append(DocumentId).Append("\n"); sb.Append(" RecipientId: ").Append(RecipientId).Append("\n"); sb.Append(" PageNumber: ").Append(PageNumber).Append("\n"); sb.Append(" XPosition: ").Append(XPosition).Append("\n"); sb.Append(" YPosition: ").Append(YPosition).Append("\n"); sb.Append(" AnchorString: ").Append(AnchorString).Append("\n"); sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n"); sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n"); sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n"); sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n"); sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n"); sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n"); sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n"); sb.Append(" TabId: ").Append(TabId).Append("\n"); sb.Append(" TemplateLocked: ").Append(TemplateLocked).Append("\n"); sb.Append(" TemplateRequired: ").Append(TemplateRequired).Append("\n"); sb.Append(" ConditionalParentLabel: ").Append(ConditionalParentLabel).Append("\n"); sb.Append(" ConditionalParentValue: ").Append(ConditionalParentValue).Append("\n"); sb.Append(" CustomTabId: ").Append(CustomTabId).Append("\n"); sb.Append(" MergeField: ").Append(MergeField).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Text); } /// <summary> /// Returns true if Text instances are equal /// </summary> /// <param name="other">Instance of Text to be compared</param> /// <returns>Boolean</returns> public bool Equals(Text other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Height == other.Height || this.Height != null && this.Height.Equals(other.Height) ) && ( this.IsPaymentAmount == other.IsPaymentAmount || this.IsPaymentAmount != null && this.IsPaymentAmount.Equals(other.IsPaymentAmount) ) && ( this.Formula == other.Formula || this.Formula != null && this.Formula.Equals(other.Formula) ) && ( this.ValidationPattern == other.ValidationPattern || this.ValidationPattern != null && this.ValidationPattern.Equals(other.ValidationPattern) ) && ( this.ValidationMessage == other.ValidationMessage || this.ValidationMessage != null && this.ValidationMessage.Equals(other.ValidationMessage) ) && ( this.Shared == other.Shared || this.Shared != null && this.Shared.Equals(other.Shared) ) && ( this.RequireInitialOnSharedChange == other.RequireInitialOnSharedChange || this.RequireInitialOnSharedChange != null && this.RequireInitialOnSharedChange.Equals(other.RequireInitialOnSharedChange) ) && ( this.SenderRequired == other.SenderRequired || this.SenderRequired != null && this.SenderRequired.Equals(other.SenderRequired) ) && ( this.RequireAll == other.RequireAll || this.RequireAll != null && this.RequireAll.Equals(other.RequireAll) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ) && ( this.OriginalValue == other.OriginalValue || this.OriginalValue != null && this.OriginalValue.Equals(other.OriginalValue) ) && ( this.Width == other.Width || this.Width != null && this.Width.Equals(other.Width) ) && ( this.Required == other.Required || this.Required != null && this.Required.Equals(other.Required) ) && ( this.Locked == other.Locked || this.Locked != null && this.Locked.Equals(other.Locked) ) && ( this.ConcealValueOnDocument == other.ConcealValueOnDocument || this.ConcealValueOnDocument != null && this.ConcealValueOnDocument.Equals(other.ConcealValueOnDocument) ) && ( this.DisableAutoSize == other.DisableAutoSize || this.DisableAutoSize != null && this.DisableAutoSize.Equals(other.DisableAutoSize) ) && ( this.MaxLength == other.MaxLength || this.MaxLength != null && this.MaxLength.Equals(other.MaxLength) ) && ( this.TabLabel == other.TabLabel || this.TabLabel != null && this.TabLabel.Equals(other.TabLabel) ) && ( this.Font == other.Font || this.Font != null && this.Font.Equals(other.Font) ) && ( this.Bold == other.Bold || this.Bold != null && this.Bold.Equals(other.Bold) ) && ( this.Italic == other.Italic || this.Italic != null && this.Italic.Equals(other.Italic) ) && ( this.Underline == other.Underline || this.Underline != null && this.Underline.Equals(other.Underline) ) && ( this.FontColor == other.FontColor || this.FontColor != null && this.FontColor.Equals(other.FontColor) ) && ( this.FontSize == other.FontSize || this.FontSize != null && this.FontSize.Equals(other.FontSize) ) && ( this.DocumentId == other.DocumentId || this.DocumentId != null && this.DocumentId.Equals(other.DocumentId) ) && ( this.RecipientId == other.RecipientId || this.RecipientId != null && this.RecipientId.Equals(other.RecipientId) ) && ( this.PageNumber == other.PageNumber || this.PageNumber != null && this.PageNumber.Equals(other.PageNumber) ) && ( this.XPosition == other.XPosition || this.XPosition != null && this.XPosition.Equals(other.XPosition) ) && ( this.YPosition == other.YPosition || this.YPosition != null && this.YPosition.Equals(other.YPosition) ) && ( this.AnchorString == other.AnchorString || this.AnchorString != null && this.AnchorString.Equals(other.AnchorString) ) && ( this.AnchorXOffset == other.AnchorXOffset || this.AnchorXOffset != null && this.AnchorXOffset.Equals(other.AnchorXOffset) ) && ( this.AnchorYOffset == other.AnchorYOffset || this.AnchorYOffset != null && this.AnchorYOffset.Equals(other.AnchorYOffset) ) && ( this.AnchorUnits == other.AnchorUnits || this.AnchorUnits != null && this.AnchorUnits.Equals(other.AnchorUnits) ) && ( this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent || this.AnchorIgnoreIfNotPresent != null && this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent) ) && ( this.AnchorCaseSensitive == other.AnchorCaseSensitive || this.AnchorCaseSensitive != null && this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive) ) && ( this.AnchorMatchWholeWord == other.AnchorMatchWholeWord || this.AnchorMatchWholeWord != null && this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord) ) && ( this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment || this.AnchorHorizontalAlignment != null && this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment) ) && ( this.TabId == other.TabId || this.TabId != null && this.TabId.Equals(other.TabId) ) && ( this.TemplateLocked == other.TemplateLocked || this.TemplateLocked != null && this.TemplateLocked.Equals(other.TemplateLocked) ) && ( this.TemplateRequired == other.TemplateRequired || this.TemplateRequired != null && this.TemplateRequired.Equals(other.TemplateRequired) ) && ( this.ConditionalParentLabel == other.ConditionalParentLabel || this.ConditionalParentLabel != null && this.ConditionalParentLabel.Equals(other.ConditionalParentLabel) ) && ( this.ConditionalParentValue == other.ConditionalParentValue || this.ConditionalParentValue != null && this.ConditionalParentValue.Equals(other.ConditionalParentValue) ) && ( this.CustomTabId == other.CustomTabId || this.CustomTabId != null && this.CustomTabId.Equals(other.CustomTabId) ) && ( this.MergeField == other.MergeField || this.MergeField != null && this.MergeField.Equals(other.MergeField) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Height != null) hash = hash * 57 + this.Height.GetHashCode(); if (this.IsPaymentAmount != null) hash = hash * 57 + this.IsPaymentAmount.GetHashCode(); if (this.Formula != null) hash = hash * 57 + this.Formula.GetHashCode(); if (this.ValidationPattern != null) hash = hash * 57 + this.ValidationPattern.GetHashCode(); if (this.ValidationMessage != null) hash = hash * 57 + this.ValidationMessage.GetHashCode(); if (this.Shared != null) hash = hash * 57 + this.Shared.GetHashCode(); if (this.RequireInitialOnSharedChange != null) hash = hash * 57 + this.RequireInitialOnSharedChange.GetHashCode(); if (this.SenderRequired != null) hash = hash * 57 + this.SenderRequired.GetHashCode(); if (this.RequireAll != null) hash = hash * 57 + this.RequireAll.GetHashCode(); if (this.Name != null) hash = hash * 57 + this.Name.GetHashCode(); if (this.Value != null) hash = hash * 57 + this.Value.GetHashCode(); if (this.OriginalValue != null) hash = hash * 57 + this.OriginalValue.GetHashCode(); if (this.Width != null) hash = hash * 57 + this.Width.GetHashCode(); if (this.Required != null) hash = hash * 57 + this.Required.GetHashCode(); if (this.Locked != null) hash = hash * 57 + this.Locked.GetHashCode(); if (this.ConcealValueOnDocument != null) hash = hash * 57 + this.ConcealValueOnDocument.GetHashCode(); if (this.DisableAutoSize != null) hash = hash * 57 + this.DisableAutoSize.GetHashCode(); if (this.MaxLength != null) hash = hash * 57 + this.MaxLength.GetHashCode(); if (this.TabLabel != null) hash = hash * 57 + this.TabLabel.GetHashCode(); if (this.Font != null) hash = hash * 57 + this.Font.GetHashCode(); if (this.Bold != null) hash = hash * 57 + this.Bold.GetHashCode(); if (this.Italic != null) hash = hash * 57 + this.Italic.GetHashCode(); if (this.Underline != null) hash = hash * 57 + this.Underline.GetHashCode(); if (this.FontColor != null) hash = hash * 57 + this.FontColor.GetHashCode(); if (this.FontSize != null) hash = hash * 57 + this.FontSize.GetHashCode(); if (this.DocumentId != null) hash = hash * 57 + this.DocumentId.GetHashCode(); if (this.RecipientId != null) hash = hash * 57 + this.RecipientId.GetHashCode(); if (this.PageNumber != null) hash = hash * 57 + this.PageNumber.GetHashCode(); if (this.XPosition != null) hash = hash * 57 + this.XPosition.GetHashCode(); if (this.YPosition != null) hash = hash * 57 + this.YPosition.GetHashCode(); if (this.AnchorString != null) hash = hash * 57 + this.AnchorString.GetHashCode(); if (this.AnchorXOffset != null) hash = hash * 57 + this.AnchorXOffset.GetHashCode(); if (this.AnchorYOffset != null) hash = hash * 57 + this.AnchorYOffset.GetHashCode(); if (this.AnchorUnits != null) hash = hash * 57 + this.AnchorUnits.GetHashCode(); if (this.AnchorIgnoreIfNotPresent != null) hash = hash * 57 + this.AnchorIgnoreIfNotPresent.GetHashCode(); if (this.AnchorCaseSensitive != null) hash = hash * 57 + this.AnchorCaseSensitive.GetHashCode(); if (this.AnchorMatchWholeWord != null) hash = hash * 57 + this.AnchorMatchWholeWord.GetHashCode(); if (this.AnchorHorizontalAlignment != null) hash = hash * 57 + this.AnchorHorizontalAlignment.GetHashCode(); if (this.TabId != null) hash = hash * 57 + this.TabId.GetHashCode(); if (this.TemplateLocked != null) hash = hash * 57 + this.TemplateLocked.GetHashCode(); if (this.TemplateRequired != null) hash = hash * 57 + this.TemplateRequired.GetHashCode(); if (this.ConditionalParentLabel != null) hash = hash * 57 + this.ConditionalParentLabel.GetHashCode(); if (this.ConditionalParentValue != null) hash = hash * 57 + this.ConditionalParentValue.GetHashCode(); if (this.CustomTabId != null) hash = hash * 57 + this.CustomTabId.GetHashCode(); if (this.MergeField != null) hash = hash * 57 + this.MergeField.GetHashCode(); if (this.Status != null) hash = hash * 57 + this.Status.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 57 + this.ErrorDetails.GetHashCode(); return hash; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// Convert.ToString(System.Object,System.IFormatProvider) /// </summary> public class ConvertToString23 { public static int Main() { ConvertToString23 testObj = new ConvertToString23(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Object,System.IFormatProvider)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Call Convert.ToString when value implements IConvertible... "; string c_TEST_ID = "P001"; TestConvertableClass tcc = new TestConvertableClass(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (tcc.ToString(null) != Convert.ToString((object)tcc,null)) { string errorDesc = "value is not " + Convert.ToString((object)tcc) + " as expected: Actual is " + tcc.ToString(); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify object is a null reference... "; string c_TEST_ID = "P002"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { object obj = null; String resValue = Convert.ToString(obj, null); if (resValue != String.Empty) { string errorDesc = "value is not \"" + resValue + "\" as expected: Actual is empty"; errorDesc += "\n when object is a null reference"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region HelpMethod public class TestConvertableClass : IConvertible { #region IConvertible Members public TypeCode GetTypeCode() { throw new Exception("The method or operation is not implemented."); } public bool ToBoolean(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public byte ToByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public char ToChar(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public DateTime ToDateTime(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public decimal ToDecimal(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public double ToDouble(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public short ToInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public int ToInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public long ToInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public sbyte ToSByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public float ToSingle(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public string ToString(IFormatProvider provider) { return "this is formatted string"; } public object ToType(Type conversionType, IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ushort ToUInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public uint ToUInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ulong ToUInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } #endregion } #endregion }
// // ProjectPackagesFolderNodeBuilder.cs: Node to control the packages in the project // // Authors: // Marcos David Marin Amador <MarcosMarin@gmail.com> // // Copyright (C) 2007 Marcos David Marin Amador // // // This source code is licenced under The MIT License: // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using Mono.Addins; using MonoDevelop.Components.Commands; using MonoDevelop.Projects; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui.Pads; using MonoDevelop.Ide.Gui.Pads.ProjectPad; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.ValaBinding.ProjectPad { public class ProjectPackagesFolderNodeBuilder : TypeNodeBuilder { ProjectPackageEventHandler addedHandler; ProjectPackageEventHandler removedHandler; public override Type NodeDataType { get { return typeof(ProjectPackageCollection); } } public override void OnNodeAdded(object dataObject) { ValaProject project = ((ProjectPackageCollection)dataObject).Project; if (project == null) return; project.PackageAddedToProject += addedHandler; project.PackageRemovedFromProject += removedHandler; } public override void OnNodeRemoved(object dataObject) { ValaProject project = ((ProjectPackageCollection)dataObject).Project; if (project == null) return; project.PackageAddedToProject -= addedHandler; project.PackageRemovedFromProject -= removedHandler; } public override Type CommandHandlerType { get { return typeof(ProjectPackagesFolderNodeCommandHandler); } } protected override void Initialize() { addedHandler = (ProjectPackageEventHandler)DispatchService.GuiDispatch(new ProjectPackageEventHandler(OnAddPackage)); removedHandler = (ProjectPackageEventHandler)DispatchService.GuiDispatch(new ProjectPackageEventHandler(OnRemovePackage)); } public override string GetNodeName(ITreeNavigator thisNode, object dataObject) { return "Packages"; } public override void BuildNode(ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo) { nodeInfo.Label = "Packages"; nodeInfo.Icon = Context.GetIcon(Stock.OpenReferenceFolder); nodeInfo.ClosedIcon = Context.GetIcon(Stock.ClosedReferenceFolder); } public override bool HasChildNodes(ITreeBuilder builder, object dataObject) { return ((ProjectPackageCollection)dataObject).Count > 0; } public override void BuildChildNodes(ITreeBuilder treeBuilder, object dataObject) { ProjectPackageCollection packages = (ProjectPackageCollection)dataObject; foreach (ProjectPackage p in packages) treeBuilder.AddChild(p); } public override string ContextMenuAddinPath { get { return "/MonoDevelop/ValaBinding/Views/ProjectBrowser/ContextMenu/PackagesFolderNode"; } } public override int CompareObjects(ITreeNavigator thisNode, ITreeNavigator otherNode) { return -1; } private void OnAddPackage(object sender, ProjectPackageEventArgs e) { ITreeBuilder builder = Context.GetTreeBuilder(e.Project.Packages); if (builder != null) builder.UpdateAll(); } private void OnRemovePackage(object sender, ProjectPackageEventArgs e) { ITreeBuilder builder = Context.GetTreeBuilder(e.Project.Packages); if (builder != null) builder.UpdateAll(); } } public class ProjectPackagesFolderNodeCommandHandler : NodeCommandHandler { [CommandHandler(MonoDevelop.ValaBinding.ValaProjectCommands.AddPackage)] public void AddPackageToProject() { ValaProject project = (ValaProject)CurrentNode.GetParentDataItem( typeof(ValaProject), false); EditPackagesDialog dialog = new EditPackagesDialog(project); dialog.Run(); IdeApp.ProjectOperations.Save(project); CurrentNode.Expanded = true; } // Currently only accepts packages and projects that compile into a static library public override bool CanDropNode(object dataObject, DragOperation operation) { if (dataObject is ProjectPackage) return true; if (dataObject is ValaProject) { ValaProject project = (ValaProject)dataObject; if (((ProjectPackageCollection)CurrentNode.DataItem).Project.Equals(project)) return false; ValaProjectConfiguration config = (ValaProjectConfiguration)project.GetConfiguration(IdeApp.Workspace.ActiveConfiguration); if (config.CompileTarget != ValaBinding.CompileTarget.Bin) return true; } return false; } public override DragOperation CanDragNode() { return DragOperation.Copy | DragOperation.Move; } public override void OnNodeDrop(object dataObject, DragOperation operation) { if (dataObject is ProjectPackage) { ProjectPackage package = (ProjectPackage)dataObject; ITreeNavigator nav = CurrentNode; ValaProject dest = nav.GetParentDataItem(typeof(ValaProject), true) as ValaProject; nav.MoveToObject(dataObject); ValaProject source = nav.GetParentDataItem(typeof(ValaProject), true) as ValaProject; dest.Packages.Add(package); IdeApp.ProjectOperations.Save(dest); if (operation == DragOperation.Move) { source.Packages.Remove(package); IdeApp.ProjectOperations.Save(source); } } else if (dataObject is ValaProject) { ValaProject draggedProject = (ValaProject)dataObject; ValaProject destProject = (CurrentNode.DataItem as ProjectPackageCollection).Project; ProjectPackage package = ProjectPackage.CreateBetween2Projects(destProject, draggedProject); if (!destProject.Packages.Contains(package)) { destProject.Packages.Add(package); IdeApp.ProjectOperations.Save(destProject); } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json.Serialization; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.Serialization { public sealed class SerializationTests : IClassFixture<IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext>> { private const string JsonDateTimeOffsetFormatSpecifier = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK"; private readonly IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext> _testContext; private readonly SerializationFakers _fakers = new(); public SerializationTests(IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext> testContext) { _testContext = testContext; testContext.UseController<MeetingAttendeesController>(); testContext.UseController<MeetingsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); }); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.IncludeExceptionStackTraceInErrors = false; options.AllowClientGeneratedIds = true; options.IncludeJsonApiVersion = false; if (!options.SerializerOptions.Converters.Any(converter => converter is JsonTimeSpanConverter)) { options.SerializerOptions.Converters.Add(new JsonTimeSpanConverter()); } } [Fact] public async Task Returns_no_body_for_successful_HEAD_request() { // Arrange Meeting meeting = _fakers.Meeting.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Meetings.Add(meeting); await dbContext.SaveChangesAsync(); }); string route = $"/meetings/{meeting.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteHeadAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeEmpty(); } [Fact] public async Task Returns_no_body_for_failed_HEAD_request() { // Arrange string route = $"/meetings/{Unknown.StringId.For<Meeting, Guid>()}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteHeadAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Should().BeEmpty(); } [Fact] public async Task Can_get_primary_resources_with_include() { // Arrange List<Meeting> meetings = _fakers.Meeting.Generate(1); meetings[0].Attendees = _fakers.MeetingAttendee.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Meeting>(); dbContext.Meetings.AddRange(meetings); await dbContext.SaveChangesAsync(); }); const string route = "/meetings?include=attendees"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings?include=attendees"", ""first"": ""http://localhost/meetings?include=attendees"" }, ""data"": [ { ""type"": ""meetings"", ""id"": """ + meetings[0].StringId + @""", ""attributes"": { ""title"": """ + meetings[0].Title + @""", ""startTime"": """ + meetings[0].StartTime.ToString(JsonDateTimeOffsetFormatSpecifier) + @""", ""duration"": """ + meetings[0].Duration + @""", ""location"": { ""lat"": " + meetings[0].Location.Latitude.ToString(CultureInfo.InvariantCulture) + @", ""lng"": " + meetings[0].Location.Longitude.ToString(CultureInfo.InvariantCulture) + @" } }, ""relationships"": { ""attendees"": { ""links"": { ""self"": ""http://localhost/meetings/" + meetings[0].StringId + @"/relationships/attendees"", ""related"": ""http://localhost/meetings/" + meetings[0].StringId + @"/attendees"" }, ""data"": [ { ""type"": ""meetingAttendees"", ""id"": """ + meetings[0].Attendees[0].StringId + @""" } ] } }, ""links"": { ""self"": ""http://localhost/meetings/" + meetings[0].StringId + @""" } } ], ""included"": [ { ""type"": ""meetingAttendees"", ""id"": """ + meetings[0].Attendees[0].StringId + @""", ""attributes"": { ""displayName"": """ + meetings[0].Attendees[0].DisplayName + @""" }, ""relationships"": { ""meeting"": { ""links"": { ""self"": ""http://localhost/meetingAttendees/" + meetings[0].Attendees[0].StringId + @"/relationships/meeting"", ""related"": ""http://localhost/meetingAttendees/" + meetings[0].Attendees[0].StringId + @"/meeting"" } } }, ""links"": { ""self"": ""http://localhost/meetingAttendees/" + meetings[0].Attendees[0].StringId + @""" } } ] }"); } [Fact] public async Task Can_get_primary_resources_with_empty_include() { // Arrange List<Meeting> meetings = _fakers.Meeting.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Meeting>(); dbContext.Meetings.AddRange(meetings); await dbContext.SaveChangesAsync(); }); const string route = "/meetings/?include=attendees"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings/?include=attendees"", ""first"": ""http://localhost/meetings/?include=attendees"" }, ""data"": [ { ""type"": ""meetings"", ""id"": """ + meetings[0].StringId + @""", ""attributes"": { ""title"": """ + meetings[0].Title + @""", ""startTime"": """ + meetings[0].StartTime.ToString(JsonDateTimeOffsetFormatSpecifier) + @""", ""duration"": """ + meetings[0].Duration + @""", ""location"": { ""lat"": " + meetings[0].Location.Latitude.ToString(CultureInfo.InvariantCulture) + @", ""lng"": " + meetings[0].Location.Longitude.ToString(CultureInfo.InvariantCulture) + @" } }, ""relationships"": { ""attendees"": { ""links"": { ""self"": ""http://localhost/meetings/" + meetings[0].StringId + @"/relationships/attendees"", ""related"": ""http://localhost/meetings/" + meetings[0].StringId + @"/attendees"" }, ""data"": [] } }, ""links"": { ""self"": ""http://localhost/meetings/" + meetings[0].StringId + @""" } } ], ""included"": [] }"); } [Fact] public async Task Can_get_primary_resource_by_ID() { // Arrange Meeting meeting = _fakers.Meeting.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Meetings.Add(meeting); await dbContext.SaveChangesAsync(); }); string route = $"/meetings/{meeting.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings/" + meeting.StringId + @""" }, ""data"": { ""type"": ""meetings"", ""id"": """ + meeting.StringId + @""", ""attributes"": { ""title"": """ + meeting.Title + @""", ""startTime"": """ + meeting.StartTime.ToString(JsonDateTimeOffsetFormatSpecifier) + @""", ""duration"": """ + meeting.Duration + @""", ""location"": { ""lat"": " + meeting.Location.Latitude.ToString(CultureInfo.InvariantCulture) + @", ""lng"": " + meeting.Location.Longitude.ToString(CultureInfo.InvariantCulture) + @" } }, ""relationships"": { ""attendees"": { ""links"": { ""self"": ""http://localhost/meetings/" + meeting.StringId + @"/relationships/attendees"", ""related"": ""http://localhost/meetings/" + meeting.StringId + @"/attendees"" } } }, ""links"": { ""self"": ""http://localhost/meetings/" + meeting.StringId + @""" } } }"); } [Fact] public async Task Cannot_get_unknown_primary_resource_by_ID() { // Arrange string meetingId = Unknown.StringId.For<Meeting, Guid>(); string route = $"/meetings/{meetingId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); string errorId = JsonApiStringConverter.ExtractErrorId(responseDocument); responseDocument.Should().BeJson(@"{ ""errors"": [ { ""id"": """ + errorId + @""", ""status"": ""404"", ""title"": ""The requested resource does not exist."", ""detail"": ""Resource of type 'meetings' with ID '" + meetingId + @"' does not exist."" } ] }"); } [Fact] public async Task Can_get_secondary_resource() { // Arrange MeetingAttendee attendee = _fakers.MeetingAttendee.Generate(); attendee.Meeting = _fakers.Meeting.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Attendees.Add(attendee); await dbContext.SaveChangesAsync(); }); string route = $"/meetingAttendees/{attendee.StringId}/meeting"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetingAttendees/" + attendee.StringId + @"/meeting"" }, ""data"": { ""type"": ""meetings"", ""id"": """ + attendee.Meeting.StringId + @""", ""attributes"": { ""title"": """ + attendee.Meeting.Title + @""", ""startTime"": """ + attendee.Meeting.StartTime.ToString(JsonDateTimeOffsetFormatSpecifier) + @""", ""duration"": """ + attendee.Meeting.Duration + @""", ""location"": { ""lat"": " + attendee.Meeting.Location.Latitude.ToString(CultureInfo.InvariantCulture) + @", ""lng"": " + attendee.Meeting.Location.Longitude.ToString(CultureInfo.InvariantCulture) + @" } }, ""relationships"": { ""attendees"": { ""links"": { ""self"": ""http://localhost/meetings/" + attendee.Meeting.StringId + @"/relationships/attendees"", ""related"": ""http://localhost/meetings/" + attendee.Meeting.StringId + @"/attendees"" } } }, ""links"": { ""self"": ""http://localhost/meetings/" + attendee.Meeting.StringId + @""" } } }"); } [Fact] public async Task Can_get_unknown_secondary_resource() { // Arrange MeetingAttendee attendee = _fakers.MeetingAttendee.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Attendees.Add(attendee); await dbContext.SaveChangesAsync(); }); string route = $"/meetingAttendees/{attendee.StringId}/meeting"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetingAttendees/" + attendee.StringId + @"/meeting"" }, ""data"": null }"); } [Fact] public async Task Can_get_secondary_resources() { // Arrange Meeting meeting = _fakers.Meeting.Generate(); meeting.Attendees = _fakers.MeetingAttendee.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Meetings.Add(meeting); await dbContext.SaveChangesAsync(); }); string route = $"/meetings/{meeting.StringId}/attendees"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings/" + meeting.StringId + @"/attendees"", ""first"": ""http://localhost/meetings/" + meeting.StringId + @"/attendees"" }, ""data"": [ { ""type"": ""meetingAttendees"", ""id"": """ + meeting.Attendees[0].StringId + @""", ""attributes"": { ""displayName"": """ + meeting.Attendees[0].DisplayName + @""" }, ""relationships"": { ""meeting"": { ""links"": { ""self"": ""http://localhost/meetingAttendees/" + meeting.Attendees[0].StringId + @"/relationships/meeting"", ""related"": ""http://localhost/meetingAttendees/" + meeting.Attendees[0].StringId + @"/meeting"" } } }, ""links"": { ""self"": ""http://localhost/meetingAttendees/" + meeting.Attendees[0].StringId + @""" } } ] }"); } [Fact] public async Task Can_get_unknown_secondary_resources() { // Arrange Meeting meeting = _fakers.Meeting.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Meetings.Add(meeting); await dbContext.SaveChangesAsync(); }); string route = $"/meetings/{meeting.StringId}/attendees"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings/" + meeting.StringId + @"/attendees"", ""first"": ""http://localhost/meetings/" + meeting.StringId + @"/attendees"" }, ""data"": [] }"); } [Fact] public async Task Can_get_ToOne_relationship() { // Arrange MeetingAttendee attendee = _fakers.MeetingAttendee.Generate(); attendee.Meeting = _fakers.Meeting.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Attendees.Add(attendee); await dbContext.SaveChangesAsync(); }); string route = $"/meetingAttendees/{attendee.StringId}/relationships/meeting"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetingAttendees/" + attendee.StringId + @"/relationships/meeting"", ""related"": ""http://localhost/meetingAttendees/" + attendee.StringId + @"/meeting"" }, ""data"": { ""type"": ""meetings"", ""id"": """ + attendee.Meeting.StringId + @""" } }"); } [Fact] public async Task Can_get_ToMany_relationship() { // Arrange Meeting meeting = _fakers.Meeting.Generate(); meeting.Attendees = _fakers.MeetingAttendee.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Meetings.Add(meeting); await dbContext.SaveChangesAsync(); }); string route = $"/meetings/{meeting.StringId}/relationships/attendees"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); string[] meetingIds = meeting.Attendees.Select(attendee => attendee.StringId).OrderBy(id => id).ToArray(); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings/" + meeting.StringId + @"/relationships/attendees"", ""related"": ""http://localhost/meetings/" + meeting.StringId + @"/attendees"", ""first"": ""http://localhost/meetings/" + meeting.StringId + @"/relationships/attendees"" }, ""data"": [ { ""type"": ""meetingAttendees"", ""id"": """ + meetingIds[0] + @""" }, { ""type"": ""meetingAttendees"", ""id"": """ + meetingIds[1] + @""" } ] }"); } [Fact] public async Task Can_create_resource_with_side_effects() { // Arrange Meeting newMeeting = _fakers.Meeting.Generate(); newMeeting.Id = Guid.NewGuid(); var requestBody = new { data = new { type = "meetings", id = newMeeting.StringId, attributes = new { title = newMeeting.Title, startTime = newMeeting.StartTime, duration = newMeeting.Duration, location = new { lat = newMeeting.Latitude, lng = newMeeting.Longitude } } } }; const string route = "/meetings"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetings"" }, ""data"": { ""type"": ""meetings"", ""id"": """ + newMeeting.StringId + @""", ""attributes"": { ""title"": """ + newMeeting.Title + @""", ""startTime"": """ + newMeeting.StartTime.ToString(JsonDateTimeOffsetFormatSpecifier) + @""", ""duration"": """ + newMeeting.Duration + @""", ""location"": { ""lat"": " + newMeeting.Location.Latitude.ToString(CultureInfo.InvariantCulture) + @", ""lng"": " + newMeeting.Location.Longitude.ToString(CultureInfo.InvariantCulture) + @" } }, ""relationships"": { ""attendees"": { ""links"": { ""self"": ""http://localhost/meetings/" + newMeeting.StringId + @"/relationships/attendees"", ""related"": ""http://localhost/meetings/" + newMeeting.StringId + @"/attendees"" } } }, ""links"": { ""self"": ""http://localhost/meetings/" + newMeeting.StringId + @""" } } }"); } [Fact] public async Task Can_update_resource_with_side_effects() { // Arrange MeetingAttendee existingAttendee = _fakers.MeetingAttendee.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Attendees.Add(existingAttendee); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "meetingAttendees", id = existingAttendee.StringId, attributes = new { displayName = existingAttendee.DisplayName } } }; string route = $"/meetingAttendees/{existingAttendee.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""links"": { ""self"": ""http://localhost/meetingAttendees/" + existingAttendee.StringId + @""" }, ""data"": { ""type"": ""meetingAttendees"", ""id"": """ + existingAttendee.StringId + @""", ""attributes"": { ""displayName"": """ + existingAttendee.DisplayName + @""" }, ""relationships"": { ""meeting"": { ""links"": { ""self"": ""http://localhost/meetingAttendees/" + existingAttendee.StringId + @"/relationships/meeting"", ""related"": ""http://localhost/meetingAttendees/" + existingAttendee.StringId + @"/meeting"" } } }, ""links"": { ""self"": ""http://localhost/meetingAttendees/" + existingAttendee.StringId + @""" } } }"); } [Fact] public async Task Can_update_resource_with_relationship_for_type_at_end() { // Arrange MeetingAttendee existingAttendee = _fakers.MeetingAttendee.Generate(); existingAttendee.Meeting = _fakers.Meeting.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Attendees.Add(existingAttendee); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { id = existingAttendee.StringId, attributes = new { displayName = existingAttendee.DisplayName }, relationships = new { meeting = new { data = new { id = existingAttendee.Meeting.StringId, type = "meetings" } } }, type = "meetingAttendees" } }; string route = $"/meetingAttendees/{existingAttendee.StringId}"; // Act (HttpResponseMessage httpResponse, _) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); } [Fact] public async Task Includes_version_on_resource_endpoint() { // Arrange var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.IncludeJsonApiVersion = true; MeetingAttendee attendee = _fakers.MeetingAttendee.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Attendees.Add(attendee); await dbContext.SaveChangesAsync(); }); string route = $"/meetingAttendees/{attendee.StringId}/meeting"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Should().BeJson(@"{ ""jsonapi"": { ""version"": ""1.1"" }, ""links"": { ""self"": ""http://localhost/meetingAttendees/" + attendee.StringId + @"/meeting"" }, ""data"": null }"); } [Fact] public async Task Includes_version_on_error_in_resource_endpoint() { // Arrange var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.IncludeJsonApiVersion = true; string attendeeId = Unknown.StringId.For<MeetingAttendee, Guid>(); string route = $"/meetingAttendees/{attendeeId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); string errorId = JsonApiStringConverter.ExtractErrorId(responseDocument); responseDocument.Should().BeJson(@"{ ""jsonapi"": { ""version"": ""1.1"" }, ""errors"": [ { ""id"": """ + errorId + @""", ""status"": ""404"", ""title"": ""The requested resource does not exist."", ""detail"": ""Resource of type 'meetingAttendees' with ID '" + attendeeId + @"' does not exist."" } ] }"); } } }
//------------------------------------------------------------------------------ // <copyright file="SqlEnums.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Data.OleDb; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using System.Data.Sql; using MSS=Microsoft.SqlServer.Server; internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maxium precision for numeric types // $ internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; // can we get rid of this (?just have a mapping?) this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0;} } private static bool _IsAnsiType(SqlDbType type) { return(type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return(type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return(type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return(type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return(type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int) type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int) SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return((int)type >= 0 && ((int)type <= (int) SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch(target) { case SqlDbType.BigInt: return MetaBigInt; case SqlDbType.Binary: return MetaBinary; case SqlDbType.Bit: return MetaBit; case SqlDbType.Char: return MetaChar; case SqlDbType.DateTime: return MetaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return MetaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return MetaInt; case SqlDbType.Money: return MetaMoney; case SqlDbType.NChar: return MetaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return MetaReal; case SqlDbType.UniqueIdentifier: return MetaUniqueId; case SqlDbType.SmallDateTime: return MetaSmallDateTime; case SqlDbType.SmallInt: return MetaSmallInt; case SqlDbType.SmallMoney: return MetaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return MetaTimestamp; case SqlDbType.TinyInt: return MetaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return MetaVarChar; case SqlDbType.Variant: return MetaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return MetaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Udt: return MetaUdt; case SqlDbType.Structured: if (isMultiValued) { return MetaTable; } else { return MetaSUDT; } case SqlDbType.Date: return MetaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return MetaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return MetaVarChar; case DbType.AnsiStringFixedLength: return MetaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return MetaTinyInt; case DbType.Boolean: return MetaBit; case DbType.Currency: return MetaMoney; case DbType.Date: case DbType.DateTime: return MetaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return MetaFloat; case DbType.Guid: return MetaUniqueId; case DbType.Int16: return MetaSmallInt; case DbType.Int32: return MetaInt; case DbType.Int64: return MetaBigInt; case DbType.Object: return MetaVariant; case DbType.Single: return MetaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return MetaNChar; case DbType.Time: return MetaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return MetaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: // return MetaMaxUdt; default: return mt; } } // // map COM+ Type to MetaType class // static internal MetaType GetMetaTypeFromType(Type dataType) { return GetMetaTypeFromValue(dataType, null, false, true); } static internal MetaType GetMetaTypeFromValue(object value, bool streamAllowed=true) { return GetMetaTypeFromValue(value.GetType(), value, true, streamAllowed); } static private MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen, bool streamAllowed) { switch (Type.GetTypeCode(dataType)) { case TypeCode.Empty: throw ADP.InvalidDataType(TypeCode.Empty); case TypeCode.Object: if (dataType == typeof(System.Byte[])) { // mdac 90455 must not default to image if inferLen is false ... // if (!inferLen || ((byte[]) value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } else if (dataType == typeof(System.Guid)) { return MetaUniqueId; } else if (dataType == typeof(System.Object)) { return MetaVariant; } // check sql types now else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return MetaBit; else if (dataType == typeof(SqlByte)) return MetaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; // MDAC 87587 else if (dataType == typeof(SqlDateTime)) return MetaDateTime; else if (dataType == typeof(SqlDouble)) return MetaFloat; else if (dataType == typeof(SqlGuid)) return MetaUniqueId; else if (dataType == typeof(SqlInt16)) return MetaSmallInt; else if (dataType == typeof(SqlInt32)) return MetaInt; else if (dataType == typeof(SqlInt64)) return MetaBigInt; else if (dataType == typeof(SqlMoney)) return MetaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return MetaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) { return ((inferLen && !((SqlString)value).IsNull) ? PromoteStringType(((SqlString)value).Value) : MetaNVarChar); // MDAC 87587 } else if (dataType == typeof(IEnumerable<DbDataRecord>) || dataType == typeof(DataTable)) { return MetaTable; } else if (dataType == typeof(TimeSpan)) { return MetaTime; } else if (dataType == typeof(DateTimeOffset)) { return MetaDateTimeOffset; } else { // UDT ? SqlUdtInfo attribs = SqlUdtInfo.TryGetFromType(dataType); if (attribs != null) { return MetaUdt; } if (streamAllowed) { // Derived from Stream ? if (typeof(Stream).IsAssignableFrom(dataType)) { return MetaVarBinary; } // Derived from TextReader ? if (typeof(TextReader).IsAssignableFrom(dataType)) { return MetaNVarChar; } // Derived from XmlReader ? if (typeof(System.Xml.XmlReader).IsAssignableFrom(dataType)) { return MetaXml; } } } throw ADP.UnknownDataType(dataType); case TypeCode.DBNull: throw ADP.InvalidDataType(TypeCode.DBNull); case TypeCode.Boolean: return MetaBit; case TypeCode.Char: throw ADP.InvalidDataType(TypeCode.Char); case TypeCode.SByte: throw ADP.InvalidDataType(TypeCode.SByte); case TypeCode.Byte: return MetaTinyInt; case TypeCode.Int16: return MetaSmallInt; case TypeCode.UInt16: throw ADP.InvalidDataType(TypeCode.UInt16); case TypeCode.Int32: return MetaInt; case TypeCode.UInt32: throw ADP.InvalidDataType(TypeCode.UInt32); case TypeCode.Int64: return MetaBigInt; case TypeCode.UInt64: throw ADP.InvalidDataType(TypeCode.UInt64); case TypeCode.Single: return MetaReal; case TypeCode.Double: return MetaFloat; case TypeCode.Decimal: return MetaDecimal; case TypeCode.DateTime: return MetaDateTime; case TypeCode.String: return (inferLen ? PromoteStringType((string)value) : MetaNVarChar); default: throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType)); } } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DataTable)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Assert(false, "Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { AssertIsUserDefinedTypeInstance(sqlVal, "unknown SqlType class stored in sqlVal"); } return comVal; } /// <summary> /// Assert that the supplied object is an instance of a SQL User-Defined Type (UDT). /// </summary> /// <param name="sqlValue">Object instance to be tested.</param> /// <remarks> /// This method is only compiled with debug builds, and it a helper method for the GetComValueFromSqlVariant method defined in this class. /// /// The presence of the SqlUserDefinedTypeAttribute on the object's type /// is used to determine if the object is a UDT instance (if present it is a UDT, else it is not). /// </remarks> /// <exception cref="NullReferenceException"> /// If sqlValue is null. Callers must ensure the object is non-null. /// </exception> [Conditional("DEBUG")] private static void AssertIsUserDefinedTypeInstance(object sqlValue, string failedAssertMessage) { Type type = sqlValue.GetType(); Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[] attributes = (Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[])type.GetCustomAttributes(typeof(Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute), true); Debug.Assert(attributes.Length > 0, failedAssertMessage); } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is System.Byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is System.Char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is System.Char[]) sqlVal = new SqlChars((System.Char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is Int16) sqlVal = new SqlInt16((Int16)comVal); else if (comVal is Int32) sqlVal = new SqlInt32((Int32)comVal); else if (comVal is Int64) sqlVal = new SqlInt64((Int64)comVal); else if (comVal is Decimal) sqlVal = new SqlDecimal((Decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Assert(false, "unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static SqlDbType GetSqlDbTypeFromOleDbType(short dbType, string typeName) { SqlDbType sqlType = SqlDbType.Variant; switch ((OleDbType)dbType) { case OleDbType.BigInt: sqlType = SqlDbType.BigInt; break; case OleDbType.Boolean: sqlType = SqlDbType.Bit; break; case OleDbType.Char: case OleDbType.VarChar: // these guys are ambiguous - server sends over DBTYPE_STR in both cases sqlType = (typeName == MetaTypeName.CHAR) ? SqlDbType.Char : SqlDbType.VarChar; break; case OleDbType.Currency: sqlType = (typeName == MetaTypeName.SMALLMONEY) ? SqlDbType.SmallMoney : SqlDbType.Money; break; case OleDbType.Date: case OleDbType.DBTimeStamp: case OleDbType.Filetime: switch (typeName) { case MetaTypeName.SMALLDATETIME: sqlType = SqlDbType.SmallDateTime; break; case MetaTypeName.DATETIME2: sqlType = SqlDbType.DateTime2; break; default: sqlType = SqlDbType.DateTime; break; } break; case OleDbType.Decimal: case OleDbType.Numeric: sqlType = SqlDbType.Decimal; break; case OleDbType.Double: sqlType = SqlDbType.Float; break; case OleDbType.Guid: sqlType = SqlDbType.UniqueIdentifier; break; case OleDbType.Integer: sqlType = SqlDbType.Int; break; case OleDbType.LongVarBinary: sqlType = SqlDbType.Image; break; case OleDbType.LongVarChar: sqlType = SqlDbType.Text; break; case OleDbType.LongVarWChar: sqlType = SqlDbType.NText; break; case OleDbType.Single: sqlType = SqlDbType.Real; break; case OleDbType.SmallInt: case OleDbType.UnsignedSmallInt: sqlType = SqlDbType.SmallInt; break; case OleDbType.TinyInt: case OleDbType.UnsignedTinyInt: sqlType = SqlDbType.TinyInt; break; case OleDbType.VarBinary: case OleDbType.Binary: sqlType = (typeName == MetaTypeName.BINARY) ? SqlDbType.Binary : SqlDbType.VarBinary; break; case OleDbType.Variant: sqlType = SqlDbType.Variant; break; case OleDbType.VarWChar: case OleDbType.WChar: case OleDbType.BSTR: // these guys are ambiguous - server sends over DBTYPE_WSTR in both cases // BSTR is always assumed to be NVARCHAR sqlType = (typeName == MetaTypeName.NCHAR) ? SqlDbType.NChar : SqlDbType.NVarChar; break; case OleDbType.DBDate: // Date sqlType = SqlDbType.Date; break; case (OleDbType)132: // Udt sqlType = SqlDbType.Udt; break; case (OleDbType)141: // Xml sqlType = SqlDbType.Xml; break; case (OleDbType)145: // Time sqlType = SqlDbType.Time; break; case (OleDbType)146: // DateTimeOffset sqlType = SqlDbType.DateTimeOffset; break; // default: break; // no direct mapping, just use SqlDbType.Variant; } return sqlType; } internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? MetaSmallMoney : MetaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? MetaSmallDateTime : MetaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? MetaInt : MetaBigInt) : ((2 == length) ? MetaSmallInt : MetaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? MetaReal : MetaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return MetaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: //goto TdsEnums.SQLBIGVARCHAR; case TdsEnums.SQLBIGVARCHAR: return MetaVarChar; case TdsEnums.SQLBINARY: //goto TdsEnums.SQLBIGBINARY; case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? MetaTimestamp : MetaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: //goto TdsEnums.SQLBIGCHAR; case TdsEnums.SQLBIGCHAR: return MetaChar; case TdsEnums.SQLINT1: return MetaTinyInt; case TdsEnums.SQLBIT: //goto TdsEnums.SQLBITN; case TdsEnums.SQLBITN: return MetaBit; case TdsEnums.SQLINT2: return MetaSmallInt; case TdsEnums.SQLINT4: return MetaInt; case TdsEnums.SQLINT8: return MetaBigInt; case TdsEnums.SQLMONEY: return MetaMoney; case TdsEnums.SQLDATETIME: return MetaDateTime; case TdsEnums.SQLFLT8: return MetaFloat; case TdsEnums.SQLFLT4: return MetaReal; case TdsEnums.SQLMONEY4: return MetaSmallMoney; case TdsEnums.SQLDATETIM4: return MetaSmallDateTime; case TdsEnums.SQLDECIMALN: //goto TdsEnums.SQLNUMERICN; case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return MetaUniqueId ; case TdsEnums.SQLNCHAR: return MetaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return MetaVariant; case TdsEnums.SQLUDT: return MetaUdt; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return MetaTable; case TdsEnums.SQLDATE: return MetaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return MetaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Assert(false, "Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); }// case } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static String GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType MetaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(System.Int64), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType MetaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(System.Double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType MetaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(System.Single), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType MetaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // syntatic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType MetaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // HACK!!! We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user! private static readonly MetaType MetaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType MetaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(System.Boolean), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType MetaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(System.Byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType MetaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(System.Int16), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType MetaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(System.Int32), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType MetaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(System.String), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType MetaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(System.String), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType MetaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(System.String), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(System.Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(System.String), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType MetaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType MetaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType MetaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType MetaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType MetaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType MetaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(System.Object), typeof(System.Object), SqlDbType.Variant, DbType.Object, 0); internal static readonly MetaType MetaUdt = new MetaType (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType MetaMaxUdt = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType MetaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); // private static readonly MetaType MetaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType MetaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType MetaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days&minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { // Disable the assert here since we do not properly handle wrong Scale value on the parameter, // see VSTFDEVDIV 795578 for more details. // But, this assert is still valid when we receive Time/DateTime2/DateTimeOffset scale from server over TDS, // so it is moved to TdsParser.CommonProcessMetaData. // For new scenarios, assert and/or validate the scale value before this call! // Debug.Assert(0 <= scale && scale <= 7); if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; // } }
using System.Configuration; using NLog; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Wintellect.PowerCollections; namespace nJocLogic.propNet.factory { using architecture; using data; using gameContainer; using gdl; using knowledge; using util.gdl; using util.gdl.GdlCleaner; using util.gdl.model; using util.gdl.model.assignments; /// <summary> /// A propnet factory meant to optimize the propnet before it's even built, mostly through transforming the GDL. (The /// transformations identify certain classes of rules that have poor performance and replace them with equivalent rules that /// have better performance, with performance measured by the size of the propnet.) /// /// Known issues: /// - Does not work on games with many advanced forms of recursion. These include: /// - Anything that breaks the SentenceModel /// - Multiple sentence forms which reference one another in rules /// - Not 100% confirmed to work on games where recursive rules have multiple recursive conjuncts /// - Currently runs some of the transformations multiple times. A Description object containing information about the /// description and its properties would alleviate this. /// - It does not have a way of automatically solving the "unaffected piece rule" problem. /// - Depending on the settings and the situation, the behavior of the CondensationIsolator can be either too aggressive or /// not aggressive enough. Both result in excessively large games. A more sophisticated version of the CondensationIsolator /// could solve these problems. A stopgap alternative is to try both settings and use the smaller propnet (or the first to /// be created, if multithreading). ///</summary> public class OptimizingPropNetFactory { private static readonly Logger Logger = LogManager.GetLogger("logic.propnet.factory"); private static readonly RelationNameProcessor TrueProcessor; private static readonly RelationNameProcessor DoesProcessor; private static readonly GroundFact TempFact; private static IComponentFactory _componentFactory; static OptimizingPropNetFactory() { DoesProcessor = new RelationNameProcessor("does", GameContainer.SymbolTable); TrueProcessor = new RelationNameProcessor("true", GameContainer.SymbolTable); TempFact = new GroundFact(GameContainer.SymbolTable, "temp"); } /// <summary> /// Creates a PropNet for the game with the given description. /// </summary> public static PropNet Create(IList<Expression> description, IComponentFactory componentFactory) { Console.WriteLine("Building propnet..."); _componentFactory = componentFactory; DateTime startTime = DateTime.UtcNow; description = GdlCleaner.Run(description); description = DeORer.Run(description); description = VariableConstrainer.ReplaceFunctionValuedVariables(description); description = Relationizer.Run(description); description = CondensationIsolator.Run(description); if (Logger.IsDebugEnabled) foreach (var gdl in description) Logger.Debug(gdl); //We want to start with a rule graph and follow the rule graph. Start by finding general information about the game ISentenceDomainModel model = SentenceDomainModelFactory.CreateWithCartesianDomains(description); //Restrict domains to values that could actually come up in rules. //See chinesecheckers4's "count" relation for an example of why this could be useful. model = SentenceDomainModelOptimizer.RestrictDomainsToUsefulValues(model); Logger.Debug("Setting constants..."); //TODO: ConstantChecker constantChecker = ConstantCheckerFactory.createWithForwardChaining(model); IConstantChecker constantChecker = ConstantCheckerFactory.CreateWithProver(model); Logger.Debug("Done setting constants"); HashSet<String> sentenceFormNames = SentenceForms.GetNames(model.SentenceForms); bool usingBase = sentenceFormNames.Contains("base"); bool usingInput = sentenceFormNames.Contains("input"); //For now, we're going to build this to work on those with a particular restriction on the dependency graph: //Recursive loops may only contain one sentence form. This describes most games, but not all legal games. IDictionary<ISentenceForm, ICollection<ISentenceForm>> dependencyGraph = model.DependencyGraph; Logger.Debug("Computing topological ordering... "); //ConcurrencyUtils.checkForInterruption(); IEnumerable<ISentenceForm> topologicalOrdering = GetTopologicalOrdering(model.SentenceForms, dependencyGraph, usingBase, usingInput); Logger.Debug("done"); List<TermObject> roles = GameContainer.GameInformation.GetRoles(); var components = new Dictionary<Fact, IComponent>(); var negations = new Dictionary<Fact, IComponent>(); IConstant trueComponent = _componentFactory.CreateConstant(true); IConstant falseComponent = _componentFactory.CreateConstant(false); var functionInfoMap = new Dictionary<ISentenceForm, FunctionInfo>(); var completedSentenceFormValues = new Dictionary<ISentenceForm, ICollection<Fact>>(); var sentenceFormAdder = new SentenceFormAdder(_componentFactory, DoesProcessor, TrueProcessor, TempFact); foreach (ISentenceForm form in topologicalOrdering) { //ConcurrencyUtils.checkForInterruption(); Logger.Debug("Adding sentence form " + form); if (constantChecker.IsConstantForm(form)) { Logger.Debug(" (constant)"); //Only add it if it's important if (form.Name.Equals(GameContainer.Parser.TokLegal) || form.Name.Equals(GameContainer.Parser.TokGoal) || form.Name.Equals(GameContainer.Parser.TokInit)) { //Add it foreach (Fact trueSentence in constantChecker.GetTrueSentences(form)) { var trueProp = _componentFactory.CreateProposition(trueSentence); trueProp.AddInput(trueComponent); trueComponent.AddOutput(trueProp); components[trueSentence] = trueComponent; } } Logger.Debug("Checking whether {0} is a functional constant...", form); AddConstantsToFunctionInfo(form, constantChecker, functionInfoMap); AddFormToCompletedValues(form, completedSentenceFormValues, constantChecker); continue; } Logger.Debug(string.Empty); //TODO: Adjust "recursive forms" appropriately //Add a temporary sentence form thingy? ... var temporaryComponents = new Dictionary<Fact, IComponent>(); var temporaryNegations = new Dictionary<Fact, IComponent>(); sentenceFormAdder.AddSentenceForm(form, model, components, negations, trueComponent, falseComponent, usingBase, usingInput, ImmutableHashSet.Create(form), temporaryComponents, temporaryNegations, functionInfoMap, constantChecker, completedSentenceFormValues); //TODO: Pass these over groups of multiple sentence forms if (temporaryComponents.Any()) Logger.Debug("Processing temporary components..."); ProcessTemporaryComponents(temporaryComponents, temporaryNegations, components, negations, trueComponent, falseComponent); AddFormToCompletedValues(form, completedSentenceFormValues, components); //TODO: Add this, but with the correct total number of components (not just Propositions) Console.WriteLine(" {0} components added", completedSentenceFormValues[form].Count); } //Connect "next" to "true" Logger.Debug("Adding transitions..."); AddTransitions(components); //Set up "init" proposition Logger.Debug("Setting up 'init' proposition..."); SetUpInit(components, trueComponent, falseComponent); //Now we can safely... RemoveUselessBasePropositions(components, negations, trueComponent, falseComponent); Logger.Debug("Creating component set..."); var componentSet = new HashSet<IComponent>(components.Values); CompleteComponentSet(componentSet); //ConcurrencyUtils.checkForInterruption(); Logger.Debug("Initializing propnet object..."); //Make it look the same as the PropNetFactory results, until we decide how we want it to look NormalizePropositions(componentSet); var propnet = new PropNet(roles, componentSet); Logger.Debug("Done setting up propnet; took {0}ms, has {1} components and {2} links", (DateTime.UtcNow - startTime).TotalMilliseconds, componentSet.Count, propnet.GetNumLinks()); Logger.Debug("Propnet has {0} ands; {1} ors; {2} nots", propnet.GetNumAnds(), propnet.GetNumOrs(), propnet.GetNumNots()); if (ConfigurationManager.AppSettings["OutputPropNet"] == "true") propnet.RenderToFile("propnet.dot"); return propnet; } private static void RemoveUselessBasePropositions(Dictionary<Fact, IComponent> components, Dictionary<Fact, IComponent> negations, IConstant trueComponent, IConstant falseComponent) { bool changedSomething = false; foreach (KeyValuePair<Fact, IComponent> entry in components) { if (entry.Key.RelationName == GameContainer.Parser.TokTrue) { IComponent comp = entry.Value; if (!comp.Inputs.Any()) { comp.AddInput(falseComponent); falseComponent.AddOutput(comp); changedSomething = true; } } } if (!changedSomething) return; OptimizeAwayTrueAndFalse(components, negations, trueComponent, falseComponent); } /// <summary> /// Changes the propositions contained in the propnet so that they correspond /// to the outputs of the PropNetFactory. This is for consistency and for /// backwards compatibility with respect to state machines designed for the /// old propnet factory. Feel free to remove this for your player. /// </summary> private static void NormalizePropositions(IEnumerable<IComponent> componentSet) { foreach (IComponent component in componentSet) { var prop = component as IProposition; if (prop != null && (prop.Name != null && prop.Name.RelationName == GameContainer.Parser.TokNext)) prop.Name = new GroundFact(GameContainer.SymbolTable, "anon"); } } private static void AddFormToCompletedValues(ISentenceForm form, Dictionary<ISentenceForm, ICollection<Fact>> completedSentenceFormValues, IConstantChecker constantChecker) { completedSentenceFormValues[form] = new List<Fact>(constantChecker.GetTrueSentences(form)); } private static void AddFormToCompletedValues(ISentenceForm form, IDictionary<ISentenceForm, ICollection<Fact>> completedSentenceFormValues, Dictionary<Fact, IComponent> components) { //Kind of inefficient. Could do better by collecting these as we go, //then adding them back into the CSFV map once the sentence forms are complete. //completedSentenceFormValues.put(form, new ArrayList<Fact>()); completedSentenceFormValues[form] = components.Keys.Where(form.Matches).ToList(); } private static void AddConstantsToFunctionInfo(ISentenceForm form, IConstantChecker constantChecker, IDictionary<ISentenceForm, FunctionInfo> functionInfoMap) { functionInfoMap[form] = FunctionInfoImpl.Create(form, constantChecker); } private static void ProcessTemporaryComponents(Dictionary<Fact, IComponent> temporaryComponents, IReadOnlyDictionary<Fact, IComponent> temporaryNegations, Dictionary<Fact, IComponent> components, Dictionary<Fact, IComponent> negations, IComponent trueComponent, IComponent falseComponent) { //For each component in temporary components, we want to "put it back" //into the main components section. //We also want to do optimization here... //We don't want to end up with anything following from true/false. //Everything following from a temporary component (its outputs) //should instead become an output of the actual component. //If there is no actual component generated, then the statement //is necessarily FALSE and should be replaced by the false //component. foreach (Fact sentence in temporaryComponents.Keys) { IComponent tempComp = temporaryComponents[sentence]; IComponent component; components.TryGetValue(sentence, out component); IComponent realComp = component ?? falseComponent; foreach (IComponent output in tempComp.Outputs) { //Disconnect output.RemoveInput(tempComp); //tempComp.removeOutput(output); //do at end //Connect output.AddInput(realComp); realComp.AddOutput(output); } tempComp.RemoveAllOutputs(); if (temporaryNegations.ContainsKey(sentence)) { //Should be pointing to a "not" that now gets input from realComp //Should be fine to put into negations negations[sentence] = temporaryNegations[sentence]; //If this follows true/false, will get resolved by the next set of optimizations } OptimizeAwayTrueAndFalse(components, negations, trueComponent, falseComponent); } } /// <summary> /// Components and negations may be null, if e.g. this is a post-optimization. /// TrueComponent and falseComponent are required. /// /// Doesn't actually work that way... shoot. Need something that will remove the /// component from the propnet entirely. /// </summary> private static void OptimizeAwayTrueAndFalse(Dictionary<Fact, IComponent> components, Dictionary<Fact, IComponent> negations, IComponent trueComponent, IComponent falseComponent) { while (HasNonEssentialChildren(trueComponent) || HasNonEssentialChildren(falseComponent)) { OptimizeAwayTrue(components, negations, null, trueComponent, falseComponent); OptimizeAwayFalse(components, negations, null, trueComponent, falseComponent); } } public static void OptimizeAwayTrueAndFalse(PropNet pn, IComponent trueComponent, IComponent falseComponent) { while (HasNonEssentialChildren(trueComponent) || HasNonEssentialChildren(falseComponent)) { OptimizeAwayTrue(null, null, pn, trueComponent, falseComponent); OptimizeAwayFalse(null, null, pn, trueComponent, falseComponent); } } //TODO: Create a version with just a set of components that we can share with post-optimizations private static void OptimizeAwayFalse(IDictionary<Fact, IComponent> components, Dictionary<Fact, IComponent> negations, PropNet pn, IComponent trueComponent, IComponent falseComponent) { Debug.Assert((components != null && negations != null) || pn != null); Debug.Assert((components == null && negations == null) || pn == null); foreach (IComponent output in falseComponent.Outputs.ToList()) { if (IsEssentialProposition(output) || output is ITransition) { //Since this is the false constant, there are a few "essential" types we don't actually want to keep around. if (!IsLegalOrGoalProposition(output)) continue; } var prop = output as IProposition; if (prop != null) { //Move its outputs to be outputs of false foreach (IComponent child in prop.Outputs) { //Disconnect child.RemoveInput(prop); //output.removeOutput(child); //do at end //Reconnect; will get children before returning, if nonessential falseComponent.AddOutput(child); child.AddInput(falseComponent); } prop.RemoveAllOutputs(); if (!IsEssentialProposition(prop)) { //Remove the proposition entirely falseComponent.RemoveOutput(prop); output.RemoveInput(falseComponent); //Update its location to the trueComponent in our map if (components != null) { components[prop.Name] = falseComponent; negations[prop.Name] = trueComponent; } else pn.RemoveComponent(prop); } } else { var and = output as IAnd; if (and != null) { //Attach children of and to falseComponent foreach (IComponent child in and.Outputs) { child.AddInput(falseComponent); falseComponent.AddOutput(child); child.RemoveInput(and); } //Disconnect and completely and.RemoveAllOutputs(); foreach (IComponent parent in and.Inputs) parent.RemoveOutput(and); and.RemoveAllInputs(); if (pn != null) pn.RemoveComponent(and); } else { var or = output as IOr; if (or != null) { //Remove as input from or or.RemoveInput(falseComponent); falseComponent.RemoveOutput(or); //If or has only one input, remove it if (or.Inputs.Count == 1) { IComponent input = or.GetSingleInput(); or.RemoveInput(input); input.RemoveOutput(or); foreach (IComponent output1 in or.Outputs) { //Disconnect from and output1.RemoveInput(or); //or.removeOutput(out); //do at end //Connect directly to the new input output1.AddInput(input); input.AddOutput(output1); } or.RemoveAllOutputs(); if (pn != null) { pn.RemoveComponent(or); } } else if (!or.Inputs.Any()) { if (pn != null) { pn.RemoveComponent(or); } } } else { var not = output as INot; if (not != null) { //Disconnect from falseComponent not.RemoveInput(falseComponent); falseComponent.RemoveOutput(not); //Connect all children of the not to trueComponent foreach (IComponent child in not.Outputs) { //Disconnect child.RemoveInput(not); //not.removeOutput(child); //Do at end //Connect to trueComponent child.AddInput(trueComponent); trueComponent.AddOutput(child); } not.RemoveAllOutputs(); if (pn != null) pn.RemoveComponent(not); } else if (output is ITransition) { //??? throw new Exception("Fix optimizeAwayFalse's case for Transitions"); } } } } } } private static bool IsLegalOrGoalProposition(IComponent comp) { var prop = comp as IProposition; if (prop == null) return false; return prop.Name.RelationName == GameContainer.Parser.TokLegal || prop.Name.RelationName == GameContainer.Parser.TokGoal; } private static void OptimizeAwayTrue(IDictionary<Fact, IComponent> components, IDictionary<Fact, IComponent> negations, PropNet pn, IComponent trueComponent, IComponent falseComponent) { Debug.Assert((components != null && negations != null) || pn != null); foreach (IComponent output in trueComponent.Outputs.ToList()) { if (IsEssentialProposition(output) || output is ITransition) continue; var prop = output as IProposition; if (prop != null) { //Move its outputs to be outputs of true foreach (IComponent child in prop.Outputs) { //Disconnect child.RemoveInput(prop); //output.removeOutput(child); //do at end //Reconnect; will get children before returning, if nonessential trueComponent.AddOutput(child); child.AddInput(trueComponent); } prop.RemoveAllOutputs(); if (!IsEssentialProposition(prop)) { //Remove the proposition entirely trueComponent.RemoveOutput(prop); output.RemoveInput(trueComponent); //Update its location to the trueComponent in our map if (components != null) { components[prop.Name] = trueComponent; Debug.Assert(negations != null, "negations != null"); negations[prop.Name] = falseComponent; } else pn.RemoveComponent(prop); } } else { var or = output as IOr; if (or != null) { //Attach children of or to trueComponent foreach (IComponent child in or.Outputs) { child.AddInput(trueComponent); trueComponent.AddOutput(child); child.RemoveInput(or); } //Disconnect or completely or.RemoveAllOutputs(); foreach (IComponent parent in or.Inputs) parent.RemoveOutput(or); or.RemoveAllInputs(); if (pn != null) pn.RemoveComponent(or); } else { var and = output as IAnd; if (and != null) { //Remove as input from and and.RemoveInput(trueComponent); trueComponent.RemoveOutput(and); //If and has only one input, remove it if (and.Inputs.Count == 1) { IComponent input = and.GetSingleInput(); and.RemoveInput(input); input.RemoveOutput(and); foreach (IComponent output1 in and.Outputs) { //Disconnect from and output1.RemoveInput(and); //and.removeOutput(out); //do at end //Connect directly to the new input output1.AddInput(input); input.AddOutput(output1); } and.RemoveAllOutputs(); if (pn != null) pn.RemoveComponent(and); } else if (and.Inputs.Any()) if (pn != null) pn.RemoveComponent(and); } else { var not = output as INot; if (not != null) { //Disconnect from trueComponent not.RemoveInput(trueComponent); trueComponent.RemoveOutput(not); //Connect all children of the not to falseComponent foreach (IComponent child in not.Outputs) { //Disconnect child.RemoveInput(not); //not.removeOutput(child); //Do at end //Connect to falseComponent child.AddInput(falseComponent); falseComponent.AddOutput(child); } not.RemoveAllOutputs(); if (pn != null) pn.RemoveComponent(not); } } } } } } private static bool HasNonEssentialChildren(IComponent trueComponent) { IEnumerable<IComponent> nonTransitions = trueComponent.Outputs.Where(child => !(child is ITransition)); foreach (IComponent child in nonTransitions) { if (!IsEssentialProposition(child)) return true; //We don't want any grandchildren, either if (child.Outputs.Any()) return true; } return false; } private static bool IsEssentialProposition(IComponent component) { if (!(component is IProposition)) return false; //We're looking for things that would be outputs of "true" or "false", //but we would still want to keep as propositions to be read by the //state machine var prop = (IProposition)component; var name = prop.Name.RelationName; //return name.Equals(LEGAL) /*|| name.Equals(NEXT)*/ || name.Equals(GOAL)|| name.Equals(INIT) || name.Equals(TERMINAL); Parser parser = GameContainer.Parser; return name == parser.TokLegal || name == parser.TokGoal || name == parser.TokInit || name == parser.TokTerminal; } private static void CompleteComponentSet(ISet<IComponent> componentSet) { var newComponents = new HashSet<IComponent>(); var componentsToTry = new HashSet<IComponent>(componentSet); while (componentsToTry.Any()) { foreach (IComponent c in componentsToTry) { IEnumerable<IComponent> outputsNotInSet = c.Outputs.Where(output => !componentSet.Contains(output)); foreach (IComponent output in outputsNotInSet) newComponents.Add(output); IEnumerable<IComponent> inputsNotInSet = c.Inputs.Where(input => !componentSet.Contains(input)); foreach (IComponent input in inputsNotInSet) newComponents.Add(input); } foreach (var comp in newComponents) componentSet.Add(comp); componentsToTry = newComponents; newComponents = new HashSet<IComponent>(); } } private static void AddTransitions(IReadOnlyDictionary<Fact, IComponent> components) { foreach (KeyValuePair<Fact, IComponent> entry in components) { Fact sentence = entry.Key; if (sentence.RelationName == GameContainer.Parser.TokNext) { //connect to true Fact trueSentence = TrueProcessor.ProcessBaseFact(sentence); IComponent nextComponent = entry.Value; IComponent trueComponent; //There might be no true component (for example, because the bases //told us so). If that's the case, don't have a transition. if (!components.TryGetValue(trueSentence, out trueComponent)) // Skipping transition to supposedly impossible 'trueSentence' continue; var transition = _componentFactory.CreateTransition(); transition.AddInput(nextComponent); nextComponent.AddOutput(transition); transition.AddOutput(trueComponent); trueComponent.AddInput(transition); } } } //TODO: Replace with version using constantChecker only //TODO: This can give problematic results if interpreted in //the standard way (see test_case_3d) private static void SetUpInit(IDictionary<Fact, IComponent> components, IConstant trueComponent, IConstant falseComponent) { var initProposition = _componentFactory.CreateProposition(new GroundFact(GameContainer.SymbolTable["INIT"])); IEnumerable<KeyValuePair<Fact, IComponent>> trueComponents = components.Where(entry => entry.Value == trueComponent); IEnumerable<KeyValuePair<Fact, IComponent>> trueInits = trueComponents.Where(entry => entry.Key.RelationName == GameContainer.Parser.TokInit); IEnumerable<Fact> trueInitFacts = trueInits.Select(entry => TrueProcessor.ProcessBaseFact(entry.Key)); IEnumerable<IComponent> initTrueSentenceComponents = trueInitFacts.Select(trueSentence => components[trueSentence]); foreach (IComponent trueSentenceComponent in initTrueSentenceComponents) { if (!trueSentenceComponent.Inputs.Any()) { //Case where there is no transition input //Add the transition input, connect to init, continue loop var transition = _componentFactory.CreateTransition(); //init goes into transition transition.AddInput(initProposition); initProposition.AddOutput(transition); //transition goes into component trueSentenceComponent.AddInput(transition); transition.AddOutput(trueSentenceComponent); } else { //The transition already exists IComponent transition = trueSentenceComponent.GetSingleInput(); //We want to add init as a thing that precedes the transition //Disconnect existing input IComponent input = transition.GetSingleInput(); //input and init go into or, or goes into transition input.RemoveOutput(transition); transition.RemoveInput(input); var orInputs = new List<IComponent>(2) { input, initProposition }; Orify(orInputs, transition, falseComponent); } } } /// <summary> /// Adds an or gate connecting the inputs to produce the output. /// Handles special optimization cases like a true/false input. /// </summary> private static void Orify(ICollection<IComponent> inputs, IComponent output, IConstant falseProp) { //TODO: Look for already-existing ors with the same inputs? //Or can this be handled with a GDL transformation? //Special case: An input is the true constant IEnumerable<IComponent> trueConstants = inputs.Where(input => input is IConstant && input.Value); foreach (IComponent input in trueConstants) { //True constant: connect that to the component, done input.AddOutput(output); output.AddInput(input); return; } //Special case: An input is "or" //I'm honestly not sure how to handle special cases here... //What if that "or" gate has multiple outputs? Could that happen? //For reals... just skip over any false constants var or = _componentFactory.CreateOr(); IEnumerable<IComponent> nonConstants = inputs.Where(input => !(input is IConstant)); foreach (IComponent input in nonConstants) { input.AddOutput(or); or.AddInput(input); } //What if they're all false? (Or inputs is empty?) Then no inputs at this point... if (!or.Inputs.Any()) { //Hook up to "false" falseProp.AddOutput(output); output.AddInput(falseProp); return; } //If there's just one, on the other hand, don't use the or gate if (or.Inputs.Count == 1) { IComponent input = or.GetSingleInput(); input.RemoveOutput(or); or.RemoveInput(input); input.AddOutput(output); output.AddInput(input); return; } or.AddOutput(output); output.AddInput(or); } //TODO: This code is currently used by multiple classes, so perhaps it should be //factored out into the SentenceModel. private static IEnumerable<ISentenceForm> GetTopologicalOrdering( ICollection<ISentenceForm> forms, IDictionary<ISentenceForm, ICollection<ISentenceForm>> dependencyGraph, bool usingBase, bool usingInput) { //We want each form as a key of the dependency graph to //follow all the forms in the dependency graph, except maybe itself var queue = new Queue<ISentenceForm>(forms); var ordering = new List<ISentenceForm>(forms.Count); var alreadyOrdered = new HashSet<ISentenceForm>(); while (queue.Any()) { ISentenceForm curForm = queue.Dequeue(); bool readyToAdd = !(dependencyGraph.ContainsKey(curForm) && dependencyGraph[curForm].Any(d => !d.Equals(curForm) && !alreadyOrdered.Contains(d))); //Don't add if there are dependencies //Don't add if it's true/next/legal/does and we're waiting for base/input if (usingBase && (curForm.Name.Equals(GameContainer.Parser.TokTrue) || curForm.Name.Equals(GameContainer.Parser.TokNext) || curForm.Name.Equals(GameContainer.Parser.TokInit))) { //Have we added the corresponding base sf yet? ISentenceForm baseForm = curForm.WithName(GameContainer.SymbolTable["base"]); if (!alreadyOrdered.Contains(baseForm)) readyToAdd = false; } if (usingInput && (curForm.Name.Equals(GameContainer.Parser.TokDoes) || curForm.Name.Equals(GameContainer.Parser.TokLegal))) { ISentenceForm inputForm = curForm.WithName(GameContainer.SymbolTable["input"]); if (!alreadyOrdered.Contains(inputForm)) readyToAdd = false; } //Add it if (readyToAdd) { ordering.Add(curForm); alreadyOrdered.Add(curForm); } else queue.Enqueue(curForm); //TODO: Add check for an infinite loop here, or stratify loops //ConcurrencyUtils.checkForInterruption(); } return ordering; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function LeapToy::initializeInput( %this ) { // General toy action map new ActionMap(ToyMap); // Gesture action map for sandbox new ActionMap(GestureMap); // Absolute palm rotation/pos action map for breakout game new ActionMap(BreakoutMap); // Absolute finger positioning for finger demo new ActionMap(FingerMap); // action map for the builder demo game new ActionMap(BuilderMap); // Create keyboard bindings ToyMap.bindObj(keyboard, tab, toggleCursorMode, %this); ToyMap.bindObj(keyboard, escape, showToolBox, %this); // Help text binding ToyMap.bindObj(keyboard, h, toggleHelpTextScene, %this); // Debugging keybinds ToyMap.bindObj(keyboard, space, simulateCircle, %this); ToyMap.bindObj(keyboard, x, simulateKeytap, %this); ToyMap.bindObj(keyboard, z, showParticle, %this); ToyMap.bindObj(keyboard, a, movePaddleLeft, %this); ToyMap.bindObj(keyboard, d, movePaddleRight, %this); // Create Leap Motion gesture bindings GestureMap.bindObj(leapdevice, circleGesture, reactToCircleGesture, %this); GestureMap.bindObj(leapdevice, screenTapGesture, reactToScreenTapGesture, %this); GestureMap.bindObj(leapdevice, swipeGesture, reactToSwipeGesture, %this); GestureMap.bindObj(leapdevice, keyTapGesture, reactToKeyTapGesture, %this); // Create the Leap Motion hand/finger bindings BreakoutMap.bindObj(leapdevice, leapHandRot, "D", %this.handRotDeadzone, trackHandRotation, %this); FingerMap.bindObj(leapdevice, leapFingerPos, trackFingerPos, %this); // Create Leap Motion Builder Demo bindings BuilderMap.bindObj(leapdevice, circleGesture, reactToCircleBuilder, %this); BuilderMap.bindObj(leapdevice, screenTapGesture, reactToScreenTapBuilder, %this); BuilderMap.bindObj(leapdevice, swipeGesture, reactToSwipeBuilder, %this); BuilderMap.bindObj(leapdevice, keyTapGesture, reactToKeyTapBuilder, %this); BuilderMap.bindObj(leapdevice, leapFingerPos, trackFingerPosBuilder, %this); // Push the LeapMap to the stack, making it active ToyMap.push(); // Initialize the Leap Motion manager initLeapMotionManager(); enableLeapMotionManager(true); enableLeapCursorControl(true); configureLeapGesture("Gesture.Circle.MinProgress", 1); configureLeapGesture("Gesture.ScreenTap.MinForwardVelocity", 0.1); configureLeapGesture("Gesture.ScreenTap.MinDistance", 0.1); configureLeapGesture("Gesture.KeyTap.MinDownVelocity", 20); configureLeapGesture("Gesture.KeyTap.MinDistance", 1.0); } //----------------------------------------------------------------------------- function LeapToy::destroyInput(%this) { FingerMap.pop(); FingerMap.delete(); BreakoutMap.pop(); BreakoutMap.delete(); GestureMap.pop(); GestureMap.delete(); ToyMap.pop(); ToyMap.delete(); BuilderMap.pop(); BuilderMap.delete(); } //----------------------------------------------------------------------------- // Called when the user makes a circle with their finger(s) // // %id - Finger ID, based on the order the finger was added to the tracking // %progress - How much of the circle has been completed // %radius - Radius of the circle created by the user's motion // %isClockwise - Toggle based on the direction the user made the circle // %state - State of the gesture progress: 1: Started, 2: Updated, 3: Stopped function LeapToy::reactToCircleGesture(%this, %id, %progress, %radius, %isClockwise, %state) { if (!%this.enableCircleGesture) return; if (%progress > 0 && %state == 3) { %this.grabObjectsInCircle(); %this.schedule(300, "hideCircleSprite"); } else if (%progress > 0 && %state != 3) { %this.showCircleSprite(%radius/5, %isClockwise); } } //----------------------------------------------------------------------------- // Called when the user makes a swipe with their finger(s) // // %id - Finger ID, based on the order the finger was added to the tracking // %state - State of the gesture progress: 1: Started, 2: Updated, 3: Stopped // %direction - 3 point vector based on the direction the finger swiped // %speed - How fast the user's finger moved. Values will be quite large function LeapToy::reactToSwipeGesture(%this, %id, %state, %direction, %speed) { if (!%this.enableSwipeGesture) return; %worldPosition = SandboxWindow.getWorldPoint(Canvas.getCursorPos()); if (isLeapCursorControlled()) %worldPosition = "0 0"; %this.createAsteroid(%worldPosition, %direction, %speed); } //----------------------------------------------------------------------------- // Called when the user makes a screen tap gesture with their finger(s) // // %id - Finger ID, based on the order the finger was added to the tracking // %position - 3 point vector based on where the finger was located in "Leap Space" // %direction - 3 point vector based on the direction the finger motion function LeapToy::reactToScreenTapGesture(%this, %id, %position, %direction) { if (!%this.enableScreenTapGesture) return; %control = Canvas.getMouseControl(); %control.performClick(); } //----------------------------------------------------------------------------- // Called when the user makes a key tap gesture with their finger(s) // // %id - Finger ID, based on the order the finger was added to the tracking // %position - 3 point vector based on where the finger was located in "Leap Space" // %direction - 3 point vector based on the direction the finger tap function LeapToy::reactToKeyTapGesture(%this, %id, %position, %direction) { if (!%this.enableKeyTapGesture) return; %this.deleteSelectedObjects(); } //----------------------------------------------------------------------------- // Constantly polling callback based on the palm position of a hand // // %id - Ordered hand ID based on when it was added to the tracking device // %position - 3 point vector based on where the hand is located in "Leap Space" function LeapToy::trackHandPosition(%this, %id, %position) { echo("Hand " @ %id @ " - x:" SPC %position._0 SPC "y:" SPC %position._1 SPC "z:" SPC %position._2); } //----------------------------------------------------------------------------- // Constantly polling callback based on the palm rotation of a hand // // %id - Ordered hand ID based on when it was added to the tracking device // %rotation - 3 point vector based on the hand's rotation: "yaw pitch roll" function LeapToy::trackHandRotation(%this, %id, %rotation) { if (isLeapCursorControlled() || !%this.enableHandRotation) return; // Grab the values. Only going to use roll in this demo %roll = %rotation._2; %this.movePaddle(%roll*-1); } //----------------------------------------------------------------------------- // Constantly polling callback based on the finger position on a hand // %id - Ordered hand ID based on when it was added to the tracking device // %position - 3 point vector based on where the finger is located in "Leap Space" function LeapToy::trackFingerPos(%this, %ids, %fingersX, %fingersY, %fingersZ) { if (!%this.enableFingerTracking) return; for(%i = 0; %i < getWordCount(%ids); %i++) { %id = getWord(%ids, %i); %position = getWord(%fingersX, %i) SPC getWord(%fingersY, %i) SPC getWord(%fingersZ, %i); %screenPosition = getPointFromProjection(%position); //%screenPosition = getPointFromIntersection(%id); %worldPosition = SandboxWindow.getWorldPoint(%screenPosition); %this.showFingerCircle(%id, %worldPosition); } } //----------------------------------------------------------------------------- // Flips a switch to activate/deactivate cursor control by the Leap Motion Manager function LeapToy::toggleCursorMode( %this, %val ) { if (!%val) return; if (isLeapCursorControlled()) enableLeapCursorControl(false); else enableLeapCursorControl(true); } //----------------------------------------------------------------------------- // Shows the Sandbox tool box function LeapToy::showToolBox( %this, %val ) { if (%val) toggleToolbox(true); } //----------------------------------------------------------------------------- // DEBUGGING FUNCTIONS function LeapToy::simulateCircle( %this, %val) { if (%val) { %this.grabObjectsInCircle(2); } } function LeapToy::simulateKeyTap( %this, %val ) { if (%val) { %this.deleteSelectedObjects(); } } function LeapToy::showParticle(%this) { %worldPosition = SandboxWindow.getWorldPoint(Canvas.getCursorPos()); %particlePlayer = new ParticlePlayer(); %particlePlayer.BodyType = static; %particlePlayer.SetPosition( %worldPosition ); %particlePlayer.SceneLayer = 0; %particlePlayer.ParticleInterpolation = true; %particlePlayer.Particle = "LeapToy:blockFadeParticle"; %particlePlayer.SizeScale = 1; SandboxScene.add( %particlePlayer ); %particlePlayer.setLifeTime(3); } function LeapToy::movePaddleLeft(%this, %val) { if (%val) { %this.paddle.setLinearVelocity(%this.PaddleSpeed*-1, 0); } else { %this.paddle.setLinearVelocity(0, 0); } } function LeapToy::movePaddleRight(%this, %val) { if (%val) { %this.paddle.setLinearVelocity(%this.PaddleSpeed, 0); } else { %this.paddle.setLinearVelocity(0, 0); } } function LeapToy::simulateFingerPositions(%this) { %numFingers = getRandom(0, 9); setRandomSeed(-1); %randomPosition = getRandom(-10, 10) SPC getRandom(-10, 10); for (%i = 0; %i < %numFingers; %i++) { %this.showFingerCircle(%i, %randomPosition); } } // DEBUGGING FUNCTIONS //-----------------------------------------------------------------------------
using System; using System.Collections.Generic; using System.Data; using System.Xml.Serialization; using MetX.Standard.Library.Extensions; using XLG.Pipeliner.Providers; // ReSharper disable NotAccessedField.Global // ReSharper disable UnassignedField.Global namespace XLG.Pipeliner.Data { /// <summary>C#CD: </summary> [Serializable] public class TableSchema { /// <summary> /// Holds information about the base table - this class should be /// static for each object /// </summary> [Serializable] public class Table { public TableColumnCollection Columns = new(); /// <summary>The field list as it goes into the SELECT sql statement used for Select, Count, Exists and paging type queries</summary> public string FieldList; public TableIndexCollection Indexes = new(); /// <summary>The basic INSERT INTO sql statement used for Insert type queries</summary> public string InsertSql; public DataProvider Instance; public TableKeyCollection Keys = new(); public string Name; public string Schema; /// <summary>The basic UPDATE sql statement used for Update type query</summary> public string UpdateSql; /// <summary>C#CD: </summary> public Table() { } /// <summary>C#CD: </summary> /// <param name="tableName">C#CD: </param> /// <param name="schemaName"></param> public Table(string tableName, string schemaName) { Name = tableName; Schema = schemaName; } public string FullName { get { if (string.IsNullOrEmpty(Schema)) Schema = "dbo"; return "[" + Schema + "].[" + Name + "]"; } } public TableColumn PrimaryKey => Columns?.GetPrimaryKey(); /// <summary>The basic SELECT sql statement used for Select, Count, Exists and paging type queries</summary> public string FromClause => Schema.IsEmpty() ? " FROM [" + Name + "] " : " FROM [" + Schema + "].[" + Name + "] "; public string SelectSql => "SELECT " + FieldList + FromClause; public string CountSql => "SELECT COUNT(*) " + FromClause; } /// <summary> /// A helper class to help define the columns in an underlying table /// </summary> [Serializable] public class TableColumn { public bool AutoIncrement; public string ColumnName; public string Description; public DbType DataType; public string DomainName; public bool IsForeignKey; public bool IsIdentity; public bool IsIndexed; public bool IsNullable; public bool IsPrimaryKey; public int MaxLength; public int Precision; public int Scale; public string SourceType; /// <summary>C#CD: </summary> public TableColumn() { } /// <summary>C#CD: </summary> /// <param name="columnName">C#CD: </param> /// <param name="dbType">C#CD: </param> /// <param name="isPrimaryKey">C#CD: </param> /// <param name="isForeignKey">C#CD: </param> public TableColumn(string columnName, DbType dbType, bool isPrimaryKey, bool isForeignKey) { ColumnName = columnName; IsPrimaryKey = isPrimaryKey; IsForeignKey = isForeignKey; DataType = dbType; } public TableColumn(string columnName, DbType dbType, bool autoIncrement, int maxLength, bool isNullable, bool isPrimaryKey, bool isForeignKey) { ColumnName = columnName; IsPrimaryKey = isPrimaryKey; IsForeignKey = isForeignKey; DataType = dbType; AutoIncrement = autoIncrement; MaxLength = maxLength; IsNullable = isNullable; } } /// <summary>C#CD: </summary> [Serializable] public class TableColumnCollection : List<TableColumn> { public TableColumn PrimaryKeyColumn; private Dictionary<string, TableColumn> _iList = new(); #region Collection Methods public new void Add(TableColumn column) { _iList.Add(column.ColumnName.ToLower(), column); base.Add(column); } /// <summary>C#CD: </summary> /// <param name="name">C#CD: </param> /// <param name="dbType">C#CD: </param> /// <param name="isNullable">C#CD: </param> /// <param name="isPrimaryKey">C#CD: </param> /// <param name="isForeignKey">C#CD: </param> public void Add(string name, DbType dbType, bool isNullable, bool isPrimaryKey, bool isForeignKey) { var col = new TableColumn { IsPrimaryKey = isPrimaryKey, IsForeignKey = isForeignKey, IsNullable = isNullable, DataType = dbType, ColumnName = name }; if (!Contains(name)) { Add(col); _iList.Add(name.ToLower(), col); } if (isPrimaryKey) PrimaryKeyColumn = col; } /// <summary>C#CD: </summary> /// <param name="name">C#CD: </param> /// <param name="dbType">C#CD: </param> /// <param name="isNullable">C#CD: </param> public void Add(string name, DbType dbType, bool isNullable) { // ReSharper disable once IntroduceOptionalParameters.Global Add(name, dbType, isNullable, false, false); } public bool Contains(string columnName) { return _iList.ContainsKey(columnName.ToLower()); } #endregion Collection Methods /// <summary>C#CD: </summary> /// <param name="columnName">C#CD: </param> public TableColumn GetColumn(string columnName) { columnName = columnName.ToLower(); if (_iList.ContainsKey(columnName)) return _iList[columnName]; return null; } /// <summary>C#CD: </summary> public TableColumn GetPrimaryKey() { if (PrimaryKeyColumn != null) return PrimaryKeyColumn; TableColumn coll = null; foreach (var child in this) { if (child.IsPrimaryKey) { coll = child; break; } } PrimaryKeyColumn = this[0]; return coll; } } /// <summary> /// This is an intermediary class that holds the current value of a table column /// for each object instance. /// </summary> [Serializable] public class TableColumnSetting { /// <summary>C#CD: </summary> private string _columnName; /// <summary>C#CD: </summary> private object _currentValue; /// <summary>C#CD: </summary> public string ColumnName { get => _columnName; set => _columnName = value; } /// <summary>C#CD: </summary> public object CurrentValue { get => _currentValue; set { if (value is int intValue && intValue == int.MinValue) _currentValue = DBNull.Value; else if (value is DateTime dateValue && dateValue == DateTime.MinValue) _currentValue = DBNull.Value; else _currentValue = value; } } } /// <summary>C#CD: </summary> [Serializable] public class TableColumnSettingCollection : Dictionary<string, TableColumnSetting> { /// <summary>C#CD: </summary> /// <param name="columnName">C#CD: </param> /// <returns>C#CD: </returns> public object GetValue(string columnName) { columnName = columnName.ToLower(); if (ContainsKey(columnName)) return this[columnName].CurrentValue; return null; } /// <summary>C#CD: </summary> /// <param name="columnName">C#CD: </param> /// <param name="oVal">C#CD: </param> public void SetValue(string columnName, object oVal) { columnName = columnName.ToLower(); if (!ContainsKey(columnName)) { var setting = new TableColumnSetting {ColumnName = columnName, CurrentValue = oVal}; Add(columnName.ToLower(), setting); } else { this[columnName].CurrentValue = oVal; } } private bool Contains(string columnName) { return ContainsKey(columnName.ToLower()); } } [Serializable] public class TableIndex { public List<string> Columns = new(); public bool IsClustered; public string Name; public TableIndex() { } public TableIndex(IDataReader rdr) { Name = rdr["name"].ToString(); IsClustered = rdr["isclustered"].ToString() == "1"; Columns.Add(rdr["column"].ToString()); } } [Serializable] public class TableIndexCollection : List<TableIndex> { } [Serializable] public class TableKey { [XmlArray(ElementName = "Columns")] [XmlArrayItem(typeof(TableKeyColumn), ElementName = "Column")] public List<TableKeyColumn> Columns = new(); public bool IsForeign; public bool IsPrimary; public bool IsReference; public string Name; } [Serializable] public class TableKeyCollection : List<TableKey> { public TableKey Find(string toFind) { foreach (var currKey in this) if (currKey.Name.ToLower() == toFind.ToLower()) return currKey; return null; } } [Serializable] public class TableKeyColumn { public string Column; public string Related; public TableKeyColumn() { } public TableKeyColumn(string column, string related) { Column = column; Related = related; } } } }
// Copyright 2016 Tom Deseyn <tom.deseyn@gmail.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Tmds.DBus.Protocol; namespace Tmds.DBus.CodeGen { internal class DBusAdapter { internal delegate Task<Message> MethodCallHandler(object o, Message methodCall, IProxyFactory factory); private enum State { Registering, Registered, Unregistered } private readonly object _gate = new object(); private readonly DBusConnection _connection; private readonly IProxyFactory _factory; private readonly ObjectPath _objectPath; private readonly SynchronizationContext _synchronizationContext; protected internal string _typeIntrospection; protected internal readonly Dictionary<string, MethodCallHandler> _methodHandlers; protected internal readonly object _object; private State _state; private List<IDisposable> _signalWatchers; protected DBusAdapter(DBusConnection connection, ObjectPath objectPath, object o, IProxyFactory factory, SynchronizationContext synchronizationContext) { _connection = connection; _objectPath = objectPath; _object = o; _state = State.Registering; _factory = factory; _synchronizationContext = synchronizationContext; _methodHandlers = new Dictionary<string, MethodCallHandler>(); _methodHandlers.Add(GetMethodLookupKey("org.freedesktop.DBus.Introspectable", "Introspect", null), HandleIntrospect); } public ObjectPath Path => _objectPath; public void Unregister() { lock (_gate) { if (_state == State.Unregistered) { return; } _state = State.Unregistered; if (_signalWatchers != null) { foreach (var disposable in _signalWatchers) { disposable.Dispose(); } _signalWatchers = null; } } } public void CompleteRegistration() { lock (_gate) { if (_state == State.Registering) { _state = State.Registered; } else if (_state == State.Unregistered) { throw new InvalidOperationException("The object has been unregistered"); } else if (_state == State.Registered) { throw new InvalidOperationException("The object has already been registered"); } } } public async Task WatchSignalsAsync() { var tasks = StartWatchingSignals(); IEnumerable<IDisposable> signalDisposables = null; try { await Task.WhenAll(tasks).ConfigureAwait(false); signalDisposables = tasks.Select(task => task.Result); if (signalDisposables.Contains(null)) { throw new InvalidOperationException("One or more Watch-methods returned a null IDisposable"); } } catch { foreach (var task in tasks) { try { var disposable = await task.ConfigureAwait(false); disposable?.Dispose(); } finally { } } throw; } lock (_gate) { if (_state == State.Registering) { _signalWatchers = new List<IDisposable>(); _signalWatchers.AddRange(signalDisposables); } else if (_state == State.Unregistered) { foreach (var disposable in signalDisposables) { disposable.Dispose(); } } } } static protected internal string GetMethodLookupKey(string iface, string member, Signature? signature) { return $"{iface}.{member}.{signature?.Value}"; } static protected internal string GetPropertyLookupKey(string iface, string member, Signature? signature) { return $"org.freedesktop.DBus.Properties.{iface}.{member}.{signature?.Value}"; } static protected internal string GetPropertyAddKey(string iface, string member, Signature? signature) { return $"org.freedesktop.DBus.Properties.{iface}.{member}.s{signature?.Value}"; } public async Task<Message> HandleMethodCall(Message methodCall) { var key = GetMethodLookupKey(methodCall.Header.Interface, methodCall.Header.Member, methodCall.Header.Signature); MethodCallHandler handler = null; if (!_methodHandlers.TryGetValue(key, out handler)) { if (methodCall.Header.Interface == "org.freedesktop.DBus.Properties") { MessageReader reader = new MessageReader(methodCall, null); var interf = reader.ReadString(); key = GetPropertyLookupKey(interf, methodCall.Header.Member, methodCall.Header.Signature); _methodHandlers.TryGetValue(key, out handler); } } if (handler != null) { if (_synchronizationContext == null) { try { return await handler(_object, methodCall, _factory).ConfigureAwait(false); } catch (DBusException be) { return MessageHelper.ConstructErrorReply(methodCall, be.ErrorName, be.ErrorMessage); } catch (Exception e) { return MessageHelper.ConstructErrorReply(methodCall, e.GetType().FullName, e.Message); } } else { var tcs = new TaskCompletionSource<Message>(); _synchronizationContext.Post(async _ => { Message reply; try { reply = await handler(_object, methodCall, _factory).ConfigureAwait(false); } catch (DBusException be) { reply = MessageHelper.ConstructErrorReply(methodCall, be.ErrorName, be.ErrorMessage); } catch (Exception e) { reply = MessageHelper.ConstructErrorReply(methodCall, e.GetType().FullName, e.Message); } tcs.SetResult(reply); }, null); return await tcs.Task.ConfigureAwait(false); } } else { var errorMessage = String.Format("Method \"{0}\" with signature \"{1}\" on interface \"{2}\" doesn't exist", methodCall.Header.Member, methodCall.Header.Signature?.Value, methodCall.Header.Interface); var replyMessage = MessageHelper.ConstructErrorReply(methodCall, "org.freedesktop.DBus.Error.UnknownMethod", errorMessage); return replyMessage; } } protected internal virtual Task<IDisposable>[] StartWatchingSignals() { return Array.Empty<Task<IDisposable>>(); } protected internal void EmitVoidSignal(string interfaceName, string signalName) { EmitNonVoidSignal(interfaceName, signalName, null, null); } protected internal void EmitNonVoidSignal(string iface, string member, Signature? inSigStr, MessageWriter writer) { if (!IsRegistered) { return; } Message signalMsg = new Message( new Header(MessageType.Signal) { Path = _objectPath, Interface = iface, Member = member, Signature = inSigStr }, writer?.ToArray(), writer?.UnixFds ); _connection.EmitSignal(signalMsg); } protected internal async Task<Message> CreateNonVoidReply<T>(Message methodCall, Task<T> resultTask, Action<MessageWriter, T> writeResult, Signature? outSignature) { uint serial = methodCall.Header.Serial; T result = await resultTask.ConfigureAwait(false); MessageWriter retWriter = new MessageWriter(); writeResult(retWriter, result); Message replyMsg = new Message( new Header(MessageType.MethodReturn) { Signature = outSignature }, retWriter.ToArray(), retWriter.UnixFds ); return replyMsg; } protected internal async Task<Message> CreateVoidReply(Message methodCall, Task task) { uint serial = methodCall.Header.Serial; await task.ConfigureAwait(false); var replyMsg = new Message( new Header(MessageType.MethodReturn), body: null, unixFds: null ); return replyMsg; } private Task<Message> HandleIntrospect(object o, Message methodCall, IProxyFactory factory) { IntrospectionWriter writer = new IntrospectionWriter(); writer.WriteDocType(); writer.WriteNodeStart(_objectPath.Value); writer.WriteLiteral(_typeIntrospection); foreach (var child in _connection.GetChildNames(_objectPath)) { writer.WriteChildNode(child); } writer.WriteNodeEnd(); var xml = writer.ToString(); var response = MessageHelper.ConstructReply(methodCall, xml); return Task.FromResult(response); } private bool IsRegistered { get { lock (_gate) { return _state == State.Registered; } } } } }
// The MIT License // // Copyright (c) 2012-2015 Jordan E. Terrell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; namespace iSynaptic.Commons.Collections.Generic { public class SmartLoop<T> { private readonly List<T> _Items; private Func<T, bool> _IgnorePredicate; private List<T> _IgnoreItems; private Action<List<T>, T> _Action; private Action<IEnumerable<T>> _BeforeAllAction; private Action<IEnumerable<T>> _AfterAllAction; private Action<T, T> _BetweenAction; private Action _NoneAction; public SmartLoop(IEnumerable<T> items) { _Items = Guard.NotNull(items, "items").ToList(); } public SmartLoop<T> Each(Action<T> action) { Guard.NotNull(action, "action"); _Action = Concat(_Action, (l, x) => action(x)); return this; } public SmartLoop<T> OnlyOne(Action<T> action) { Guard.NotNull(action, "action"); _Action = Concat(_Action, (l, x) => { if (l.Count == 1) action(x); }); return this; } public SmartLoop<T> MoreThanOne(Action<T> action) { Guard.NotNull(action, "action"); _Action = Concat(_Action, (l, x) => { if (l.Count > 1) action(x); }); return this; } public SmartLoop<T> Ignore(params T[] items) { Guard.NotNullOrEmpty(items, "items"); IgnoreItems.AddRange(items); return this; } public SmartLoop<T> Ignore(Func<T, bool> ignorePredicate) { Guard.NotNull(ignorePredicate, "ignorePredicate"); if (_IgnorePredicate == null) _IgnorePredicate = ignorePredicate; else _IgnorePredicate = x => _IgnorePredicate(x) || ignorePredicate(x); return this; } public SmartLoop<T> When(T item, Action<T> action) { return When(x => EqualityComparer<T>.Default.Equals(x, item), action); } public SmartLoop<T> When(Func<T, bool> predicate, Action<T> action) { Guard.NotNull(predicate, "predicate"); Guard.NotNull(action, "action"); _Action = Concat(_Action, (l, x) => { if(predicate(x)) action(x); }); return this; } public SmartLoop<T> BeforeAll(Action<IEnumerable<T>> action) { Guard.NotNull(action, "action"); _BeforeAllAction = Concat(_BeforeAllAction, action); return this; } public SmartLoop<T> AfterAll(Action<IEnumerable<T>> action) { Guard.NotNull(action, "action"); _AfterAllAction = Concat(_AfterAllAction, action); return this; } public SmartLoop<T> None(Action action) { Guard.NotNull(action, "action"); _NoneAction = Concat(_NoneAction, action); return this; } public SmartLoop<T> Between(Action<T, T> action) { Guard.NotNull(action, "action"); _BetweenAction = Concat(_BetweenAction, action); return this; } public void Execute() { var finalItems = _Items .Where(x => _IgnorePredicate == null || _IgnorePredicate(x) != true) .Where(x => IgnoreItems.Contains(x) != true) .ToList(); if (finalItems.Count <= 0) { if (_NoneAction != null) _NoneAction(); return; } if (_BeforeAllAction != null) _BeforeAllAction(finalItems); for (int i = 0; i < finalItems.Count; i++) { var item = finalItems[i]; if(_Action != null) _Action(finalItems, item); if (_BetweenAction != null && (finalItems.Count - 1) != i) // not last one _BetweenAction(finalItems[i], finalItems[i + 1]); } if (_AfterAllAction != null) _AfterAllAction(finalItems); } private static Action Concat(Action left, Action right) { if (left == null || right == null) return left ?? right; return () => { left(); right(); }; } private static Action<T1> Concat<T1>(Action<T1> left, Action<T1> right) { if (left == null || right == null) return left ?? right; return t1 => { left(t1); right(t1); }; } private static Action<T1, T2> Concat<T1, T2>(Action<T1, T2> left, Action<T1, T2> right) { if (left == null || right == null) return left ?? right; return (t1, t2) => { left(t1, t2); right(t1, t2); }; } protected List<T> IgnoreItems { get { return _IgnoreItems ?? (_IgnoreItems = new List<T>()); } } } }
using UnityEngine; using System.Collections; namespace RVP { [RequireComponent(typeof(DriveForce))] [ExecuteInEditMode] [DisallowMultipleComponent] [AddComponentMenu("RVP/Drivetrain/Wheel", 1)] //Class for the wheel public class Wheel : MonoBehaviour { [System.NonSerialized] public Transform tr; Rigidbody rb; [System.NonSerialized] public VehicleParent vp; [System.NonSerialized] public Suspension suspensionParent; [System.NonSerialized] public Transform rim; Transform tire; Vector3 localVel; [Tooltip("Generate a sphere collider to represent the wheel for side collisions")] public bool generateHardCollider = true; SphereCollider sphereCol;//Hard collider Transform sphereColTr;//Hard collider transform [Header("Rotation")] [Tooltip("Bias for feedback RPM lerp between target RPM and raw RPM")] [Range(0, 1)] public float feedbackRpmBias; [Tooltip("Curve for setting final RPM of wheel based on driving torque/brake force, x-axis = torque/brake force, y-axis = lerp between raw RPM and target RPM")] public AnimationCurve rpmBiasCurve = AnimationCurve.Linear(0, 0, 1, 1); [Tooltip("As the RPM of the wheel approaches this value, the RPM bias curve is interpolated with the default linear curve")] public float rpmBiasCurveLimit = Mathf.Infinity; [Range(0, 10)] public float axleFriction; [Header("Friction")] [Range(0, 1)] public float frictionSmoothness = 0.5f; public float forwardFriction = 1; public float sidewaysFriction = 1; public float forwardRimFriction = 0.5f; public float sidewaysRimFriction = 0.5f; public float forwardCurveStretch = 1; public float sidewaysCurveStretch = 1; Vector3 frictionForce = Vector3.zero; [Tooltip("X-axis = slip, y-axis = friction")] public AnimationCurve forwardFrictionCurve = AnimationCurve.Linear(0, 0, 1, 1); [Tooltip("X-axis = slip, y-axis = friction")] public AnimationCurve sidewaysFrictionCurve = AnimationCurve.Linear(0, 0, 1, 1); [System.NonSerialized] public float forwardSlip; [System.NonSerialized] public float sidewaysSlip; public enum SlipDependenceMode { dependent, forward, sideways, independent }; public SlipDependenceMode slipDependence = SlipDependenceMode.sideways; [Range(0, 2)] public float forwardSlipDependence = 2; [Range(0, 2)] public float sidewaysSlipDependence = 2; [Tooltip("Adjusts how much friction the wheel has based on the normal of the ground surface. X-axis = normal dot product, y-axis = friction multiplier")] public AnimationCurve normalFrictionCurve = AnimationCurve.Linear(0, 1, 1, 1); [Tooltip("How much the suspension compression affects the wheel friction")] [Range(0, 1)] public float compressionFrictionFactor = 0.5f; [Header("Size")] public float tireRadius; public float rimRadius; public float tireWidth; public float rimWidth; [System.NonSerialized] public float setTireWidth; [System.NonSerialized] public float tireWidthPrev; [System.NonSerialized] public float setTireRadius; [System.NonSerialized] public float tireRadiusPrev; [System.NonSerialized] public float setRimWidth; [System.NonSerialized] public float rimWidthPrev; [System.NonSerialized] public float setRimRadius; [System.NonSerialized] public float rimRadiusPrev; [System.NonSerialized] public float actualRadius; [Header("Tire")] [Range(0, 1)] public float tirePressure = 1; [System.NonSerialized] public float setTirePressure; [System.NonSerialized] public float tirePressurePrev; float initialTirePressure; public bool popped; [System.NonSerialized] public bool setPopped; [System.NonSerialized] public bool poppedPrev; public bool canPop; [Tooltip("Requires deform shader")] public float deformAmount; Material rimMat; Material tireMat; float airLeakTime = -1; [Range(0, 1)] public float rimGlow; float glowAmount; Color glowColor; [System.NonSerialized] public bool updatedSize; [System.NonSerialized] public bool updatedPopped; float currentRPM; [System.NonSerialized] public DriveForce targetDrive; [System.NonSerialized] public float rawRPM;//RPM based purely on velocity [System.NonSerialized] public WheelContact contactPoint = new WheelContact(); [System.NonSerialized] public bool getContact = true;//Should the wheel try to get contact info? [System.NonSerialized] public bool grounded; float airTime; [System.NonSerialized] public float travelDist; Vector3 upDir;//Up direction float circumference; [System.NonSerialized] public Vector3 contactVelocity;//Velocity of contact point float actualEbrake; float actualTargetRPM; float actualTorque; [System.NonSerialized] public Vector3 forceApplicationPoint;//Point at which friction forces are applied [Tooltip("Apply friction forces at ground point")] public bool applyForceAtGroundContact; [Header("Audio")] public AudioSource impactSnd; public AudioClip[] tireHitClips; public AudioClip rimHitClip; public AudioClip tireAirClip; public AudioClip tirePopClip; [Header("Damage")] public float detachForce = Mathf.Infinity; [System.NonSerialized] public float damage; public float mass = 0.05f; [System.NonSerialized] public bool canDetach; [System.NonSerialized] public bool connected = true; public Mesh tireMeshLoose;//Tire mesh for detached wheel collider public Mesh rimMeshLoose;//Rim mesh for detached wheel collider GameObject detachedWheel; GameObject detachedTire; MeshCollider detachedCol; Rigidbody detachedBody; MeshFilter detachFilter; MeshFilter detachTireFilter; public PhysicMaterial detachedTireMaterial; public PhysicMaterial detachedRimMaterial; void Start() { tr = transform; rb = tr.GetTopmostParentComponent<Rigidbody>(); vp = tr.GetTopmostParentComponent<VehicleParent>(); suspensionParent = tr.parent.GetComponent<Suspension>(); travelDist = suspensionParent.targetCompression; canDetach = detachForce < Mathf.Infinity && Application.isPlaying; initialTirePressure = tirePressure; if (tr.childCount > 0) { //Get rim rim = tr.GetChild(0); //Set up rim glow material if (rimGlow > 0 && Application.isPlaying) { rimMat = new Material(rim.GetComponent<MeshRenderer>().sharedMaterial); rimMat.EnableKeyword("_EMISSION"); rim.GetComponent<MeshRenderer>().material = rimMat; } //Create detached wheel if (canDetach) { detachedWheel = new GameObject(vp.transform.name + "'s Detached Wheel"); detachedWheel.layer = LayerMask.NameToLayer("Detachable Part"); detachFilter = detachedWheel.AddComponent<MeshFilter>(); detachFilter.sharedMesh = rim.GetComponent<MeshFilter>().sharedMesh; MeshRenderer detachRend = detachedWheel.AddComponent<MeshRenderer>(); detachRend.sharedMaterial = rim.GetComponent<MeshRenderer>().sharedMaterial; detachedCol = detachedWheel.AddComponent<MeshCollider>(); detachedCol.convex = true; detachedBody = detachedWheel.AddComponent<Rigidbody>(); detachedBody.mass = mass; } //Get tire if (rim.childCount > 0) { tire = rim.GetChild(0); if (deformAmount > 0 && Application.isPlaying) { tireMat = new Material(tire.GetComponent<MeshRenderer>().sharedMaterial); tire.GetComponent<MeshRenderer>().material = tireMat; } //Create detached tire if (canDetach) { detachedTire = new GameObject("Detached Tire"); detachedTire.transform.parent = detachedWheel.transform; detachedTire.transform.localPosition = Vector3.zero; detachedTire.transform.localRotation = Quaternion.identity; detachTireFilter = detachedTire.AddComponent<MeshFilter>(); detachTireFilter.sharedMesh = tire.GetComponent<MeshFilter>().sharedMesh; MeshRenderer detachTireRend = detachedTire.AddComponent<MeshRenderer>(); detachTireRend.sharedMaterial = tireMat ? tireMat : tire.GetComponent<MeshRenderer>().sharedMaterial; } } if (Application.isPlaying) { //Generate hard collider if (generateHardCollider) { GameObject sphereColNew = new GameObject("Rim Collider"); sphereColNew.layer = GlobalControl.ignoreWheelCastLayer; sphereColTr = sphereColNew.transform; sphereCol = sphereColNew.AddComponent<SphereCollider>(); sphereColTr.parent = tr; sphereColTr.localPosition = Vector3.zero; sphereColTr.localRotation = Quaternion.identity; sphereCol.radius = Mathf.Min(rimWidth * 0.5f, rimRadius * 0.5f); sphereCol.material = GlobalControl.frictionlessMatStatic; } if (canDetach) { detachedWheel.SetActive(false); } } } targetDrive = GetComponent<DriveForce>(); currentRPM = 0; } void FixedUpdate() { upDir = tr.up; actualRadius = popped ? rimRadius : Mathf.Lerp(rimRadius, tireRadius, tirePressure); circumference = Mathf.PI * actualRadius * 2; localVel = rb.GetPointVelocity(forceApplicationPoint); //Get proper inputs actualEbrake = suspensionParent.ebrakeEnabled ? suspensionParent.ebrakeForce : 0; actualTargetRPM = targetDrive.rpm * (suspensionParent.driveInverted ? -1 : 1); actualTorque = suspensionParent.driveEnabled ? Mathf.Lerp(targetDrive.torque, Mathf.Abs(vp.accelInput), vp.burnout) : 0; if (getContact) { GetWheelContact(); } else if (grounded) { contactPoint.point += localVel * Time.fixedDeltaTime; } airTime = grounded ? 0 : airTime + Time.fixedDeltaTime; forceApplicationPoint = applyForceAtGroundContact ? contactPoint.point : tr.position; if (connected) { GetRawRPM(); ApplyDrive(); } else { rawRPM = 0; currentRPM = 0; targetDrive.feedbackRPM = 0; } //Get travel distance travelDist = suspensionParent.compression < travelDist || grounded ? suspensionParent.compression : Mathf.Lerp(travelDist, suspensionParent.compression, suspensionParent.extendSpeed * Time.fixedDeltaTime); PositionWheel(); if (connected) { //Update hard collider size upon changed radius or width if (generateHardCollider) { setRimWidth = rimWidth; setRimRadius = rimRadius; setTireWidth = tireWidth; setTireRadius = tireRadius; setTirePressure = tirePressure; if (rimWidthPrev != setRimWidth || rimRadiusPrev != setRimRadius) { sphereCol.radius = Mathf.Min(rimWidth * 0.5f, rimRadius * 0.5f); updatedSize = true; } else if (tireWidthPrev != setTireWidth || tireRadiusPrev != setTireRadius || tirePressurePrev != setTirePressure) { updatedSize = true; } else { updatedSize = false; } rimWidthPrev = setRimWidth; rimRadiusPrev = setRimRadius; tireWidthPrev = setTireWidth; tireRadiusPrev = setTireRadius; tirePressurePrev = setTirePressure; } GetSlip(); ApplyFriction(); //Burnout spinning if (vp.burnout > 0 && targetDrive.rpm != 0 && actualEbrake * vp.ebrakeInput == 0 && connected && grounded) { rb.AddForceAtPosition(suspensionParent.forwardDir * -suspensionParent.flippedSideFactor * (vp.steerInput * vp.burnoutSpin * currentRPM * Mathf.Min(0.1f, targetDrive.torque) * 0.001f) * vp.burnout * (popped ? 0.5f : 1) * contactPoint.surfaceFriction, suspensionParent.tr.position, vp.wheelForceMode); } //Popping logic setPopped = popped; if (poppedPrev != setPopped) { if (tire) { tire.gameObject.SetActive(!popped); } updatedPopped = true; } else { updatedPopped = false; } poppedPrev = setPopped; //Air leak logic if (airLeakTime >= 0) { tirePressure = Mathf.Clamp01(tirePressure - Time.fixedDeltaTime * 0.5f); if (grounded) { airLeakTime += Mathf.Max(Mathf.Abs(currentRPM) * 0.001f, localVel.magnitude * 0.1f) * Time.timeScale * TimeMaster.inverseFixedTimeFactor; if (airLeakTime > 1000 && tirePressure == 0) { popped = true; airLeakTime = -1; if (impactSnd && tirePopClip) { impactSnd.PlayOneShot(tirePopClip); impactSnd.pitch = 1; } } } } } } void Update() { RotateWheel(); if (!Application.isPlaying) { PositionWheel(); } else { //Update tire and rim materials if (deformAmount > 0 && tireMat && connected) { if (tireMat.HasProperty("_DeformNormal")) { //Deform tire (requires deform shader) Vector3 deformNormal = grounded ? contactPoint.normal * Mathf.Max(-suspensionParent.penetration * (1 - suspensionParent.compression) * 10, 1 - tirePressure) * deformAmount : Vector3.zero; tireMat.SetVector("_DeformNormal", new Vector4(deformNormal.x, deformNormal.y, deformNormal.z, 0)); } } if (rimMat) { if (rimMat.HasProperty("_EmissionColor")) { //Make the rim glow float targetGlow = connected && GroundSurfaceMaster.surfaceTypesStatic[contactPoint.surfaceType].leaveSparks ? Mathf.Abs(F.MaxAbs(forwardSlip, sidewaysSlip)) : 0; glowAmount = popped ? Mathf.Lerp(glowAmount, targetGlow, (targetGlow > glowAmount ? 2 : 0.2f) * Time.deltaTime) : 0; glowColor = new Color(glowAmount, glowAmount * 0.5f, 0); rimMat.SetColor("_EmissionColor", popped ? Color.Lerp(Color.black, glowColor, glowAmount * rimGlow) : Color.black); } } } } //Use raycasting to find the current contact point for the wheel void GetWheelContact() { float castDist = Mathf.Max(suspensionParent.suspensionDistance * Mathf.Max(0.001f, suspensionParent.targetCompression) + actualRadius, 0.001f); RaycastHit[] wheelHits = Physics.RaycastAll(suspensionParent.maxCompressPoint, suspensionParent.springDirection, castDist, GlobalControl.wheelCastMaskStatic); RaycastHit hit; int hitIndex = 0; bool validHit = false; float hitDist = Mathf.Infinity; if (connected) { //Loop through raycast hits to find closest one for (int i = 0; i < wheelHits.Length; i++) { if (!wheelHits[i].transform.IsChildOf(vp.tr) && wheelHits[i].distance < hitDist) { hitIndex = i; hitDist = wheelHits[i].distance; validHit = true; } } } else { validHit = false; } //Set contact point variables if (validHit) { hit = wheelHits[hitIndex]; if (!grounded && impactSnd && ((tireHitClips.Length > 0 && !popped) || (rimHitClip && popped))) { impactSnd.PlayOneShot(popped ? rimHitClip : tireHitClips[Mathf.RoundToInt(Random.Range(0, tireHitClips.Length - 1))], Mathf.Clamp01(airTime * airTime)); impactSnd.pitch = Mathf.Clamp(airTime * 0.2f + 0.8f, 0.8f, 1); } grounded = true; contactPoint.distance = hit.distance - actualRadius; contactPoint.point = hit.point + localVel * Time.fixedDeltaTime; contactPoint.grounded = true; contactPoint.normal = hit.normal; contactPoint.relativeVelocity = tr.InverseTransformDirection(localVel); contactPoint.col = hit.collider; if (hit.collider.attachedRigidbody) { contactVelocity = hit.collider.attachedRigidbody.GetPointVelocity(contactPoint.point); contactPoint.relativeVelocity -= tr.InverseTransformDirection(contactVelocity); } else { contactVelocity = Vector3.zero; } GroundSurfaceInstance curSurface = hit.collider.GetComponent<GroundSurfaceInstance>(); TerrainSurface curTerrain = hit.collider.GetComponent<TerrainSurface>(); if (curSurface) { contactPoint.surfaceFriction = curSurface.friction; contactPoint.surfaceType = curSurface.surfaceType; } else if (curTerrain) { contactPoint.surfaceType = curTerrain.GetDominantSurfaceTypeAtPoint(contactPoint.point); contactPoint.surfaceFriction = curTerrain.GetFriction(contactPoint.surfaceType); } else { contactPoint.surfaceFriction = hit.collider.material.dynamicFriction * 2; contactPoint.surfaceType = 0; } if (contactPoint.col.CompareTag("Pop Tire") && canPop && airLeakTime == -1 && !popped) { Deflate(); } } else { grounded = false; contactPoint.distance = suspensionParent.suspensionDistance; contactPoint.point = Vector3.zero; contactPoint.grounded = false; contactPoint.normal = upDir; contactPoint.relativeVelocity = Vector3.zero; contactPoint.col = null; contactVelocity = Vector3.zero; contactPoint.surfaceFriction = 0; contactPoint.surfaceType = 0; } } //Calculate what the RPM of the wheel would be based purely on its velocity void GetRawRPM() { if (grounded) { rawRPM = (contactPoint.relativeVelocity.x / circumference) * (Mathf.PI * 100) * -suspensionParent.flippedSideFactor; } else { rawRPM = Mathf.Lerp(rawRPM, actualTargetRPM, (actualTorque + suspensionParent.brakeForce * vp.brakeInput + actualEbrake * vp.ebrakeInput) * Time.timeScale); } } //Calculate the current slip amount void GetSlip() { if (grounded) { sidewaysSlip = (contactPoint.relativeVelocity.z * 0.1f) / sidewaysCurveStretch; forwardSlip = (0.01f * (rawRPM - currentRPM)) / forwardCurveStretch; } else { sidewaysSlip = 0; forwardSlip = 0; } } //Apply actual forces to rigidbody based on wheel simulation void ApplyFriction() { if (grounded) { float forwardSlipFactor = (int)slipDependence == 0 || (int)slipDependence == 1 ? forwardSlip - sidewaysSlip : forwardSlip; float sidewaysSlipFactor = (int)slipDependence == 0 || (int)slipDependence == 2 ? sidewaysSlip - forwardSlip : sidewaysSlip; float forwardSlipDependenceFactor = Mathf.Clamp01(forwardSlipDependence - Mathf.Clamp01(Mathf.Abs(sidewaysSlip))); float sidewaysSlipDependenceFactor = Mathf.Clamp01(sidewaysSlipDependence - Mathf.Clamp01(Mathf.Abs(forwardSlip))); float targetForceX = forwardFrictionCurve.Evaluate(Mathf.Abs(forwardSlipFactor)) * -System.Math.Sign(forwardSlip) * (popped ? forwardRimFriction : forwardFriction) * forwardSlipDependenceFactor * -suspensionParent.flippedSideFactor; float targetForceZ = sidewaysFrictionCurve.Evaluate(Mathf.Abs(sidewaysSlipFactor)) * -System.Math.Sign(sidewaysSlip) * (popped ? sidewaysRimFriction : sidewaysFriction) * sidewaysSlipDependenceFactor * normalFrictionCurve.Evaluate(Mathf.Clamp01(Vector3.Dot(contactPoint.normal, GlobalControl.worldUpDir))) * (vp.burnout > 0 && Mathf.Abs(targetDrive.rpm) != 0 && actualEbrake * vp.ebrakeInput == 0 && grounded ? (1 - vp.burnout) * (1 - Mathf.Abs(vp.accelInput)) : 1); Vector3 targetForce = tr.TransformDirection(targetForceX, 0, targetForceZ); float targetForceMultiplier = ((1 - compressionFrictionFactor) + (1 - suspensionParent.compression) * compressionFrictionFactor * Mathf.Clamp01(Mathf.Abs(suspensionParent.tr.InverseTransformDirection(localVel).z) * 10)) * contactPoint.surfaceFriction; frictionForce = Vector3.Lerp(frictionForce, targetForce * targetForceMultiplier, 1 - frictionSmoothness); rb.AddForceAtPosition(frictionForce, forceApplicationPoint, vp.wheelForceMode); //If resting on a rigidbody, apply opposing force to it if (contactPoint.col.attachedRigidbody) { contactPoint.col.attachedRigidbody.AddForceAtPosition(-frictionForce, contactPoint.point, vp.wheelForceMode); } } } //Do torque and RPM calculations/simulation void ApplyDrive() { float brakeForce = 0; float brakeCheckValue = suspensionParent.skidSteerBrake ? vp.localAngularVel.y : vp.localVelocity.z; //Set brake force if (vp.brakeIsReverse) { if (brakeCheckValue > 0) { brakeForce = suspensionParent.brakeForce * vp.brakeInput; } else if (brakeCheckValue <= 0) { brakeForce = suspensionParent.brakeForce * Mathf.Clamp01(vp.accelInput); } } else { brakeForce = suspensionParent.brakeForce * vp.brakeInput; } brakeForce += axleFriction * 0.1f * (Mathf.Approximately(actualTorque, 0) ? 1 : 0); if (targetDrive.rpm != 0) { brakeForce *= (1 - vp.burnout); } //Set final RPM if (!suspensionParent.jammed && connected) { bool validTorque = (!(Mathf.Approximately(actualTorque, 0) && Mathf.Abs(actualTargetRPM) < 0.01f) && !Mathf.Approximately(actualTargetRPM, 0)) || brakeForce + actualEbrake * vp.ebrakeInput > 0; currentRPM = Mathf.Lerp(rawRPM, Mathf.Lerp( Mathf.Lerp(rawRPM, actualTargetRPM, validTorque ? EvaluateTorque(actualTorque) : actualTorque), 0, Mathf.Max(brakeForce, actualEbrake * vp.ebrakeInput)), validTorque ? EvaluateTorque(actualTorque + brakeForce + actualEbrake * vp.ebrakeInput) : actualTorque + brakeForce + actualEbrake * vp.ebrakeInput); targetDrive.feedbackRPM = Mathf.Lerp(currentRPM, rawRPM, feedbackRpmBias); } else { currentRPM = 0; targetDrive.feedbackRPM = 0; } } //Extra method for evaluating torque to make the ApplyDrive method more readable float EvaluateTorque(float t) { float torque = Mathf.Lerp(rpmBiasCurve.Evaluate(t), t, rawRPM / (rpmBiasCurveLimit * Mathf.Sign(actualTargetRPM))); return torque; } //Visual wheel positioning void PositionWheel() { if (suspensionParent) { rim.position = suspensionParent.maxCompressPoint + suspensionParent.springDirection * suspensionParent.suspensionDistance * (Application.isPlaying ? travelDist : suspensionParent.targetCompression) + suspensionParent.upDir * Mathf.Pow(Mathf.Max(Mathf.Abs(Mathf.Sin(suspensionParent.sideAngle * Mathf.Deg2Rad)), Mathf.Abs(Mathf.Sin(suspensionParent.casterAngle * Mathf.Deg2Rad))), 2) * actualRadius + suspensionParent.pivotOffset * suspensionParent.tr.TransformDirection(Mathf.Sin(tr.localEulerAngles.y * Mathf.Deg2Rad), 0, Mathf.Cos(tr.localEulerAngles.y * Mathf.Deg2Rad)) - suspensionParent.pivotOffset * (Application.isPlaying ? suspensionParent.forwardDir : suspensionParent.tr.forward); } if (Application.isPlaying && generateHardCollider && connected) { sphereColTr.position = rim.position; } } //Visual wheel rotation void RotateWheel() { if (tr && suspensionParent) { float ackermannVal = Mathf.Sign(suspensionParent.steerAngle) == suspensionParent.flippedSideFactor ? 1 + suspensionParent.ackermannFactor : 1 - suspensionParent.ackermannFactor; tr.localEulerAngles = new Vector3( suspensionParent.camberAngle + suspensionParent.casterAngle * suspensionParent.steerAngle * suspensionParent.flippedSideFactor, -suspensionParent.toeAngle * suspensionParent.flippedSideFactor + suspensionParent.steerDegrees * ackermannVal, 0); } if (Application.isPlaying) { rim.Rotate(Vector3.forward, currentRPM * suspensionParent.flippedSideFactor * Time.deltaTime); if (damage > 0) { rim.localEulerAngles = new Vector3( Mathf.Sin(-rim.localEulerAngles.z * Mathf.Deg2Rad) * Mathf.Clamp(damage, 0, 10), Mathf.Cos(-rim.localEulerAngles.z * Mathf.Deg2Rad) * Mathf.Clamp(damage, 0, 10), rim.localEulerAngles.z); } else if (rim.localEulerAngles.x != 0 || rim.localEulerAngles.y != 0) { rim.localEulerAngles = new Vector3(0, 0, rim.localEulerAngles.z); } } } //Begin deflating the tire/leaking air public void Deflate() { airLeakTime = 0; if (impactSnd && tireAirClip) { impactSnd.PlayOneShot(tireAirClip); impactSnd.pitch = 1; } } public void FixTire() { popped = false; tirePressure = initialTirePressure; airLeakTime = -1; } //Detach the wheel from the vehicle public void Detach() { if (connected && canDetach) { connected = false; detachedWheel.SetActive(true); detachedWheel.transform.position = rim.position; detachedWheel.transform.rotation = rim.rotation; detachedCol.sharedMaterial = popped ? detachedRimMaterial : detachedTireMaterial; if (tire) { detachedTire.SetActive(!popped); detachedCol.sharedMesh = airLeakTime >= 0 || popped ? (rimMeshLoose ? rimMeshLoose : detachFilter.sharedMesh) : (tireMeshLoose ? tireMeshLoose : detachTireFilter.sharedMesh); } else { detachedCol.sharedMesh = rimMeshLoose ? rimMeshLoose : detachFilter.sharedMesh; } rb.mass -= mass; detachedBody.velocity = rb.GetPointVelocity(rim.position); detachedBody.angularVelocity = rb.angularVelocity; rim.gameObject.SetActive(false); if (sphereColTr) { sphereColTr.gameObject.SetActive(false); } } } //Automatically sets wheel dimensions based on rim/tire meshes public void GetWheelDimensions(float radiusMargin, float widthMargin) { Mesh rimMesh = null; Mesh tireMesh = null; Mesh checker; Transform scaler = transform; if (transform.childCount > 0) { if (transform.GetChild(0).GetComponent<MeshFilter>()) { rimMesh = transform.GetChild(0).GetComponent<MeshFilter>().sharedMesh; scaler = transform.GetChild(0); } if (transform.GetChild(0).childCount > 0) { if (transform.GetChild(0).GetChild(0).GetComponent<MeshFilter>()) { tireMesh = transform.GetChild(0).GetChild(0).GetComponent<MeshFilter>().sharedMesh; } } checker = tireMesh ? tireMesh : rimMesh; if (checker) { float maxWidth = 0; float maxRadius = 0; foreach (Vector3 curVert in checker.vertices) { if (new Vector2(curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y).magnitude > maxRadius) { maxRadius = new Vector2(curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y).magnitude; } if (Mathf.Abs(curVert.z * scaler.localScale.z) > maxWidth) { maxWidth = Mathf.Abs(curVert.z * scaler.localScale.z); } } tireRadius = maxRadius + radiusMargin; tireWidth = maxWidth + widthMargin; if (tireMesh && rimMesh) { maxWidth = 0; maxRadius = 0; foreach (Vector3 curVert in rimMesh.vertices) { if (new Vector2(curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y).magnitude > maxRadius) { maxRadius = new Vector2(curVert.x * scaler.localScale.x, curVert.y * scaler.localScale.y).magnitude; } if (Mathf.Abs(curVert.z * scaler.localScale.z) > maxWidth) { maxWidth = Mathf.Abs(curVert.z * scaler.localScale.z); } } rimRadius = maxRadius + radiusMargin; rimWidth = maxWidth + widthMargin; } else { rimRadius = maxRadius * 0.5f + radiusMargin; rimWidth = maxWidth * 0.5f + widthMargin; } } else { Debug.LogError("No rim or tire meshes found for getting wheel dimensions.", this); } } } //Attach the wheel back onto its vehicle if detached public void Reattach() { if (!connected) { connected = true; detachedWheel.SetActive(false); rb.mass += mass; rim.gameObject.SetActive(true); if (sphereColTr) { sphereColTr.gameObject.SetActive(true); } } } //visualize wheel void OnDrawGizmosSelected() { tr = transform; if (tr.childCount > 0) { //Rim is the first child of this object rim = tr.GetChild(0); //Tire mesh should be first child of rim if (rim.childCount > 0) { tire = rim.GetChild(0); } } float tireActualRadius = Mathf.Lerp(rimRadius, tireRadius, tirePressure); if (tirePressure < 1 && tirePressure > 0) { Gizmos.color = new Color(1, 1, 0, popped ? 0.5f : 1); GizmosExtra.DrawWireCylinder(rim.position, rim.forward, tireActualRadius, tireWidth * 2); } Gizmos.color = Color.white; GizmosExtra.DrawWireCylinder(rim.position, rim.forward, tireRadius, tireWidth * 2); Gizmos.color = tirePressure == 0 || popped ? Color.green : Color.cyan; GizmosExtra.DrawWireCylinder(rim.position, rim.forward, rimRadius, rimWidth * 2); Gizmos.color = new Color(1, 1, 1, tirePressure < 1 ? 0.5f : 1); GizmosExtra.DrawWireCylinder(rim.position, rim.forward, tireRadius, tireWidth * 2); Gizmos.color = tirePressure == 0 || popped ? Color.green : Color.cyan; GizmosExtra.DrawWireCylinder(rim.position, rim.forward, rimRadius, rimWidth * 2); } //Destroy detached wheel void OnDestroy() { if (Application.isPlaying) { if (detachedWheel) { Destroy(detachedWheel); } } } } //Contact point class public class WheelContact { public bool grounded;//Is the contact point grounded? public Collider col;//The collider of the contact point public Vector3 point;//The position of the contact point public Vector3 normal;//The normal of the contact point public Vector3 relativeVelocity;//Relative velocity between the wheel and the contact point object public float distance;//Distance from the suspension to the contact point minus the wheel radius public float surfaceFriction;//Friction of the contact surface public int surfaceType;//The surface type identified by the surface types array of GroundSurfaceMaster } }
#define SQLITE_ASCII #define SQLITE_DISABLE_LFS #define SQLITE_ENABLE_OVERSIZE_CELL_CHECK #define SQLITE_MUTEX_OMIT #define SQLITE_OMIT_AUTHORIZATION #define SQLITE_OMIT_DEPRECATED #define SQLITE_OMIT_GET_TABLE #define SQLITE_OMIT_INCRBLOB #define SQLITE_OMIT_LOOKASIDE #define SQLITE_OMIT_SHARED_CACHE #define SQLITE_OMIT_UTF16 #define SQLITE_OMIT_WAL #define SQLITE_OS_WIN #define SQLITE_SYSTEM_MALLOC #define VDBE_PROFILE_OFF #define WINDOWS_MOBILE #define NDEBUG #define _MSC_VER #define YYFALLBACK using System; using System.Diagnostics; using HANDLE = System.IntPtr; using System.Text; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ #if !SQLITE_CORE //#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ const int SQLITE_CORE = 1; #endif //#include "sqlite3ext.h" //#include "sqliteInt.h" //#include <string.h> #if !SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #if !SQLITE_ENABLE_COLUMN_METADATA //# define sqlite3_column_database_name 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name 0 //# define sqlite3_column_origin_name16 0 //# define sqlite3_table_column_metadata 0 #endif #if SQLITE_OMIT_AUTHORIZATION //# define sqlite3_set_authorizer 0 #endif #if SQLITE_OMIT_UTF16 //# define sqlite3_bind_text16 0 //# define sqlite3_collation_needed16 0 //# define sqlite3_column_decltype16 0 //# define sqlite3_column_name16 0 //# define sqlite3_column_text16 0 //# define sqlite3_complete16 0 //# define sqlite3_create_collation16 0 //# define sqlite3_create_function16 0 //# define sqlite3_errmsg16 0 static string sqlite3_errmsg16( sqlite3 db ) { return ""; } //# define sqlite3_open16 0 //# define sqlite3_prepare16 0 //# define sqlite3_prepare16_v2 0 //# define sqlite3_result_error16 0 //# define sqlite3_result_text16 0 static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel ) { } //# define sqlite3_result_text16be 0 //# define sqlite3_result_text16le 0 //# define sqlite3_value_text16 0 //# define sqlite3_value_text16be 0 //# define sqlite3_value_text16le 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name16 0 #endif #if SQLITE_OMIT_COMPLETE //# define sqlite3_complete 0 //# define sqlite3_complete16 0 #endif #if SQLITE_OMIT_DECLTYPE //# define sqlite3_column_decltype16 0 //# define sqlite3_column_decltype 0 #endif #if SQLITE_OMIT_PROGRESS_CALLBACK //# define sqlite3_progress_handler 0 static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if SQLITE_OMIT_VIRTUALTABLE //# define sqlite3_create_module 0 //# define sqlite3_create_module_v2 0 //# define sqlite3_declare_vtab 0 #endif #if SQLITE_OMIT_SHARED_CACHE //# define sqlite3_enable_shared_cache 0 #endif #if SQLITE_OMIT_TRACE //# define sqlite3_profile 0 //# define sqlite3_trace 0 #endif #if SQLITE_OMIT_GET_TABLE //# define //sqlite3_free_table 0 //# define sqlite3_get_table 0 static public int sqlite3_get_table( sqlite3 db, /* An open database */ string zSql, /* SQL to be evaluated */ ref string[] pazResult, /* Results of the query */ ref int pnRow, /* Number of result rows written here */ ref int pnColumn, /* Number of result columns written here */ ref string pzErrmsg /* Error msg written here */ ) { return 0; } #endif #if SQLITE_OMIT_INCRBLOB //#define sqlite3_bind_zeroblob 0 //#define sqlite3_blob_bytes 0 //#define sqlite3_blob_close 0 //#define sqlite3_blob_open 0 //#define sqlite3_blob_read 0 //#define sqlite3_blob_write 0 #endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ public class sqlite3_api_routines { public sqlite3 context_db_handle; }; static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); //{ // sqlite3_aggregate_context, #if !SQLITE_OMIT_DEPRECATED / sqlite3_aggregate_count, #else // 0, #endif // sqlite3_bind_blob, // sqlite3_bind_double, // sqlite3_bind_int, // sqlite3_bind_int64, // sqlite3_bind_null, // sqlite3_bind_parameter_count, // sqlite3_bind_parameter_index, // sqlite3_bind_parameter_name, // sqlite3_bind_text, // sqlite3_bind_text16, // sqlite3_bind_value, // sqlite3_busy_handler, // sqlite3_busy_timeout, // sqlite3_changes, // sqlite3_close, // sqlite3_collation_needed, // sqlite3_collation_needed16, // sqlite3_column_blob, // sqlite3_column_bytes, // sqlite3_column_bytes16, // sqlite3_column_count, // sqlite3_column_database_name, // sqlite3_column_database_name16, // sqlite3_column_decltype, // sqlite3_column_decltype16, // sqlite3_column_double, // sqlite3_column_int, // sqlite3_column_int64, // sqlite3_column_name, // sqlite3_column_name16, // sqlite3_column_origin_name, // sqlite3_column_origin_name16, // sqlite3_column_table_name, // sqlite3_column_table_name16, // sqlite3_column_text, // sqlite3_column_text16, // sqlite3_column_type, // sqlite3_column_value, // sqlite3_commit_hook, // sqlite3_complete, // sqlite3_complete16, // sqlite3_create_collation, // sqlite3_create_collation16, // sqlite3_create_function, // sqlite3_create_function16, // sqlite3_create_module, // sqlite3_data_count, // sqlite3_db_handle, // sqlite3_declare_vtab, // sqlite3_enable_shared_cache, // sqlite3_errcode, // sqlite3_errmsg, // sqlite3_errmsg16, // sqlite3_exec, #if !SQLITE_OMIT_DEPRECATED //sqlite3_expired, #else //0, #endif // sqlite3_finalize, // //sqlite3_free, // //sqlite3_free_table, // sqlite3_get_autocommit, // sqlite3_get_auxdata, // sqlite3_get_table, // 0, /* Was sqlite3_global_recover(), but that function is deprecated */ // sqlite3_interrupt, // sqlite3_last_insert_rowid, // sqlite3_libversion, // sqlite3_libversion_number, // sqlite3_malloc, // sqlite3_mprintf, // sqlite3_open, // sqlite3_open16, // sqlite3_prepare, // sqlite3_prepare16, // sqlite3_profile, // sqlite3_progress_handler, // sqlite3_realloc, // sqlite3_reset, // sqlite3_result_blob, // sqlite3_result_double, // sqlite3_result_error, // sqlite3_result_error16, // sqlite3_result_int, // sqlite3_result_int64, // sqlite3_result_null, // sqlite3_result_text, // sqlite3_result_text16, // sqlite3_result_text16be, // sqlite3_result_text16le, // sqlite3_result_value, // sqlite3_rollback_hook, // sqlite3_set_authorizer, // sqlite3_set_auxdata, // sqlite3_snprintf, // sqlite3_step, // sqlite3_table_column_metadata, #if !SQLITE_OMIT_DEPRECATED //sqlite3_thread_cleanup, #else // 0, #endif // sqlite3_total_changes, // sqlite3_trace, #if !SQLITE_OMIT_DEPRECATED //sqlite3_transfer_bindings, #else // 0, #endif // sqlite3_update_hook, // sqlite3_user_data, // sqlite3_value_blob, // sqlite3_value_bytes, // sqlite3_value_bytes16, // sqlite3_value_double, // sqlite3_value_int, // sqlite3_value_int64, // sqlite3_value_numeric_type, // sqlite3_value_text, // sqlite3_value_text16, // sqlite3_value_text16be, // sqlite3_value_text16le, // sqlite3_value_type, // sqlite3_vmprintf, // /* // ** The original API set ends here. All extensions can call any // ** of the APIs above provided that the pointer is not NULL. But // ** before calling APIs that follow, extension should check the // ** sqlite3_libversion_number() to make sure they are dealing with // ** a library that is new enough to support that API. // ************************************************************************* // */ // sqlite3_overload_function, // /* // ** Added after 3.3.13 // */ // sqlite3_prepare_v2, // sqlite3_prepare16_v2, // sqlite3_clear_bindings, // /* // ** Added for 3.4.1 // */ // sqlite3_create_module_v2, // /* // ** Added for 3.5.0 // */ // sqlite3_bind_zeroblob, // sqlite3_blob_bytes, // sqlite3_blob_close, // sqlite3_blob_open, // sqlite3_blob_read, // sqlite3_blob_write, // sqlite3_create_collation_v2, // sqlite3_file_control, // sqlite3_memory_highwater, // sqlite3_memory_used, #if SQLITE_MUTEX_OMIT // 0, // 0, // 0, // 0, // 0, #else // sqlite3MutexAlloc, // sqlite3_mutex_enter, // sqlite3_mutex_free, // sqlite3_mutex_leave, // sqlite3_mutex_try, #endif // sqlite3_open_v2, // sqlite3_release_memory, // sqlite3_result_error_nomem, // sqlite3_result_error_toobig, // sqlite3_sleep, // sqlite3_soft_heap_limit, // sqlite3_vfs_find, // sqlite3_vfs_register, // sqlite3_vfs_unregister, // /* // ** Added for 3.5.8 // */ // sqlite3_threadsafe, // sqlite3_result_zeroblob, // sqlite3_result_error_code, // sqlite3_test_control, // sqlite3_randomness, // sqlite3_context_db_handle, // /* // ** Added for 3.6.0 // */ // sqlite3_extended_result_codes, // sqlite3_limit, // sqlite3_next_stmt, // sqlite3_sql, // sqlite3_status, // /* // ** Added for 3.7.4 // */ // sqlite3_backup_finish, // sqlite3_backup_init, // sqlite3_backup_pagecount, // sqlite3_backup_remaining, // sqlite3_backup_step, //#if !SQLITE_OMIT_COMPILEOPTION_DIAGS // sqlite3_compileoption_get, // sqlite3_compileoption_used, //#else // 0, // 0, //#endif // sqlite3_create_function_v2, // sqlite3_db_config, // sqlite3_db_mutex, // sqlite3_db_status, // sqlite3_extended_errcode, // sqlite3_log, // sqlite3_soft_heap_limit64, // sqlite3_sourceid, // sqlite3_stmt_status, // sqlite3_strnicmp, //#if SQLITE_ENABLE_UNLOCK_NOTIFY // sqlite3_unlock_notify, //#else // 0, //#endif //#if !SQLITE_OMIT_WAL // sqlite3_wal_autocheckpoint, // sqlite3_wal_checkpoint, // sqlite3_wal_hook, //#else // 0, // 0, // 0, //#endif //}; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with ** error message text. The calling function should free this memory ** by calling sqlite3DbFree(db, ). */ static int sqlite3LoadExtension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { sqlite3_vfs pVfs = db.pVfs; HANDLE handle; //dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines); StringBuilder zErrmsg = new StringBuilder( 100 ); //object aHandle; const int nMsg = 300; if ( pzErrMsg != null ) pzErrMsg = null; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call sqlite3_enable_load_extension() to turn on extension ** loading. Otherwise you get the following error. */ if ( ( db.flags & SQLITE_LoadExtension ) == 0 ) { //if( pzErrMsg != null){ pzErrMsg = sqlite3_mprintf( "not authorized" ); //} return SQLITE_ERROR; } if ( zProc == null || zProc == "" ) { zProc = "sqlite3_extension_init"; } handle = sqlite3OsDlOpen( pVfs, zFile ); if ( handle == IntPtr.Zero ) { // if( pzErrMsg ){ pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); //if( zErrmsg !=null){ sqlite3_snprintf( nMsg, zErrmsg, "unable to open shared library [%s]", zFile ); sqlite3OsDlError( pVfs, nMsg - 1, zErrmsg.ToString() ); return SQLITE_ERROR; } //xInit = (int()(sqlite3*,char**,const sqlite3_api_routines)) // sqlite3OsDlSym(pVfs, handle, zProc); //xInit = (dxInit)sqlite3OsDlSym( pVfs, handle, ref zProc ); Debugger.Break(); // TODO -- //if( xInit==0 ){ // if( pzErrMsg ){ // *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); // if( zErrmsg ){ // sqlite3_snprintf(nMsg, zErrmsg, // "no entry point [%s] in shared library [%s]", zProc,zFile); // sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); // } // sqlite3OsDlClose(pVfs, handle); // } // return SQLITE_ERROR; // }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){ //// if( pzErrMsg !=null){ // pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); // //} // sqlite3DbFree(db,ref zErrmsg); // sqlite3OsDlClose(pVfs, ref handle); // return SQLITE_ERROR; // } // /* Append the new shared library handle to the db.aExtension array. */ // aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1); // if( aHandle==null ){ // return SQLITE_NOMEM; // } // if( db.nExtension>0 ){ // memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension)); // } // sqlite3DbFree(db,ref db.aExtension); // db.aExtension = aHandle; // db.aExtension[db.nExtension++] = handle; return SQLITE_OK; } static public int sqlite3_load_extension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { int rc; sqlite3_mutex_enter( db.mutex ); rc = sqlite3LoadExtension( db, zFile, zProc, ref pzErrMsg ); rc = sqlite3ApiExit( db, rc ); sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ static void sqlite3CloseExtensions( sqlite3 db ) { int i; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); for ( i = 0; i < db.nExtension; i++ ) { sqlite3OsDlClose( db.pVfs, (HANDLE)db.aExtension[i] ); } sqlite3DbFree( db, ref db.aExtension ); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ static public int sqlite3_enable_load_extension( sqlite3 db, int onoff ) { sqlite3_mutex_enter( db.mutex ); if ( onoff != 0 ) { db.flags |= SQLITE_LoadExtension; } else { db.flags &= ~SQLITE_LoadExtension; } sqlite3_mutex_leave( db.mutex ); return SQLITE_OK; } #endif //* SQLITE_OMIT_LOAD_EXTENSION */ /* ** The auto-extension code added regardless of whether or not extension ** loading is supported. We need a dummy sqlite3Apis pointer for that ** code if regular extension loading is not available. This is that ** dummy pointer. */ #if SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines sqlite3Apis = null; #endif /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ //typedef struct sqlite3AutoExtList sqlite3AutoExtList; public class sqlite3AutoExtList { public int nExt = 0; /* Number of entries in aExt[] */ public dxInit[] aExt = null; /* Pointers to the extension init functions */ public sqlite3AutoExtList( int nExt, dxInit[] aExt ) { this.nExt = nExt; this.aExt = aExt; } } static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList( 0, null ); /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) //# define wsdAutoext x[0] #else //# define wsdAutoextInit static void wsdAutoextInit() { } //# define wsdAutoext sqlite3Autoext static sqlite3AutoExtList wsdAutoext = sqlite3Autoext; #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ static int sqlite3_auto_extension( dxInit xInit ) { int rc = SQLITE_OK; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if ( rc != 0 ) { return rc; } else #endif { int i; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif wsdAutoextInit(); sqlite3_mutex_enter( mutex ); for ( i = 0; i < wsdAutoext.nExt; i++ ) { if ( wsdAutoext.aExt[i] == xInit ) break; } //if( i==wsdAutoext.nExt ){ // int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); // void **aNew; // aNew = sqlite3_realloc(wsdAutoext.aExt, nByte); // if( aNew==0 ){ // rc = SQLITE_NOMEM; // }else{ Array.Resize( ref wsdAutoext.aExt, wsdAutoext.nExt + 1 );// wsdAutoext.aExt = aNew; wsdAutoext.aExt[wsdAutoext.nExt] = xInit; wsdAutoext.nExt++; //} sqlite3_mutex_leave( mutex ); Debug.Assert( ( rc & 0xff ) == rc ); return rc; } } /* ** Reset the automatic extension loading mechanism. */ static void sqlite3_reset_auto_extension() { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() == SQLITE_OK ) #endif { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif wsdAutoextInit(); sqlite3_mutex_enter( mutex ); #if SQLITE_OMIT_WSD //sqlite3_free( ref wsdAutoext.aExt ); wsdAutoext.aExt = null; wsdAutoext.nExt = 0; #else //sqlite3_free( ref sqlite3Autoext.aExt ); sqlite3Autoext.aExt = null; sqlite3Autoext.nExt = 0; #endif sqlite3_mutex_leave( mutex ); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ static void sqlite3AutoLoadExtensions( sqlite3 db ) { int i; bool go = true; dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines); wsdAutoextInit(); #if SQLITE_OMIT_WSD if ( wsdAutoext.nExt == 0 ) #else if ( sqlite3Autoext.nExt == 0 ) #endif { /* Common case: early out without every having to acquire a mutex */ return; } for ( i = 0; go; i++ ) { string zErrmsg = ""; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter( mutex ); if ( i >= wsdAutoext.nExt ) { xInit = null; go = false; } else { xInit = (dxInit) wsdAutoext.aExt[i]; } sqlite3_mutex_leave( mutex ); zErrmsg = ""; if ( xInit != null && xInit( db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis ) != 0 ) { sqlite3Error( db, SQLITE_ERROR, "automatic extension loading failed: %s", zErrmsg ); go = false; } sqlite3DbFree( db, ref zErrmsg ); } } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ namespace UniversalDetector.Core { enum InputState { PureASCII=0, EscASCII=1, Highbyte=2 }; public abstract class UniversalDetector { protected const int FILTER_CHINESE_SIMPLIFIED = 1; protected const int FILTER_CHINESE_TRADITIONAL = 2; protected const int FILTER_JAPANESE = 4; protected const int FILTER_KOREAN = 8; protected const int FILTER_NON_CJK = 16; protected const int FILTER_ALL = 31; protected static int FILTER_CHINESE = FILTER_CHINESE_SIMPLIFIED | FILTER_CHINESE_TRADITIONAL; protected static int FILTER_CJK = FILTER_JAPANESE | FILTER_KOREAN | FILTER_CHINESE_SIMPLIFIED | FILTER_CHINESE_TRADITIONAL; protected const float SHORTCUT_THRESHOLD = 0.95f; protected const float MINIMUM_THRESHOLD = 0.20f; internal InputState inputState; protected bool start; protected bool gotData; protected bool done; protected byte lastChar; protected int bestGuess; protected const int PROBERS_NUM = 3; protected int languageFilter; protected CharsetProber[] charsetProbers = new CharsetProber[PROBERS_NUM]; protected CharsetProber escCharsetProber; protected string detectedCharset; public UniversalDetector(int languageFilter) { this.start = true; this.inputState = InputState.PureASCII; this.lastChar = 0x00; this.bestGuess = -1; this.languageFilter = languageFilter; } public virtual void Feed(byte[] buf, int offset, int len) { if (done) { return; } if (len > 0) gotData = true; // If the data starts with BOM, we know it is UTF if (start) { start = false; if (len > 3) { switch (buf[0]) { case 0xEF: if (0xBB == buf[1] && 0xBF == buf[2]) detectedCharset = "UTF-8"; break; case 0xFE: if (0xFF == buf[1] && 0x00 == buf[2] && 0x00 == buf[3]) // FE FF 00 00 UCS-4, unusual octet order BOM (3412) detectedCharset = "X-ISO-10646-UCS-4-3412"; else if (0xFF == buf[1]) detectedCharset = "UTF-16BE"; break; case 0x00: if (0x00 == buf[1] && 0xFE == buf[2] && 0xFF == buf[3]) detectedCharset = "UTF-32BE"; else if (0x00 == buf[1] && 0xFF == buf[2] && 0xFE == buf[3]) // 00 00 FF FE UCS-4, unusual octet order BOM (2143) detectedCharset = "X-ISO-10646-UCS-4-2143"; break; case 0xFF: if (0xFE == buf[1] && 0x00 == buf[2] && 0x00 == buf[3]) detectedCharset = "UTF-32LE"; else if (0xFE == buf[1]) detectedCharset = "UTF-16LE"; break; } // switch } if (detectedCharset != null) { done = true; return; } } for (int i = 0; i < len; i++) { // other than 0xa0, if every other character is ascii, the page is ascii if ((buf[i] & 0x80) != 0 && buf[i] != 0xA0) { // we got a non-ascii byte (high-byte) if (inputState != InputState.Highbyte) { inputState = InputState.Highbyte; // kill EscCharsetProber if it is active if (escCharsetProber != null) { escCharsetProber = null; } // start multibyte and singlebyte charset prober if (charsetProbers[0] == null) charsetProbers[0] = new MBCSGroupProber(); if (charsetProbers[1] == null) charsetProbers[1] = new SBCSGroupProber(); if (charsetProbers[2] == null) charsetProbers[2] = new Latin1Prober(); } } else { if (inputState == InputState.PureASCII && (buf[i] == 0x33 || (buf[i] == 0x7B && lastChar == 0x7E))) { // found escape character or HZ "~{" inputState = InputState.EscASCII; } lastChar = buf[i]; } } ProbingState st = ProbingState.NotMe; switch (inputState) { case InputState.EscASCII: if (escCharsetProber == null) { escCharsetProber = new EscCharsetProber(); } st = escCharsetProber.HandleData(buf, offset, len); if (st == ProbingState.FoundIt) { done = true; detectedCharset = escCharsetProber.GetCharsetName(); } break; case InputState.Highbyte: for (int i = 0; i < PROBERS_NUM; i++) { if (charsetProbers[i] != null) { st = charsetProbers[i].HandleData(buf, offset, len); #if DEBUG charsetProbers[i].DumpStatus(); #endif if (st == ProbingState.FoundIt) { done = true; detectedCharset = charsetProbers[i].GetCharsetName(); return; } } } break; default: // pure ascii break; } return; } /// <summary> /// Notify detector that no further data is available. /// </summary> public virtual void DataEnd() { if (!gotData) { // we haven't got any data yet, return immediately // caller program sometimes call DataEnd before anything has // been sent to detector return; } if (detectedCharset != null) { done = true; Report(detectedCharset, 1.0f); return; } if (inputState == InputState.Highbyte) { float proberConfidence = 0.0f; float maxProberConfidence = 0.0f; int maxProber = 0; for (int i = 0; i < PROBERS_NUM; i++) { if (charsetProbers[i] != null) { proberConfidence = charsetProbers[i].GetConfidence(); if (proberConfidence > maxProberConfidence) { maxProberConfidence = proberConfidence; maxProber = i; } } } if (maxProberConfidence > MINIMUM_THRESHOLD) { Report(charsetProbers[maxProber].GetCharsetName(), maxProberConfidence); } } else if (inputState == InputState.PureASCII) { Report("ASCII", 1.0f); } } /// <summary> /// Clear internal state of charset detector. /// In the original interface this method is protected. /// </summary> public virtual void Reset() { done = false; start = true; detectedCharset = null; gotData = false; bestGuess = -1; inputState = InputState.PureASCII; lastChar = 0x00; if (escCharsetProber != null) escCharsetProber.Reset(); for (int i = 0; i < PROBERS_NUM; i++) if (charsetProbers[i] != null) charsetProbers[i].Reset(); } protected abstract void Report(string charset, float confidence); } }
/* * 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 OpenSim.Framework.Monitoring; using System; using System.Collections.Generic; using System.Threading; namespace OpenSim.Region.ScriptEngine.Yengine { public partial class Yengine { private int m_WakeUpOne = 0; public object m_WakeUpLock = new object(); private Dictionary<int, XMRInstance> m_RunningInstances = new Dictionary<int, XMRInstance>(); private bool m_SuspendScriptThreadFlag = false; private bool m_WakeUpThis = false; public DateTime m_LastRanAt = DateTime.MinValue; public long m_ScriptExecTime = 0; [ThreadStatic] private static int m_ScriptThreadTID; public static bool IsScriptThread { get { return m_ScriptThreadTID != 0; } } public void StartThreadWorker(int i) { Thread thd; if(i >= 0) thd = Yengine.StartMyThread(RunScriptThread, "YScript" + i.ToString(), ThreadPriority.BelowNormal); else thd = Yengine.StartMyThread(RunScriptThread, "YScript", ThreadPriority.BelowNormal); lock(m_WakeUpLock) m_RunningInstances.Add(thd.ManagedThreadId, null); } public void StopThreadWorkers() { lock(m_WakeUpLock) { while(m_RunningInstances.Count != 0) { Monitor.PulseAll(m_WakeUpLock); Monitor.Wait(m_WakeUpLock, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2); } } } /** * @brief Something was just added to the Start or Yield queue so * wake one of the RunScriptThread() instances to run it. */ public void WakeUpOne() { lock(m_WakeUpLock) { m_WakeUpOne++; Monitor.Pulse(m_WakeUpLock); } } public void SuspendThreads() { lock(m_WakeUpLock) { m_SuspendScriptThreadFlag = true; Monitor.PulseAll(m_WakeUpLock); } } public void ResumeThreads() { lock(m_WakeUpLock) { m_SuspendScriptThreadFlag = false; Monitor.PulseAll(m_WakeUpLock); } } /** * @brief Thread that runs the scripts. * * There are NUMSCRIPTHREADWKRS of these. * Each sits in a loop checking the Start and Yield queues for * a script to run and calls the script as a microthread. */ private void RunScriptThread() { int tid = System.Threading.Thread.CurrentThread.ManagedThreadId; ThreadStart thunk; XMRInstance inst; bool didevent; m_ScriptThreadTID = tid; while(!m_Exiting) { Yengine.UpdateMyThread(); lock(m_WakeUpLock) { // Maybe there are some scripts waiting to be migrated in or out. thunk = null; if(m_ThunkQueue.Count > 0) thunk = m_ThunkQueue.Dequeue(); // Handle 'xmr resume/suspend' commands. else if(m_SuspendScriptThreadFlag && !m_Exiting) { Monitor.Wait(m_WakeUpLock, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2); Yengine.UpdateMyThread(); continue; } } if(thunk != null) { thunk(); continue; } if(m_StartProcessing) { // If event just queued to any idle scripts // start them right away. But only start so // many so we can make some progress on yield // queue. int numStarts; didevent = false; for(numStarts = 5; numStarts >= 0; --numStarts) { lock(m_StartQueue) inst = m_StartQueue.RemoveHead(); if(inst == null) break; if(inst.m_IState != XMRInstState.ONSTARTQ) throw new Exception("bad state"); RunInstance(inst, tid); if(m_SuspendScriptThreadFlag || m_Exiting) continue; didevent = true; } // If there is something to run, run it // then rescan from the beginning in case // a lot of things have changed meanwhile. // // These are considered lower priority than // m_StartQueue as they have been taking at // least one quantum of CPU time and event // handlers are supposed to be quick. lock(m_YieldQueue) inst = m_YieldQueue.RemoveHead(); if(inst != null) { if(inst.m_IState != XMRInstState.ONYIELDQ) throw new Exception("bad state"); RunInstance(inst, tid); continue; } // If we left something dangling in the m_StartQueue or m_YieldQueue, go back to check it. if(didevent) continue; } // Nothing to do, sleep. lock(m_WakeUpLock) { if(!m_WakeUpThis && (m_WakeUpOne <= 0) && !m_Exiting) Monitor.Wait(m_WakeUpLock, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2); m_WakeUpThis = false; if((m_WakeUpOne > 0) && (--m_WakeUpOne > 0)) Monitor.Pulse(m_WakeUpLock); } } lock(m_WakeUpLock) m_RunningInstances.Remove(tid); Yengine.MyThreadExiting(); } /** * @brief A script instance was just removed from the Start or Yield Queue. * So run it for a little bit then stick in whatever queue it should go in. */ private void RunInstance(XMRInstance inst, int tid) { m_LastRanAt = DateTime.UtcNow; m_ScriptExecTime -= (long)(m_LastRanAt - DateTime.MinValue).TotalMilliseconds; inst.m_IState = XMRInstState.RUNNING; lock(m_WakeUpLock) m_RunningInstances[tid] = inst; XMRInstState newIState = inst.RunOne(); lock(m_WakeUpLock) m_RunningInstances[tid] = null; HandleNewIState(inst, newIState); m_ScriptExecTime += (long)(DateTime.UtcNow - DateTime.MinValue).TotalMilliseconds; } } }
using Foundation; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using UIKit; using zsquared; namespace vitavol { public partial class VC_MySignUps : UIViewController { // Input: // LoggedInUser // SelectedDate // SelectedSite // CalendarDate ??? // AllSites C_Global Global; C_VitaUser LoggedInUser; public VC_MySignUps (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); B_Back.TouchUpInside += (sender, e) => PerformSegue("Segue_MySignUpsToVolunteerOptions", this); AI_Busy.StartAnimating(); EnableUI(false); Task.Run(async () => { // get all workintents for this user List<C_SignUp> OurSignUps = Global.GetSignUpsForUser(Global.LoggedInUserId); // make sure we only look at the current items (today and beyond) C_YMD today = C_YMD.Now; var ou = OurSignUps.Where(wi => wi.Date >= today); List<C_SignUp> OurWorkItems2 = ou.ToList(); // sort to make the list nicer OurWorkItems2.Sort(C_SignUp.CompareByDateThenSiteAscending); bool succ1 = await Global.EnsureShiftsInCacheForSignUps(LoggedInUser.Token, OurSignUps); UIApplication.SharedApplication.InvokeOnMainThread( new Action(() => { AI_Busy.StopAnimating(); EnableUI(true); C_MySignUpsTableSourceWorkIntents ts = new C_MySignUpsTableSourceWorkIntents(Global, OurWorkItems2); TV_SignUps.Source = ts; TV_SignUps.Delegate = new C_MySignUpsTableDelegateWorkIntents(Global, this, ts); TV_SignUps.ReloadData(); })); }); } public override void ViewDidAppear(bool animated) { // set the standard background color View.BackgroundColor = C_Common.StandardBackground; TV_SignUps.BackgroundColor = C_Common.StandardBackground; } private void EnableUI(bool en) { TV_SignUps.UserInteractionEnabled = en; B_Back.Enabled = en; } /// <summary> /// Class is the table view delegate to handle slide, aka delete of signup; and the touch of a row /// </summary> public class C_MySignUpsTableDelegateWorkIntents : UITableViewDelegate { readonly C_Global Global; readonly VC_MySignUps OurVC; readonly C_MySignUpsTableSourceWorkIntents TableSource; public C_MySignUpsTableDelegateWorkIntents(C_Global global, VC_MySignUps vc, C_MySignUpsTableSourceWorkIntents tsource) { Global = global; OurVC = vc; TableSource = tsource; } public override UITableViewRowAction[] EditActionsForRow(UITableView tableView, NSIndexPath indexPath) { UITableViewRowAction hiButton = UITableViewRowAction.Create(UITableViewRowActionStyle.Default, "Remove", async delegate { C_SignUp signupToRemove = TableSource.OurSignUps[indexPath.Row]; OurVC.AI_Busy.StartAnimating(); OurVC.EnableUI(false); C_VitaUser loggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); C_VitaSite site = Global.GetSiteFromSlugNoFetch(signupToRemove.SiteSlug); C_IOResult ior = await Global.RemoveIntent(signupToRemove, loggedInUser.Token); Global.RemoveFromSignUps(signupToRemove); Global.AdjustSiteSchedueCacheForRemovedSignUp(signupToRemove, loggedInUser, site); // remove from the calendar entry, shifts, signups C_CalendarEntry calEntry = site.GetCalendarEntryForDate(signupToRemove.Date); foreach(C_WorkShift ws in calEntry.WorkShifts) { C_WorkShiftSignUp str = null; foreach(C_WorkShiftSignUp wssu in ws.SignUps) { if (wssu.User.UserId == Global.LoggedInUserId) { str = wssu; break; } } if (str != null) { ws.SignUps.Remove(str); break; } } TableSource.OurSignUps.Remove(signupToRemove); OurVC.EnableUI(true); OurVC.AI_Busy.StopAnimating(); OurVC.TV_SignUps.ReloadData(); }); return new UITableViewRowAction[] { hiButton }; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { // identify the specific signup Global.SelectedSignUp = TableSource.OurSignUps[indexPath.Row]; // make sure the calendar starts on today if we get there Global.CalendarDate = null; // these are required by VC_SignUp Global.ViewCameFrom = E_ViewCameFrom.MySignUps; Global.SelectedDate = Global.SelectedSignUp.Date; Global.SelectedSiteSlug = Global.SelectedSignUp.SiteSlug; C_WorkShift ws = Global.GetWorkShiftById(Global.SelectedSignUp.ShiftId); Global.SelectedShift = ws; OurVC.PerformSegue("Segue_MySignUpsToSignUp", OurVC); } } public class C_MySignUpsTableSourceWorkIntents : UITableViewSource { const string CellIdentifier = "TableCell_SignUpsTableSourceMySignUps"; public List<C_SignUp> OurSignUps; readonly C_Global Global; public C_MySignUpsTableSourceWorkIntents(C_Global global, List<C_SignUp> ourWorkItems) { Global = global; OurSignUps = ourWorkItems; } public override nint RowsInSection(UITableView tableview, nint section) { int count = 0; if (OurSignUps != null) count = OurSignUps.Count; return count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); //---- if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier); C_SignUp wi = OurSignUps[indexPath.Row]; C_WorkShift ws = Global.GetWorkShiftById(wi.ShiftId); cell.TextLabel.Text = wi.SiteName; cell.DetailTextLabel.Text = wi.Date.ToString() + " [" + ws.OpenTime.ToString("hh:mm p").Trim() + " - " + ws.CloseTime.ToString("hh:mm p") + "]"; return cell; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using EasyRoads3D; public class RoadObjectScript : MonoBehaviour { static public string version = ""; public int objectType = 0; public bool displayRoad = true; public float roadWidth = 5.0f; public float indent = 3.0f; public float surrounding = 5.0f; public float raise = 1.0f; public float raiseMarkers = 0.5f; public bool OOQDOOQQ = false; public bool renderRoad = true; public bool beveledRoad = false; public bool applySplatmap = false; public int splatmapLayer = 4; public bool autoUpdate = true; public float geoResolution = 5.0f; public int roadResolution = 1; public float tuw = 15.0f; public int splatmapSmoothLevel; public float opacity = 1.0f; public int expand = 0; public int offsetX = 0; public int offsetY = 0; private Material surfaceMaterial; public float surfaceOpacity = 1.0f; public float smoothDistance = 1.0f; public float smoothSurDistance = 3.0f; private bool handleInsertFlag; public bool handleVegetation = true; public float OOQCQCCODC = 2.0f; public float OCCCCQCDCO = 1f; public int materialType = 0; String[] materialStrings; public string uname; public string email; private MarkerScript[] mSc; private bool OOOCDCDDOC; private bool[] OQOCCODCDC = null; private bool[] OQCCQQDDCD = null; public string[] OOOOCCDODD; public string[] ODODQOQO; public int[] ODODQOQOInt; public int ODQQOODQCD = -1; public int ODCDOCQQQC = -1; static public GUISkin ODCQOCODOC; static public GUISkin OQODOOOQQQ; public bool OODCDQCQDD = false; private Vector3 cPos; private Vector3 ePos; public bool OCQQQCOCOD; static public Texture2D ODOODQCOCO; public int markers = 1; public OCQCCDQCDQ OQDDQQDOOD; private GameObject ODOQDQOO; public bool ODQDDDCCOQ; public bool doTerrain; private Transform OQOCODQDCD = null; public GameObject[] OQOCODQDCDs; private static string OOQQQODDOO = null; public Transform obj; private string OOOQCDOQCD; public static string erInit = ""; static public Transform ODQQCQCOQC; private RoadObjectScript OQOCCDQQCQ; public bool flyby; private Vector3 pos; private float fl; private float oldfl; private bool OQODQQDDOO; private bool OCQODDQCDD; private bool ODQCOQCCDD; public Transform ODQOCCDOQQ; public int OdQODQOD = 1; public float OOQQQDOD = 0f; public float OOQQQDODOffset = 0f; public float OOQQQDODLength = 0f; public bool ODODDDOO = false; static public string[] ODOQDOQO; static public string[] ODODOQQO; static public string[] ODODQOOQ; public int ODQDOOQO = 0; public string[] ODQQQQQO; public string[] ODODDQOO; public bool[] ODODQQOD; public int[] OOQQQOQO; public int ODOQOOQO = 0; public bool forceY = false; public float yChange = 0f; public float floorDepth = 2f; public float waterLevel = 1.5f; public bool lockWaterLevel = true; public float lastY = 0f; public string distance = "0"; public string markerDisplayStr = "Hide Markers"; static public string[] objectStrings; public string objectText = "Road"; public bool applyAnimation = false; public float waveSize = 1.5f; public float waveHeight = 0.15f; public bool snapY = true; private TextAnchor origAnchor; public bool autoODODDQQO; public Texture2D roadTexture; public Texture2D roadMaterial; public string[] ODOCQCDCDQ; public string[] OCCOOCQDOO; public int selectedWaterMaterial; public int selectedWaterScript; private bool doRestore = false; public bool doFlyOver; public static GameObject tracer; public Camera goCam; public float speed = 1f; public float offset = 0f; public bool camInit; public GameObject customMesh = null; static public bool disableFreeAlerts = true; public bool multipleTerrains; public bool editRestore = true; public Material roadMaterialEdit; static public int backupLocation = 0; public string[] backupStrings = new string[2]{"Outside Assets folder path","Inside Assets folder path"}; public Vector3[] leftVecs = new Vector3[0]; public Vector3[] rightVecs = new Vector3[0]; public bool applyTangents = false; public bool sosBuild = false; public float splinePos = 0; public float camHeight = 3; public Vector3 splinePosV3 = Vector3.zero; public bool blendFlag; public float startBlendDistance = 5; public float endBlendDistance = 5; public bool iOS = false; static public string extensionPath = ""; public void OQOOODDDDO(List<ODODDQQO> arr, String[] DOODQOQO, String[] OODDQOQO){ ODQOODDCCC(transform, arr, DOODQOQO, OODDQOQO); } public void ODQDDDQOQC(MarkerScript markerScript){ OQOCODQDCD = markerScript.transform; List<GameObject> tmp = new List<GameObject>(); for(int i=0;i<OQOCODQDCDs.Length;i++){ if(OQOCODQDCDs[i] != markerScript.gameObject)tmp.Add(OQOCODQDCDs[i]); } tmp.Add(markerScript.gameObject); OQOCODQDCDs = tmp.ToArray(); OQOCODQDCD = markerScript.transform; OQDDQQDOOD.ODOCCCCQQO(OQOCODQDCD, OQOCODQDCDs, markerScript.ODQOQOQOQO, markerScript.OQOCOODCQC, ODQOCCDOQQ, out markerScript.OQOCODQDCDs, out markerScript.trperc, OQOCODQDCDs); ODCDOCQQQC = -1; } public void OQCCQQODQO(MarkerScript markerScript){ if(markerScript.OQOCOODCQC != markerScript.ODOOQQOO || markerScript.OQOCOODCQC != markerScript.ODOOQQOO){ OQDDQQDOOD.ODOCCCCQQO(OQOCODQDCD, OQOCODQDCDs, markerScript.ODQOQOQOQO, markerScript.OQOCOODCQC, ODQOCCDOQQ, out markerScript.OQOCODQDCDs, out markerScript.trperc, OQOCODQDCDs); markerScript.ODQDOQOO = markerScript.ODQOQOQOQO; markerScript.ODOOQQOO = markerScript.OQOCOODCQC; } if(OQOCCDQQCQ.autoUpdate) ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); } public void ResetMaterials(MarkerScript markerScript){ if(OQDDQQDOOD != null)OQDDQQDOOD.ODOCCCCQQO(OQOCODQDCD, OQOCODQDCDs, markerScript.ODQOQOQOQO, markerScript.OQOCOODCQC, ODQOCCDOQQ, out markerScript.OQOCODQDCDs, out markerScript.trperc, OQOCODQDCDs); } public void OQODOQDQOC(MarkerScript markerScript){ if(markerScript.OQOCOODCQC != markerScript.ODOOQQOO){ OQDDQQDOOD.ODOCCCCQQO(OQOCODQDCD, OQOCODQDCDs, markerScript.ODQOQOQOQO, markerScript.OQOCOODCQC, ODQOCCDOQQ, out markerScript.OQOCODQDCDs, out markerScript.trperc, OQOCODQDCDs); markerScript.ODOOQQOO = markerScript.OQOCOODCQC; } ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); } private void ODDODDCQOQ(string ctrl, MarkerScript markerScript){ int i = 0; foreach(Transform tr in markerScript.OQOCODQDCDs){ MarkerScript wsScript = (MarkerScript) tr.GetComponent<MarkerScript>(); if(ctrl == "rs") wsScript.LeftSurrounding(markerScript.rs - markerScript.ODOQQOOO, markerScript.trperc[i]); else if(ctrl == "ls") wsScript.RightSurrounding(markerScript.ls - markerScript.DODOQQOO, markerScript.trperc[i]); else if(ctrl == "ri") wsScript.LeftIndent(markerScript.ri - markerScript.OOQOQQOO, markerScript.trperc[i]); else if(ctrl == "li") wsScript.RightIndent(markerScript.li - markerScript.ODODQQOO, markerScript.trperc[i]); else if(ctrl == "rt") wsScript.LeftTilting(markerScript.rt - markerScript.ODDQODOO, markerScript.trperc[i]); else if(ctrl == "lt") wsScript.RightTilting(markerScript.lt - markerScript.ODDOQOQQ, markerScript.trperc[i]); else if(ctrl == "floorDepth") wsScript.FloorDepth(markerScript.floorDepth - markerScript.oldFloorDepth, markerScript.trperc[i]); i++; } } public void OQQOQQCQDO(){ if(markers > 1) ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); } public void ODQOODDCCC(Transform tr, List<ODODDQQO> arr, String[] DOODQOQO, String[] OODDQOQO){ version = "2.5.8"; ODCQOCODOC = (GUISkin)Resources.Load("ER3DSkin", typeof(GUISkin)); ODOODQCOCO = (Texture2D)Resources.Load("ER3DLogo", typeof(Texture2D)); if(RoadObjectScript.objectStrings == null){ RoadObjectScript.objectStrings = new string[3]; RoadObjectScript.objectStrings[0] = "Road Object"; RoadObjectScript.objectStrings[1]="River Object";RoadObjectScript.objectStrings[2]="Procedural Mesh Object"; } obj = tr; OQDDQQDOOD = new OCQCCDQCDQ(); OQOCCDQQCQ = obj.GetComponent<RoadObjectScript>(); foreach(Transform child in obj){ if(child.name == "Markers") ODQOCCDOQQ = child; } RoadObjectScript[] rscrpts = (RoadObjectScript[])FindObjectsOfType(typeof(RoadObjectScript)); OCQCCDQCDQ.terrainList.Clear(); Terrain[] terrains = (Terrain[])FindObjectsOfType(typeof(Terrain)); foreach(Terrain terrain in terrains) { Terrains t = new Terrains(); t.terrain = terrain; if(!terrain.gameObject.GetComponent<EasyRoads3DTerrainID>()){ EasyRoads3DTerrainID terrainscript = (EasyRoads3DTerrainID)terrain.gameObject.AddComponent<EasyRoads3DTerrainID>(); string id = UnityEngine.Random.Range(100000000,999999999).ToString(); terrainscript.terrainid = id; t.id = id; }else{ t.id = terrain.gameObject.GetComponent<EasyRoads3DTerrainID>().terrainid; } OQDDQQDOOD.OOCCQCDQOD(t); } ODDDCQCDCO.OOCCQCDQOD(); if(roadMaterialEdit == null){ roadMaterialEdit = (Material)Resources.Load("materials/roadMaterialEdit", typeof(Material)); } if(objectType == 0 && GameObject.Find(gameObject.name + "/road") == null){ GameObject road = new GameObject("road"); road.transform.parent = transform; } OQDDQQDOOD.ODOOCCDDDO(obj, OOQQQODDOO, OQOCCDQQCQ.roadWidth, surfaceOpacity, out OCQQQCOCOD, out indent, applyAnimation, waveSize, waveHeight); OQDDQQDOOD.OCCCCQCDCO = OCCCCQCDCO; OQDDQQDOOD.OOQCQCCODC = OOQCQCCODC; OQDDQQDOOD.OdQODQOD = OdQODQOD + 1; OQDDQQDOOD.OOQQQDOD = OOQQQDOD; OQDDQQDOOD.OOQQQDODOffset = OOQQQDODOffset; OQDDQQDOOD.OOQQQDODLength = OOQQQDODLength; OQDDQQDOOD.objectType = objectType; OQDDQQDOOD.snapY = snapY; OQDDQQDOOD.terrainRendered = ODQDDDCCOQ; OQDDQQDOOD.handleVegetation = handleVegetation; OQDDQQDOOD.raise = raise; OQDDQQDOOD.roadResolution = roadResolution; OQDDQQDOOD.multipleTerrains = multipleTerrains; OQDDQQDOOD.editRestore = editRestore; OQDDQQDOOD.roadMaterialEdit = roadMaterialEdit; OQDDQQDOOD.renderRoad = renderRoad; OQDDQQDOOD.rscrpts = rscrpts.Length; OQDDQQDOOD.blendFlag = blendFlag; OQDDQQDOOD.startBlendDistance = startBlendDistance; OQDDQQDOOD.endBlendDistance = endBlendDistance; if(backupLocation == 0)OCDOQDQQDQ.backupFolder = "/EasyRoads3D"; else OCDOQDQQDQ.backupFolder = OCDOQDQQDQ.extensionPath + "/Backups"; ODODQOQO = OQDDQQDOOD.OOCODCOOQC(); ODODQOQOInt = OQDDQQDOOD.ODQODCCOOO(); if(ODQDDDCCOQ){ doRestore = true; } OQOQDCCDDD(); if(arr != null || ODODQOOQ == null) ODQQOCCDCC(arr, DOODQOQO, OODDQOQO); if(doRestore) return; } public void UpdateBackupFolder(){ } public void ODQDOQCQCQ(){ if(!ODODDDOO || objectType == 2){ if(OQOCCODCDC != null){ for(int i = 0; i < OQOCCODCDC.Length; i++){ OQOCCODCDC[i] = false; OQCCQQDDCD[i] = false; } } } } public void OODDQQCOOQ(Vector3 pos){ if(!displayRoad){ displayRoad = true; OQDDQQDOOD.OCQOQQOCCQ(displayRoad, ODQOCCDOQQ); } pos.y += OQOCCDQQCQ.raiseMarkers; if(forceY && ODOQDQOO != null){ float dist = Vector3.Distance(pos, ODOQDQOO.transform.position); pos.y = ODOQDQOO.transform.position.y + (yChange * (dist / 100f)); }else if(forceY && markers == 0) lastY = pos.y; GameObject go = null; if (ODOQDQOO != null) go = (GameObject)Instantiate (ODOQDQOO); else { go = Instantiate (Resources.Load ("marker", typeof(GameObject))) as GameObject; } Transform newnode = go.transform; newnode.position = pos; newnode.parent = ODQOCCDOQQ; markers++; string n; if(markers < 10) n = "Marker000" + markers.ToString(); else if (markers < 100) n = "Marker00" + markers.ToString(); else n = "Marker0" + markers.ToString(); newnode.gameObject.name = n; MarkerScript scr = newnode.GetComponent<MarkerScript>(); foreach(Transform child in go.transform) { if(child.name == "surface"){ scr.surface = child; if(child.GetComponent<MeshFilter>()){ if(child.GetComponent<MeshFilter> ().sharedMesh == null)child.GetComponent<MeshFilter> ().sharedMesh = new Mesh (); if(child.GetComponent<MeshCollider>()){ child.GetComponent<MeshCollider> ().sharedMesh = child.GetComponent<MeshFilter> ().sharedMesh; } } } } scr.OCQQQCOCOD = false; scr.objectScript = obj.GetComponent<RoadObjectScript>(); if(ODOQDQOO == null){ scr.waterLevel = OQOCCDQQCQ.waterLevel; scr.floorDepth = OQOCCDQQCQ.floorDepth; scr.ri = OQOCCDQQCQ.indent; scr.li = OQOCCDQQCQ.indent; scr.rs = OQOCCDQQCQ.surrounding; scr.ls = OQOCCDQQCQ.surrounding; scr.tension = 0.5f; if(objectType == 1){ pos.y -= waterLevel; newnode.position = pos; } } if(objectType == 2){ #if UNITY_3_5 if(scr.surface != null)scr.surface.gameObject.active = false; #else if(scr.surface != null)scr.surface.gameObject.SetActive(false); #endif } ODOQDQOO = newnode.gameObject; if(markers > 1){ ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); if(materialType == 0){ OQDDQQDOOD.OOCQQDOODD(materialType); } } } public void ODOCDCQOCC(float geo, bool renderMode, bool camMode){ OQDDQQDOOD.ODQOQOOQOD.Clear(); int ii = 0; OOCDDDDOQQ k; foreach(Transform child in obj) { if(child.name == "Markers"){ foreach(Transform marker in child) { MarkerScript markerScript = marker.GetComponent<MarkerScript>(); markerScript.objectScript = obj.GetComponent<RoadObjectScript>(); if(!markerScript.OCQQQCOCOD) markerScript.OCQQQCOCOD = OQDDQQDOOD.ODDCOODQQC(marker); k = new OOCDDDDOQQ(); k.position = marker.position; k.num = OQDDQQDOOD.ODQOQOOQOD.Count; k.object1 = marker; k.object2 = markerScript.surface; k.tension = markerScript.tension; k.ri = markerScript.ri; if(k.ri < 1)k.ri = 1f; k.li =markerScript.li; if(k.li < 1)k.li = 1f; k.rt = markerScript.rt; k.lt = markerScript.lt; k.rs = markerScript.rs; if(k.rs < 1)k.rs = 1f; k.OQCCQDOOCD = markerScript.rs; k.ls = markerScript.ls; if(k.ls < 1)k.ls = 1f; k.OCDQOOQQDD = markerScript.ls; k.renderFlag = markerScript.bridgeObject; k.OOCQOQOODD = markerScript.distHeights; k.newSegment = markerScript.newSegment; k.tunnelFlag = markerScript.tunnelFlag; k.floorDepth = markerScript.floorDepth; k.waterLevel = waterLevel; k.lockWaterLevel = markerScript.lockWaterLevel; k.sharpCorner = markerScript.sharpCorner; k.OCOOQQOQDQ = OQDDQQDOOD; markerScript.markerNum = ii; markerScript.distance = "-1"; markerScript.OCDQDCCQQD = "-1"; OQDDQQDOOD.ODQOQOOQOD.Add(k); ii++; } } } distance = "-1"; OQDDQQDOOD.OCCQOODDDC = OQOCCDQQCQ.roadWidth; OQDDQQDOOD.OCDDDCCDOD(geo, obj, OQOCCDQQCQ.OOQDOOQQ, renderMode, camMode, objectType); if(OQDDQQDOOD.leftVecs.Count > 0){ leftVecs = OQDDQQDOOD.leftVecs.ToArray(); rightVecs = OQDDQQDOOD.rightVecs.ToArray(); } } public void StartCam(){ ODOCDCQOCC(0.5f, false, true); } public void OQOQDCCDDD(){ int i = 0; foreach(Transform child in obj) { if(child.name == "Markers"){ i = 1; string n; foreach(Transform marker in child) { if(i < 10) n = "Marker000" + i.ToString(); else if (i < 100) n = "Marker00" + i.ToString(); else n = "Marker0" + i.ToString(); marker.name = n; ODOQDQOO = marker.gameObject; i++; } } } markers = i - 1; ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); } public List<Transform> RebuildObjs(){ RoadObjectScript[] scripts = (RoadObjectScript[])FindObjectsOfType(typeof(RoadObjectScript)); List<Transform> rObj = new List<Transform>(); foreach (RoadObjectScript script in scripts) { if(script.transform != transform) rObj.Add(script.transform); } return rObj; } public void RestoreTerrain1(){ ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); if(OQDDQQDOOD != null) OQDDQQDOOD.OCQQQQODCD(); ODODDDOO = false; } public void OCCQQCQCCD(){ OQDDQQDOOD.OCCQQCQCCD(OQOCCDQQCQ.applySplatmap, OQOCCDQQCQ.splatmapSmoothLevel, OQOCCDQQCQ.renderRoad, OQOCCDQQCQ.tuw, OQOCCDQQCQ.roadResolution, OQOCCDQQCQ.raise, OQOCCDQQCQ.opacity, OQOCCDQQCQ.expand, OQOCCDQQCQ.offsetX, OQOCCDQQCQ.offsetY, OQOCCDQQCQ.beveledRoad, OQOCCDQQCQ.splatmapLayer, OQOCCDQQCQ.OdQODQOD, OOQQQDOD, OOQQQDODOffset, OOQQQDODLength); } public void OOCDQCCDQC(){ OQDDQQDOOD.OOCDQCCDQC(OQOCCDQQCQ.renderRoad, OQOCCDQQCQ.tuw, OQOCCDQQCQ.roadResolution, OQOCCDQQCQ.raise, OQOCCDQQCQ.beveledRoad, OQOCCDQQCQ.OdQODQOD, OOQQQDOD, OOQQQDODOffset, OOQQQDODLength); } public void OQQDQCDQCQ(Vector3 pos, bool doInsert){ if(!displayRoad){ displayRoad = true; OQDDQQDOOD.OCQOQQOCCQ(displayRoad, ODQOCCDOQQ); } int first = -1; int second = -1; float dist1 = 10000; float dist2 = 10000; Vector3 newpos = pos; OOCDDDDOQQ k; OOCDDDDOQQ k1 = (OOCDDDDOQQ)OQDDQQDOOD.ODQOQOOQOD[0]; OOCDDDDOQQ k2 = (OOCDDDDOQQ)OQDDQQDOOD.ODQOQOOQOD[1]; if(doInsert){ } OQDDQQDOOD.ODDDQDQDCQ(pos, out first, out second, out dist1, out dist2, out k1, out k2, out newpos, doInsert); if(doInsert){ } pos = newpos; if(doInsert && first >= 0 && second >= 0){ if(OQOCCDQQCQ.OOQDOOQQ && second == OQDDQQDOOD.ODQOQOOQOD.Count - 1){ OODDQQCOOQ(pos); }else{ k = (OOCDDDDOQQ)OQDDQQDOOD.ODQOQOOQOD[second]; string name = k.object1.name; string n; int j = second + 2; for(int i = second; i < OQDDQQDOOD.ODQOQOOQOD.Count - 1; i++){ k = (OOCDDDDOQQ)OQDDQQDOOD.ODQOQOOQOD[i]; if(j < 10) n = "Marker000" + j.ToString(); else if (j < 100) n = "Marker00" + j.ToString(); else n = "Marker0" + j.ToString(); k.object1.name = n; j++; } k = (OOCDDDDOQQ)OQDDQQDOOD.ODQOQOOQOD[first]; Transform newnode = (Transform)Instantiate(k.object1.transform, pos, k.object1.rotation); newnode.gameObject.name = name; newnode.parent = ODQOCCDOQQ; newnode.SetSiblingIndex(second); MarkerScript scr = newnode.GetComponent<MarkerScript>(); scr.OCQQQCOCOD = false; float totalDist = dist1 + dist2; float perc1 = dist1 / totalDist; float paramDif = k1.ri - k2.ri; scr.ri = k1.ri - (paramDif * perc1); paramDif = k1.li - k2.li; scr.li = k1.li - (paramDif * perc1); paramDif = k1.rt - k2.rt; scr.rt = k1.rt - (paramDif * perc1); paramDif = k1.lt - k2.lt; scr.lt = k1.lt - (paramDif * perc1); paramDif = k1.rs - k2.rs; scr.rs = k1.rs - (paramDif * perc1); paramDif = k1.ls - k2.ls; scr.ls = k1.ls - (paramDif * perc1); ODOCDCQOCC(OQOCCDQQCQ.geoResolution, false, false); if(materialType == 0)OQDDQQDOOD.OOCQQDOODD(materialType); #if UNITY_3_5 if(objectType == 2) scr.surface.gameObject.active = false; #else if(objectType == 2) scr.surface.gameObject.SetActive(false); #endif } } OQOQDCCDDD(); } public void ODDCDODOQD(){ DestroyImmediate(OQOCCDQQCQ.OQOCODQDCD.gameObject); OQOCODQDCD = null; OQOQDCCDDD(); } public void OOOQOCOCCO(){ } public List<SideObjectParams> OOCOCDOQCQ(){ return null; } public void OCCCDDQQDO(){ } public void ODQQOCCDCC(List<ODODDQQO> arr, String[] DOODQOQO, String[] OODDQOQO){ } public void SetMultipleTerrains(bool flag){ RoadObjectScript[] scrpts = (RoadObjectScript[])FindObjectsOfType(typeof(RoadObjectScript)); foreach(RoadObjectScript scr in scrpts){ scr.multipleTerrains = flag; if(scr.OQDDQQDOOD != null)scr.OQDDQQDOOD.multipleTerrains = flag; } } public bool CheckWaterHeights(){ if(ODDDCQCDCO.terrain == null) return false; bool flag = true; float y = ODDDCQCDCO.terrain.transform.position.y; foreach(Transform child in obj) { if(child.name == "Markers"){ foreach(Transform marker in child) { if(marker.position.y - y <= 0.1f) flag = false; } } } return flag; } }
/* * 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.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace Aurora.Modules.Agent.Xfer { public class XferModule : INonSharedRegionModule, IXfer { private readonly Dictionary<string, FileData> NewFiles = new Dictionary<string, FileData>(); private readonly Dictionary<ulong, XferDownLoad> Transfers = new Dictionary<ulong, XferDownLoad>(); private IScene m_scene; public bool IsSharedModule { get { return false; } } #region INonSharedRegionModule Members public void Initialise(IConfigSource config) { } public void AddRegion(IScene scene) { m_scene = scene; m_scene.EventManager.OnNewClient += NewClient; m_scene.EventManager.OnClosingClient += OnClosingClient; m_scene.RegisterModuleInterface<IXfer>(this); } public void RemoveRegion(IScene scene) { m_scene.EventManager.OnNewClient -= NewClient; m_scene.EventManager.OnClosingClient -= OnClosingClient; m_scene.UnregisterModuleInterface<IXfer>(this); } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public void Close() { } public string Name { get { return "XferModule"; } } #endregion #region IXfer Members /// <summary> /// Let the Xfer module know about a file that the client is about to request. /// Caller is responsible for making sure that the file is here before /// the client starts the XferRequest. /// </summary> /// <param name = "fileName"></param> /// <param name = "data"></param> /// <returns></returns> public bool AddNewFile(string fileName, byte[] data) { lock (NewFiles) { if (NewFiles.ContainsKey(fileName)) { NewFiles[fileName].Count++; NewFiles[fileName].Data = data; } else { FileData fd = new FileData {Count = 1, Data = data}; NewFiles.Add(fileName, fd); } } return true; } #endregion public void PostInitialise() { } public void NewClient(IClientAPI client) { client.OnRequestXfer += RequestXfer; client.OnConfirmXfer += AckPacket; } private void OnClosingClient(IClientAPI client) { client.OnRequestXfer -= RequestXfer; client.OnConfirmXfer -= AckPacket; } ///<summary> ///</summary> ///<param name = "remoteClient"></param> ///<param name = "xferID"></param> ///<param name = "fileName"></param> public void RequestXfer(IClientAPI remoteClient, ulong xferID, string fileName) { lock (NewFiles) { if (NewFiles.ContainsKey(fileName)) { if (!Transfers.ContainsKey(xferID)) { byte[] fileData = NewFiles[fileName].Data; XferDownLoad transaction = new XferDownLoad(fileName, fileData, xferID, remoteClient); Transfers.Add(xferID, transaction); if (transaction.StartSend()) RemoveXferData(xferID); // The transaction for this file is either complete or on its way RemoveOrDecrement(fileName); } } else MainConsole.Instance.WarnFormat("[Xfer]: {0} not found", fileName); } } public void AckPacket(IClientAPI remoteClient, ulong xferID, uint packet) { lock (NewFiles) // This is actually to lock Transfers { if (Transfers.ContainsKey(xferID)) { XferDownLoad dl = Transfers[xferID]; if (Transfers[xferID].AckPacket(packet)) { RemoveXferData(xferID); RemoveOrDecrement(dl.FileName); } } } } private void RemoveXferData(ulong xferID) { // NewFiles must be locked! if (Transfers.ContainsKey(xferID)) { XferDownLoad xferItem = Transfers[xferID]; //string filename = xferItem.FileName; Transfers.Remove(xferID); xferItem.Data = new byte[0]; // Clear the data xferItem.DataPointer = 0; } } public void AbortXfer(IClientAPI remoteClient, ulong xferID) { lock (NewFiles) { if (Transfers.ContainsKey(xferID)) RemoveOrDecrement(Transfers[xferID].FileName); RemoveXferData(xferID); } } private void RemoveOrDecrement(string fileName) { // NewFiles must be locked if (NewFiles.ContainsKey(fileName)) { if (NewFiles[fileName].Count == 1) NewFiles.Remove(fileName); else NewFiles[fileName].Count--; } } #region Nested type: FileData private class FileData { public int Count; public byte[] Data; } #endregion #region Nested type: XferDownLoad public class XferDownLoad { public IClientAPI Client; public byte[] Data = new byte[0]; public int DataPointer; public string FileName = String.Empty; public uint Packet; public uint Serial = 1; public ulong XferID; private bool complete; public XferDownLoad(string fileName, byte[] data, ulong xferID, IClientAPI client) { FileName = fileName; Data = data; XferID = xferID; Client = client; } public XferDownLoad() { } /// <summary> /// Start a transfer /// </summary> /// <returns>True if the transfer is complete, false if not</returns> public bool StartSend() { if (Data.Length < 1000) { // for now (testing) we only support files under 1000 bytes byte[] transferData = new byte[Data.Length + 4]; Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4); Array.Copy(Data, 0, transferData, 4, Data.Length); Client.SendXferPacket(XferID, 0 + 0x80000000, transferData); complete = true; } else { byte[] transferData = new byte[1000 + 4]; Array.Copy(Utils.IntToBytes(Data.Length), 0, transferData, 0, 4); Array.Copy(Data, 0, transferData, 4, 1000); Client.SendXferPacket(XferID, 0, transferData); Packet++; DataPointer = 1000; } return complete; } /// <summary> /// Respond to an ack packet from the client /// </summary> /// <param name = "packet"></param> /// <returns>True if the transfer is complete, false otherwise</returns> public bool AckPacket(uint packet) { if (!complete) { if ((Data.Length - DataPointer) > 1000) { byte[] transferData = new byte[1000]; Array.Copy(Data, DataPointer, transferData, 0, 1000); Client.SendXferPacket(XferID, Packet, transferData); Packet++; DataPointer += 1000; } else { byte[] transferData = new byte[Data.Length - DataPointer]; Array.Copy(Data, DataPointer, transferData, 0, Data.Length - DataPointer); uint endPacket = Packet |= 0x80000000; Client.SendXferPacket(XferID, endPacket, transferData); Packet++; DataPointer += (Data.Length - DataPointer); complete = true; } } return complete; } } #endregion #region Nested type: XferRequest public struct XferRequest { public string fileName; public IClientAPI remoteClient; public DateTime timeStamp; public ulong xferID; } #endregion } }
using System.Threading; using MetaDslx.Compiler; using MetaDslx.Compiler.Syntax; using MetaDslx.Compiler.Text; namespace DevToolsX.Documents.Compilers.SeleniumUI.Syntax { public enum SeleniumUITokenKind : int { None = 0, Comment, Identifier, Keyword, Number, String, Whitespace } public enum SeleniumUILexerMode : int { None = 0, DEFAULT_MODE = 0, LMultilineComment = 1, DOUBLEQUOTE_VERBATIM_STRING = 2, SINGLEQUOTE_VERBATIM_STRING = 3 } public class SeleniumUISyntaxFacts : SyntaxFacts { public static readonly SeleniumUISyntaxFacts Instance = new SeleniumUISyntaxFacts(); protected override int DefaultEndOfLineSyntaxKindCore { get { return (int)SeleniumUISyntaxKind.LCrLf; } } protected override int DefaultWhitespaceSyntaxKindCore { get { return (int)SeleniumUISyntaxKind.LWhiteSpace; } } public override bool IsToken(int rawKind) { return this.IsToken((SeleniumUISyntaxKind)rawKind); } public bool IsToken(SeleniumUISyntaxKind kind) { switch (kind) { case SeleniumUISyntaxKind.Eof: case SeleniumUISyntaxKind.KParent: case SeleniumUISyntaxKind.KAncestor: case SeleniumUISyntaxKind.KNamespace: case SeleniumUISyntaxKind.KPage: case SeleniumUISyntaxKind.KElement: case SeleniumUISyntaxKind.KTag: case SeleniumUISyntaxKind.TSemicolon: case SeleniumUISyntaxKind.TColon: case SeleniumUISyntaxKind.TDot: case SeleniumUISyntaxKind.TComma: case SeleniumUISyntaxKind.TAssign: case SeleniumUISyntaxKind.TOpenParen: case SeleniumUISyntaxKind.TCloseParen: case SeleniumUISyntaxKind.TOpenBracket: case SeleniumUISyntaxKind.TCloseBracket: case SeleniumUISyntaxKind.TOpenBrace: case SeleniumUISyntaxKind.TCloseBrace: case SeleniumUISyntaxKind.TLessThan: case SeleniumUISyntaxKind.TGreaterThan: case SeleniumUISyntaxKind.TQuestion: case SeleniumUISyntaxKind.LIdentifier: case SeleniumUISyntaxKind.LInteger: case SeleniumUISyntaxKind.LDecimal: case SeleniumUISyntaxKind.LScientific: case SeleniumUISyntaxKind.LRegularString: case SeleniumUISyntaxKind.LUtf8Bom: case SeleniumUISyntaxKind.LWhiteSpace: case SeleniumUISyntaxKind.LCrLf: case SeleniumUISyntaxKind.LLineEnd: case SeleniumUISyntaxKind.LSingleLineComment: case SeleniumUISyntaxKind.LComment: case SeleniumUISyntaxKind.LDoubleQuoteVerbatimString: case SeleniumUISyntaxKind.LSingleQuoteVerbatimString: case SeleniumUISyntaxKind.DoubleQuoteVerbatimStringLiteralStart: case SeleniumUISyntaxKind.SingleQuoteVerbatimStringLiteralStart: case SeleniumUISyntaxKind.LCommentStart: case SeleniumUISyntaxKind.LComment_Star: return true; default: return false; } } public override bool IsFixedToken(int rawKind) { return this.IsFixedToken((SeleniumUISyntaxKind)rawKind); } public bool IsFixedToken(SeleniumUISyntaxKind kind) { switch (kind) { case SeleniumUISyntaxKind.Eof: case SeleniumUISyntaxKind.KParent: case SeleniumUISyntaxKind.KAncestor: case SeleniumUISyntaxKind.KNamespace: case SeleniumUISyntaxKind.KPage: case SeleniumUISyntaxKind.KElement: case SeleniumUISyntaxKind.KTag: case SeleniumUISyntaxKind.TSemicolon: case SeleniumUISyntaxKind.TColon: case SeleniumUISyntaxKind.TDot: case SeleniumUISyntaxKind.TComma: case SeleniumUISyntaxKind.TAssign: case SeleniumUISyntaxKind.TOpenParen: case SeleniumUISyntaxKind.TCloseParen: case SeleniumUISyntaxKind.TOpenBracket: case SeleniumUISyntaxKind.TCloseBracket: case SeleniumUISyntaxKind.TOpenBrace: case SeleniumUISyntaxKind.TCloseBrace: case SeleniumUISyntaxKind.TLessThan: case SeleniumUISyntaxKind.TGreaterThan: case SeleniumUISyntaxKind.TQuestion: case SeleniumUISyntaxKind.DoubleQuoteVerbatimStringLiteralStart: case SeleniumUISyntaxKind.SingleQuoteVerbatimStringLiteralStart: case SeleniumUISyntaxKind.LCommentStart: case SeleniumUISyntaxKind.LComment_Star: case SeleniumUISyntaxKind.LDoubleQuoteVerbatimString: case SeleniumUISyntaxKind.LSingleQuoteVerbatimString: return true; default: return false; } } public override string GetText(int rawKind) { return this.GetText((SeleniumUISyntaxKind)rawKind); } public string GetText(SeleniumUISyntaxKind kind) { switch (kind) { case SeleniumUISyntaxKind.KParent: return "parent"; case SeleniumUISyntaxKind.KAncestor: return "ancestor"; case SeleniumUISyntaxKind.KNamespace: return "namespace"; case SeleniumUISyntaxKind.KPage: return "page"; case SeleniumUISyntaxKind.KElement: return "element"; case SeleniumUISyntaxKind.KTag: return "tag"; case SeleniumUISyntaxKind.TSemicolon: return ";"; case SeleniumUISyntaxKind.TColon: return ":"; case SeleniumUISyntaxKind.TDot: return "."; case SeleniumUISyntaxKind.TComma: return ","; case SeleniumUISyntaxKind.TAssign: return "="; case SeleniumUISyntaxKind.TOpenParen: return "("; case SeleniumUISyntaxKind.TCloseParen: return ")"; case SeleniumUISyntaxKind.TOpenBracket: return "["; case SeleniumUISyntaxKind.TCloseBracket: return "]"; case SeleniumUISyntaxKind.TOpenBrace: return "{"; case SeleniumUISyntaxKind.TCloseBrace: return "}"; case SeleniumUISyntaxKind.TLessThan: return "<"; case SeleniumUISyntaxKind.TGreaterThan: return ">"; case SeleniumUISyntaxKind.TQuestion: return "?"; case SeleniumUISyntaxKind.DoubleQuoteVerbatimStringLiteralStart: return "@\""; case SeleniumUISyntaxKind.SingleQuoteVerbatimStringLiteralStart: return "@\'"; case SeleniumUISyntaxKind.LCommentStart: return "/*"; case SeleniumUISyntaxKind.LComment_Star: return "*"; case SeleniumUISyntaxKind.LDoubleQuoteVerbatimString: return "\""; case SeleniumUISyntaxKind.LSingleQuoteVerbatimString: return "\'"; default: return string.Empty; } } public SeleniumUISyntaxKind GetKind(string text) { switch (text) { case "parent": return SeleniumUISyntaxKind.KParent; case "ancestor": return SeleniumUISyntaxKind.KAncestor; case "namespace": return SeleniumUISyntaxKind.KNamespace; case "page": return SeleniumUISyntaxKind.KPage; case "element": return SeleniumUISyntaxKind.KElement; case "tag": return SeleniumUISyntaxKind.KTag; case ";": return SeleniumUISyntaxKind.TSemicolon; case ":": return SeleniumUISyntaxKind.TColon; case ".": return SeleniumUISyntaxKind.TDot; case ",": return SeleniumUISyntaxKind.TComma; case "=": return SeleniumUISyntaxKind.TAssign; case "(": return SeleniumUISyntaxKind.TOpenParen; case ")": return SeleniumUISyntaxKind.TCloseParen; case "[": return SeleniumUISyntaxKind.TOpenBracket; case "]": return SeleniumUISyntaxKind.TCloseBracket; case "{": return SeleniumUISyntaxKind.TOpenBrace; case "}": return SeleniumUISyntaxKind.TCloseBrace; case "<": return SeleniumUISyntaxKind.TLessThan; case ">": return SeleniumUISyntaxKind.TGreaterThan; case "?": return SeleniumUISyntaxKind.TQuestion; case "@\"": return SeleniumUISyntaxKind.DoubleQuoteVerbatimStringLiteralStart; case "@\'": return SeleniumUISyntaxKind.SingleQuoteVerbatimStringLiteralStart; case "/*": return SeleniumUISyntaxKind.LCommentStart; case "*": return SeleniumUISyntaxKind.LComment_Star; case "\"": return SeleniumUISyntaxKind.LDoubleQuoteVerbatimString; case "\'": return SeleniumUISyntaxKind.LSingleQuoteVerbatimString; default: return SeleniumUISyntaxKind.None; } } public override string GetKindText(int rawKind) { return this.GetKindText((SeleniumUISyntaxKind)rawKind); } public string GetKindText(SeleniumUISyntaxKind kind) { return kind.ToString(); } public override bool IsTriviaWithEndOfLine(int rawKind) { return this.IsTriviaWithEndOfLine((SeleniumUISyntaxKind)rawKind); } public bool IsTriviaWithEndOfLine(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.LCrLf: return true; case SeleniumUISyntaxKind.LLineEnd: return true; default: return false; } } public bool IsKeyword(int rawKind) { return this.IsKeyword((SeleniumUISyntaxKind)rawKind); } public bool IsKeyword(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.KParent: case SeleniumUISyntaxKind.KAncestor: case SeleniumUISyntaxKind.KNamespace: case SeleniumUISyntaxKind.KPage: case SeleniumUISyntaxKind.KElement: case SeleniumUISyntaxKind.KTag: return true; default: return false; } } public bool IsIdentifier(int rawKind) { return this.IsIdentifier((SeleniumUISyntaxKind)rawKind); } public bool IsIdentifier(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.LIdentifier: return true; default: return false; } } public bool IsNumber(int rawKind) { return this.IsNumber((SeleniumUISyntaxKind)rawKind); } public bool IsNumber(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.LInteger: return true; case SeleniumUISyntaxKind.LDecimal: return true; case SeleniumUISyntaxKind.LScientific: return true; default: return false; } } public bool IsString(int rawKind) { return this.IsString((SeleniumUISyntaxKind)rawKind); } public bool IsString(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.LRegularString: return true; case SeleniumUISyntaxKind.LDoubleQuoteVerbatimString: return true; case SeleniumUISyntaxKind.LSingleQuoteVerbatimString: return true; default: return false; } } public bool IsWhitespace(int rawKind) { return this.IsWhitespace((SeleniumUISyntaxKind)rawKind); } public bool IsWhitespace(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.LUtf8Bom: return true; case SeleniumUISyntaxKind.LWhiteSpace: return true; case SeleniumUISyntaxKind.LCrLf: return true; case SeleniumUISyntaxKind.LLineEnd: return true; default: return false; } } public bool IsComment(int rawKind) { return this.IsComment((SeleniumUISyntaxKind)rawKind); } public bool IsComment(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.LSingleLineComment: return true; case SeleniumUISyntaxKind.LComment: return true; default: return false; } } public SeleniumUITokenKind GetTokenKind(int rawKind) { return this.GetTokenKind((SeleniumUISyntaxKind)rawKind); } public SeleniumUITokenKind GetTokenKind(SeleniumUISyntaxKind kind) { switch(kind) { case SeleniumUISyntaxKind.KParent: case SeleniumUISyntaxKind.KAncestor: case SeleniumUISyntaxKind.KNamespace: case SeleniumUISyntaxKind.KPage: case SeleniumUISyntaxKind.KElement: case SeleniumUISyntaxKind.KTag: return SeleniumUITokenKind.Keyword; case SeleniumUISyntaxKind.LIdentifier: return SeleniumUITokenKind.Identifier; case SeleniumUISyntaxKind.LInteger: return SeleniumUITokenKind.Number; case SeleniumUISyntaxKind.LDecimal: return SeleniumUITokenKind.Number; case SeleniumUISyntaxKind.LScientific: return SeleniumUITokenKind.Number; case SeleniumUISyntaxKind.LRegularString: return SeleniumUITokenKind.String; case SeleniumUISyntaxKind.LUtf8Bom: return SeleniumUITokenKind.Whitespace; case SeleniumUISyntaxKind.LWhiteSpace: return SeleniumUITokenKind.Whitespace; case SeleniumUISyntaxKind.LCrLf: return SeleniumUITokenKind.Whitespace; case SeleniumUISyntaxKind.LLineEnd: return SeleniumUITokenKind.Whitespace; case SeleniumUISyntaxKind.LSingleLineComment: return SeleniumUITokenKind.Comment; case SeleniumUISyntaxKind.LComment: return SeleniumUITokenKind.Comment; case SeleniumUISyntaxKind.LDoubleQuoteVerbatimString: return SeleniumUITokenKind.String; case SeleniumUISyntaxKind.LSingleQuoteVerbatimString: return SeleniumUITokenKind.String; default: return SeleniumUITokenKind.None; } } public SeleniumUITokenKind GetModeTokenKind(int rawKind) { return this.GetModeTokenKind((SeleniumUILexerMode)rawKind); } public SeleniumUITokenKind GetModeTokenKind(SeleniumUILexerMode kind) { switch(kind) { case SeleniumUILexerMode.LMultilineComment: return SeleniumUITokenKind.Comment; case SeleniumUILexerMode.DOUBLEQUOTE_VERBATIM_STRING: return SeleniumUITokenKind.String; case SeleniumUILexerMode.SINGLEQUOTE_VERBATIM_STRING: return SeleniumUITokenKind.String; default: return SeleniumUITokenKind.None; } } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.DeviceSystem.PCI; using System.Collections.Generic; namespace Mosa.DeviceSystem { /// <summary> /// Setup for the Device Driver System. /// </summary> public static class Setup { static private DeviceDriverRegistry deviceDriverRegistry; static private IDeviceManager deviceManager; static private IResourceManager resourceManager; static private PCIControllerManager pciControllerManager; /// <summary> /// Gets the device driver library /// </summary> /// <value>The device driver library.</value> static public DeviceDriverRegistry DeviceDriverRegistry { get { return deviceDriverRegistry; } } /// <summary> /// Gets the device manager. /// </summary> /// <value>The device manager.</value> static public IDeviceManager DeviceManager { get { return deviceManager; } } /// <summary> /// Gets the resource manager. /// </summary> /// <value>The resource manager.</value> static public IResourceManager ResourceManager { get { return resourceManager; } } /// <summary> /// Initializes the Device Driver System. /// </summary> static public void Initialize() { // Create the Device Driver Manager deviceDriverRegistry = new DeviceDriverRegistry(PlatformArchitecture.X86); // Create Resource Manager resourceManager = new ResourceManager(); // Create Device Manager deviceManager = new DeviceManager(); // Create the PCI Controller Manager pciControllerManager = new PCIControllerManager(deviceManager); } /// <summary> /// Start the Device Driver System. /// </summary> static public void Start() { // Find all drviers deviceDriverRegistry.RegisterBuiltInDeviceDrivers(); // Start drivers for ISA devices StartISADevices(); // Start drivers for PCI devices StartPCIDevices(); } /// <summary> /// Starts the PCI devices. /// </summary> static public void StartPCIDevices() { pciControllerManager.CreatePCIDevices(); foreach (var device in deviceManager.GetDevices(new FindDevice.IsPCIDevice(), new FindDevice.IsAvailable())) { StartDevice(device as IPCIDevice); } } /// <summary> /// Starts the device. /// </summary> /// <param name="pciDevice">The pci device.</param> static public void StartDevice(IPCIDevice pciDevice) { var deviceDriver = deviceDriverRegistry.FindDriver(pciDevice); if (deviceDriver == null) { pciDevice.SetNoDriverFound(); return; } var hardwareDevice = System.Activator.CreateInstance(deviceDriver.DriverType) as IHardwareDevice; StartDevice(pciDevice, deviceDriver, hardwareDevice); } static private void StartDevice(IPCIDevice pciDevice, DeviceDriver deviceDriver, IHardwareDevice hardwareDevice) { var ioPortRegions = new LinkedList<IIOPortRegion>(); var memoryRegions = new LinkedList<IMemoryRegion>(); foreach (var pciBaseAddress in pciDevice.BaseAddresses) { switch (pciBaseAddress.Region) { case AddressType.IO: ioPortRegions.AddLast(new IOPortRegion((ushort)pciBaseAddress.Address, (ushort)pciBaseAddress.Size)); break; case AddressType.Memory: memoryRegions.AddLast(new MemoryRegion(pciBaseAddress.Address, pciBaseAddress.Size)); break; default: break; } } foreach (var memoryAttribute in deviceDriver.MemoryAttributes) { if (memoryAttribute.MemorySize > 0) { var memory = HAL.AllocateMemory(memoryAttribute.MemorySize, memoryAttribute.MemoryAlignment); memoryRegions.AddLast(new MemoryRegion(memory.Address, memory.Size)); } } var hardwareResources = new HardwareResources(resourceManager, ioPortRegions.ToArray(), memoryRegions.ToArray(), new InterruptHandler(resourceManager.InterruptManager, pciDevice.IRQ, hardwareDevice), pciDevice as IDeviceResource); if (resourceManager.ClaimResources(hardwareResources)) { hardwareResources.EnableIRQ(); hardwareDevice.Setup(hardwareResources); if (hardwareDevice.Start() == DeviceDriverStartStatus.Started) { pciDevice.SetDeviceOnline(); } else { hardwareResources.DisableIRQ(); resourceManager.ReleaseResources(hardwareResources); } } } /// <summary> /// Starts the ISA devices. /// </summary> static public void StartISADevices() { var deviceDrivers = deviceDriverRegistry.GetISADeviceDrivers(); foreach (var deviceDriver in deviceDrivers) { StartDevice(deviceDriver); } } /// <summary> /// Starts the device. /// </summary> /// <param name="deviceDriver">The device driver.</param> static public void StartDevice(DeviceDriver deviceDriver) { var driverAtttribute = deviceDriver.Attribute as ISADeviceDriverAttribute; if (driverAtttribute.AutoLoad) { var hardwareDevice = System.Activator.CreateInstance(deviceDriver.DriverType) as IHardwareDevice; var ioPortRegions = new LinkedList<IIOPortRegion>(); var memoryRegions = new LinkedList<IMemoryRegion>(); ioPortRegions.AddLast(new IOPortRegion(driverAtttribute.BasePort, driverAtttribute.PortRange)); if (driverAtttribute.AltBasePort != 0x00) ioPortRegions.AddLast(new IOPortRegion(driverAtttribute.AltBasePort, driverAtttribute.AltPortRange)); if (driverAtttribute.BaseAddress != 0x00) memoryRegions.AddLast(new MemoryRegion(driverAtttribute.BaseAddress, driverAtttribute.AddressRange)); foreach (var memoryAttribute in deviceDriver.MemoryAttributes) if (memoryAttribute.MemorySize > 0) { IMemory memory = HAL.AllocateMemory(memoryAttribute.MemorySize, memoryAttribute.MemoryAlignment); memoryRegions.AddLast(new MemoryRegion(memory.Address, memory.Size)); } var hardwareResources = new HardwareResources(resourceManager, ioPortRegions.ToArray(), memoryRegions.ToArray(), new InterruptHandler(resourceManager.InterruptManager, driverAtttribute.IRQ, hardwareDevice)); hardwareDevice.Setup(hardwareResources); if (resourceManager.ClaimResources(hardwareResources)) { hardwareResources.EnableIRQ(); if (hardwareDevice.Start() == DeviceDriverStartStatus.Started) { deviceManager.Add(hardwareDevice); } else { hardwareResources.DisableIRQ(); resourceManager.ReleaseResources(hardwareResources); } } } } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; using System.Threading; using System.Linq; using Sandbox.ModAPI; using Sandbox.ModAPI.Interfaces; using Sandbox.Common.ObjectBuilders; using Sandbox.Definitions; using VRage; using VRage.ModAPI; using VRage.ObjectBuilders; using VRage.Game; using VRage.Game.ModAPI; using Ingame = VRage.Game.ModAPI.Ingame; using ModIngame = Sandbox.ModAPI.Ingame; //using Ingame = VRage.ModAPI.Ingame; using VRage.Game.Entity; namespace SimpleInventorySort { public class TransferQueueItem { public IMyInventory Inventory; public IMyInventory InventorySource; public SortDefinitionItem Item; public List<SortDefinitionItem> compList; } /// <summary> /// This static class does all the actual inventory sorting. Anything that has to do with Inventory happens here. /// </summary> public static class Inventory { private static Dictionary<long, List<SortDefinitionItem>> m_cargoDictionary = new Dictionary<long, List<SortDefinitionItem>>(); private static Dictionary<MyDefinitionBase, List<IMyEntity>> m_splitGroups = new Dictionary<MyDefinitionBase, List<IMyEntity>>(); private static Dictionary<MyDefinitionBase, List<IMyEntity>> m_shareGroups = new Dictionary<MyDefinitionBase, List<IMyEntity>>(); private static HashSet<IMyEntity> m_emptySet = new HashSet<IMyEntity>(); private static Queue<TransferQueueItem> m_queueItems = new Queue<TransferQueueItem>(); private static HashSet<IMyInventory> m_inventoryTake = new HashSet<IMyInventory>(); private static HashSet<IMyInventory> m_inventoryTaken = new HashSet<IMyInventory>(); private static bool m_rebuild = true; private static DateTime m_lastRebuild = DateTime.Now; private static int m_entityCount = 0; private static volatile bool m_queueReady = false; /// <summary> /// Should we rebuild our sort list? /// </summary> public static bool ShouldRebuild { get { return m_rebuild; } } /// <summary> /// Is our Queue ready for processing in the game thread? /// </summary> public static bool QueueReady { get { return m_queueReady; } set { m_queueReady = value; } } public static int QueueCount { get { return m_queueItems.Count; } } /// <summary> /// Last time we rebuilt our sort list /// </summary> public static DateTime LastRebuild { get { return m_lastRebuild; } } public static void NewSortInventory() { if (m_queueReady) return; if (Core.Debug) Logging.Instance.WriteLine("===== BEGIN SORT BLOCK ===="); try { // Debug Timing DateTime start = DateTime.Now; // Setup up lists and sets HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); HashSet<IMyEntity> pullerProcessed = new HashSet<IMyEntity>(); HashSet<IMyEntity> pulleeProcessed = new HashSet<IMyEntity>(); List<IMyTerminalBlock> pullerBlocks = new List<IMyTerminalBlock>(); List<IMyTerminalBlock> pulleeBlocks = new List<IMyTerminalBlock>(); List<IMyTerminalBlock> blocks = new List<IMyTerminalBlock>(); // Grab all the grids, we're doing them all. MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid && !x.Closed && x.Physics != null); if (Core.Debug) Logging.Instance.WriteLine(String.Format("Total Grids: {0}", entities.Count)); // Rebuild our grid tracking list if (entities.Count != m_entityCount || CubeGridTracker.ShouldRebuild) { m_entityCount = entities.Count; CubeGridTracker.Rebuild(); } // Rebuild our sort list if (ShouldRebuild) RebuildSortListFromEntities(entities); // We need to call this to reset split groups each pass. ResetSplitGroups(); if (Core.Debug) Logging.Instance.WriteLine(String.Format("Total Connected Grids: {0}", entities.Count)); // Loop through our grids foreach (IMyEntity entity in entities) { DateTime startGridLoop = DateTime.Now; try { IMyCubeGrid cubeGrid = (IMyCubeGrid)entity; pulleeBlocks.Clear(); pullerBlocks.Clear(); m_emptySet.Clear(); // Get a list to all the empty blocks on the grid. We won't pull from those try { Sandbox.ModAPI.Ingame.IMyGridTerminalSystem gridSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(cubeGrid); if (gridSystem == null) continue; List<ModIngame.IMyTerminalBlock> inBlocks = new List<ModIngame.IMyTerminalBlock>(); gridSystem.GetBlocks(inBlocks); blocks = inBlocks.ConvertAll(x => (IMyTerminalBlock)x); foreach(var terminalBlock in blocks.Where(x => IsValidPulleeObjectBuilder(x))) { IMyCubeBlock block = (IMyCubeBlock)terminalBlock; IMyTerminalBlock terminal = (IMyTerminalBlock)block; //Ingame.IMyInventoryOwner inventoryOwner = (Ingame.IMyInventoryOwner)((MyEntity)block).GetInventoryBase(); MyEntity blockEntity = (MyEntity)block; /* * I want refineries to be able to pull from other refineries ore stock. This is for a priority issue where a refineries * in front of another refinery will pull first without caring about priority. if (block.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery) && inventoryOwner.GetInventory(1) != null && inventoryOwner.GetInventory(1).CurrentVolume.RawValue == 0) { m_emptySet.Add(block); continue; } */ if (blockEntity is ModIngame.IMyAssembler) { ModIngame.IMyAssembler assembler = (ModIngame.IMyAssembler)blockEntity; if (assembler.DisassembleEnabled && blockEntity.GetInventoryBase(0) != null && blockEntity.GetInventoryBase(0).CurrentVolume == 0) { continue; } else if (!assembler.DisassembleEnabled && blockEntity.GetInventoryBase(1) != null && blockEntity.GetInventoryBase(1).CurrentVolume == 0) { continue; } } if(blockEntity is ModIngame.IMyRefinery || blockEntity is ModIngame.IMyAssembler) { pulleeBlocks.Add(terminalBlock); continue; } else if (blockEntity.GetInventoryBase(0) != null && blockEntity.GetInventoryBase(0).CurrentVolume == 0) { continue; } pulleeBlocks.Add(terminalBlock); } } catch (Exception ex) { Logging.Instance.WriteLine(String.Format("FindEmptyError: {0}", ex.ToString())); } foreach (var terminalBlock in blocks.Where(x => IsValidPullerObjectBuilder(x)).OrderBy(x => GetHighestPriority(x))) { DateTime startBlockLoop = DateTime.Now; //IMyCubeBlock cubeBlock = (IMyCubeBlock)terminalBlock; try { //Ingame.IMyInventoryOwner inventoryOwner = (Ingame.IMyInventoryOwner)cubeBlock; MyEntity cubeBlockEntity = (MyEntity)terminalBlock; IMyInventory inventory; // Check to see if assembler is in disassemble mode if (terminalBlock is ModIngame.IMyAssembler) { ModIngame.IMyAssembler assembler = (ModIngame.IMyAssembler)terminalBlock; if (assembler.DisassembleEnabled) inventory = (IMyInventory)cubeBlockEntity.GetInventoryBase(1); else inventory = (IMyInventory)cubeBlockEntity.GetInventoryBase(0); } else inventory = (IMyInventory)cubeBlockEntity.GetInventoryBase(0); // Get the components we want to pull List<SortDefinitionItem> compList = GetSortComponentsFromEntity(terminalBlock); DateTime compStart = DateTime.Now; try { if (compList.Count > 0) { // Pull the components from other cargo holds foreach (SortDefinitionItem item in compList) { if (item.Ignore) continue; FindAndTakeInventoryItem(pulleeBlocks, terminalBlock, inventory, item, compList); } } } finally { if (Core.Debug && (DateTime.Now - compStart).Milliseconds > 1) Logging.Instance.WriteLine(String.Format("compList Loop: {0}ms", (DateTime.Now - compStart).Milliseconds)); } } finally { if (Core.Debug && DateTime.Now - startBlockLoop > TimeSpan.FromMilliseconds(1)) Logging.Instance.WriteLine(String.Format("Single Block Loop Took: {0}ms", (DateTime.Now - startBlockLoop).Milliseconds)); } } } finally { if (Core.Debug && DateTime.Now - startGridLoop > TimeSpan.FromMilliseconds(1)) Logging.Instance.WriteLine(String.Format("Single Grid Loop Took: {0}ms - {1}blocks", (DateTime.Now - startGridLoop).Milliseconds, pulleeBlocks.Count)); } } if (Core.Debug) Logging.Instance.WriteLine(String.Format("Complete sort took {0}ms", (DateTime.Now - start).Milliseconds)); } catch (Exception ex) { Logging.Instance.WriteLine(String.Format("SortInventory(): {0}", ex.ToString())); } finally { m_queueReady = true; } if (Core.Debug) { Logging.Instance.WriteLine(String.Format("Total Items Queued: {0}", m_queueItems.Count)); Logging.Instance.WriteLine("===== END SORT BLOCK ===="); } } /// <summary> /// Perform the inventory sort. Called once per second. NOT USED ANYMORE /// </summary> public static void SortInventory(long checkPlayerId = 0) { if (m_queueReady && !MyAPIGateway.Multiplayer.MultiplayerActive) return; if (Core.Debug) Logging.Instance.WriteLine("===== BEGIN SORT BLOCK ===="); try { // Debug Timing DateTime start = DateTime.Now; // Grab player id of this client long playerId = 0; if (checkPlayerId == 0) playerId = MyAPIGateway.Session.Player.IdentityId; else playerId = checkPlayerId; // Setup up lists and sets HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); HashSet<IMyEntity> pullerProcessed = new HashSet<IMyEntity>(); HashSet<IMyEntity> pulleeProcessed = new HashSet<IMyEntity>(); List<IMySlimBlock> pullerSlimBlocks = new List<IMySlimBlock>(); List<IMySlimBlock> pulleeSlimBlocks = new List<IMySlimBlock>(); //List<IMySlimBlock> slimBlocks = new List<IMySlimBlock>(); // Grab the grids that we're an owner of MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid && IsValidCubeGrid(x, playerId)); if (Core.Debug) Logging.Instance.WriteLine(String.Format("Total Grids: {0}", entities.Count)); // Rebuild our grid tracking list if (entities.Count != m_entityCount || CubeGridTracker.ShouldRebuild) { m_entityCount = entities.Count; CubeGridTracker.Rebuild(); } // Rebuild our conveyor list // Conveyor check no longer works (and isn't needed) //if (Conveyor.ShouldRebuild) // Conveyor.RebuildConveyorList(entities); // Rebuild our sort list if (ShouldRebuild) RebuildSortListFromEntities(entities, playerId); // We need to call this to reset split groups each pass. ResetSplitGroups(); entities.Clear(); //MyAPIGateway.TerminalActionsHelper Grid.GetConnectedGrids(entities, x => x is IMyCubeGrid && IsValidCubeGrid(x, playerId)); // MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid && IsValidCubeGrid(x, playerId)); if (Core.Debug) Logging.Instance.WriteLine(String.Format("Total Connected Grids: {0}", entities.Count)); // Loop through our grids foreach (IMyEntity entity in entities) { DateTime startGridLoop = DateTime.Now; try { IMyCubeGrid cubeGrid = (IMyCubeGrid)entity; pulleeSlimBlocks.Clear(); pullerSlimBlocks.Clear(); //slimBlocks.Clear(); m_emptySet.Clear(); // Get a list to all the empty blocks on the grid. We won't pull from those try { Grid.GetAllConnectedBlocks(pulleeProcessed, cubeGrid, pulleeSlimBlocks, x => x.FatBlock != null && IsValidPulleeObjectBuilder(x) && IsValidOwner(x, playerId)); foreach (IMySlimBlock slimBlock in pulleeSlimBlocks) { if (slimBlock.FatBlock == null || !(slimBlock.FatBlock is IMyCubeBlock)) continue; IMyCubeBlock block = (IMyCubeBlock)slimBlock.FatBlock; IMyTerminalBlock terminal = (IMyTerminalBlock)block; //Ingame.IMyInventoryOwner inventoryOwner = (Ingame.IMyInventoryOwner)block; MyEntity blockEntity = (MyEntity)block; /* * I want refineries to be able to pull from other refineries ore stock. This is for a priority issue where a refineries * in front of another refinery will pull first without caring about priority. if (block.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery) && inventoryOwner.GetInventory(1) != null && inventoryOwner.GetInventory(1).CurrentVolume.RawValue == 0) { m_emptySet.Add(block); continue; } */ if(block.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler)) { MyObjectBuilder_Assembler assembler = (MyObjectBuilder_Assembler)block.GetObjectBuilderCubeBlock(); if(assembler.DisassembleEnabled && blockEntity.GetInventoryBase(0) != null && blockEntity.GetInventoryBase(0).CurrentVolume.RawValue == 0) { m_emptySet.Add(block); continue; } if(!assembler.DisassembleEnabled && blockEntity.GetInventoryBase(1) != null && blockEntity.GetInventoryBase(1).CurrentVolume.RawValue == 0) { m_emptySet.Add(block); continue; } } if (block.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery)) continue; if (blockEntity.GetInventoryBase(0) != null && blockEntity.GetInventoryBase(0).CurrentVolume.RawValue == 0) { m_emptySet.Add(block); } } } catch (Exception ex) { Logging.Instance.WriteLine(String.Format("FindEmptyError: {0}", ex.ToString())); } Grid.GetAllConnectedBlocks(pullerProcessed, cubeGrid, pullerSlimBlocks, x => x.FatBlock != null && IsValidPullerObjectBuilder(x) && IsValidOwner(x, playerId)); // Loop through our cargo holds (can change this to any type later) foreach (IMySlimBlock slimBlock in pullerSlimBlocks.OrderBy(x => GetHighestPriority(x.FatBlock))) { DateTime startBlockLoop = DateTime.Now; IMyCubeBlock cubeBlock = slimBlock.FatBlock; try { //Ingame.IMyInventoryOwner inventoryOwner = (Ingame.IMyInventoryOwner)cubeBlock; MyEntity cubeEntity = (MyEntity)cubeBlock; IMyInventory inventory; // Check to see if assembler is in disassemble mode if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler)) { MyObjectBuilder_Assembler assembler = (MyObjectBuilder_Assembler)cubeBlock.GetObjectBuilderCubeBlock(); if (assembler.DisassembleEnabled) inventory = (IMyInventory)cubeEntity.GetInventoryBase(1); else inventory = (IMyInventory)cubeEntity.GetInventoryBase(0); } else inventory = (IMyInventory)cubeEntity.GetInventoryBase(0); // Get the components we want to pull List<SortDefinitionItem> compList = GetSortComponentsFromEntity(cubeBlock); DateTime compStart = DateTime.Now; try { if (compList.Count > 0) { // Pull the components from other cargo holds foreach (SortDefinitionItem item in compList) { if(item.Ignore) continue; //FindAndTakeInventoryItem(pulleeSlimBlocks, slimBlock, inventory, item, compList); //FindAndTakeInventoryItem(cubeGrid, slimBlock, inventory, item, compList); } } } finally { if (Core.Debug && (DateTime.Now - compStart).Milliseconds > 1) Logging.Instance.WriteLine(String.Format("compList Loop: {0}ms", (DateTime.Now - compStart).Milliseconds)); } } finally { if (Core.Debug && DateTime.Now - startBlockLoop > TimeSpan.FromMilliseconds(1)) Logging.Instance.WriteLine(String.Format("Single Block Loop Took: {0}ms", (DateTime.Now - startBlockLoop).Milliseconds)); } } } finally { if (Core.Debug && DateTime.Now - startGridLoop > TimeSpan.FromMilliseconds(1)) Logging.Instance.WriteLine(String.Format("Single Grid Loop Took: {0}ms - {1}blocks", (DateTime.Now - startGridLoop).Milliseconds, pulleeSlimBlocks.Count)); } } if (Core.Debug) Logging.Instance.WriteLine(String.Format("Complete sort took {0}ms", (DateTime.Now - start).Milliseconds)); } catch (Exception ex) { Logging.Instance.WriteLine(String.Format("SortInventory(): {0}", ex.ToString())); } finally { m_queueReady = true; } if (Core.Debug) { Logging.Instance.WriteLine(String.Format("Total Items Queued: {0}", m_queueItems.Count)); Logging.Instance.WriteLine("===== END SORT BLOCK ===="); } } /// <summary> /// Trigger an inventory rebuild /// </summary> public static void TriggerRebuild() { m_rebuild = true; } /// <summary> /// Processes our Transfer Queue. This occurs in the game thread, so writes are safe. /// </summary> public static void ProcessQueue() { DateTime start = DateTime.Now; List<TransferQueueItem> queueReset = new List<TransferQueueItem>(); try { m_inventoryTake.Clear(); m_inventoryTaken.Clear(); if (Core.Debug) { Logging.Instance.WriteLine(String.Format("==== START PROCESS QUEUE BLOCK ====")); Logging.Instance.WriteLine(String.Format("Queue: {0}", m_queueItems.Count)); } while (m_queueItems.Count() > 0) { TransferQueueItem item = m_queueItems.Dequeue(); /* // No longer doing this, as I've moved inventory management to the server if (MyAPIGateway.Multiplayer.MultiplayerActive && !MyAPIGateway.Multiplayer.IsServer) { if (m_inventoryTake.Contains(item.Inventory) || m_inventoryTaken.Contains(item.InventorySource)) { queueReset.Add(item); continue; } } */ TransferCargo(item.Inventory, item.InventorySource, item.Item, item.compList); } foreach (TransferQueueItem item in queueReset) { m_queueItems.Enqueue(item); } if (Core.Debug) { Logging.Instance.WriteLine(String.Format("ProcessQueue: {0} ms", (DateTime.Now - start).Milliseconds)); if(MyAPIGateway.Multiplayer.MultiplayerActive && !MyAPIGateway.Multiplayer.IsServer) { Logging.Instance.WriteLine(String.Format("Queue Reset: {0}", m_queueItems.Count)); } Logging.Instance.WriteLine(String.Format("==== END PROCESS QUEUE BLOCK ====")); } } catch (Exception ex) { Logging.Instance.WriteLine(String.Format("ProcessQueue(): {0}", ex.ToString())); } finally { if(m_queueItems.Count < 1) m_queueReady = false; } } /// <summary> /// This extracts the component list from tags in entity custom names, and then stores them in a hashset for use during the sort. /// </summary> /// <param name="entities">A list of all the entities we want to check</param> /// <param name="playerId">The playerId of the local player</param> private static void RebuildSortListFromEntities(HashSet<IMyEntity> entities, long playerId) { m_rebuild = false; m_lastRebuild = DateTime.Now; DateTime start = DateTime.Now; try { m_cargoDictionary.Clear(); m_splitGroups.Clear(); HashSet<IMyEntity> processedGrids = new HashSet<IMyEntity>(); List<IMySlimBlock> slimBlocks = new List<IMySlimBlock>(); foreach (IMyEntity grid in entities) { IMyCubeGrid cubeGrid = (IMyCubeGrid)grid; slimBlocks.Clear(); //cubeGrid.GetBlocks(slimBlocks, x => x.FatBlock != null && IsValidPullerObjectBuilder(x) && IsValidOwner(x, playerId)); Grid.GetAllConnectedBlocks(processedGrids, cubeGrid, slimBlocks, x => x.FatBlock != null && IsValidPullerObjectBuilder(x) && IsValidOwner(x, playerId)); foreach (IMySlimBlock slimblock in slimBlocks) { IMyEntity entity = slimblock.FatBlock; if (!(entity is IMyCubeBlock)) continue; List<SortDefinitionItem> components = SortDefinitionItem.CreateFromEntity(entity); //List<SortDefinitionItem> components = new List<SortDefinitionItem>(); m_cargoDictionary.Add(entity.EntityId, components); foreach (SortDefinitionItem item in components) { if (item.SortOperators.ContainsKey(SortOperatorOptions.Split)) AddToSplitGroup(item); } } } } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("RebuildSortListFromEntities(): {0}", ex.ToString())); } if (Core.Debug) Logging.Instance.WriteLine(String.Format("RebuildSortListFromEntities {0}ms", (DateTime.Now - start).Milliseconds)); } /// <summary> /// This extracts the component list from tags in entity custom names, and then stores them in a hashset for use during the sort. /// </summary> /// <param name="entities">A list of all the entities we want to check</param> private static void RebuildSortListFromEntities(HashSet<IMyEntity> entities) { m_rebuild = false; m_lastRebuild = DateTime.Now; DateTime start = DateTime.Now; try { m_cargoDictionary.Clear(); m_splitGroups.Clear(); HashSet<IMyEntity> processedGrids = new HashSet<IMyEntity>(); List<Sandbox.ModAPI.Ingame.IMyTerminalBlock> blocks = new List<Sandbox.ModAPI.Ingame.IMyTerminalBlock>(); foreach (IMyEntity grid in entities) { IMyCubeGrid cubeGrid = (IMyCubeGrid)grid; blocks.Clear(); Sandbox.ModAPI.Ingame.IMyGridTerminalSystem gridSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)grid); if(gridSystem == null) continue; gridSystem.GetBlocks(blocks); foreach (IMyTerminalBlock block in blocks) { if (m_cargoDictionary.ContainsKey(block.EntityId)) continue; List<SortDefinitionItem> components = SortDefinitionItem.CreateFromEntity(block); m_cargoDictionary.Add(block.EntityId, components); foreach (SortDefinitionItem item in components) { if (item.SortOperators.ContainsKey(SortOperatorOptions.Split)) AddToSplitGroup(item); } } } } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("RebuildSortListFromEntities(): {0}", ex.ToString())); } if (Core.Debug) Logging.Instance.WriteLine(String.Format("RebuildSortListFromEntities {0}ms", (DateTime.Now - start).Milliseconds)); } private static void ResetSplitGroups() { foreach (KeyValuePair<MyDefinitionBase, List<IMyEntity>> p in m_splitGroups) { foreach (IMyEntity item in p.Value) { SortDefinitionItem sortItem = m_cargoDictionary[item.EntityId].FirstOrDefault(x => x.Definition.Equals(p.Key)); if (sortItem != null) { //- 11/24 - Conveyor no longer works //sortItem.splitGroup = p.Value.Where(x => Conveyor.AreEntitiesConnected(x, sortItem.ContainerEntity)).ToList(); sortItem.splitGroup = p.Value.ToList(); sortItem.SortOperators[SortOperatorOptions.Split] = sortItem.splitGroup.Count(); } } } } /// <summary> /// Add this item to a group of other items for splitting when inventory transfer occurs /// </summary> /// <param name="item"></param> private static void AddToSplitGroup(SortDefinitionItem item) { if (m_splitGroups.ContainsKey(item.Definition)) { m_splitGroups[item.Definition].Add(item.ContainerEntity); } else { List<IMyEntity> list = new List<IMyEntity>(); list.Add(item.ContainerEntity); m_splitGroups.Add(item.Definition, list); } } /// <summary> /// Update the amount of sort items in the split group that will apply a divider to the item amount to transfer. /// /// TODO: Reset this each sort /// /// </summary> /// <param name="item"></param> private static void UpdateSplitGroup(SortDefinitionItem item) { foreach (IMyEntity entity in item.splitGroup) { List<SortDefinitionItem> list = m_cargoDictionary[entity.EntityId]; SortDefinitionItem check = list.FirstOrDefault(x => x.Definition.Equals(item.Definition) && item != x); if (check == null) continue; check.Split--; } } /// <summary> /// Is the block a valid puller of inventory? /// </summary> /// <param name="x"></param> /// <returns></returns> private static bool IsValidPullerObjectBuilder(IMySlimBlock x) { if (x.FatBlock == null) return false; MyEntity entity = x.FatBlock as MyEntity; if (!entity.HasInventory) return false; if (entity.InventoryCount < 1) return false; return true; } private static bool IsValidPullerObjectBuilder(IMyTerminalBlock x) { MyEntity entity = x as MyEntity; if (!entity.HasInventory) return false; if (entity.InventoryCount < 1) return false; return true; } /// <summary> /// Is the block a valid target of inventory pulling? /// </summary> /// <param name="x"></param> /// <returns></returns> private static bool IsValidPulleeObjectBuilder(IMySlimBlock x) { /* MyObjectBuilderType typeId = x.FatBlock.BlockDefinition.TypeId; return typeId == typeof(MyObjectBuilder_CargoContainer) || typeId == typeof(MyObjectBuilder_Refinery) || typeId == typeof(MyObjectBuilder_Assembler) || typeId == typeof(MyObjectBuilder_ShipConnector) || typeId == typeof(MyObjectBuilder_Drill) || typeId == typeof(MyObjectBuilder_ShipGrinder) || typeId == typeof(MyObjectBuilder_Collector); */ if (x.FatBlock == null) return false; MyEntity entity = x.FatBlock as MyEntity; if (!entity.HasInventory) return false; if (entity.InventoryCount < 1) return false; return true; } private static bool IsValidPulleeObjectBuilder(Sandbox.ModAPI.Ingame.IMyTerminalBlock x) { MyEntity entity = x as MyEntity; if (!entity.HasInventory) return false; if (entity.InventoryCount < 1) return false; return true; } private static bool IsValidOwner(IMySlimBlock x, long playerId) { if (x.FatBlock == null || !(x.FatBlock is Sandbox.ModAPI.Ingame.IMyTerminalBlock)) return false; ModIngame.IMyTerminalBlock block = (ModIngame.IMyTerminalBlock)x.FatBlock; if (Settings.Instance.Faction) { return block.HasPlayerAccess(playerId); } else { return block.OwnerId == playerId; } } private static bool IsValidCubeGrid(IMyEntity x, long playerId) { if (!(x is IMyCubeGrid)) return false; IMyCubeGrid grid = (IMyCubeGrid)x; if (Settings.Instance.Faction) { if(grid.BigOwners.FindAll(p => MyAPIGateway.Session.Player.GetRelationTo(p) == MyRelationsBetweenPlayerAndBlock.FactionShare || MyAPIGateway.Session.Player.GetRelationTo(p) == MyRelationsBetweenPlayerAndBlock.Owner) != null) { return true; } if (grid.SmallOwners.FindAll(p => MyAPIGateway.Session.Player.GetRelationTo(p) == MyRelationsBetweenPlayerAndBlock.FactionShare || MyAPIGateway.Session.Player.GetRelationTo(p) == MyRelationsBetweenPlayerAndBlock.Owner) != null) { return true; } return false; } if (grid.BigOwners.Contains(playerId) || grid.SmallOwners.Contains(playerId)) return true; return false; } /// <summary> /// Finds and takes inventory from other entities on the grid. This can probably be a FindAndTake(IMyCubeGrid, IMyCubeBlock, MyDefinitionBase def) for /// clarity in the future. /// </summary> /// <param name="slimBlocks">List of blocks in this grid</param> /// <param name="slimBlock">The block that is pulling inventory</param> /// <param name="inventory">The blocks inventory object</param> /// <param name="def">A definition of the component we're pulling</param> private static void FindAndTakeInventoryItem(List<IMySlimBlock> slimBlocks, IMySlimBlock slimBlock, IMyInventory inventory, SortDefinitionItem item, List<SortDefinitionItem> compList) { DateTime start = DateTime.Now; MyDefinitionBase def = item.Definition; // Loop through the rest of the grid and find other inventories foreach (IMySlimBlock slimBlockSource in slimBlocks) { // Not this one if (slimBlockSource == slimBlock) continue; IMyCubeBlock cubeBlockSource = slimBlockSource.FatBlock; MyEntity cubeEntity = (MyEntity)cubeBlockSource; //Ingame.IMyInventoryOwner inventoryOwnerSource = (Ingame.IMyInventoryOwner)cubeBlockSource; // if (!inventoryOwnerSource.UseConveyorSystem) // continue; ModIngame.IMyTerminalBlock terminalSource = (ModIngame.IMyTerminalBlock)cubeBlockSource; IMyInventory inventorySource; //MyObjectBuilderType typeId = cubeEntity.BlockDefinition.TypeId; // Special case, let refineries pull ore from other refineries. This is due to priority (first come first serve will pull ore and // not give up that ore once it's pull, ignoring priority) if (cubeEntity is ModIngame.IMyRefinery && slimBlock.FatBlock is ModIngame.IMyRefinery) { inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(0); } else if (cubeEntity is ModIngame.IMyRefinery) { inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(1); } else if (cubeEntity is ModIngame.IMyAssembler) { ModIngame.IMyAssembler assembler = (ModIngame.IMyAssembler)cubeBlockSource; // Check to see if assembler is in disassemble mode, and flip inventories if (assembler.DisassembleEnabled) inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(0); else inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(1); } else inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(0); // Check if two entities are connected via conveyor system //- 11/24 - Conveyor no longer works (and isn't required, we already group grids) //if (!Conveyor.AreEntitiesConnected(slimBlock.FatBlock, cubeBlockSource)) //{ // continue; //} // Check if this inventory also wants to item we're taking, if so, ignore it if (terminalSource.CustomName != null) { if (terminalSource.CustomName.ToLower().Contains("exempt")) continue; // This needs to change, as it's pretty ugly. if (GetSortComponentsFromEntity(cubeBlockSource).Where(x => x.Priority <= item.Priority).FirstOrDefault(f => f.Definition.Equals(def)) != null) { continue; } } QueueTransferCargo(inventory, inventorySource, item, compList); //TransferCargo(inventory, inventorySource, item, compList); } if(Core.Debug && (DateTime.Now - start).Milliseconds > 1) Logging.Instance.WriteLine(String.Format("FindAndTakeInventoryItem {0}ms", (DateTime.Now - start).Milliseconds)); } private static void FindAndTakeInventoryItem(List<IMyTerminalBlock> blocks, IMyTerminalBlock block, IMyInventory inventory, SortDefinitionItem item, List<SortDefinitionItem> compList) { DateTime start = DateTime.Now; MyDefinitionBase def = item.Definition; // Loop through the rest of the grid and find other inventories foreach (IMyTerminalBlock blockItem in blocks) { // Not this one if (blockItem == block) continue; if (!blockItem.HasPlayerAccess(block.OwnerId)) return; //IMyCubeBlock cubeBlockSource = (IMyCubeBlock)blockItem; ModIngame.IMyTerminalBlock terminalSource = blockItem; MyEntity cubeEntity = (MyEntity)blockItem; //Ingame.IMyInventoryOwner inventoryOwnerSource = (Ingame.IMyInventoryOwner)cubeBlockSource; IMyInventory inventorySource; //MyObjectBuilderType typeId = blockItem.BlockDefinition.TypeId; // Special case, let refineries pull ore from other refineries. This is due to priority (first come first serve will pull ore and // not give up that ore once it's pull, ignoring priority) if (cubeEntity is ModIngame.IMyRefinery && block is ModIngame.IMyRefinery) { inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(0); } else if (cubeEntity is ModIngame.IMyRefinery) { inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(1); } else if (cubeEntity is ModIngame.IMyAssembler) { ModIngame.IMyAssembler assembler = (ModIngame.IMyAssembler)cubeEntity; // Check to see if assembler is in disassemble mode, and flip inventories if (assembler.DisassembleEnabled) inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(0); else inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(1); } else inventorySource = (IMyInventory)cubeEntity.GetInventoryBase(0); // Check if this inventory also wants to item we're taking, if so, ignore it if (terminalSource.CustomName != null) { if (terminalSource.CustomName.ToLower().Contains("exempt")) continue; // This needs to change, as it's pretty ugly. if (GetSortComponentsFromEntity(cubeEntity).Where(x => x.Priority <= item.Priority).FirstOrDefault(f => f.Definition.Equals(def)) != null) { continue; } } QueueTransferCargo(inventory, inventorySource, item, compList); } if (Core.Debug && (DateTime.Now - start).Milliseconds > 1) Logging.Instance.WriteLine(String.Format("FindAndTakeInventoryItem {0}ms", (DateTime.Now - start).Milliseconds)); } private static void QueueTransferCargo(IMyInventory inventory, IMyInventory inventorySource, SortDefinitionItem item, List<SortDefinitionItem> compList) { MyDefinitionBase def = item.Definition; // Transfer cargo int indexSource = 0; int index = 0; double count = 0; // These aren't thread safe. We'll catch the exception, and our state is still safe if this fails // as we can just come back to this in another pass. Ingame.IMyInventoryItem sourceItem = FindItemInInventory(inventorySource, def, out indexSource); Ingame.IMyInventoryItem targetItem = FindItemInInventory(inventory, def, out index, out count); if (sourceItem != null) { TransferQueueItem queueItem = new TransferQueueItem(); queueItem.Inventory = inventory; queueItem.InventorySource = inventorySource; queueItem.Item = item; queueItem.compList = compList; m_queueItems.Enqueue(queueItem); if(Core.Debug) LogTransfer(inventory, inventorySource, item, 0, true); } } /// <summary> /// Actually transfer cargo from one IMyInventory to another IMyInventory /// </summary> /// <param name="inventory"></param> /// <param name="inventorySource"></param> /// <param name="item"></param> /// <param name="compList"></param> private static void TransferCargo(IMyInventory inventory, IMyInventory inventorySource, SortDefinitionItem item, List<SortDefinitionItem> compList) { //if (!inventorySource.IsConnectedTo(inventory)) // return; DateTime start = DateTime.Now; try { MyDefinitionBase def = item.Definition; // Transfer cargo int indexSource = 0; int index = 0; double count = 0; Ingame.IMyInventoryItem sourceItem = FindItemInInventory(inventorySource, def, out indexSource); Ingame.IMyInventoryItem targetItem = FindItemInInventory(inventory, def, out index, out count); if (sourceItem != null) { if (ShouldExcludeInventoryItem(compList, sourceItem)) { return; } if ((item.MaxCount > 0) && targetItem != null && count >= (double)item.MaxCount) { return; } double maxAmount = (double)inventory.MaxVolume - (double)inventory.CurrentVolume; double itemVolume = (double)(MyDefinitionManager.Static.GetPhysicalItemDefinition(def.Id).Volume); if (maxAmount / 1000 < 50000000) // Survival { double countToTransfer = maxAmount / itemVolume; // Sanity if (countToTransfer < 0) countToTransfer = 0; MyFixedPoint amount = (MyFixedPoint)countToTransfer; if ((double)amount > (double)sourceItem.Amount) amount = sourceItem.Amount; // Huh, this is kind of cheap way of splitting, and doesn't account for inventory size differences. I think what should happen // is I process all items in the group at the same time, hmm if (item.Split > 0) { if ((double)amount / item.Split > itemVolume) { amount = (MyFixedPoint)((double)amount / item.Split); } // If we're splitting anything other than ore and ignots, we only want integer amounts if (!(def.Id.ToString().Contains("Ore/") || def.Id.ToString().Contains("Ingot/"))) amount = MyFixedPoint.Floor(amount); UpdateSplitGroup(item); } if (item.MaxCount > 0) { MyFixedPoint maxCount = (MyFixedPoint)((double)item.MaxCount); if (targetItem != null && ((double)maxCount) + count >= item.MaxCount) { maxCount = (MyFixedPoint)((double)item.MaxCount - count); } if ((double)amount > (double)maxCount) amount = maxCount; } // If we're not dealing with ore or ingots, do not transfer fractional amounts, only integer amounts if (amount < 1 && !(def.Id.ToString().Contains("Ore/") || def.Id.ToString().Contains("Ingot/"))) return; if ((double)amount < 0.01) return; //inventory.CanItemsBeAdded(amount, new Sandbox.Common.ObjectBuilders.Definitions.SerializableDefinitionId(def.Id.TypeId, def.Id.SubtypeName)); if (inventory.CanItemsBeAdded(amount, new SerializableDefinitionId(item.Definition.Id.TypeId, item.Definition.Id.SubtypeName))) { /* if (MyAPIGateway.Multiplayer.MultiplayerActive && !MyAPIGateway.Multiplayer.IsServer) { m_inventoryTake.Add(inventory); m_inventoryTaken.Add(inventorySource); } */ if(inventorySource.TransferItemTo(inventory, indexSource, null, true, amount, true)) LogTransfer(inventory, inventorySource, item, amount); } } else // Creative { MyFixedPoint amount = sourceItem.Amount; if (item.Split > 0) { if ((double)amount / item.Split > itemVolume) { amount = (MyFixedPoint)((double)amount / item.Split); } UpdateSplitGroup(item); } if (item.MaxCount > 0) { MyFixedPoint maxCount = (MyFixedPoint)((double)item.MaxCount); if (targetItem != null && ((double)maxCount) + count >= item.MaxCount) { maxCount = (MyFixedPoint)((double)item.MaxCount - count); } if ((double)amount > (double)maxCount) amount = maxCount; } if (inventory.CanItemsBeAdded(amount, new SerializableDefinitionId(item.Definition.Id.TypeId, item.Definition.Id.SubtypeName))) { if(inventorySource.TransferItemTo(inventory, indexSource, null, true, amount, true)) LogTransfer(inventory, inventorySource, item, amount); } /* if (MyAPIGateway.Multiplayer.MultiplayerActive && !MyAPIGateway.Multiplayer.IsServer) { m_inventoryTake.Add(inventory); m_inventoryTaken.Add(inventorySource); } */ } } } catch (Exception ex) { Logging.Instance.WriteLine(String.Format("TransferCargo(): {0}", ex.ToString())); } if (Core.Debug && (DateTime.Now - start).Milliseconds > 1) Logging.Instance.WriteLine(String.Format("TransferCargo: {0}ms", (DateTime.Now - start).Milliseconds)); } /// <summary> /// Log cargo transfer /// </summary> /// <param name="inventory"></param> /// <param name="inventorySource"></param> /// <param name="item"></param> /// <param name="amount"></param> private static void LogTransfer(IMyInventory inventory, IMyInventory inventorySource, SortDefinitionItem item, MyFixedPoint amount, bool queue = false) { int i = 0; try { if (inventory == null || inventorySource == null || inventory.Owner == null || inventorySource.Owner == null) { //Logging.Instance.WriteLine(string.Format("inv: {0} - invsource: {1} - invown: {2} - invsourceown: {3}", inventory == null, inventorySource == null, inventory.Owner == null, inventorySource.Owner == null)); return; } ModIngame.IMyTerminalBlock terminalEntity = MyAPIGateway.Entities.GetEntityById(inventory.Owner.EntityId) as ModIngame.IMyTerminalBlock; if (terminalEntity == null) { //Logging.Instance.WriteLine(string.Format("TerminalEntity is null")); return; } ModIngame.IMyTerminalBlock terminalSourceEntity = MyAPIGateway.Entities.GetEntityById(inventorySource.Owner.EntityId) as ModIngame.IMyTerminalBlock; if (terminalSourceEntity == null) { //Logging.Instance.WriteLine(string.Format("TerminalSourceEntity is null")); return; } if(Core.Debug) Logging.Instance.WriteLine(String.Format("{7}Moving {0:F2} {1} from '{2}' ({3}) to '{4}' ({5}) - {6}", (float)amount, item.Definition.Id.SubtypeName, terminalSourceEntity.CustomName, terminalSourceEntity.DisplayNameText, terminalEntity.CustomName, terminalEntity.DisplayNameText, terminalEntity.CubeGrid.EntityId, queue ? "Queued " : "")); } catch(Exception ex) { Logging.Instance.WriteLine(string.Format("Here: {0} - {1}", i, ex.ToString())); } } /// <summary> /// Find an IMyInventoryItem in an IMyInventory. /// </summary> /// <param name="inventory"></param> /// <param name="def"></param> /// <returns></returns> private static Ingame.IMyInventoryItem FindItemInInventory(IMyInventory inventory, MyDefinitionBase def) { int index = 0; double count = 0d; return FindItemInInventory(inventory, def, out index, out count); } private static Ingame.IMyInventoryItem FindItemInInventory(IMyInventory inventory, MyDefinitionBase def, out int index) { double count = 0d; return FindItemInInventory(inventory, def, out index, out count); } private static Ingame.IMyInventoryItem FindItemInInventory(IMyInventory inventory, MyDefinitionBase def, out int index, out double count) { index = 0; count = 0d; Ingame.IMyInventoryItem foundItem = null; bool found = false; List<IMyInventoryItem> items; try { items = inventory.GetItems(); } catch(Exception ex) { return null; } for(int r = 0; r < items.Count; r++) { Ingame.IMyInventoryItem item = items[r]; if (found && item.Content.TypeId == def.Id.TypeId && item.Content.SubtypeId == def.Id.SubtypeId) { count += item.Amount.RawValue; } if (!found && item.Content.TypeId == def.Id.TypeId && item.Content.SubtypeId == def.Id.SubtypeId) { index = r; found = true; foundItem = item; count += (double)item.Amount; } } if (found) return foundItem; return null; } /// <summary> /// This gets a list of components that an entity wants /// </summary> /// <param name="entity">The entity to check</param> /// <returns>A list of MyDefinitionBase objects that contain definition information of the components that this entity wants</returns> private static List<SortDefinitionItem> GetSortComponentsFromEntity(IMyEntity entity) { if (m_cargoDictionary.ContainsKey(entity.EntityId)) return m_cargoDictionary[entity.EntityId]; else return new List<SortDefinitionItem>(); } private static long GetHighestPriority(IMyEntity entity) { long result = long.MaxValue; List<SortDefinitionItem> list = GetSortComponentsFromEntity(entity); foreach (SortDefinitionItem item in list) { result = Math.Min(result, item.Priority); } return result; } /// <summary> /// Should we exclude this IMyInventoryItem from being transferred? Basically a not operator check /// </summary> /// <param name="compList"></param> /// <param name="source"></param> /// <returns></returns> private static bool ShouldExcludeInventoryItem(List<SortDefinitionItem> compList, Ingame.IMyInventoryItem source) { return compList.FirstOrDefault(x => x.Ignore && x.Definition.Id.TypeId == source.Content.TypeId && x.Definition.Id.SubtypeId == source.Content.SubtypeId) != null; } } }
/* * 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 { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Ignite start/stop tests. /// </summary> [Category(TestUtils.CategoryIntensive)] public class IgniteStartStopTest { /// <summary> /// /// </summary> [SetUp] public void SetUp() { TestUtils.KillProcesses(); } /// <summary> /// /// </summary> [TearDown] public void TearDown() { TestUtils.KillProcesses(); Ignition.StopAll(true); } /// <summary> /// /// </summary> [Test] public void TestStartDefault() { var cfg = new IgniteConfiguration {JvmClasspath = TestUtils.CreateTestClasspath()}; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid); Assert.AreEqual(1, grid.GetCluster().GetNodes().Count); } /// <summary> /// /// </summary> [Test] public void TestStartWithConfigPath() { var cfg = new IgniteConfiguration { SpringConfigUrl = "config/default-config.xml", JvmClasspath = TestUtils.CreateTestClasspath() }; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid); Assert.AreEqual(1, grid.GetCluster().GetNodes().Count); } /// <summary> /// /// </summary> [Test] public void TestStartGetStop() { var cfgs = new List<string> { "config\\start-test-grid1.xml", "config\\start-test-grid2.xml", "config\\start-test-grid3.xml" }; var cfg = new IgniteConfiguration { SpringConfigUrl = cfgs[0], JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; var grid1 = Ignition.Start(cfg); Assert.AreEqual("grid1", grid1.Name); Assert.AreSame(grid1, Ignition.GetIgnite()); Assert.AreSame(grid1, Ignition.GetAll().Single()); cfg.SpringConfigUrl = cfgs[1]; var grid2 = Ignition.Start(cfg); Assert.AreEqual("grid2", grid2.Name); Assert.Throws<IgniteException>(() => Ignition.GetIgnite()); cfg.SpringConfigUrl = cfgs[2]; var grid3 = Ignition.Start(cfg); Assert.IsNull(grid3.Name); Assert.AreSame(grid1, Ignition.GetIgnite("grid1")); Assert.AreSame(grid1, Ignition.TryGetIgnite("grid1")); Assert.AreSame(grid2, Ignition.GetIgnite("grid2")); Assert.AreSame(grid2, Ignition.TryGetIgnite("grid2")); Assert.AreSame(grid3, Ignition.GetIgnite(null)); Assert.AreSame(grid3, Ignition.GetIgnite()); Assert.AreSame(grid3, Ignition.TryGetIgnite(null)); Assert.AreSame(grid3, Ignition.TryGetIgnite()); Assert.AreEqual(new[] {grid3, grid1, grid2}, Ignition.GetAll().OrderBy(x => x.Name).ToArray()); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("invalid_name")); Assert.IsNull(Ignition.TryGetIgnite("invalid_name")); Assert.IsTrue(Ignition.Stop("grid1", true)); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid1")); grid2.Dispose(); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid2")); grid3.Dispose(); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid3")); foreach (var cfgName in cfgs) { cfg.SpringConfigUrl = cfgName; cfg.JvmOptions = TestUtils.TestJavaOptions(); Ignition.Start(cfg); } foreach (var gridName in new List<string> { "grid1", "grid2", null }) Assert.IsNotNull(Ignition.GetIgnite(gridName)); Ignition.StopAll(true); foreach (var gridName in new List<string> {"grid1", "grid2", null}) Assert.Throws<IgniteException>(() => Ignition.GetIgnite(gridName)); } /// <summary> /// /// </summary> [Test] public void TestStartTheSameName() { var cfg = new IgniteConfiguration { SpringConfigUrl = "config\\start-test-grid1.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; var grid1 = Ignition.Start(cfg); Assert.AreEqual("grid1", grid1.Name); try { Ignition.Start(cfg); Assert.Fail("Start should fail."); } catch (IgniteException e) { Console.WriteLine("Expected exception: " + e); } } /// <summary> /// Tests automatic grid name generation. /// </summary> [Test] public void TestStartUniqueName() { var cfg = TestUtils.GetTestConfiguration(); cfg.AutoGenerateIgniteInstanceName = true; Ignition.Start(cfg); Assert.IsNotNull(Ignition.GetIgnite()); Ignition.Start(cfg); Assert.Throws<IgniteException>(() => Ignition.GetIgnite()); Assert.AreEqual(2, Ignition.GetAll().Count); } /// <summary> /// /// </summary> [Test] public void TestUsageAfterStop() { var cfg = new IgniteConfiguration { SpringConfigUrl = "config\\start-test-grid1.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid.GetCache<int, int>("cache1")); grid.Dispose(); try { grid.GetCache<int, int>("cache1"); Assert.Fail(); } catch (InvalidOperationException e) { Console.WriteLine("Expected exception: " + e); } } /// <summary> /// /// </summary> [Test] public void TestStartStopLeak() { var cfg = new IgniteConfiguration { SpringConfigUrl = "config\\start-test-grid1.xml", JvmOptions = new List<string> {"-Xcheck:jni", "-Xms256m", "-Xmx256m", "-XX:+HeapDumpOnOutOfMemoryError"}, JvmClasspath = TestUtils.CreateTestClasspath() }; for (var i = 0; i < 20; i++) { Console.WriteLine("Iteration: " + i); var grid = Ignition.Start(cfg); UseIgnite(grid); if (i % 2 == 0) // Try to stop ignite from another thread. { var t = new Thread(() => { grid.Dispose(); }); t.Start(); t.Join(); } else grid.Dispose(); GC.Collect(); // At the time of writing java references are cleaned from finalizer, so GC is needed. } } /// <summary> /// Tests the client mode flag. /// </summary> [Test] public void TestClientMode() { var servCfg = new IgniteConfiguration { SpringConfigUrl = "config\\start-test-grid1.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; var clientCfg = new IgniteConfiguration { SpringConfigUrl = "config\\start-test-grid2.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; try { using (var serv = Ignition.Start(servCfg)) // start server-mode ignite first { Assert.IsFalse(serv.GetCluster().GetLocalNode().IsClient); Ignition.ClientMode = true; using (var grid = Ignition.Start(clientCfg)) { Assert.IsTrue(grid.GetCluster().GetLocalNode().IsClient); UseIgnite(grid); } } } finally { Ignition.ClientMode = false; } } /// <summary> /// Uses the ignite. /// </summary> /// <param name="ignite">The ignite.</param> private static void UseIgnite(IIgnite ignite) { // Create objects holding references to java objects. var comp = ignite.GetCompute(); // ReSharper disable once RedundantAssignment comp = comp.WithKeepBinary(); var prj = ignite.GetCluster().ForOldest(); Assert.IsTrue(prj.GetNodes().Count > 0); Assert.IsNotNull(prj.GetCompute()); var cache = ignite.GetCache<int, int>("cache1"); Assert.IsNotNull(cache); cache.GetAndPut(1, 1); Assert.AreEqual(1, cache.Get(1)); } /// <summary> /// Tests the processor initialization and grid usage right after topology enter. /// </summary> [Test] public void TestProcessorInit() { var cfg = new IgniteConfiguration { SpringConfigUrl = "config\\start-test-grid1.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; // Start local node var grid = Ignition.Start(cfg); // Start remote node in a separate process // ReSharper disable once UnusedVariable var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + Path.GetFullPath(cfg.SpringConfigUrl), "-J-Xms512m", "-J-Xmx512m"); var cts = new CancellationTokenSource(); var token = cts.Token; // Spam message subscriptions on a separate thread // to test race conditions during processor init on remote node var listenTask = Task.Factory.StartNew(() => { var filter = new MessageListener(); while (!token.IsCancellationRequested) { var listenId = grid.GetMessaging().RemoteListen(filter); grid.GetMessaging().StopRemoteListen(listenId); } // ReSharper disable once FunctionNeverReturns }); // Wait for remote node to join Assert.IsTrue(grid.WaitTopology(2)); // Wait some more for initialization Thread.Sleep(1000); // Cancel listen task and check that it finishes cts.Cancel(); Assert.IsTrue(listenTask.Wait(5000)); } /// <summary> /// Noop message filter. /// </summary> [Serializable] private class MessageListener : IMessageListener<int> { /** <inheritdoc /> */ public bool Invoke(Guid nodeId, int message) { return true; } } } }
using System; using System.Xml; using System.Data; using System.Data.OleDb; namespace MyMeta { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)] #endif public class Table : Single, ITable, INameValueItem, ITabularEntity { public Table() { } #region Collections public IColumns Columns { get { if(null == _columns) { _columns = (Columns)this.dbRoot.ClassFactory.CreateColumns(); _columns.Table = this; _columns.dbRoot = this.dbRoot; _columns.LoadForTable(); } return _columns; } } public IForeignKeys ForeignKeys { get { if(null == _foreignKeys) { _foreignKeys = (ForeignKeys)this.dbRoot.ClassFactory.CreateForeignKeys(); _foreignKeys.Table = this; _foreignKeys.dbRoot = this.dbRoot; _foreignKeys.LoadAll(); } return _foreignKeys; } } public IForeignKeys IndirectForeignKeys { get { if(null == _indirectForeignKeys) { _indirectForeignKeys = (ForeignKeys)this.dbRoot.ClassFactory.CreateForeignKeys(); _indirectForeignKeys.Table = this; _indirectForeignKeys.dbRoot = this.dbRoot; _indirectForeignKeys.LoadAllIndirect(); } return _indirectForeignKeys; } } public IIndexes Indexes { get { if(null == _indexes) { _indexes = (Indexes)this.dbRoot.ClassFactory.CreateIndexes(); _indexes.Table = this; _indexes.dbRoot = this.dbRoot; _indexes.LoadAll(); } return _indexes; } } virtual public IPropertyCollection GlobalProperties { get { Database db = this.Tables.Database as Database; if(null == db._tableProperties) { db._tableProperties = new PropertyCollection(); db._tableProperties.Parent = this; string xPath = this.GlobalUserDataXPath; XmlNode xmlNode = this.dbRoot.UserData.SelectSingleNode(xPath, null); if(xmlNode == null) { XmlNode parentNode = db.CreateGlobalXmlNode(); xmlNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Table", null); parentNode.AppendChild(xmlNode); } db._tableProperties.LoadAllGlobal(xmlNode); } return db._tableProperties; } } virtual public IPropertyCollection AllProperties { get { if(null == _allProperties) { _allProperties = new PropertyCollectionAll(); _allProperties.Load(this.Properties, this.GlobalProperties); } return _allProperties; } } internal PropertyCollectionAll _allProperties = null; public virtual IColumns PrimaryKeys { get { return null; } } #endregion #region Objects public IDatabase Database { get { return this.Tables.Database; } } #endregion #region Properties #if ENTERPRISE [DispId(0)] #endif override public string Alias { get { XmlNode node = null; if(this.GetXmlNode(out node, false)) { string niceName = null; if(this.GetUserData(node, "n", out niceName)) { if(string.Empty != niceName) return niceName; } } // There was no nice name return this.Name; } set { XmlNode node = null; if(this.GetXmlNode(out node, true)) { this.SetUserData(node, "n", value); } } } override public string Name { get { return this.GetString(Tables.f_Name); } } public string Schema { get { return this.GetString(Tables.f_Schema); } } public string Type { get { return this.GetString(Tables.f_Type); } } public Guid Guid { get { return this.GetGuid(Tables.f_Guid); } } public string Description { get { return this.GetString(Tables.f_Description); } } public System.Int32 PropID { get { return this.GetInt32(Tables.f_PropID); } } public DateTime DateCreated { get { return this.GetDateTime(Tables.f_DateCreated); } } public DateTime DateModified { get { return this.GetDateTime(Tables.f_DateModified); } } #endregion #region XML User Data #if ENTERPRISE [ComVisible(false)] #endif override public string UserDataXPath { get { return Tables.UserDataXPath + @"/Table[@p='" + this.Name + "']"; } } #if ENTERPRISE [ComVisible(false)] #endif override public string GlobalUserDataXPath { get { return this.Tables.Database.GlobalUserDataXPath + "/Table"; } } #if ENTERPRISE [ComVisible(false)] #endif override internal bool GetXmlNode(out XmlNode node, bool forceCreate) { node = null; bool success = false; if(null == _xmlNode) { // Get the parent node XmlNode parentNode = null; if(this.Tables.GetXmlNode(out parentNode, forceCreate)) { // See if our user data already exists string xPath = @"./Table[@p='" + this.Name + "']"; if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate) { // Create it, and try again this.CreateUserMetaData(parentNode); GetUserData(xPath, parentNode, out _xmlNode); } } } if(null != _xmlNode) { node = _xmlNode; success = true; } return success; } #if ENTERPRISE [ComVisible(false)] #endif override public void CreateUserMetaData(XmlNode parentNode) { XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Table", null); parentNode.AppendChild(myNode); XmlAttribute attr; attr = parentNode.OwnerDocument.CreateAttribute("p"); attr.Value = this.Name; myNode.Attributes.Append(attr); attr = parentNode.OwnerDocument.CreateAttribute("n"); attr.Value = ""; myNode.Attributes.Append(attr); } #endregion internal Tables Tables = null; protected Columns _columns = null; protected Columns _primaryKeys = null; protected ForeignKeys _foreignKeys = null; protected ForeignKeys _indirectForeignKeys = null; protected Indexes _indexes = null; #region INameValueCollection Members public string ItemName { get { return this.Name; } } public string ItemValue { get { return this.Name; } } #endregion #region IEquatable<Table> Members public bool Equals(ITable other) { if (other == null) return false; var o = other as Table; if (o == null) throw new NotImplementedException(); return this.dbRoot == o.dbRoot && this._row == o._row; } #endregion } }
using AutoMapper; using FizzWare.NBuilder; using NUnit.Framework; using ReMi.BusinessEntities.DeploymentTool; using ReMi.Common.Constants.BusinessRules; using ReMi.Common.Constants.ProductRequests; using ReMi.Common.Constants.ReleaseCalendar; using ReMi.Common.Constants.ReleaseExecution; using ReMi.Common.Constants.ReleasePlan; using ReMi.Common.Utils; using ReMi.Common.Utils.Enums; using ReMi.TestUtils.UnitTests; using ReMi.Contracts.Plugins.Data; using ReMi.DataAccess.AutoMapper; using ReMi.DataEntities.Api; using ReMi.DataEntities.BusinessRules; using ReMi.DataEntities.Metrics; using ReMi.DataEntities.Plugins; using ReMi.DataEntities.ProductRequests; using ReMi.DataEntities.Products; using ReMi.DataEntities.ReleaseCalendar; using ReMi.DataEntities.ReleasePlan; using System; using System.Collections.Generic; using System.Linq; using BusinessAccount = ReMi.BusinessEntities.Auth.Account; using BusinessBusinessUnit = ReMi.BusinessEntities.Products.BusinessUnit; using BusinessProduct = ReMi.BusinessEntities.Products.Product; using BusinessProductView = ReMi.BusinessEntities.Products.ProductView; using BusinessReleaseWindow = ReMi.BusinessEntities.ReleaseCalendar.ReleaseWindow; using CommandPermission = ReMi.DataEntities.Auth.CommandPermission; using DataAccount = ReMi.DataEntities.Auth.Account; using DataAccountProduct = ReMi.DataEntities.Auth.AccountProduct; using DataProduct = ReMi.DataEntities.Products.Product; using DataReleaseNote = ReMi.DataEntities.ReleaseCalendar.ReleaseNote; using DataReleaseType = ReMi.Common.Constants.ReleaseCalendar.ReleaseType; using DataReleaseWindow = ReMi.DataEntities.ReleaseCalendar.ReleaseWindow; using ReleaseJob = ReMi.DataEntities.ReleasePlan.ReleaseJob; using Role = ReMi.DataEntities.Auth.Role; using SignOff = ReMi.DataEntities.ReleaseExecution.SignOff; namespace ReMi.DataAccess.Tests.AutoMapper { [TestFixture] public class DataEntityToBusinessEntityMappingProfileTest : TestClassFor<IMappingEngine> { protected override IMappingEngine ConstructSystemUnderTest() { Mapper.Initialize( c => c.AddProfile(new DataEntityToBusinessEntityMappingProfile())); return Mapper.Engine; } [Test] public void ProductMapping_ShouldReturnMappedProduct_WhenMapInvoked() { var product = CreateProduct(); var expected = CreateProduct(product); var actual = Sut.Map<DataProduct, BusinessProduct>(product); Assert.AreEqual(expected.ExternalId, actual.ExternalId); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.BusinessUnit.ExternalId, actual.BusinessUnit.ExternalId); } [Test] public void ProductToProductViewMapping_ShouldReturnMappedProductView_WhenMapInvoked() { var product = CreateProduct(); var actual = Sut.Map<DataProduct, BusinessProductView>(product); Assert.AreEqual(product.ExternalId, actual.ExternalId); Assert.AreEqual(product.Description, actual.Name); } [Test] public void BusinessUnitMapping_ShouldReturnMappedBusinessUnit_WhenMapInvoked() { var businessUnit = new BusinessUnit { ExternalId = Guid.NewGuid(), BusinessUnitId = RandomData.RandomInt(int.MaxValue), Description = RandomData.RandomString(30), Name = RandomData.RandomString(10), Packages = Builder<Product>.CreateListOfSize(5) .All() .Do(x => x.ExternalId = Guid.NewGuid()) .Build() }; var actual = Sut.Map<BusinessUnit, BusinessBusinessUnit>(businessUnit); Assert.AreEqual(businessUnit.ExternalId, actual.ExternalId); Assert.AreEqual(businessUnit.Description, actual.Description); Assert.AreEqual(businessUnit.Name, actual.Name); Assert.IsNull(actual.Packages); } [Test] public void AccountMapping_ShouldReturnMappedAccountWithProducts_WhenMapInvoked() { var account = CreateAccount(); var actual = Sut.Map<DataAccount, BusinessAccount>(account); Assert.AreEqual(account.ExternalId, actual.ExternalId); Assert.AreEqual(account.CreatedOn, actual.CreatedOn); Assert.AreEqual(account.Description, actual.Description); Assert.AreEqual(account.Email, actual.Email); Assert.AreEqual(account.FullName, actual.FullName); Assert.AreEqual(account.IsBlocked, actual.IsBlocked); Assert.AreEqual(account.Name, actual.Name); Assert.AreEqual(account.Role.Name, actual.Role.Name); CollectionAssertHelper.AreEqual(account.AccountProducts, actual.Products, (e, a) => e.Product.ExternalId == a.ExternalId && e.Product.Description == a.Name && e.IsDefault == a.IsDefault); } [Test] public void AccountMapping_ShouldReturnMappedAccountWithoutProducts_WhenMapInvokedWithoutProducts() { var account = CreateAccount(); account.AccountProducts = null; var actual = Sut.Map<DataAccount, BusinessAccount>(account); Assert.IsEmpty(actual.Products); } [Test] public void ReleaseWindowMapping_ShouldReturnReleaseWindow_WhenMapInvoked() { var releaseWindow = CreateReleaseWindow(); var expected = CreateReleaseWindow(releaseWindow); var actual = Sut.Map<DataReleaseWindow, BusinessReleaseWindow>(releaseWindow); Assert.AreEqual(expected.ExternalId, actual.ExternalId); Assert.AreEqual(expected.ReleaseType, actual.ReleaseType); Assert.AreEqual(expected.StartTime, actual.StartTime); Assert.AreEqual(expected.OriginalStartTime, actual.OriginalStartTime); Assert.AreEqual(expected.Sprint, actual.Sprint); Assert.AreEqual(expected.RequiresDowntime, actual.RequiresDowntime); Assert.AreEqual(expected.ReleaseDecision, actual.ReleaseDecision); Assert.AreEqual(expected.IsFailed, actual.IsFailed); Assert.AreEqual(EnumDescriptionHelper.GetDescription(releaseWindow.ReleaseType), actual.ReleaseTypeDescription); Assert.AreEqual(EnumDescriptionHelper.GetDescription(releaseWindow.ReleaseDecision), actual.ReleaseDecision); if (expected.ClosedOn != null) Assert.AreEqual(expected.ClosedOn.Value.ToLocalTime(), actual.ClosedOn); if (expected.ApprovedOn != null) Assert.AreEqual(expected.ApprovedOn.Value.ToLocalTime(), actual.ApprovedOn); Assert.IsNull(actual.ReleaseNotes); CollectionAssert.AreEquivalent(releaseWindow.ReleaseProducts.Select(x => x.Product.Description).ToList(), actual.Products); } [Test] public void ReleaseContentMapping_ShouldReturnTicket_WhenMapInvoked() { var releaseContent = Builder<ReleaseContent>.CreateNew() .With(x => x.Comment, RandomData.RandomString(10)) .With(x => x.Description, RandomData.RandomString(10)) .With(x => x.Assignee, RandomData.RandomString(10)) .With(x => x.TicketId, Guid.NewGuid()) .With(x => x.TicketKey, "RM-" + RandomData.RandomInt(4)) .With(x => x.TicketRisk, RandomData.RandomEnum<TicketRisk>()) .With(x => x.TicketUrl, RandomData.RandomString(10)) .With(x => x.LastChangedByAccount, Builder<DataAccount>.CreateNew() .With(y => y.ExternalId, Guid.NewGuid()) .Build()) .Build(); var expected = Builder<BusinessEntities.ReleasePlan.ReleaseContentTicket>.CreateNew() .With(x => x.Comment, releaseContent.Comment) .With(x => x.TicketDescription, releaseContent.Description) .With(x => x.Assignee, releaseContent.Assignee) .With(x => x.TicketName, releaseContent.TicketKey) .With(x => x.TicketId, releaseContent.TicketId) .With(x => x.Risk, releaseContent.TicketRisk) .With(x => x.TicketUrl, releaseContent.TicketUrl) .With(x => x.LastChangedByAccount, releaseContent.LastChangedByAccount.ExternalId) .Build(); var actual = Sut.Map<ReleaseContent, BusinessEntities.ReleasePlan.ReleaseContentTicket>(releaseContent); Assert.AreEqual(expected.Comment, actual.Comment); Assert.AreEqual(expected.Assignee, actual.Assignee); Assert.AreEqual(expected.TicketDescription, actual.TicketDescription); Assert.AreEqual(expected.TicketId, actual.TicketId); Assert.AreEqual(expected.TicketName, actual.TicketName); Assert.AreEqual(expected.Risk, actual.Risk); Assert.AreEqual(expected.LastChangedByAccount, actual.LastChangedByAccount); Assert.AreEqual(expected.TicketUrl, actual.TicketUrl); } [Test] public void CommandMapping_ShouldReturnBusinessCommand_WhenMapInvoked() { var command = Builder<Command>.CreateNew() .With(x => x.Name, RandomData.RandomString(10)) .With(x => x.Description, RandomData.RandomString(10)) .With(x => x.IsBackground, RandomData.RandomBool()) .With(x => x.CommandId, RandomData.RandomInt(6)) .With(x => x.Group, RandomData.RandomString(10)) .With(x => x.CommandPermissions, Builder<CommandPermission>.CreateListOfSize(3) .All() .Do(y => y.Role = Builder<Role>.CreateNew() .With(z => z.ExternalId, Guid.NewGuid()) .With(z => z.Description, RandomData.RandomString(10)) .With(z => z.Id, RandomData.RandomInt(10000)) .With(z => z.Name, RandomData.RandomString(10)) .Build()) .Build()) .Build(); var expected = Builder<BusinessEntities.Api.Command>.CreateNew() .With(x => x.Name, command.Name) .With(x => x.Description, command.Description) .With(x => x.IsBackground, command.IsBackground) .With(x => x.CommandId, command.CommandId) .With(x => x.Group, command.Group) .With(x => x.Roles, command.CommandPermissions.Select(y => new BusinessEntities.Auth.Role { Description = y.Role.Description, Name = y.Role.Name, ExternalId = y.Role.ExternalId })) .Build(); var actual = Sut.Map<Command, BusinessEntities.Api.Command>(command); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.IsBackground, actual.IsBackground); Assert.AreEqual(expected.CommandId, actual.CommandId); Assert.AreEqual(expected.Group, actual.Group); Assert.AreEqual(expected.Roles.Count(), actual.Roles.Count()); CollectionAssertHelper.AreEqual<BusinessEntities.Auth.Role, BusinessEntities.Auth.Role>(expected.Roles, actual.Roles, (e, a) => e.Description == a.Description && e.Name == a.Name && e.ExternalId == a.ExternalId); } [Test] public void RoleMapping_ShouldReturnRole_WhenMapInvoked() { var role = Builder<Role>.CreateNew() .With(x => x.Name, RandomData.RandomString(10)) .With(x => x.Description, RandomData.RandomString(10)) .With(x => x.ExternalId, Guid.NewGuid()) .With(x => x.Id, RandomData.RandomInt(10000)) .Build(); var expected = Builder<BusinessEntities.Auth.Role>.CreateNew() .With(x => x.Name, role.Name) .With(x => x.Description, role.Description) .With(x => x.ExternalId, role.ExternalId) .Build(); var actual = Sut.Map<Role, BusinessEntities.Auth.Role>(role); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.ExternalId, actual.ExternalId); } [Test] public void SignOffMapping_ShouldReturnSigner_WhenMapInvoked() { var signer = Builder<SignOff>.CreateNew() .With(x => x.SignedOff, SystemTime.Now) .With(x => x.Account, new DataAccount { ExternalId = Guid.NewGuid() }) .With(x => x.ExternalId, Guid.NewGuid()) .Build(); var expected = Builder<BusinessEntities.ReleaseExecution.SignOff>.CreateNew() .With(x => x.SignedOff, true) .With(x => x.Signer, new BusinessAccount { ExternalId = signer.Account.ExternalId }) .With(x => x.ExternalId, signer.ExternalId) .Build(); var actual = Sut.Map<SignOff, BusinessEntities.ReleaseExecution.SignOff>(signer); Assert.AreEqual(expected.Signer.ExternalId, actual.Signer.ExternalId); Assert.AreEqual(expected.SignedOff, actual.SignedOff); Assert.AreEqual(expected.ExternalId, actual.ExternalId); } [Test] public void MetricMapping_ShouldReturnMetric_WhenMapInvoked() { var metric = Builder<Metric>.CreateNew() .With(x => x.ExecutedOn, DateTime.UtcNow) .With(x => x.MetricType, MetricType.SiteDown) .With(x => x.ExternalId, Guid.NewGuid()) .Build(); var expected = Builder<BusinessEntities.Metrics.Metric>.CreateNew() .With(x => x.ExecutedOn, metric.ExecutedOn) .With(x => x.MetricType, MetricType.SiteDown) .With(x => x.Order, 3) .With(x => x.ExternalId, metric.ExternalId) .Build(); var actual = Sut.Map<Metric, BusinessEntities.Metrics.Metric>(metric); Assert.AreEqual(expected.ExecutedOn.Value.ToLocalTime(), actual.ExecutedOn, "executed on"); Assert.AreEqual(expected.ExternalId, actual.ExternalId, "external id"); Assert.AreEqual(expected.MetricType, actual.MetricType, "metric type"); Assert.AreEqual(expected.Order, actual.Order, "order"); } [Test] public void ReleaseDeploymentMeasurement_ShouldReturnJobMeasurement_WhenMapInvoked() { var dt = RandomData.RandomDateTime(DateTimeKind.Utc); var source = Builder<ReleaseDeploymentMeasurement>.CreateNew() .With(o => o.StartTime, dt.AddMinutes(-RandomData.RandomInt(1, 100))) .With(o => o.StartTime, dt.AddMinutes(RandomData.RandomInt(1, 100))) .With(o => o.StepId, RandomData.RandomString(10)) .With(o => o.StepName, RandomData.RandomString(20)) .With(o => o.Locator, RandomData.RandomString(50)) .Build(); var expected = Builder<ReleaseDeploymentMeasurement>.CreateNew() .With(o => o.StartTime, source.StartTime.Value.ToLocalTime()) .With(o => o.FinishTime, source.FinishTime.Value.ToLocalTime()) .With(o => o.StepId, source.StepId) .With(o => o.StepName, source.StepName) .With(o => o.Locator, source.Locator) .Build(); var actual = Sut.Map<ReleaseDeploymentMeasurement, JobMeasurement>(source); Assert.AreEqual(expected.FinishTime.Value.Subtract(expected.StartTime.Value).TotalMilliseconds, actual.Duration, "duration"); Assert.AreEqual(expected.Locator, actual.Locator, "locator"); Assert.AreEqual(expected.StartTime, actual.StartTime, "start time"); Assert.AreEqual(DateTimeKind.Local, actual.StartTime.Value.Kind, "local start time"); Assert.AreEqual(expected.FinishTime, actual.FinishTime, "finish time"); Assert.AreEqual(DateTimeKind.Local, actual.FinishTime.Value.Kind, "local finish time"); Assert.AreEqual(expected.StepName, actual.StepName, "step name"); Assert.AreEqual(expected.StepId, actual.StepId, "step id"); Assert.AreEqual(expected.BuildNumber, actual.BuildNumber, "BuildNumber"); Assert.AreEqual(expected.NumberOfTries, actual.NumberOfTries, "NumberOfTries"); Assert.IsNull(actual.ChildSteps, "child steps"); } [Test] public void BusinessRuleParameterMapping_ShouldReturnProperType_WhenConvertingToBusinessType() { var parameter = new BusinessRuleParameter { BusinessRuleId = 1, ExternalId = Guid.NewGuid(), Name = RandomData.RandomString(10), Type = "int", TestData = new BusinessRuleTestData { BusinessRuleTestDataId = 1, ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) } }; var actual = Sut.Map<BusinessRuleParameter, BusinessEntities.BusinessRules.BusinessRuleParameter>(parameter); Assert.AreEqual(parameter.Type, actual.Type); Assert.AreEqual(parameter.ExternalId, actual.ExternalId); Assert.AreEqual(parameter.Name, actual.Name); Assert.AreEqual(parameter.TestData.JsonData, actual.TestData.JsonData); Assert.AreEqual(parameter.TestData.ExternalId, actual.TestData.ExternalId); } [Test] public void BusinessRuleTestDataMapping_ShouldReturnProperType_WhenConvertingToBusinessType() { var testData = new BusinessRuleTestData { BusinessRuleTestDataId = 1, ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) }; var actual = Sut.Map<BusinessRuleTestData, BusinessEntities.BusinessRules.BusinessRuleTestData>(testData); Assert.AreEqual(testData.JsonData, actual.JsonData); Assert.AreEqual(testData.ExternalId, actual.ExternalId); } [Test] public void BusinessRuleAccountTestDataMapping_ShouldReturnProperType_WhenConvertingToBusinessType() { var testData = new BusinessRuleAccountTestData { BusinessRuleAccountTestDataId = 1, ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) }; var actual = Sut.Map<BusinessRuleAccountTestData, BusinessEntities.BusinessRules.BusinessRuleAccountTestData>(testData); Assert.AreEqual(testData.ExternalId, actual.ExternalId); } [Test] public void BusinessRuleDescriptionMapping_ShouldReturnProperEnumType_WhenConvertingToBusinessType() { var rule = new BusinessRuleDescription { Script = RandomData.RandomString(10), Group = RandomData.RandomEnum<BusinessRuleGroup>(), ExternalId = Guid.NewGuid(), Parameters = new List<BusinessRuleParameter> { new BusinessRuleParameter { BusinessRuleId = 1, ExternalId = Guid.NewGuid(), Name = RandomData.RandomString(10), Type = "System.Int32" } }, AccountTestData = new BusinessRuleAccountTestData { BusinessRuleAccountTestDataId = 1, ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) } }; var actual = Sut.Map<BusinessRuleDescription, BusinessEntities.BusinessRules.BusinessRuleDescription>(rule); Assert.AreEqual(rule.Group, actual.Group); Assert.AreEqual(rule.ExternalId, actual.ExternalId); Assert.AreEqual(rule.Script, actual.Script); Assert.AreEqual(rule.Parameters.Count, actual.Parameters.Count()); Assert.AreEqual(rule.AccountTestData.ExternalId, actual.AccountTestData.ExternalId); } [Test] public void BusinessRuleDescriptionMapping_ShouldReturnBusinessRuleView_WhenConvertingToBusinessType() { var rule = new BusinessRuleDescription { Script = "012345678901234567890123456789012345678901234567890123456789", Group = RandomData.RandomEnum<BusinessRuleGroup>(), Name = RandomData.RandomString(10), Description = RandomData.RandomString(10), ExternalId = Guid.NewGuid(), Parameters = new List<BusinessRuleParameter> { new BusinessRuleParameter { BusinessRuleId = 1, ExternalId = Guid.NewGuid(), Name = RandomData.RandomString(10), Type = "System.Int32" } }, AccountTestData = new BusinessRuleAccountTestData { BusinessRuleAccountTestDataId = 1, ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) } }; var actual = Sut.Map<BusinessRuleDescription, BusinessEntities.BusinessRules.BusinessRuleView>(rule); Assert.AreEqual(rule.Group, actual.Group); Assert.AreEqual(rule.ExternalId, actual.ExternalId); Assert.AreEqual("012345678901234567890123456789 ...", actual.CodeBeggining); Assert.AreEqual(rule.Name, actual.Name); Assert.AreEqual(rule.Description, actual.Description); } [Test] public void ProductRequestType_ShouldReturnProperType_WhenConvertingToBusinessType() { var mapping = new ProductRequestType { ProductRequestTypeId = RandomData.RandomInt(1, int.MaxValue), Name = RandomData.RandomString(100), ExternalId = Guid.NewGuid(), RequestGroups = new[] { new ProductRequestGroup { ProductRequestGroupId = RandomData.RandomInt(1, int.MaxValue), ExternalId = Guid.NewGuid(), Name = RandomData.RandomString(1, 100), ProductRequestTypeId = RandomData.RandomInt(1, int.MaxValue), } } }; var actual = Sut.Map<ProductRequestType, BusinessEntities.ProductRequests.ProductRequestType>(mapping); Assert.AreEqual(mapping.Name, actual.Name); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.RequestGroups.Count, actual.RequestGroups.Count()); Assert.AreEqual(mapping.RequestGroups.First().ExternalId, actual.RequestGroups.First().ExternalId); Assert.AreEqual(mapping.RequestGroups.First().Name, actual.RequestGroups.First().Name); } [Test] public void ProductRequestGroup_WhenConvertingToBusinessType() { var mapping = new ProductRequestGroup { ProductRequestTypeId = RandomData.RandomInt(1, int.MaxValue), Name = RandomData.RandomString(100), ExternalId = Guid.NewGuid(), RequestTasks = null, RequestType = Builder<ProductRequestType>.CreateNew() .With(o => o.ExternalId, Guid.NewGuid()) .Build() }; var actual = Sut.Map<ProductRequestGroup, BusinessEntities.ProductRequests.ProductRequestGroup>(mapping); Assert.AreEqual(mapping.Name, actual.Name); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.RequestType.ExternalId, actual.ProductRequestTypeId); Assert.IsFalse(actual.RequestTasks.Any()); } [Test] public void ProductRequestTask_WhenConvertingToBusinessType() { var mapping = new ProductRequestTask { ProductRequestTaskId = RandomData.RandomInt(1, int.MaxValue), Question = RandomData.RandomString(100), ExternalId = Guid.NewGuid(), RequestGroup = new ProductRequestGroup { ExternalId = Guid.NewGuid(), } }; var actual = Sut.Map<ProductRequestTask, BusinessEntities.ProductRequests.ProductRequestTask>(mapping); Assert.AreEqual(mapping.Question, actual.Question); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.RequestGroup.ExternalId, actual.ProductRequestGroupId); } [Test] public void ProductRequestGroupAssignee_WhenConvertingToBusinessType() { var mapping = new ProductRequestGroupAssignee { ProductRequestGroupAssigneeId = RandomData.RandomInt(1, int.MaxValue), AccountId = RandomData.RandomInt(1, int.MaxValue), RequestGroup = new ProductRequestGroup { ExternalId = Guid.NewGuid(), }, Account = new DataAccount { ExternalId = Guid.NewGuid(), FullName = RandomData.RandomString(1, 100), Email = RandomData.RandomEmail() } }; var actual = Sut.Map<ProductRequestGroupAssignee, BusinessEntities.Auth.Account>(mapping); Assert.AreEqual(mapping.Account.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.Account.FullName, actual.FullName); Assert.AreEqual(mapping.Account.Email, actual.Email); } [Test] public void ProductRequestRegistration() { var mapping = new ProductRequestRegistration { Description = RandomData.RandomString(1, 1024), ExternalId = Guid.NewGuid(), ProductRequestTypeId = RandomData.RandomInt(1, int.MaxValue), ProductRequestType = new ProductRequestType { ExternalId = Guid.NewGuid() }, CreatedBy = new DataAccount { ExternalId = Guid.NewGuid() }, CreatedOn = DateTime.UtcNow, Tasks = Builder<ProductRequestRegistrationTask>.CreateListOfSize(RandomData.RandomInt(1, 5)) .All() .With(o => o.ProductRequestTask, Builder<ProductRequestTask>.CreateNew().With(x => x.ExternalId, Guid.NewGuid()).Build()) .With(o => o.IsCompleted, false) .Build() }; var actual = Sut.Map<ProductRequestRegistration, BusinessEntities.ProductRequests.ProductRequestRegistration>(mapping); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(EnumDescriptionHelper.GetDescription(ProductRequestRegistrationStatus.New), actual.Status); Assert.AreEqual(mapping.Description, actual.Description); Assert.AreEqual(mapping.CreatedBy.ExternalId, actual.CreatedByAccountId); Assert.AreEqual(mapping.CreatedOn.ToUniversalTime(), actual.CreatedOn.ToUniversalTime(), "created on"); Assert.AreEqual(DateTimeKind.Local, actual.CreatedOn.Kind); Assert.AreEqual(mapping.ProductRequestType.ExternalId, actual.ProductRequestTypeId); Assert.AreEqual(mapping.Tasks.Count, actual.Tasks.Count(), "tasks"); foreach (var task in mapping.Tasks) { Assert.IsTrue(actual.Tasks.Any(o => o.ProductRequestTaskId == task.ProductRequestTask.ExternalId), "task not mapped"); } } [Test] public void ProductRequestRegistrationTask() { var mapping = new ProductRequestRegistrationTask { IsCompleted = RandomData.RandomBool(), ProductRequestTask = new ProductRequestTask { ExternalId = Guid.NewGuid() }, LastChangedByAccountId = RandomData.RandomInt(1, int.MaxValue), ProductRequestRegistration = new ProductRequestRegistration { ExternalId = Guid.NewGuid() }, LastChangedBy = new DataAccount { ExternalId = Guid.NewGuid() }, LastChangedOn = DateTime.UtcNow }; var actual = Sut.Map<ProductRequestRegistrationTask, BusinessEntities.ProductRequests.ProductRequestRegistrationTask>(mapping); Assert.AreEqual(mapping.IsCompleted, actual.IsCompleted); Assert.AreEqual(mapping.ProductRequestTask.ExternalId, actual.ProductRequestTaskId); Assert.AreEqual(mapping.LastChangedBy.ExternalId, actual.LastChangedByAccountId); Assert.AreEqual(mapping.LastChangedOn.Value.ToUniversalTime(), actual.LastChangedOn.Value.ToUniversalTime()); Assert.AreEqual(DateTimeKind.Local, actual.LastChangedOn.Value.Kind); } [Test] public void PluginConfiguration_To_GlobalPluginConfiguration_ShouldConvert_WhenAllPropertiesFilledOut() { var mapping = new PluginConfiguration { ExternalId = Guid.NewGuid(), PluginId = 1234, PluginConfigurationId = RandomData.RandomInt(int.MaxValue), PluginType = RandomData.RandomEnum<PluginType>(), Plugin = new DataEntities.Plugins.Plugin { ExternalId = Guid.NewGuid() } }; var actual = Sut.Map<PluginConfiguration, BusinessEntities.Plugins.GlobalPluginConfiguration>(mapping); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.PluginType, actual.PluginType); Assert.AreEqual(mapping.Plugin.ExternalId, actual.PluginId); } [Test] public void PluginConfiguration_To_GlobalPluginConfiguration_ShouldConvert_WhenPluginIsNotAssigned() { var mapping = new PluginConfiguration { ExternalId = Guid.NewGuid(), PluginId = null, PluginConfigurationId = RandomData.RandomInt(int.MaxValue), PluginType = RandomData.RandomEnum<PluginType>(), Plugin = null }; var actual = Sut.Map<PluginConfiguration, BusinessEntities.Plugins.GlobalPluginConfiguration>(mapping); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.PluginType, actual.PluginType); Assert.IsNull(actual.PluginId); } [Test] public void PackagePluginConfiguration_To_PackagePluginConfiguration_ShouldConvert_WhenAllPropertiesFilledOut() { var mapping = new PluginPackageConfiguration { ExternalId = Guid.NewGuid(), PluginId = RandomData.RandomInt(int.MaxValue), PluginPackageConfigurationId = RandomData.RandomInt(int.MaxValue), PluginType = RandomData.RandomEnum<PluginType>(), Plugin = new DataEntities.Plugins.Plugin { ExternalId = Guid.NewGuid() }, PackageId = RandomData.RandomInt(int.MaxValue), Package = new Product { ExternalId = Guid.NewGuid(), Description = RandomData.RandomString(10), BusinessUnit = new BusinessUnit { Description = RandomData.RandomString(10) } } }; var actual = Sut.Map<PluginPackageConfiguration, BusinessEntities.Plugins.PackagePluginConfiguration>(mapping); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.PluginType, actual.PluginType); Assert.AreEqual(mapping.Plugin.ExternalId, actual.PluginId); Assert.AreEqual(mapping.Package.ExternalId, actual.PackageId); Assert.AreEqual(mapping.Package.Description, actual.PackageName); Assert.AreEqual(mapping.Package.BusinessUnit.Description, actual.BusinessUnit); } [Test] public void PackagePluginConfiguration_To_PackagePluginConfiguration_ShouldConvert_WhenPluginIsNotAssigned() { var mapping = new PluginPackageConfiguration { ExternalId = Guid.NewGuid(), PluginId = null, PluginPackageConfigurationId = RandomData.RandomInt(int.MaxValue), PluginType = RandomData.RandomEnum<PluginType>(), Plugin = null, PackageId = RandomData.RandomInt(int.MaxValue), Package = new Product { ExternalId = Guid.NewGuid(), Description = RandomData.RandomString(10) } }; var actual = Sut.Map<PluginPackageConfiguration, BusinessEntities.Plugins.PackagePluginConfiguration>(mapping); Assert.AreEqual(mapping.ExternalId, actual.ExternalId); Assert.AreEqual(mapping.PluginType, actual.PluginType); Assert.IsNull(actual.PluginId); Assert.AreEqual(mapping.Package.ExternalId, actual.PackageId); Assert.AreEqual(mapping.Package.Description, actual.PackageName); } [Test] public void Plugin_To_Plugin_ShouldConvert_WhenMapped() { var mapping = new DataEntities.Plugins.Plugin { ExternalId = Guid.NewGuid(), PluginId = RandomData.RandomInt(int.MaxValue), PluginType = PluginType.Authentication | PluginType.HelpDesk | PluginType.DeploymentTool, Key = RandomData.RandomString(10) }; var actual = Sut.Map<DataEntities.Plugins.Plugin, BusinessEntities.Plugins.Plugin>(mapping); Assert.AreEqual(mapping.ExternalId, actual.PluginId); Assert.AreEqual(mapping.Key, actual.PluginKey); Assert.AreEqual(3, actual.PluginTypes.Count()); Assert.IsTrue(actual.PluginTypes.Contains(PluginType.Authentication)); Assert.IsTrue(actual.PluginTypes.Contains(PluginType.HelpDesk)); Assert.IsTrue(actual.PluginTypes.Contains(PluginType.DeploymentTool)); } [Test] public void ReleaseJob_ShouldReturnDataReleaseJob_WhenMapFromBusinessEntity() { var releaseJob = new ReleaseJob { ExternalId = Guid.NewGuid(), IsIncluded = RandomData.RandomBool(), JobId = Guid.NewGuid(), Name = RandomData.RandomString(10), Order = RandomData.RandomInt(100) }; var result = Sut.Map<ReleaseJob, BusinessEntities.DeploymentTool.ReleaseJob>(releaseJob); Assert.AreEqual(releaseJob.ExternalId, result.ExternalId); Assert.AreEqual(releaseJob.IsIncluded, result.IsIncluded); Assert.AreEqual(releaseJob.JobId, result.JobId); Assert.AreEqual(releaseJob.Name, result.Name); Assert.AreEqual(releaseJob.Order, result.Order); } [Test] public void ReleaseTask_ShouldReturnDataReleaseTask_WhenMapFromBusinessEntity() { var releaseJob = new ReleaseTask { ReleaseWindow = new ReleaseWindow { ExternalId = Guid.NewGuid() }, ExternalId = Guid.NewGuid(), CreatedBy = new DataAccount { FullName = RandomData.RandomString(10), ExternalId = Guid.NewGuid() }, CreatedOn = RandomData.RandomDateTime(DateTimeKind.Utc), CompletedOn = RandomData.RandomDateTime(DateTimeKind.Utc), Assignee = new DataAccount { FullName = RandomData.RandomString(10), ExternalId = Guid.NewGuid() }, HelpDeskReference = RandomData.RandomString(10), HelpDeskUrl = RandomData.RandomString(10) }; var result = Sut.Map<ReleaseTask, BusinessEntities.ReleasePlan.ReleaseTask>(releaseJob); Assert.AreEqual(releaseJob.ReleaseWindow.ExternalId, result.ReleaseWindowId); Assert.AreEqual(releaseJob.ExternalId, result.ExternalId); Assert.AreEqual(releaseJob.CreatedBy.FullName, result.CreatedBy); Assert.AreEqual(releaseJob.CreatedBy.ExternalId, result.CreatedByExternalId); Assert.AreEqual(releaseJob.CreatedOn.ToLocalTime(), result.CreatedOn); Assert.AreEqual(releaseJob.CompletedOn.Value.ToLocalTime(), result.CompletedOn); Assert.AreEqual(releaseJob.Assignee.FullName, result.Assignee); Assert.AreEqual(releaseJob.HelpDeskReference, result.HelpDeskTicketReference); Assert.AreEqual(releaseJob.HelpDeskUrl, result.HelpDeskTicketUrl); Assert.AreEqual(releaseJob.Assignee.ExternalId, result.AssigneeExternalId); } #region Helpers private DataReleaseWindow CreateReleaseWindow() { return Builder<DataReleaseWindow>.CreateNew() .With(o => o.ExternalId, Guid.NewGuid()) .With(o => o.Sprint = RandomData.RandomString(5)) .With(o => o.StartTime, RandomData.RandomDateTime(DateTimeKind.Utc)) .With(o => o.ReleaseType = RandomData.RandomEnum<DataReleaseType>()) .With(o => o.CreatedOn, RandomData.RandomDateTime(DateTimeKind.Utc)) .With(o => o.OriginalStartTime, RandomData.RandomDateTime(DateTimeKind.Utc)) .With(o => o.ReleaseWindowId, RandomData.RandomInt(int.MaxValue)) .With(o => o.RequiresDowntime, RandomData.RandomBool()) .With(o => o.Metrics, Builder<Metric>.CreateListOfSize(2) .TheFirst(1) .With(x => x.ExecutedOn, RandomData.RandomDateTime(DateTimeKind.Utc)) .With(x => x.MetricType, MetricType.Close) .TheNext(1) .With(x => x.ExecutedOn, RandomData.RandomDateTime(DateTimeKind.Utc)) .With(x => x.MetricType, MetricType.Approve) .Build()) .With(o => o.ReleaseDecision, RandomData.RandomEnum<ReleaseDecision>()) .With(o => o.ReleaseProducts, Builder<ReleaseProduct>.CreateListOfSize(RandomData.RandomInt(3, 5)) .All() .With(x => x.Product = Builder<DataProduct>.CreateNew().With(p => p.Description = RandomData.RandomString(5)).Build()) .Build()) .With(o => o.ReleaseNotes, Builder<DataReleaseNote>.CreateNew() .With(x => x.ReleaseNotes, RandomData.RandomString(100)) .With(x => x.ReleaseNoteId, RandomData.RandomInt(int.MaxValue)) .With(x => x.Issues, RandomData.RandomString(100)) .Build()) .With(o => o.IsFailed, RandomData.RandomBool()) .Build(); } private BusinessReleaseWindow CreateReleaseWindow(DataReleaseWindow releaseWindow) { return Builder<BusinessReleaseWindow>.CreateNew() .With(o => o.ExternalId, releaseWindow.ExternalId) .With(o => o.Products = releaseWindow.ReleaseProducts.Select(x => x.Product.Description).ToList()) .With(o => o.Sprint = releaseWindow.Sprint) .With(o => o.StartTime, releaseWindow.StartTime.ToLocalTime()) .With(o => o.ReleaseType, releaseWindow.ReleaseType) .With(o => o.OriginalStartTime, releaseWindow.OriginalStartTime.ToLocalTime()) .With(o => o.RequiresDowntime, releaseWindow.RequiresDowntime) .With(o => o.ApprovedOn, releaseWindow.Metrics.IsNullOrEmpty() ? releaseWindow.Metrics.First(x => x.MetricType == MetricType.Approve).ExecutedOn : null) .With(o => o.ClosedOn, releaseWindow.Metrics.IsNullOrEmpty() ? releaseWindow.Metrics.First(x => x.MetricType == MetricType.Close).ExecutedOn : null) .With(o => o.ReleaseDecision, EnumDescriptionHelper.GetDescription(releaseWindow.ReleaseDecision)) .With(o => o.IsFailed, releaseWindow.IsFailed) .Build(); } private DataProduct CreateProduct() { return Builder<DataProduct>.CreateNew() .With(o => o.ProductId = RandomData.RandomInt(1000)) .With(o => o.Description = RandomData.RandomString(5)) .With(o => o.ExternalId = Guid.NewGuid()) .With(o => o.BusinessUnit, new BusinessUnit { ExternalId = Guid.NewGuid() }) .Build(); } private BusinessProduct CreateProduct(DataProduct product) { return Builder<BusinessProduct>.CreateNew() .With(o => o.ExternalId = product.ExternalId) .With(o => o.Description = product.Description) .With(o => o.BusinessUnit = new BusinessBusinessUnit { ExternalId = product.BusinessUnit.ExternalId }) .Build(); } private DataAccountProduct CreateAccountProduct() { var product = CreateProduct(); return Builder<DataAccountProduct>.CreateNew() .With(o => o.AccountProductId, RandomData.RandomInt(500)) .With(o => o.CreatedOn, RandomData.RandomDate()) .With(o => o.IsDefault, RandomData.RandomBool()) .With(o => o.Product, product) .With(o => o.ProductId, product.ProductId) .Build(); } private DataAccount CreateAccount() { var acc = Builder<DataAccount>.CreateNew() .With(o => o.AccountId, RandomData.RandomInt(500)) .With(o => o.ExternalId, Guid.NewGuid()) .With(o => o.CreatedOn, RandomData.RandomDate()) .With(o => o.Description, RandomData.RandomString(5)) .With(o => o.Email, RandomData.RandomEmail()) .With(o => o.FullName, RandomData.RandomString(10)) .With(o => o.IsBlocked, RandomData.RandomBool()) .With(o => o.Name, RandomData.RandomString(10)) .With(o => o.Role, new Role()) .With(o => o.AccountProducts, new List<DataAccountProduct> { CreateAccountProduct(), CreateAccountProduct() }) .Build(); return acc; } #endregion } }
// ------------------------------------------------------------------------ // Orthello 2D Framework Example Source Code // (C)opyright 2011 - WyrmTale Games - http://www.wyrmtale.com // ------------------------------------------------------------------------ // More info http://www.wyrmtale.com/orthello // ------------------------------------------------------------------------ // Example 3 // Using 'collidable' animating sprites and handle collisions // - asteroid 'full' animation // - gun : 2 single frameset (idle/shoot) animation // ------------------------------------------------------------------------ // Main Example 3 Demo class // ------------------------------------------------------------------------ using UnityEngine; using System.Collections; public class CExample3 : MonoBehaviour { // sprite prototypes that will be used when creating objects public OTSprite bullet; // the asteroid prototypes will be de-activated on start public OTAnimatingSprite a1; public OTAnimatingSprite a2; public OTAnimatingSprite a3; OTAnimatingSprite gun; // gun sprite reference bool initialized = false; // initialization notifier void Awake() { // keep our prototypes by de-activating them. a1.gameObject.SetActive(false); a2.gameObject.SetActive(false); a3.gameObject.SetActive(false); // lets create all sprites passive OT.createPassive = true; // By de-acivating a gameobject is becomes invisible but can still // be used them to instantiate copies. } int dp = 100; // This method will create an asteroid at a random position on screen and with // relative min/max (0-1) size. An OTObject can be provided to act as a base to // determine the new size. OTAnimatingSprite RandomBlock(Rect r, float min, float max, OTObject o) { // Determine random 1-3 asteroid type int t = 1 + (int)Mathf.Floor(Random.value * 3); // Determine random size modifier (min-max) float s = min + Random.value * (max - min); GameObject g = null; // Create a new asteroid switch (t) { case 1: g = OT.CreateObject("asteroid1"); break; case 2: g = OT.CreateObject("asteroid2"); break; case 3: g = OT.CreateObject("asteroid3"); break; } if (g != null) { // Find this new asteroid's animating sprite OTAnimatingSprite sprite = g.GetComponent<OTAnimatingSprite>(); // If a base object was provided use it for size scaling if (o != null) sprite.size = o.size * s; else sprite.size = sprite.size * s; // Set sprite's random position sprite.position = new Vector2(r.xMin + Random.value * r.width, r.yMin + Random.value * r.height); // Set sprote's random rotation sprite.rotation = Random.value * 360; // Set sprite's name sprite.depth = dp++; if (dp > 750) dp = 100; // Return new sprite sprite.enabled = true; return sprite; } // we did not manage to create a sprite/asteroid return null; } // Create objects for this application void CreateObjectPools() { OT.PreFabricate("asteroid1",250); OT.PreFabricate("asteroid2",250); OT.PreFabricate("asteroid3",250); } // application initialization void Initialize() { // Get reference to gun animation sprite gun = OT.ObjectByName("gun") as OTAnimatingSprite; // Set gun animation finish delegate // HINT : We could use sprite.InitCallBacks(this) as well. // but because delegates are the C# way we will use this technique gun.onAnimationFinish = OnAnimationFinish; // Create our object pool if we want. OT.objectPooling = true; if (OT.objectPooling) CreateObjectPools(); // set our initialization notifier - we only want to initialize once initialized = true; } // This method will explode an asteroid public void Explode(OTObject o, CBullet3 bullet) { // Determine how many debree has to be be created int blocks = 2 + (int)Mathf.Floor(Random.value * 2); // Create debree for (int b = 0; b < blocks; b++) { // Shrink asteroid's rect to act as the random position container // for the debree Rect r = new Rect( o.rect.x + o.rect.width / 4, o.rect.y + o.rect.height / 4, o.rect.width / 2, o.rect.height / 2); // Create a debree that is relatively smaller than the asteroid that was detroyed OTAnimatingSprite a = RandomBlock(r, 0.6f, 0.75f, o); // Add this debree to the bullet telling the bullet to ignore this debree // in this update cycle - otherwise the bullet explosions could enter some // recursive 'dead' loop creating LOTS of debree bullet.AddDebree(a); // Recusively explode 2 asteroids if they are big enough, to get a nice // exploding debree effect. if (b < 2 && a.size.x > 30) Explode(a, bullet); } // Notify that this asteroid has to be destroyed OT.DestroyObject(o); } // Update is called once per frame void Update () { // only go one if Orthello is initialized if (!OT.isValid) return; // We call the application initialization function from Update() once // because we want to be sure that all Orthello objects have been started. if (!initialized) { Initialize(); return; } // Rotate the gun animation sprite towards the mouse on screen gun.RotateTowards(OT.view.mouseWorldPosition); // Rotate our bullet prototype as well so we will instantiate a // 'already rotated' bullet when we shoot bullet.rotation = gun.rotation; // check if the left mouse button was clicked if (Input.GetMouseButtonDown(0)) { // Create a new bullet OTSprite nBullet = OT.CreateSprite("bullet"); // Set bullet's position at approximately the gun's shooting barrel nBullet.position = gun.position + (gun.yVector * (gun.size.y / 2)); // Play the gun's shooting animation frameset once gun.PlayOnce("shoot"); } // If we have less than 15 objects within Orthello we will create a random asteroid if (OT.objectCount <= 15) RandomBlock(OT.view.worldRect, 0.6f, 1.2f, null); } // The OnAnimationFinish delegate will be called when an animation or animation frameset // finishes playing. public void OnAnimationFinish(OTObject owner) { if (owner == gun) { // Because the only animation that finishes will be the gun's 'shoot' animation frameset // we know that we have to switch to the gun's looping 'idle' animation frameset gun.PlayLoop("idle"); } } }
using System; using System.Collections.Generic; using Xunit; using Xunit.Abstractions; using Microsoft.Azure.Management.StorSimple8000Series; using Microsoft.Azure.Management.StorSimple8000Series.Models; namespace StorSimple8000Series.Tests { public class DeviceSettingsTests : StorSimpleTestBase { public DeviceSettingsTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } [Fact] public void TestDeviceSettingsOperationsOnConfiguredDevice() { var device = Helpers.CheckAndGetConfiguredDevice(this, TestConstants.DefaultDeviceName); var deviceName = device.Name; try { //Create Time Settings var timeSettings = CreateAndValidateTimeSettings(deviceName); //Create Alert Settings var alertSettings = CreateAndValidateAlertSettings(deviceName); //Create Network Settings var networkSettings = CreateAndValidateNetworkSettings(deviceName); //Create Security Settings var securitySettings = CreateAndValidateSecuritySettings(deviceName); } catch (Exception e) { Assert.Null(e); } } [Fact] public void TestSyncRemoteManagementCertificateAPI() { var device = Helpers.CheckAndGetConfiguredDevice(this, TestConstants.DefaultDeviceName); var deviceName = device.Name; try { //update remote management settings RemoteManagementSettingsPatch remoteManagementSettings = new RemoteManagementSettingsPatch(RemoteManagementModeConfiguration.HttpsAndHttpEnabled); SecuritySettingsPatch securitySettingsPatch = new SecuritySettingsPatch() { RemoteManagementSettings = remoteManagementSettings }; this.Client.DeviceSettings.UpdateSecuritySettings( deviceName.GetDoubleEncoded(), securitySettingsPatch, this.ResourceGroupName, this.ManagerName); //sync remote management certificate between appliance and service this.Client.DeviceSettings.SyncRemotemanagementCertificate( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); //validation var securitySettings = this.Client.DeviceSettings.GetSecuritySettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); var remoteManagementCertificate = securitySettings.RemoteManagementSettings.RemoteManagementCertificate; Assert.True(!string.IsNullOrEmpty(remoteManagementCertificate), "Remote management certificate is not synced correctly."); } catch (Exception e) { Assert.Null(e); } } /// <summary> /// Create TimeSettings on the Device. /// </summary> private TimeSettings CreateAndValidateTimeSettings(string deviceName) { TimeSettings timeSettingsToCreate = new TimeSettings("Pacific Standard Time"); timeSettingsToCreate.PrimaryTimeServer = "time.windows.com"; timeSettingsToCreate.SecondaryTimeServer = new List<string>() { "8.8.8.8" }; this.Client.DeviceSettings.CreateOrUpdateTimeSettings( deviceName.GetDoubleEncoded(), timeSettingsToCreate, this.ResourceGroupName, this.ManagerName); var timeSettings = this.Client.DeviceSettings.GetTimeSettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); //validation Assert.True(timeSettings != null && timeSettings.PrimaryTimeServer.Equals("time.windows.com") && timeSettings.SecondaryTimeServer[0].Equals("8.8.8.8"), "Creation of Time Setting was not successful."); return timeSettings; } /// <summary> /// Create AlertSettings on the Device. /// </summary> private AlertSettings CreateAndValidateAlertSettings(string deviceName) { AlertSettings alertsettingsToCreate = new AlertSettings(AlertEmailNotificationStatus.Enabled); alertsettingsToCreate.AlertNotificationCulture = "en-US"; alertsettingsToCreate.NotificationToServiceOwners = AlertEmailNotificationStatus.Enabled; alertsettingsToCreate.AdditionalRecipientEmailList = new List<string>(); this.Client.DeviceSettings.CreateOrUpdateAlertSettings( deviceName.GetDoubleEncoded(), alertsettingsToCreate, this.ResourceGroupName, this.ManagerName); var alertSettings = this.Client.DeviceSettings.GetAlertSettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); //validation Assert.True(alertSettings != null && alertSettings.AlertNotificationCulture.Equals("en-US") && alertSettings.EmailNotification.Equals(AlertEmailNotificationStatus.Enabled) && alertSettings.NotificationToServiceOwners.Equals(AlertEmailNotificationStatus.Enabled), "Creation of Alert Setting was not successful."); return alertSettings; } /// <summary> /// Create NetworkSettings on the Device. /// </summary> private NetworkSettings CreateAndValidateNetworkSettings(string deviceName) { var networkSettingsBeforeUpdate = this.Client.DeviceSettings.GetNetworkSettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName ); DNSSettings dnsSettings = new DNSSettings(); dnsSettings.PrimaryDnsServer = networkSettingsBeforeUpdate.DnsSettings.PrimaryDnsServer; dnsSettings.SecondaryDnsServers = new List<string>() { "8.8.8.8" }; NetworkSettingsPatch networkSettingsPatch = new NetworkSettingsPatch(); networkSettingsPatch.DnsSettings = dnsSettings; return this.Client.DeviceSettings.UpdateNetworkSettings( deviceName.GetDoubleEncoded(), networkSettingsPatch, this.ResourceGroupName, this.ManagerName); } /// <summary> /// Create SecuritySettings on the Device. /// </summary> private SecuritySettings CreateAndValidateSecuritySettings(string deviceName) { RemoteManagementSettingsPatch remoteManagementSettings = new RemoteManagementSettingsPatch( RemoteManagementModeConfiguration.HttpsAndHttpEnabled); AsymmetricEncryptedSecret deviceAdminpassword = this.Client.Managers.GetAsymmetricEncryptedSecret( this.ResourceGroupName, this.ManagerName, "test-adminp13"); AsymmetricEncryptedSecret snapshotmanagerPassword = this.Client.Managers.GetAsymmetricEncryptedSecret( this.ResourceGroupName, this.ManagerName, "test-ssmpas1235"); ChapSettings chapSettings = new ChapSettings( "test-initiator-user", this.Client.Managers.GetAsymmetricEncryptedSecret(this.ResourceGroupName, this.ManagerName, "chapsetInitP124"), "test-target-user", this.Client.Managers.GetAsymmetricEncryptedSecret(this.ResourceGroupName, this.ManagerName, "chapsetTargP1235")); SecuritySettingsPatch securitySettingsPatch = new SecuritySettingsPatch( remoteManagementSettings, deviceAdminpassword, snapshotmanagerPassword, chapSettings); this.Client.DeviceSettings.UpdateSecuritySettings( deviceName.GetDoubleEncoded(), securitySettingsPatch, this.ResourceGroupName, this.ManagerName); var securitySettings = this.Client.DeviceSettings.GetSecuritySettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); //validation Assert.True(securitySettings != null && securitySettings.RemoteManagementSettings.RemoteManagementMode.Equals(RemoteManagementModeConfiguration.HttpsAndHttpEnabled) && securitySettings.ChapSettings.InitiatorUser.Equals("test-initiator-user") && securitySettings.ChapSettings.TargetUser.Equals("test-target-user"), "Creation of Security Setting was not successful."); return securitySettings; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class divremTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunDivRem_TwoLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } } [Fact] public static void RunDivRem_TwoSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } } [Fact] public static void RunDivRem_OneSmallOneLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - One Large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void RunDivRem_OneLargeOne0BI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - One Large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void RunDivRem_OneSmallOne0BI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } } [Fact] public static void Boundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivRemString(Math.Pow(2, 32) + " 2 bDivRem"); // 32 bit boundary n1=0 n2=1 VerifyDivRemString(Math.Pow(2, 33) + " 2 bDivRem"); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void RunDivRemTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // DivRem Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } // DivRem Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } // DivRem Method - One Large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); } // DivRem Method - One Large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } // DivRem Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivRemString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivRem"); Assert.Throws<DivideByZeroException>(() => { VerifyDivRemString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivRem"); }); } // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivRemString(Math.Pow(2, 32) + " 2 bDivRem"); // 32 bit boundary n1=0 n2=1 VerifyDivRemString(Math.Pow(2, 33) + " 2 bDivRem"); } private static void VerifyDivRemString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); sc.VerifyOutParameter(); } } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
using System; using System.Collections.Generic; namespace LibGit2Sharp { /// <summary> /// A Repository is the primary interface into a git repository /// </summary> public interface IRepository : IDisposable { /// <summary> /// Shortcut to return the branch pointed to by HEAD /// </summary> Branch Head { get; } /// <summary> /// Provides access to the configuration settings for this repository. /// </summary> Configuration Config { get; } /// <summary> /// Gets the index. /// </summary> Index Index { get; } /// <summary> /// Lookup and enumerate references in the repository. /// </summary> ReferenceCollection Refs { get; } /// <summary> /// Lookup and enumerate commits in the repository. /// Iterating this collection directly starts walking from the HEAD. /// </summary> IQueryableCommitLog Commits { get; } /// <summary> /// Lookup and enumerate branches in the repository. /// </summary> BranchCollection Branches { get; } /// <summary> /// Lookup and enumerate tags in the repository. /// </summary> TagCollection Tags { get; } /// <summary> /// Provides high level information about this repository. /// </summary> RepositoryInformation Info { get; } /// <summary> /// Provides access to diffing functionalities to show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk. /// </summary> Diff Diff {get;} /// <summary> /// Gets the database. /// </summary> ObjectDatabase ObjectDatabase { get; } /// <summary> /// Lookup notes in the repository. /// </summary> NoteCollection Notes { get; } /// <summary> /// Submodules in the repository. /// </summary> SubmoduleCollection Submodules { get; } /// <summary> /// Checkout the commit pointed at by the tip of the specified <see cref="Branch"/>. /// <para> /// If this commit is the current tip of the branch as it exists in the repository, the HEAD /// will point to this branch. Otherwise, the HEAD will be detached, pointing at the commit sha. /// </para> /// </summary> /// <param name="branch">The <see cref="Branch"/> to check out.</param> /// <param name="options"><see cref="CheckoutOptions"/> controlling checkout behavior.</param> /// <returns>The <see cref="Branch"/> that was checked out.</returns> Branch Checkout(Branch branch, CheckoutOptions options); /// <summary> /// Checkout the specified branch, reference or SHA. /// <para> /// If the committishOrBranchSpec parameter resolves to a branch name, then the checked out HEAD will /// will point to the branch. Otherwise, the HEAD will be detached, pointing at the commit sha. /// </para> /// </summary> /// <param name="committishOrBranchSpec">A revparse spec for the commit or branch to checkout.</param> /// <param name="options"><see cref="CheckoutOptions"/> controlling checkout behavior.</param> /// <returns>The <see cref="Branch"/> that was checked out.</returns> Branch Checkout(string committishOrBranchSpec, CheckoutOptions options); /// <summary> /// Checkout the specified <see cref="LibGit2Sharp.Commit"/>. /// <para> /// Will detach the HEAD and make it point to this commit sha. /// </para> /// </summary> /// <param name="commit">The <see cref="LibGit2Sharp.Commit"/> to check out.</param> /// <param name="options"><see cref="CheckoutOptions"/> controlling checkout behavior.</param> /// <returns>The <see cref="Branch"/> that was checked out.</returns> Branch Checkout(Commit commit, CheckoutOptions options); /// <summary> /// Updates specifed paths in the index and working directory with the versions from the specified branch, reference, or SHA. /// <para> /// This method does not switch branches or update the current repository HEAD. /// </para> /// </summary> /// <param name = "committishOrBranchSpec">A revparse spec for the commit or branch to checkout paths from.</param> /// <param name="paths">The paths to checkout.</param> /// <param name="checkoutOptions">Collection of parameters controlling checkout behavior.</param> void CheckoutPaths(string committishOrBranchSpec, IEnumerable<string> paths, CheckoutOptions checkoutOptions); /// <summary> /// Try to lookup an object by its <see cref="ObjectId"/>. If no matching object is found, null will be returned. /// </summary> /// <param name="id">The id to lookup.</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(ObjectId id); /// <summary> /// Try to lookup an object by its sha or a reference canonical name. If no matching object is found, null will be returned. /// </summary> /// <param name="objectish">A revparse spec for the object to lookup.</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(string objectish); /// <summary> /// Try to lookup an object by its <see cref="ObjectId"/> and <see cref="ObjectType"/>. If no matching object is found, null will be returned. /// </summary> /// <param name="id">The id to lookup.</param> /// <param name="type">The kind of GitObject being looked up</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(ObjectId id, ObjectType type); /// <summary> /// Try to lookup an object by its sha or a reference canonical name and <see cref="ObjectType"/>. If no matching object is found, null will be returned. /// </summary> /// <param name="objectish">A revparse spec for the object to lookup.</param> /// <param name="type">The kind of <see cref="GitObject"/> being looked up</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(string objectish, ObjectType type); /// <summary> /// Stores the content of the <see cref="Repository.Index"/> as a new <see cref="LibGit2Sharp.Commit"/> into the repository. /// The tip of the <see cref="Repository.Head"/> will be used as the parent of this new Commit. /// Once the commit is created, the <see cref="Repository.Head"/> will move forward to point at it. /// </summary> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="options">The <see cref="CommitOptions"/> that specify the commit behavior.</param> /// <returns>The generated <see cref="LibGit2Sharp.Commit"/>.</returns> Commit Commit(string message, Signature author, Signature committer, CommitOptions options); /// <summary> /// Sets the current <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and /// the content of the working tree to match. /// </summary> /// <param name="resetMode">Flavor of reset operation to perform.</param> /// <param name="commit">The target commit object.</param> void Reset(ResetMode resetMode, Commit commit); /// <summary> /// Replaces entries in the <see cref="Repository.Index"/> with entries from the specified commit. /// </summary> /// <param name="commit">The target commit object.</param> /// <param name="paths">The list of paths (either files or directories) that should be considered.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> [Obsolete("This method will be removed in the next release. Please use Index.Replace() instead.")] void Reset(Commit commit, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions); /// <summary> /// Clean the working tree by removing files that are not under version control. /// </summary> void RemoveUntrackedFiles(); /// <summary> /// Revert the specified commit. /// </summary> /// <param name="commit">The <see cref="Commit"/> to revert.</param> /// <param name="reverter">The <see cref="Signature"/> of who is performing the reverte.</param> /// <param name="options"><see cref="RevertOptions"/> controlling revert behavior.</param> /// <returns>The result of the revert.</returns> RevertResult Revert(Commit commit, Signature reverter, RevertOptions options); /// <summary> /// Merge changes from commit into the branch pointed at by HEAD.. /// </summary> /// <param name="commit">The commit to merge into the branch pointed at by HEAD.</param> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult Merge(Commit commit, Signature merger, MergeOptions options); /// <summary> /// Merges changes from branch into the branch pointed at by HEAD.. /// </summary> /// <param name="branch">The branch to merge into the branch pointed at by HEAD.</param> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult Merge(Branch branch, Signature merger, MergeOptions options); /// <summary> /// Merges changes from the commit into the branch pointed at by HEAD. /// </summary> /// <param name="committish">The commit to merge into branch pointed at by HEAD.</param> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult Merge(string committish, Signature merger, MergeOptions options); /// <summary> /// Merge the reference that was recently fetched. This will merge /// the branch on the fetched remote that corresponded to the /// current local branch when we did the fetch. This is the /// second step in performing a pull operation (after having /// performed said fetch). /// </summary> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult MergeFetchedRefs(Signature merger, MergeOptions options); /// <summary> /// Cherry picks changes from the commit into the branch pointed at by HEAD. /// </summary> /// <param name="commit">The commit to cherry pick into branch pointed at by HEAD.</param> /// <param name="committer">The <see cref="Signature"/> of who is performing the cherry pick.</param> /// <param name="options">Specifies optional parameters controlling cherry pick behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> CherryPickResult CherryPick(Commit commit, Signature committer, CherryPickOptions options); /// <summary> /// Manipulate the currently ignored files. /// </summary> Ignore Ignore { get; } /// <summary> /// Provides access to network functionality for a repository. /// </summary> Network Network { get; } ///<summary> /// Lookup and enumerate stashes in the repository. ///</summary> StashCollection Stashes { get; } /// <summary> /// Find where each line of a file originated. /// </summary> /// <param name="path">Path of the file to blame.</param> /// <param name="options">Specifies optional parameters; if null, the defaults are used.</param> /// <returns>The blame for the file.</returns> BlameHunkCollection Blame(string path, BlameOptions options); /// <summary> /// Promotes to the staging area the latest modifications of a file in the working directory (addition, updation or removal). /// /// If this path is ignored by configuration then it will not be staged unless <see cref="StageOptions.IncludeIgnored"/> is unset. /// </summary> /// <param name="path">The path of the file within the working directory.</param> /// <param name="stageOptions">Determines how paths will be staged.</param> void Stage(string path, StageOptions stageOptions); /// <summary> /// Promotes to the staging area the latest modifications of a collection of files in the working directory (addition, updation or removal). /// /// Any paths (even those listed explicitly) that are ignored by configuration will not be staged unless <see cref="StageOptions.IncludeIgnored"/> is unset. /// </summary> /// <param name="paths">The collection of paths of the files within the working directory.</param> /// <param name="stageOptions">Determines how paths will be staged.</param> void Stage(IEnumerable<string> paths, StageOptions stageOptions); /// <summary> /// Removes from the staging area all the modifications of a file since the latest commit (addition, updation or removal). /// </summary> /// <param name="path">The path of the file within the working directory.</param> /// <param name="explicitPathsOptions"> /// The passed <paramref name="path"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> void Unstage(string path, ExplicitPathsOptions explicitPathsOptions); /// <summary> /// Removes from the staging area all the modifications of a collection of file since the latest commit (addition, updation or removal). /// </summary> /// <param name="paths">The collection of paths of the files within the working directory.</param> /// <param name="explicitPathsOptions"> /// The passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> void Unstage(IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions); /// <summary> /// Moves and/or renames a file in the working directory and promotes the change to the staging area. /// </summary> /// <param name="sourcePath">The path of the file within the working directory which has to be moved/renamed.</param> /// <param name="destinationPath">The target path of the file within the working directory.</param> void Move(string sourcePath, string destinationPath); /// <summary> /// Moves and/or renames a collection of files in the working directory and promotes the changes to the staging area. /// </summary> /// <param name="sourcePaths">The paths of the files within the working directory which have to be moved/renamed.</param> /// <param name="destinationPaths">The target paths of the files within the working directory.</param> void Move(IEnumerable<string> sourcePaths, IEnumerable<string> destinationPaths); /// <summary> /// Removes a file from the staging area, and optionally removes it from the working directory as well. /// <para> /// If the file has already been deleted from the working directory, this method will only deal /// with promoting the removal to the staging area. /// </para> /// <para> /// The default behavior is to remove the file from the working directory as well. /// </para> /// <para> /// When not passing a <paramref name="explicitPathsOptions"/>, the passed path will be treated as /// a pathspec. You can for example use it to pass the relative path to a folder inside the working directory, /// so that all files beneath this folders, and the folder itself, will be removed. /// </para> /// </summary> /// <param name="path">The path of the file within the working directory.</param> /// <param name="removeFromWorkingDirectory">True to remove the file from the working directory, False otherwise.</param> /// <param name="explicitPathsOptions"> /// The passed <paramref name="path"/> will be treated as an explicit path. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> void Remove(string path, bool removeFromWorkingDirectory, ExplicitPathsOptions explicitPathsOptions); /// <summary> /// Removes a collection of fileS from the staging, and optionally removes them from the working directory as well. /// <para> /// If a file has already been deleted from the working directory, this method will only deal /// with promoting the removal to the staging area. /// </para> /// <para> /// The default behavior is to remove the files from the working directory as well. /// </para> /// <para> /// When not passing a <paramref name="explicitPathsOptions"/>, the passed paths will be treated as /// a pathspec. You can for example use it to pass the relative paths to folders inside the working directory, /// so that all files beneath these folders, and the folders themselves, will be removed. /// </para> /// </summary> /// <param name="paths">The collection of paths of the files within the working directory.</param> /// <param name="removeFromWorkingDirectory">True to remove the files from the working directory, False otherwise.</param> /// <param name="explicitPathsOptions"> /// The passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> void Remove(IEnumerable<string> paths, bool removeFromWorkingDirectory, ExplicitPathsOptions explicitPathsOptions); /// <summary> /// Retrieves the state of a file in the working directory, comparing it against the staging area and the latest commmit. /// </summary> /// <param name="filePath">The relative path within the working directory to the file.</param> /// <returns>A <see cref="FileStatus"/> representing the state of the <paramref name="filePath"/> parameter.</returns> FileStatus RetrieveStatus(string filePath); /// <summary> /// Retrieves the state of all files in the working directory, comparing them against the staging area and the latest commmit. /// </summary> /// <param name="options">If set, the options that control the status investigation.</param> /// <returns>A <see cref="RepositoryStatus"/> holding the state of all the files.</returns> RepositoryStatus RetrieveStatus(StatusOptions options); /// <summary> /// Finds the most recent annotated tag that is reachable from a commit. /// <para> /// If the tag points to the commit, then only the tag is shown. Otherwise, /// it suffixes the tag name with the number of additional commits on top /// of the tagged object and the abbreviated object name of the most recent commit. /// </para> /// <para> /// Optionally, the <paramref name="options"/> parameter allow to tweak the /// search strategy (considering lightweith tags, or even branches as reference points) /// and the formatting of the returned identifier. /// </para> /// </summary> /// <param name="commit">The commit to be described.</param> /// <param name="options">Determines how the commit will be described.</param> /// <returns>A descriptive identifier for the commit based on the nearest annotated tag.</returns> string Describe(Commit commit, DescribeOptions options); } }
/* Copyright 2015 System Era Softworks 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. * The Strange IOC Framework is hosted at https://github.com/strangeioc/strangeioc. * Code contained here may contain modified code which is subject to the license * at this link. */ using UnityEngine; using strange.extensions.injector.api; using strange.extensions.injector.impl; using strange.extensions.context.api; using strange.extensions.nestedcontext.api; using strange.extensions.context.impl; using strange.framework.api; using strange.framework.impl; using strange.extensions.mediation.api; using strange.extensions.dispatcher.eventdispatcher.api; using strange.extensions.dispatcher.api; using strange.extensions.dispatcher.eventdispatcher.impl; namespace strange.extensions.nestedcontext.impl { public class NestedContext : Context, INestedContext { private IBinder _crossContextBridge; /// A Binder that handles dependency injection binding and instantiation public ICrossContextInjectionBinder injectionBinder { get; set; } /// A specific instance of EventDispatcher that communicates /// across multiple contexts. An event sent across this /// dispatcher will be re-dispatched by the various context-wide /// dispatchers. So a dispatch to other contexts is simply /// /// `crossContextDispatcher.Dispatch(MY_EVENT, payload)`; /// /// Other contexts don't need to listen to the cross-context dispatcher /// as such, just map the necessary event to your local context /// dispatcher and you'll receive it. protected IEventDispatcher _crossContextDispatcher; // The parent context in the nested hierarchy public IContext parentContext { get; set; } public NestedContext() : this(null) { } public NestedContext(MonoBehaviour view, bool autoMapping) : this(view, (autoMapping) ? ContextStartupFlags.MANUAL_MAPPING : ContextStartupFlags.MANUAL_LAUNCH | ContextStartupFlags.MANUAL_MAPPING) { } public NestedContext(object view) : this(view, ContextStartupFlags.AUTOMATIC) { } public NestedContext(object view, ContextStartupFlags flags) { if (view is strange.extensions.nestedcontext.api.INestedCapableView) parentContext = (view as strange.extensions.nestedcontext.api.INestedCapableView).overrideContext; if (view is INestedContextView) (view as INestedContextView).context = this; SetContextView(view); if (parentContext == null) SetParentContext(); //If firstContext was unloaded, the contextView will be null. Assign the new context as firstContext. if (firstContext == null || firstContext.GetContextView() == null) { firstContext = this; } else { parentContext.AddContext(this); } addCoreComponents(); this.autoStartup = (flags & ContextStartupFlags.MANUAL_LAUNCH) != ContextStartupFlags.MANUAL_LAUNCH; if ((flags & ContextStartupFlags.MANUAL_MAPPING) != ContextStartupFlags.MANUAL_MAPPING) { Start(); } } virtual public void SetParentContext() { parentContext = firstContext; } protected override void addCoreComponents() { base.addCoreComponents(); injectionBinder = new NestedContextInjectionBinder(); if (parentContext != null && parentContext is NestedContext) { var newInjectionBinder = new NestedContextInjectionBinder(); newInjectionBinder.CrossContextBinder = (parentContext as NestedContext).injectionBinder.CrossContextBinder; injectionBinder.CrossContextBinder = newInjectionBinder; } else { injectionBinder.CrossContextBinder = new NestedContextInjectionBinder(); } if (firstContext == this) { injectionBinder.Bind<IEventDispatcher>().To<EventDispatcher>().ToSingleton().ToName(ContextKeys.CROSS_CONTEXT_DISPATCHER).CrossContext(); injectionBinder.Bind<CrossContextBridge>().ToSingleton().CrossContext(); } injectionBinder.Bind<INestedContext>().ToValue(this).CrossContext(); } protected override void instantiateCoreComponents() { base.instantiateCoreComponents(); IInjectionBinding dispatcherBinding = injectionBinder.GetBinding<IEventDispatcher>(ContextKeys.CONTEXT_DISPATCHER); if (dispatcherBinding != null) { IEventDispatcher dispatcher = injectionBinder.GetInstance<IEventDispatcher>(ContextKeys.CONTEXT_DISPATCHER) as IEventDispatcher; if (dispatcher != null) { crossContextDispatcher = injectionBinder.GetInstance<IEventDispatcher>(ContextKeys.CROSS_CONTEXT_DISPATCHER) as IEventDispatcher; (crossContextDispatcher as ITriggerProvider).AddTriggerable(dispatcher as ITriggerable); (dispatcher as ITriggerProvider).AddTriggerable(crossContextBridge as ITriggerable); } } } override public IContext AddContext(IContext context) { base.AddContext(context); if (context is ICrossContextCapable) { AssignCrossContext((ICrossContextCapable)context); } return this; } virtual public void AssignCrossContext(ICrossContextCapable childContext) { childContext.crossContextDispatcher = crossContextDispatcher; } virtual public void RemoveCrossContext(ICrossContextCapable childContext) { if (childContext.crossContextDispatcher != null) { ((childContext.crossContextDispatcher) as ITriggerProvider).RemoveTriggerable(childContext.GetComponent<IEventDispatcher>(ContextKeys.CONTEXT_DISPATCHER) as ITriggerable); childContext.crossContextDispatcher = null; } } override public IContext RemoveContext(IContext context) { if (context is ICrossContextCapable) { RemoveCrossContext((ICrossContextCapable)context); } return base.RemoveContext(context); } virtual public IDispatcher crossContextDispatcher { get { return _crossContextDispatcher; } set { _crossContextDispatcher = value as IEventDispatcher; } } virtual public IBinder crossContextBridge { get { if (_crossContextBridge == null) { _crossContextBridge = injectionBinder.GetInstance<CrossContextBridge>() as IBinder; } return _crossContextBridge; } set { _crossContextDispatcher = value as IEventDispatcher; } } } }
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 Waste_Bin_Collections.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; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text.RegularExpressions; using System.Threading; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Transactions; /// <summary> /// Managed environment. Acts as a gateway for native code. /// </summary> internal static class ExceptionUtils { /** NoClassDefFoundError fully-qualified class name which is important during startup phase. */ private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError"; /** NoSuchMethodError fully-qualified class name which is important during startup phase. */ private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError"; /** InteropCachePartialUpdateException. */ private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException"; /** Map with predefined exceptions. */ private static readonly IDictionary<string, ExceptionFactoryDelegate> Exs = new Dictionary<string, ExceptionFactoryDelegate>(); /** Exception factory delegate. */ private delegate Exception ExceptionFactoryDelegate(IIgnite ignite, string msg, Exception innerEx); /** Inner class regex. */ private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled); /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability")] static ExceptionUtils() { // Common Java exceptions mapped to common .Net exceptions. Exs["java.lang.IllegalArgumentException"] = (i, m, e) => new ArgumentException(m, e); Exs["java.lang.IllegalStateException"] = (i, m, e) => new InvalidOperationException(m, e); Exs["java.lang.UnsupportedOperationException"] = (i, m, e) => new NotImplementedException(m, e); Exs["java.lang.InterruptedException"] = (i, m, e) => new ThreadInterruptedException(m, e); // Generic Ignite exceptions. Exs["org.apache.ignite.IgniteException"] = (i, m, e) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteCheckedException"] = (i, m, e) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (i, m, e) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (i, m, e) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); // Cluster exceptions. Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (i, m, e) => new ClusterGroupEmptyException(m, e); Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (i, m, e) => new ClusterTopologyException(m, e); // Compute exceptions. Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (i, m, e) => new ComputeExecutionRejectedException(m, e); Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (i, m, e) => new ComputeJobFailoverException(m, e); Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (i, m, e) => new ComputeTaskCancelledException(m, e); Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (i, m, e) => new ComputeTaskTimeoutException(m, e); Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (i, m, e) => new ComputeUserUndeclaredException(m, e); // Cache exceptions. Exs["javax.cache.CacheException"] = (i, m, e) => new CacheException(m, e); Exs["javax.cache.integration.CacheLoaderException"] = (i, m, e) => new CacheStoreException(m, e); Exs["javax.cache.integration.CacheWriterException"] = (i, m, e) => new CacheStoreException(m, e); Exs["javax.cache.processor.EntryProcessorException"] = (i, m, e) => new CacheEntryProcessorException(m, e); Exs["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = (i, m, e) => new CacheAtomicUpdateTimeoutException(m, e); // Transaction exceptions. Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (i, m, e) => new TransactionOptimisticException(m, e); Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (i, m, e) => new TransactionTimeoutException(m, e); Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (i, m, e) => new TransactionRollbackException(m, e); Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (i, m, e) => new TransactionHeuristicException(m, e); // Security exceptions. Exs["org.apache.ignite.IgniteAuthenticationException"] = (i, m, e) => new SecurityException(m, e); Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (i, m, e) => new SecurityException(m, e); // Future exceptions Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (i, m, e) => new IgniteFutureCancelledException(m, e); Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (i, m, e) => new IgniteFutureCancelledException(m, e); } /// <summary> /// Creates exception according to native code class and message. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="clsName">Exception class name.</param> /// <param name="msg">Exception message.</param> /// <param name="reader">Error data reader.</param> /// <returns>Exception.</returns> public static Exception GetException(IIgnite ignite, string clsName, string msg, BinaryReader reader = null) { ExceptionFactoryDelegate ctor; if (Exs.TryGetValue(clsName, out ctor)) { var match = InnerClassRegex.Match(msg ?? string.Empty); ExceptionFactoryDelegate innerCtor; if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor)) return ctor(ignite, msg, innerCtor(ignite, match.Groups[2].Value, null)); return ctor(ignite, msg, null); } if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " + "variable?): " + msg); if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " + "variable?): " + msg); if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return ProcessCachePartialUpdateException(ignite, msg, reader); return new IgniteException("Java exception occurred [class=" + clsName + ", message=" + msg + ']'); } /// <summary> /// Process cache partial update exception. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="msg">Message.</param> /// <param name="reader">Reader.</param> /// <returns>CachePartialUpdateException.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static Exception ProcessCachePartialUpdateException(IIgnite ignite, string msg, BinaryReader reader) { if (reader == null) return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available.")); bool dataExists = reader.ReadBoolean(); Debug.Assert(dataExists); if (reader.ReadBoolean()) { bool keepBinary = reader.ReadBoolean(); BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary); try { return new CachePartialUpdateException(msg, ReadNullableList(keysReader)); } catch (Exception e) { // Failed to deserialize data. return new CachePartialUpdateException(msg, e); } } // Was not able to write keys. string innerErrCls = reader.ReadString(); string innerErrMsg = reader.ReadString(); Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg); return new CachePartialUpdateException(msg, innerErr); } /// <summary> /// Create JVM initialization exception. /// </summary> /// <param name="clsName">Class name.</param> /// <param name="msg">Message.</param> /// <returns>Exception.</returns> public static Exception GetJvmInitializeException(string clsName, string msg) { if (clsName != null) return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg)); if (msg != null) return new IgniteException("Failed to initialize JVM: " + msg); return new IgniteException("Failed to initialize JVM."); } /// <summary> /// Reads nullable list. /// </summary> /// <param name="reader">Reader.</param> /// <returns>List.</returns> private static List<object> ReadNullableList(BinaryReader reader) { if (!reader.ReadBoolean()) return null; var size = reader.ReadInt(); var list = new List<object>(size); for (int i = 0; i < size; i++) list.Add(reader.ReadObject<object>()); return list; } } }
namespace Application.WebServices.Areas.HelpPage.SampleGeneration { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return this.GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return this.SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType( Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { var genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } var genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { var collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } var closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { var dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } var closedDictionaryType = typeof(IDictionary<,>).MakeGenericType( genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { var genericArgs = type.GetGenericArguments(); var parameterValues = new object[genericArgs.Length]; var failedToCreateTuple = true; var objectGenerator = new ObjectGenerator(); for (var i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } var result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair( Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { var genericArgs = keyValuePairType.GetGenericArguments(); var typeK = genericArgs[0]; var typeV = genericArgs[1]; var objectGenerator = new ObjectGenerator(); var keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); var valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } var result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { var type = arrayType.GetElementType(); var result = Array.CreateInstance(type, size); var areAllElementsNull = true; var objectGenerator = new ObjectGenerator(); for (var i = 0; i < size; i++) { var element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary( Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { var typeK = typeof(object); var typeV = typeof(object); if (dictionaryType.IsGenericType) { var genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } var result = Activator.CreateInstance(dictionaryType); var addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); var containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); var objectGenerator = new ObjectGenerator(); for (var i = 0; i < size; i++) { var newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } var containsKey = (bool)containsMethod.Invoke(result, new[] { newKey }); if (!containsKey) { var newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { var possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable( Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { var isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { var listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { var argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); var asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return ((IEnumerable)list).AsQueryable(); } private static object GenerateCollection( Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { var type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); var result = Activator.CreateInstance(collectionType); var addMethod = collectionType.GetMethod("Add"); var areAllElementsNull = true; var objectGenerator = new ObjectGenerator(); for (var i = 0; i < size; i++) { var element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { var type = nullableType.GetGenericArguments()[0]; var objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { var defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var objectGenerator = new ObjectGenerator(); foreach (var property in properties) { if (property.CanWrite) { var propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); var objectGenerator = new ObjectGenerator(); foreach (var field in fields) { var fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); private long _index; [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => index + 0.1 }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % short.MaxValue) }, { typeof(Int32), index => (Int32)(index % int.MaxValue) }, { typeof(Int64), index => index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return string.Format( CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % ushort.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % uint.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri( string.Format( CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++this._index); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedVpnGatewaysClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListVpnGatewaysRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) AggregatedListVpnGatewaysRequest request = new AggregatedListVpnGatewaysRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<VpnGatewayAggregatedList, KeyValuePair<string, VpnGatewaysScopedList>> response = vpnGatewaysClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, VpnGatewaysScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (VpnGatewayAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, VpnGatewaysScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListVpnGatewaysRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) AggregatedListVpnGatewaysRequest request = new AggregatedListVpnGatewaysRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<VpnGatewayAggregatedList, KeyValuePair<string, VpnGatewaysScopedList>> response = vpnGatewaysClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, VpnGatewaysScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((VpnGatewayAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, VpnGatewaysScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<VpnGatewayAggregatedList, KeyValuePair<string, VpnGatewaysScopedList>> response = vpnGatewaysClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, VpnGatewaysScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (VpnGatewayAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, VpnGatewaysScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<VpnGatewayAggregatedList, KeyValuePair<string, VpnGatewaysScopedList>> response = vpnGatewaysClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, VpnGatewaysScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((VpnGatewayAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, VpnGatewaysScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, VpnGatewaysScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteVpnGatewayRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) DeleteVpnGatewayRequest request = new DeleteVpnGatewayRequest { RequestId = "", Region = "", Project = "", VpnGateway = "", }; // Make the request lro::Operation<Operation, Operation> response = vpnGatewaysClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = vpnGatewaysClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteVpnGatewayRequest, CallSettings) // Additional: DeleteAsync(DeleteVpnGatewayRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) DeleteVpnGatewayRequest request = new DeleteVpnGatewayRequest { RequestId = "", Region = "", Project = "", VpnGateway = "", }; // Make the request lro::Operation<Operation, Operation> response = await vpnGatewaysClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await vpnGatewaysClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string vpnGateway = ""; // Make the request lro::Operation<Operation, Operation> response = vpnGatewaysClient.Delete(project, region, vpnGateway); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = vpnGatewaysClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string vpnGateway = ""; // Make the request lro::Operation<Operation, Operation> response = await vpnGatewaysClient.DeleteAsync(project, region, vpnGateway); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await vpnGatewaysClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetVpnGatewayRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) GetVpnGatewayRequest request = new GetVpnGatewayRequest { Region = "", Project = "", VpnGateway = "", }; // Make the request VpnGateway response = vpnGatewaysClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetVpnGatewayRequest, CallSettings) // Additional: GetAsync(GetVpnGatewayRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) GetVpnGatewayRequest request = new GetVpnGatewayRequest { Region = "", Project = "", VpnGateway = "", }; // Make the request VpnGateway response = await vpnGatewaysClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string vpnGateway = ""; // Make the request VpnGateway response = vpnGatewaysClient.Get(project, region, vpnGateway); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string vpnGateway = ""; // Make the request VpnGateway response = await vpnGatewaysClient.GetAsync(project, region, vpnGateway); // End snippet } /// <summary>Snippet for GetStatus</summary> public void GetStatusRequestObject() { // Snippet: GetStatus(GetStatusVpnGatewayRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) GetStatusVpnGatewayRequest request = new GetStatusVpnGatewayRequest { Region = "", Project = "", VpnGateway = "", }; // Make the request VpnGatewaysGetStatusResponse response = vpnGatewaysClient.GetStatus(request); // End snippet } /// <summary>Snippet for GetStatusAsync</summary> public async Task GetStatusRequestObjectAsync() { // Snippet: GetStatusAsync(GetStatusVpnGatewayRequest, CallSettings) // Additional: GetStatusAsync(GetStatusVpnGatewayRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) GetStatusVpnGatewayRequest request = new GetStatusVpnGatewayRequest { Region = "", Project = "", VpnGateway = "", }; // Make the request VpnGatewaysGetStatusResponse response = await vpnGatewaysClient.GetStatusAsync(request); // End snippet } /// <summary>Snippet for GetStatus</summary> public void GetStatus() { // Snippet: GetStatus(string, string, string, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string vpnGateway = ""; // Make the request VpnGatewaysGetStatusResponse response = vpnGatewaysClient.GetStatus(project, region, vpnGateway); // End snippet } /// <summary>Snippet for GetStatusAsync</summary> public async Task GetStatusAsync() { // Snippet: GetStatusAsync(string, string, string, CallSettings) // Additional: GetStatusAsync(string, string, string, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string vpnGateway = ""; // Make the request VpnGatewaysGetStatusResponse response = await vpnGatewaysClient.GetStatusAsync(project, region, vpnGateway); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertVpnGatewayRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) InsertVpnGatewayRequest request = new InsertVpnGatewayRequest { RequestId = "", Region = "", VpnGatewayResource = new VpnGateway(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = vpnGatewaysClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = vpnGatewaysClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertVpnGatewayRequest, CallSettings) // Additional: InsertAsync(InsertVpnGatewayRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) InsertVpnGatewayRequest request = new InsertVpnGatewayRequest { RequestId = "", Region = "", VpnGatewayResource = new VpnGateway(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await vpnGatewaysClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await vpnGatewaysClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, VpnGateway, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; VpnGateway vpnGatewayResource = new VpnGateway(); // Make the request lro::Operation<Operation, Operation> response = vpnGatewaysClient.Insert(project, region, vpnGatewayResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = vpnGatewaysClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, VpnGateway, CallSettings) // Additional: InsertAsync(string, string, VpnGateway, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; VpnGateway vpnGatewayResource = new VpnGateway(); // Make the request lro::Operation<Operation, Operation> response = await vpnGatewaysClient.InsertAsync(project, region, vpnGatewayResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await vpnGatewaysClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListVpnGatewaysRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) ListVpnGatewaysRequest request = new ListVpnGatewaysRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<VpnGatewayList, VpnGateway> response = vpnGatewaysClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (VpnGateway item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (VpnGatewayList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (VpnGateway item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<VpnGateway> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (VpnGateway item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListVpnGatewaysRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) ListVpnGatewaysRequest request = new ListVpnGatewaysRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<VpnGatewayList, VpnGateway> response = vpnGatewaysClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((VpnGateway item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((VpnGatewayList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (VpnGateway item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<VpnGateway> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (VpnGateway item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<VpnGatewayList, VpnGateway> response = vpnGatewaysClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (VpnGateway item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (VpnGatewayList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (VpnGateway item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<VpnGateway> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (VpnGateway item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<VpnGatewayList, VpnGateway> response = vpnGatewaysClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((VpnGateway item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((VpnGatewayList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (VpnGateway item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<VpnGateway> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (VpnGateway item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for SetLabels</summary> public void SetLabelsRequestObject() { // Snippet: SetLabels(SetLabelsVpnGatewayRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) SetLabelsVpnGatewayRequest request = new SetLabelsVpnGatewayRequest { RequestId = "", Region = "", Resource = "", Project = "", RegionSetLabelsRequestResource = new RegionSetLabelsRequest(), }; // Make the request lro::Operation<Operation, Operation> response = vpnGatewaysClient.SetLabels(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = vpnGatewaysClient.PollOnceSetLabels(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetLabelsAsync</summary> public async Task SetLabelsRequestObjectAsync() { // Snippet: SetLabelsAsync(SetLabelsVpnGatewayRequest, CallSettings) // Additional: SetLabelsAsync(SetLabelsVpnGatewayRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) SetLabelsVpnGatewayRequest request = new SetLabelsVpnGatewayRequest { RequestId = "", Region = "", Resource = "", Project = "", RegionSetLabelsRequestResource = new RegionSetLabelsRequest(), }; // Make the request lro::Operation<Operation, Operation> response = await vpnGatewaysClient.SetLabelsAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await vpnGatewaysClient.PollOnceSetLabelsAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetLabels</summary> public void SetLabels() { // Snippet: SetLabels(string, string, string, RegionSetLabelsRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string resource = ""; RegionSetLabelsRequest regionSetLabelsRequestResource = new RegionSetLabelsRequest(); // Make the request lro::Operation<Operation, Operation> response = vpnGatewaysClient.SetLabels(project, region, resource, regionSetLabelsRequestResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = vpnGatewaysClient.PollOnceSetLabels(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetLabelsAsync</summary> public async Task SetLabelsAsync() { // Snippet: SetLabelsAsync(string, string, string, RegionSetLabelsRequest, CallSettings) // Additional: SetLabelsAsync(string, string, string, RegionSetLabelsRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string resource = ""; RegionSetLabelsRequest regionSetLabelsRequestResource = new RegionSetLabelsRequest(); // Make the request lro::Operation<Operation, Operation> response = await vpnGatewaysClient.SetLabelsAsync(project, region, resource, regionSetLabelsRequestResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await vpnGatewaysClient.PollOnceSetLabelsAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissionsRequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsVpnGatewayRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) TestIamPermissionsVpnGatewayRequest request = new TestIamPermissionsVpnGatewayRequest { Region = "", Resource = "", Project = "", TestPermissionsRequestResource = new TestPermissionsRequest(), }; // Make the request TestPermissionsResponse response = vpnGatewaysClient.TestIamPermissions(request); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsRequestObjectAsync() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsVpnGatewayRequest, CallSettings) // Additional: TestIamPermissionsAsync(TestIamPermissionsVpnGatewayRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsVpnGatewayRequest request = new TestIamPermissionsVpnGatewayRequest { Region = "", Resource = "", Project = "", TestPermissionsRequestResource = new TestPermissionsRequest(), }; // Make the request TestPermissionsResponse response = await vpnGatewaysClient.TestIamPermissionsAsync(request); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions() { // Snippet: TestIamPermissions(string, string, string, TestPermissionsRequest, CallSettings) // Create client VpnGatewaysClient vpnGatewaysClient = VpnGatewaysClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string resource = ""; TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest(); // Make the request TestPermissionsResponse response = vpnGatewaysClient.TestIamPermissions(project, region, resource, testPermissionsRequestResource); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CallSettings) // Additional: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CancellationToken) // Create client VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string resource = ""; TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest(); // Make the request TestPermissionsResponse response = await vpnGatewaysClient.TestIamPermissionsAsync(project, region, resource, testPermissionsRequestResource); // End snippet } } }
using NUnit.Framework; using Tautalos.Unity.Mobius.Broadcasters; using Tautalos.Unity.Mobius.Signals; using System; using Tautalos.Unity.Mobius.Channels; using System.Collections.Generic; namespace Tautalos.Unity.Mobius.Tests { [TestFixture()] internal class WatcherTest { Watcher watcher; [SetUp] public void Setup () { watcher = new Watcher (); } [TearDown] public void TearDown () { watcher = null; } [Test, Category("Given a Watcher"), Description("When asked if empty, Then it should answer negative")] public void ShouldBeEmpty () { Assert.IsFalse (watcher.IsEmpty); } [Test, Category("Given a Watcher"), Description("When instantiated with onSignal handler, Then it call the handler on OnNext observation")] public void ShouldCallTheProvidedOnSignalHandler () { var result = false; var watcher = new Watcher (onSignal: (ISignal signal) => { result = true; }); watcher.OnNext (EmptySignal.Instance); Assert.IsTrue (result); } [Test, Category("Given a Watcher"), Description("When instantiated with onError handler, Then it call the handler on OnError observation")] public void ShouldCallProvidedOnErrorHandler () { var exception = new Exception (); Exception result = null; var watcher = new Watcher (onError: (Exception error) => { result = error; }); watcher.OnError (exception); Assert.IsNotNull (result); Assert.AreSame (exception, result); } [Test, Category("Given a Watcher"), Description("When instantiated with onDone handler, Then it call the handler on OnCompleted observation")] public void ShouldCallProvidedOnDoneHandler () { var result = false; var watcher = new Watcher (onDone: () => { result = true; }); watcher.OnCompleted (); Assert.IsTrue (result); } [Test, Category("Given a Watcher"), Description("When told to ignore a EventTag, Then it should not call the OnSignal handler for that EventTag")] public void ShouldNotCallHandlerOnSignalWithIgnoredEventTag () { var result = "unchanged"; var watcher = new Watcher (onSignal: (ISignal signal) => { result = "called"; }); watcher.Ignore (EmptyEventTag.Instance); watcher.OnNext (EmptySignal.Instance); Assert.AreEqual ("unchanged", result); } [Test, Category("Given a Watcher"), Description("When told to ignore a EventTag and stop ignoring, Then it should call the OnSignal handler for that EventTag")] public void ShouldCallOnSignalHandlerIfIgnoreIsLongerIgnored () { var result = 0; var watcher = new Watcher (onSignal: (ISignal signal) => { result++; }); watcher.Ignore (EmptyEventTag.Instance); watcher.OnNext (EmptySignal.Instance); watcher.DontIgnore (EmptyEventTag.Instance); watcher.OnNext (EmptySignal.Instance); Assert.AreEqual (1, result); } [Test, Category("Given a Watcher"), Description("When if it is ignoring a EventTag, Then it should answer accuretely")] public void ShouldTellUsIfAnEventTagIsBeingIgnored () { Assert.IsTrue (watcher.IsIgnoring (null)); watcher.Ignore (EmptyEventTag.Instance); Assert.IsTrue (watcher.IsIgnoring (EmptyEventTag.Instance)); watcher.DontIgnore (EmptyEventTag.Instance); Assert.IsFalse (watcher.IsIgnoring (EmptyEventTag.Instance)); } [Test, Category("Given a Watcher"), Description("When observing a Broadcaster, Then it should process all signal from it")] public void ShouldProcessAllSignalsFromBroadcaster () { var eventTag_1 = new EventTag ("event-one"); var eventTag_2 = new EventTag ("event-two"); var eventTags = new EventTag[]{ eventTag_1, eventTag_2}; var channel = new Channel (); var broadcaster = new Broadcaster (channel, eventTags, "the-broadcaster"); var signaller = new Signaller (channel: channel, owner: this); var signal_1 = new Signal (signaller, eventTag_1, null); var signal_2 = new Signal (signaller, eventTag_2, null); var observedSignals = new List<ISignal> (); var watcher = new Watcher (onSignal: (ISignal signal) => { observedSignals.Add (signal); }); watcher.WatchAll (broadcaster); channel.Emit (signal_1); channel.Emit (signal_2); Assert.AreEqual (2, observedSignals.Count); Assert.Contains (signal_1, observedSignals); Assert.Contains (signal_2, observedSignals); } [Test, Category("Given a Watcher"), Description("When observing some EventTags from a Broadcaster, Then it should process only those broadcasts")] public void ShouldProcessOnlyGivenEventTags () { var eventTag_1 = new EventTag ("event-one"); var eventTag_2 = new EventTag ("event-two"); var eventTag_3 = new EventTag ("event-three"); var eventTags = new EventTag[]{ eventTag_1, eventTag_2, eventTag_3}; var channel = new Channel (); var broadcaster = new Broadcaster (channel, eventTags, "the-broadcaster"); var signaller = new Signaller (channel: channel, owner: this); var signal_1 = new Signal (signaller, eventTag_1, null); var signal_2 = new Signal (signaller, eventTag_2, null); var signal_3 = new Signal (signaller, eventTag_3, null); var observedSignals = new List<String> (); var watcher = new Watcher (onSignal: (ISignal signal) => { observedSignals.Add (signal.EventTag.Name); }); watcher.Watch (broadcaster, new IEventTag[]{ eventTag_1, eventTag_3 }); channel.Emit (signal_1); // yes channel.Emit (signal_2); // no channel.Emit (signal_1); // yes channel.Emit (signal_3); // yes channel.Emit (signal_2); // no Assert.AreEqual (3, observedSignals.Count); Assert.Contains (signal_1.EventTag.Name, observedSignals); } [Test, Category("Given a Watcher"), Description("When asking if it observing and EventTag, Then it should answer accurately")] public void ShouldInformUsIfItOrNotWatchingAGivenEventTag () { var eventTag_1 = new EventTag ("event-one"); var eventTag_2 = new EventTag ("event-two"); var eventTag_3 = new EventTag ("event-three"); var eventTags = new EventTag[]{ eventTag_1, eventTag_2, eventTag_3}; var channel = new Channel (); var broadcaster = new Broadcaster (channel, eventTags, "the-broadcaster"); var watcher = new Watcher (onSignal: (ISignal signal) => {}); watcher.Watch (broadcaster, new IEventTag[]{ eventTag_1, eventTag_3 }); Assert.IsTrue (watcher.IsWatching (eventTag_1)); Assert.IsTrue (watcher.IsWatching (eventTag_3)); Assert.IsFalse (watcher.IsWatching (eventTag_2)); Assert.IsFalse (watcher.IsWatching (null)); } [Test, Category("Given a Watcher"), Description("When asking if it observing all EventTags from an Broadcaster, Then it should answer accurately")] public void ShouldInformUsIfItOrNotWatchingAllBroadcasterTags () { var eventTag_1 = new EventTag ("event-one"); var eventTag_2 = new EventTag ("event-two"); var eventTag_3 = new EventTag ("event-three"); var allEventTags = new EventTag[]{ eventTag_1, eventTag_2, eventTag_3}; var channel = new Channel (); var broadcaster = new Broadcaster (channel, allEventTags, "the-broadcaster"); var watcher = new Watcher (onSignal: (ISignal signal) => {}); watcher.Watch (broadcaster, new IEventTag[]{ eventTag_1, eventTag_3 }); Assert.IsFalse (watcher.IsWatchingAll (broadcaster)); watcher.Watch (broadcaster, allEventTags); Assert.IsTrue (watcher.IsWatchingAll (broadcaster)); } [Test, Category("Given a Watcher"), Description("When a watcher is stopped, Then it should no longer observer any Broadcaster")] public void ShouldStopObservingAllBroadcasters () { var eventTag_1 = new EventTag ("event-one"); var eventTag_2 = new EventTag ("event-two"); var eventTag_3 = new EventTag ("event-three"); var channel = new Channel ("channel-one"); var broadcaster_1 = new Broadcaster (channel, new IEventTag[]{ eventTag_1 }, "b-1"); var broadcaster_2 = new Broadcaster (channel, new IEventTag[]{ eventTag_2 }, "b-2"); var broadcaster_3 = new Broadcaster (channel, new IEventTag[]{ eventTag_3 }, "tb-3"); var signaller_1 = new Signaller (channel: channel, owner: this); var signal_1 = new Signal (signaller_1, eventTag_1, null); var signal_2 = new Signal (signaller_1, eventTag_2, null); var signal_3 = new Signal (signaller_1, eventTag_3, null); var observedSignals = new List<String> (); var watcher = new Watcher (onSignal: (ISignal signal) => { observedSignals.Add (signal.EventTag.Name); }); watcher.WatchAll (broadcaster_1); watcher.WatchAll (broadcaster_2); watcher.WatchAll (broadcaster_3); channel.Emit (signal_1); channel.Emit (signal_2); channel.Emit (signal_3); Assert.AreEqual (3, observedSignals.Count); watcher.Stop (); observedSignals.Clear (); channel.Emit (signal_1); channel.Emit (signal_2); channel.Emit (signal_3); Assert.IsEmpty (observedSignals); watcher.WatchAll (broadcaster_1); channel.Emit (signal_1); channel.Emit (signal_2); Assert.AreEqual (1, observedSignals.Count); } [Test, Category("Given a Watcher"), Description("When a watcher is silenced, Then it should no longer observer any Broadcaster")] public void ShouldBeSilentWhenAsked () { var eventTag_1 = new EventTag ("event-one"); var eventTag_2 = new EventTag ("event-two"); var eventTag_3 = new EventTag ("event-three"); var channel = new Channel ("channel-one"); var broadcaster_1 = new Broadcaster (channel, new IEventTag[]{ eventTag_1 }, "b-1"); var broadcaster_2 = new Broadcaster (channel, new IEventTag[]{ eventTag_2 }, "b-2"); var broadcaster_3 = new Broadcaster (channel, new IEventTag[]{ eventTag_3 }, "tb-3"); var signaller = new Signaller (channel: channel, owner: this); var signal_1 = new Signal (signaller, eventTag_1, null); var signal_2 = new Signal (signaller, eventTag_2, null); var signal_3 = new Signal (signaller, eventTag_3, null); var observedSignals = new List<String> (); var watcher = new Watcher (onSignal: (ISignal signal) => { observedSignals.Add (signal.EventTag.Name); }); watcher.WatchAll (broadcaster_1); watcher.WatchAll (broadcaster_2); watcher.WatchAll (broadcaster_3); channel.Emit (signal_1); channel.Emit (signal_2); channel.Emit (signal_3); Assert.AreEqual (3, observedSignals.Count); watcher.Silence (true); observedSignals.Clear (); channel.Emit (signal_1); channel.Emit (signal_2); channel.Emit (signal_3); watcher.Silence (false); channel.Emit (signal_1); channel.Emit (signal_2); Assert.AreEqual (2, observedSignals.Count); } } }
// <copyright file="DummyClient.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.BasicApi { using System; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.OurUtils; using UnityEngine.SocialPlatforms; /// <summary> /// Dummy client used in Editor. /// </summary> /// <remarks>Google Play Game Services are not supported in the Editor /// environment, so this client is used as a placeholder. /// </remarks> public class DummyClient : IPlayGamesClient { /// <summary> /// Starts the authentication process. /// </summary> /// <remarks> If silent == true, no UIs will be shown /// (if UIs are needed, it will fail rather than show them). If silent == false, /// this may show UIs, consent dialogs, etc. /// At the end of the process, callback will be invoked to notify of the result. /// Once the callback returns true, the user is considered to be authenticated /// forever after. /// </remarks> /// <param name="callback">Callback when completed.</param> /// <param name="silent">If set to <c>true</c> silent.</param> public void Authenticate(Action<bool, string> callback, bool silent) { LogUsage(); if (callback != null) { callback(false, "Not implemented on this platform"); } } /// <summary> /// Returns whether or not user is authenticated. /// </summary> /// <returns>true if authenticated</returns> /// <c>false</c> public bool IsAuthenticated() { LogUsage(); return false; } /// <summary> /// Signs the user out. /// </summary> public void SignOut() { LogUsage(); } /// <summary> /// Retrieves an id token, which can be verified server side, if they are logged in. /// </summary> /// <param name="idTokenCallback">The callback invoked with the token</param> /// <returns>The identifier token.</returns> public string GetIdToken() { LogUsage(); return null; } /// <summary> /// Returns the authenticated user's ID. Note that this value may change if a user signs /// on and signs in with a different account. /// </summary> /// <returns>The user identifier.</returns> public string GetUserId() { LogUsage(); return "DummyID"; } public string GetServerAuthCode() { LogUsage(); return null; } public void GetAnotherServerAuthCode(bool reAuthenticateIfNeeded, Action<string> callback) { LogUsage(); callback(null); } /// <summary> /// Gets the user's email. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available.</remarks> /// <returns>The user email or null if not authenticated or the permission is /// not available.</returns> public string GetUserEmail() { return string.Empty; } /// <summary> /// Gets the player stats. /// </summary> /// <param name="callback">Callback for response.</param> public void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback) { LogUsage(); callback(CommonStatusCodes.ApiNotConnected, new PlayerStats()); } /// <summary> /// Returns a human readable name for the user, if they are logged in. /// </summary> /// <returns>The user display name.</returns> public string GetUserDisplayName() { LogUsage(); return "Player"; } /// <summary> /// Returns the user's avatar url, if they are logged in and have an avatar. /// </summary> /// <returns>The user image URL.</returns> public string GetUserImageUrl() { LogUsage(); return null; } /// <summary> /// Loads the players specified. /// </summary> /// <remarks> This is mainly used by the leaderboard /// APIs to get the information of a high scorer. /// </remarks> /// <param name="userIds">User identifiers.</param> /// <param name="callback">Callback to invoke when completed.</param> public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback) { LogUsage(); if (callback != null) { callback.Invoke(null); } } /// <summary> /// Loads the achievements for the current player. /// </summary> /// <param name="callback">Callback to invoke when completed.</param> public void LoadAchievements(Action<Achievement[]> callback) { LogUsage(); if (callback != null) { callback.Invoke(null); } } /// <summary> /// Returns the achievement corresponding to the passed achievement identifier. /// </summary> /// <returns>The achievement.</returns> /// <param name="achId">Achievement identifier.</param> public Achievement GetAchievement(string achId) { LogUsage(); return null; } /// <summary> /// Unlocks the achievement. /// </summary> /// <param name="achId">Achievement identifier.</param> /// <param name="callback">Callback to invoke when complete.</param> public void UnlockAchievement(string achId, Action<bool> callback) { LogUsage(); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Reveals the achievement. /// </summary> /// <param name="achId">Achievement identifier.</param> /// <param name="callback">Callback to invoke when complete.</param> public void RevealAchievement(string achId, Action<bool> callback) { LogUsage(); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Increments the achievement. /// </summary> /// <param name="achId">Achievement identifier.</param> /// <param name="steps">Steps to increment by..</param> /// <param name="callback">Callback to invoke when complete.</param> public void IncrementAchievement(string achId, int steps, Action<bool> callback) { LogUsage(); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Set an achievement to have at least the given number of steps completed. /// </summary> /// <remarks> /// Calling this method while the achievement already has more steps than /// the provided value is a no-op. Once the achievement reaches the /// maximum number of steps, the achievement is automatically unlocked, /// and any further mutation operations are ignored. /// </remarks> /// <param name="achId">Achievement identifier.</param> /// <param name="steps">Steps to increment to at least.</param> /// <param name="callback">Callback to invoke when complete.</param> public void SetStepsAtLeast(string achId, int steps, Action<bool> callback) { LogUsage(); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Shows the achievements UI /// </summary> /// <param name="callback">Callback to invoke when complete.</param> public void ShowAchievementsUI(Action<UIStatus> callback) { LogUsage(); if (callback != null) { callback.Invoke(UIStatus.VersionUpdateRequired); } } /// <summary> /// Shows the leaderboard UI /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="span">Timespan to display.</param> /// <param name="callback">Callback to invoke when complete.</param> public void ShowLeaderboardUI( string leaderboardId, LeaderboardTimeSpan span, Action<UIStatus> callback) { LogUsage(); if (callback != null) { callback.Invoke(UIStatus.VersionUpdateRequired); } } /// <summary> /// Returns the max number of scores returned per call. /// </summary> /// <returns>The max results.</returns> public int LeaderboardMaxResults() { return 25; } /// <summary> /// Loads the score data for the given leaderboard. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="start">Start indicating the top scores or player centric</param> /// <param name="rowCount">Row count.</param> /// <param name="collection">Collection to display.</param> /// <param name="timeSpan">Time span.</param> /// <param name="callback">Callback to invoke when complete.</param> public void LoadScores( string leaderboardId, LeaderboardStart start, int rowCount, LeaderboardCollection collection, LeaderboardTimeSpan timeSpan, Action<LeaderboardScoreData> callback) { LogUsage(); if (callback != null) { callback(new LeaderboardScoreData( leaderboardId, ResponseStatus.LicenseCheckFailed)); } } /// <summary> /// Loads the more scores for the leaderboard. /// </summary> /// <remarks>The token is accessed /// by calling LoadScores() with a positive row count. /// </remarks> /// <param name="token">Token used to start loading scores.</param> /// <param name="rowCount">Max number of scores to return. /// This can be limited by the SDK.</param> /// <param name="callback">Callback to invoke when complete.</param> public void LoadMoreScores( ScorePageToken token, int rowCount, Action<LeaderboardScoreData> callback) { LogUsage(); if (callback != null) { callback(new LeaderboardScoreData( token.LeaderboardId, ResponseStatus.LicenseCheckFailed)); } } /// <summary> /// Submits the score. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="score">Score to submit.</param> /// <param name="callback">Callback to invoke when complete.</param> public void SubmitScore(string leaderboardId, long score, Action<bool> callback) { LogUsage(); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Submits the score for the currently signed-in player /// to the leaderboard associated with a specific id /// and metadata (such as something the player did to earn the score). /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="score">Score value to submit.</param> /// <param name="metadata">Metadata about the score.</param> /// <param name="callback">Callback upon completion.</param> public void SubmitScore( string leaderboardId, long score, string metadata, Action<bool> callback) { LogUsage(); if (callback != null) { callback.Invoke(false); } } /// <summary> /// Returns a real-time multiplayer client. /// </summary> /// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"></seealso> /// <returns>The rtmp client.</returns> public IRealTimeMultiplayerClient GetRtmpClient() { LogUsage(); return null; } /// <summary> /// Returns a turn-based multiplayer client. /// </summary> /// <returns>The tbmp client.</returns> public ITurnBasedMultiplayerClient GetTbmpClient() { LogUsage(); return null; } /// <summary> /// Gets the saved game client. /// </summary> /// <returns>The saved game client.</returns> public SavedGame.ISavedGameClient GetSavedGameClient() { LogUsage(); return null; } /// <summary> /// Gets the events client. /// </summary> /// <returns>The events client.</returns> public GooglePlayGames.BasicApi.Events.IEventsClient GetEventsClient() { LogUsage(); return null; } /// <summary> /// Gets the quests client. /// </summary> /// <returns>The quests client.</returns> [Obsolete("Quests are being removed in 2018.")] public GooglePlayGames.BasicApi.Quests.IQuestsClient GetQuestsClient() { LogUsage(); return null; } /// <summary> /// Gets the video client. /// </summary> /// <returns>The video client.</returns> public GooglePlayGames.BasicApi.Video.IVideoClient GetVideoClient() { LogUsage(); return null; } /// <summary> /// Registers the invitation delegate. /// </summary> /// <param name="invitationDelegate">Invitation delegate.</param> public void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate) { LogUsage(); } /// <summary> /// Gets the invitation from notification. /// </summary> /// <returns>The invitation from notification.</returns> public Invitation GetInvitationFromNotification() { LogUsage(); return null; } /// <summary> /// Determines whether this instance has invitation from notification. /// </summary> /// <returns><c>true</c> if this instance has invitation from notification; otherwise, <c>false</c>.</returns> public bool HasInvitationFromNotification() { LogUsage(); return false; } /// <summary> /// Load friends of the authenticated user /// </summary> /// <param name="callback">Callback invoked when complete. bool argument /// indicates success.</param> public void LoadFriends(Action<bool> callback) { LogUsage(); callback(false); } /// <summary> /// Gets the friends. /// </summary> /// <returns>The friends.</returns> public IUserProfile[] GetFriends() { LogUsage(); return new IUserProfile[0]; } /// <summary> /// Gets the Android API client. Returns null on non-Android players. /// </summary> /// <returns>The API client.</returns> public IntPtr GetApiClient() { LogUsage(); return IntPtr.Zero; } /// <summary> /// Sets the gravity for popups (Android only). /// </summary> /// <remarks>This can only be called after authentication. It affects /// popups for achievements and other game services elements.</remarks> /// <param name="gravity">Gravity for the popup.</param> public void SetGravityForPopups(Gravity gravity) { LogUsage(); } /// <summary> /// Logs the usage. /// </summary> private static void LogUsage() { Logger.d("Received method call on DummyClient - using stub implementation."); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Composition.Convention.UnitTests; using System.Composition.Hosting; using System.Linq; using System.Reflection; using Xunit; namespace System.Composition.Convention { public class PartBuilderOfTTests { public interface IFirst { } private interface IFoo { } private class FooImpl { public string P1 { get; set; } public string P2 { get; set; } public IEnumerable<IFoo> P3 { get; set; } } private class FooImplWithConstructors { public FooImplWithConstructors() { } public FooImplWithConstructors(int id) { } public FooImplWithConstructors(IEnumerable<IFoo> ids) { } public FooImplWithConstructors(int id, string name) { } } [Export] public class OnImportsSatisfiedMultipleClass { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } public void OnImportsSatisfied1() { OnImportsSatisfiedInvoked += 2; } public void OnImportsSatisfied2() { OnImportsSatisfiedInvoked += 4; } } [Export] public class OnImportsSatisfiedConfiguredClass { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } [OnImportsSatisfied] public void OnImportsSatisfied() { ++OnImportsSatisfiedInvoked; } } [Export] public class OnImportsSatisfiedTestClass { public int OnImportsSatisfiedInvoked = 0; [Import("P1", AllowDefault = true)] public string P1 { get; set; } [Import("P2", AllowDefault = true)] public string P2 { get; set; } public int OnImportsSatisfiedInvalidReturnValue() { return 1; } public void OnImportsSatisfiedInvalidArgs(int arg1) { } public void OnImportsSatisfied() { ++OnImportsSatisfiedInvoked; } } [Export] public class OnImportsSatisfiedDerivedClass : OnImportsSatisfiedTestClass { } public class ExportValues { public ExportValues() { P1 = "Hello, World from P1"; P2 = "Hello, World from P2"; } [Export("P1")] public string P1 { get; set; } [Export("P2")] public string P2 { get; set; } } [Fact] public void NoOperations_ShouldGenerateNoAttributesOnAnyMember() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>(); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportSelf_ShouldGenerateSingleExportAttribute() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().Export(); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(1, attributes.Count()); Assert.NotNull(attributes[0] as ExportAttribute); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportOfT_ShouldGenerateSingleExportAttributeWithContractType() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().Export<IFoo>(); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes[0] as ExportAttribute; Assert.NotNull(exportAttribute); Assert.Equal(typeof(IFoo), exportAttribute.ContractType); Assert.Null(exportAttribute.ContractName); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void AddMetadata_ShouldGeneratePartMetadataAttribute() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().Export<IFoo>().AddPartMetadata("name", "value"); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(2, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Equal(typeof(IFoo), exportAttribute.ContractType); Assert.Null(exportAttribute.ContractName); var mdAttribute = attributes.First((t) => t.GetType() == typeof(PartMetadataAttribute)) as PartMetadataAttribute; Assert.Equal("name", mdAttribute.Name); Assert.Equal("value", mdAttribute.Value); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void AddMetadataWithFunc_ShouldGeneratePartMetadataAttribute() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().Export<IFoo>().AddPartMetadata("name", t => t.Name); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(2, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Equal(typeof(IFoo), exportAttribute.ContractType); Assert.Null(exportAttribute.ContractName); var mdAttribute = attributes.First((t) => t.GetType() == typeof(PartMetadataAttribute)) as PartMetadataAttribute; Assert.Equal("name", mdAttribute.Name); Assert.Equal(typeof(FooImpl).Name, mdAttribute.Value); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportProperty_ShouldGenerateExportForPropertySelected() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().ExportProperty(p => p.P1); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Null(exportAttribute.ContractName); Assert.Null(exportAttribute.ContractType); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ImportProperty_ShouldGenerateImportForPropertySelected() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().ImportProperty(p => p.P1); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var importAttribute = attributes.First((t) => t.GetType() == typeof(ImportAttribute)) as ImportAttribute; Assert.Null(importAttribute.ContractName); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ImportProperty_ShouldGenerateImportForPropertySelected_And_ApplyImportMany() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().ImportProperty(p => p.P3); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(1, attributes.Count()); var importAttribute = attributes.First((t) => t.GetType() == typeof(ImportManyAttribute)) as ImportManyAttribute; Assert.Null(importAttribute.ContractName); } [Fact] public void ExportPropertyWithConfiguration_ShouldGenerateExportForPropertySelected() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().ExportProperty(p => p.P1, c => c.AsContractName("hey").AsContractType<IFoo>()); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Same("hey", exportAttribute.ContractName); Assert.Same(typeof(IFoo), exportAttribute.ContractType); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportPropertyWithConfiguration_ShouldGenerateExportForAllProperties() { var builder = new ConventionBuilder(); builder.ForType<FooImpl>().ExportProperty(p => p.P1, c => c.AsContractName("hey").AsContractType<IFoo>()); var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1"); Assert.Equal(1, attributes.Count()); var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute; Assert.Same("hey", exportAttribute.ContractName); Assert.Same(typeof(IFoo), exportAttribute.ContractType); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2"); Assert.Equal(0, attributes.Count()); attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3"); Assert.Equal(0, attributes.Count()); } [Fact] public void ConventionSelectsConstructor_SelectsTheOneWithMostParameters() { var builder = new ConventionBuilder(); builder.ForType<FooImplWithConstructors>(); var selectedConstructor = GetSelectedConstructor(builder, typeof(FooImplWithConstructors)); Assert.NotNull(selectedConstructor); Assert.Equal(2, selectedConstructor.GetParameters().Length); // Should select public FooImplWithConstructors(int id, string name) { } var attributes = GetAttributesFromMember(builder, typeof(FooImpl), null); Assert.Equal(0, attributes.Count()); } [Fact] public void ManuallySelectingConstructor_SelectsTheExplicitOne() { var builder = new ConventionBuilder(); builder.ForType<FooImplWithConstructors>().SelectConstructor(param => new FooImplWithConstructors(param.Import<int>())); var selectedConstructor = GetSelectedConstructor(builder, typeof(FooImplWithConstructors)); Assert.NotNull(selectedConstructor); Assert.Equal(1, selectedConstructor.GetParameters().Length); // Should select public FooImplWithConstructors(IEnumerable<IFoo>) { } var pi = selectedConstructor.GetParameters()[0]; Assert.Equal(typeof(int), pi.ParameterType); var attributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), pi); Assert.Equal(1, attributes.Count()); Assert.NotNull(attributes[0] as ImportAttribute); attributes = GetAttributesFromMember(builder, typeof(FooImplWithConstructors), null); Assert.Equal(0, attributes.Count()); } [Fact] public void ManuallySelectingConstructor_SelectsTheExplicitOne_IEnumerableParameterBecomesImportMany() { var builder = new ConventionBuilder(); builder.ForType<FooImplWithConstructors>().SelectConstructor(param => new FooImplWithConstructors(param.Import<IEnumerable<IFoo>>())); var selectedConstructor = GetSelectedConstructor(builder, typeof(FooImplWithConstructors)); Assert.NotNull(selectedConstructor); Assert.Equal(1, selectedConstructor.GetParameters().Length); // Should select public FooImplWithConstructors(IEnumerable<IFoo>) { } var pi = selectedConstructor.GetParameters()[0]; Assert.Equal(typeof(IEnumerable<IFoo>), pi.ParameterType); var attributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), pi); Assert.Equal(1, attributes.Count()); Assert.NotNull(attributes[0] as ImportManyAttribute); attributes = GetAttributesFromMember(builder, typeof(FooImplWithConstructors), null); Assert.Equal(0, attributes.Count()); } [Fact] public void ExportInterfaceSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null, null)); } [Fact] public void ImportSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ImportProperty(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ImportProperty(null, null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ImportProperty<IFirst>(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ImportProperty<IFirst>(null, null)); } [Fact] public void ConstructorSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("constructorSelector", () => builder.ForTypesMatching<IFoo>((t) => true).SelectConstructor(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("importConfiguration", () => builder.ForTypesMatching<IFoo>((t) => true).SelectConstructor(null, null)); } [Fact] public void ExportSelectorNull_ShouldThrowArgumentNull() { var builder = new ConventionBuilder(); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty(null, null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty<IFirst>(null)); ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty<IFirst>(null, null)); } private static Attribute[] GetAttributesFromMember(ConventionBuilder builder, Type type, string member) { if (string.IsNullOrEmpty(member)) { var list = builder.GetDeclaredAttributes(null, type.GetTypeInfo()); return list; } else { var pi = type.GetRuntimeProperty(member); var list = builder.GetDeclaredAttributes(type, pi); return list; } } private static ConstructorInfo GetSelectedConstructor(ConventionBuilder builder, Type type) { ConstructorInfo reply = null; foreach (var ci in type.GetTypeInfo().DeclaredConstructors) { var li = builder.GetDeclaredAttributes(type, ci); if (li.Length > 0) { Assert.True(reply == null); // Fail if we got more than one constructor reply = ci; } } return reply; } [Fact] public void NotifyImportsSatisfied_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForType<OnImportsSatisfiedTestClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied()); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedTestClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedTestClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(1, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedAttributeAlreadyApplied_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForType<OnImportsSatisfiedConfiguredClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied()); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedConfiguredClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedConfiguredClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(1, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedAttributeAppliedToBaseClass_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForType<OnImportsSatisfiedDerivedClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied()); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedDerivedClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedDerivedClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(1, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedAttributeAppliedToDerivedClassExportBase_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForType<OnImportsSatisfiedDerivedClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied()); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedTestClass>(builder) .WithPart<OnImportsSatisfiedDerivedClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedTestClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(0, test.OnImportsSatisfiedInvoked); } [Fact] public void NotifyImportsSatisfiedTwice_ShouldSucceed() { var builder = new ConventionBuilder(); builder.ForType<OnImportsSatisfiedMultipleClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied1()); builder.ForType<OnImportsSatisfiedMultipleClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied2()); var container = new ContainerConfiguration() .WithPart<OnImportsSatisfiedMultipleClass>(builder) .WithPart<ExportValues>(builder) .CreateContainer(); var test = container.GetExport<OnImportsSatisfiedMultipleClass>(); Assert.NotNull(test.P1); Assert.NotNull(test.P2); Assert.Equal(6, test.OnImportsSatisfiedInvoked); } } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // David Stephensen (mailto:David.Stephensen@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.IO; using System.Reflection; using MigraDoc.DocumentObjectModel.Internals; using MigraDoc.DocumentObjectModel.Visitors; using MigraDoc.DocumentObjectModel.Tables; using MigraDoc.DocumentObjectModel.Shapes; using MigraDoc.DocumentObjectModel.IO; namespace MigraDoc.DocumentObjectModel { /// <summary> /// Represents a footnote in a paragraph. /// </summary> public class Footnote : DocumentObject, IVisitable { /// <summary> /// Initializes a new instance of the Footnote class. /// </summary> public Footnote() { //NYI: Nested footnote check! } /// <summary> /// Initializes a new instance of the Footnote class with the specified parent. /// </summary> internal Footnote(DocumentObject parent) : base(parent) { } /// <summary> /// Initializes a new instance of the Footnote class with a text the Footnote shall content. /// </summary> internal Footnote(string content) : this() { this.Elements.AddParagraph(content); } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new Footnote Clone() { return (Footnote)DeepCopy(); } /// <summary> /// Implements the deep copy of the object. /// </summary> protected override object DeepCopy() { Footnote footnote = (Footnote)base.DeepCopy(); if (footnote.elements != null) { footnote.elements = footnote.elements.Clone(); footnote.elements.parent = footnote; } if (footnote.format != null) { footnote.format = footnote.format.Clone(); footnote.format.parent = footnote; } return footnote; } /// <summary> /// Adds a new paragraph to the footnote. /// </summary> public Paragraph AddParagraph() { return this.Elements.AddParagraph(); } /// <summary> /// Adds a new paragraph with the specified text to the footnote. /// </summary> public Paragraph AddParagraph(string text) { return this.Elements.AddParagraph(text); } /// <summary> /// Adds a new table to the footnote. /// </summary> public Table AddTable() { return this.Elements.AddTable(); } /// <summary> /// Adds a new image to the footnote. /// </summary> public Image AddImage(string name) { return this.Elements.AddImage(name); } /// <summary> /// Adds a new Image to the paragraph from a MemoryStream. /// </summary> /// <returns></returns> public Image AddImage(MemoryStream stream) { return this.Elements.AddImage(stream); } /// <summary> /// Adds a new paragraph to the footnote. /// </summary> public void Add(Paragraph paragraph) { this.Elements.Add(paragraph); } /// <summary> /// Adds a new table to the footnote. /// </summary> public void Add(Table table) { this.Elements.Add(table); } /// <summary> /// Adds a new image to the footnote. /// </summary> public void Add(Image image) { this.Elements.Add(image); } #endregion #region Properties /// <summary> /// Gets the collection of paragraph elements that defines the footnote. /// </summary> public DocumentElements Elements { get { if (this.elements == null) this.elements = new DocumentElements(this); return this.elements; } set { SetParent(value); this.elements = value; } } [DV(ItemType = typeof(DocumentObject))] internal DocumentElements elements; /// <summary> /// Gets or sets the character to be used to mark the footnote. /// </summary> public string Reference { get { return this.reference.Value; } set { this.reference.Value = value; } } [DV] internal NString reference = NString.NullValue; /// <summary> /// Gets or sets the style name of the footnote. /// </summary> public string Style { get { return this.style.Value; } set { this.style.Value = value; } } [DV] internal NString style = NString.NullValue; /// <summary> /// Gets the format of the footnote. /// </summary> public ParagraphFormat Format { get { if (this.format == null) this.format = new ParagraphFormat(this); return this.format; } set { SetParent(value); this.format = value; } } [DV] internal ParagraphFormat format; #endregion #region Internal /// <summary> /// Converts Footnote into DDL. /// </summary> internal override void Serialize(Serializer serializer) { serializer.WriteLine("\\footnote"); int pos = serializer.BeginAttributes(); if (this.reference.Value != string.Empty) serializer.WriteSimpleAttribute("Reference", this.Reference); if (this.style.Value != string.Empty) serializer.WriteSimpleAttribute("Style", this.Style); if (!this.IsNull("Format")) this.format.Serialize(serializer, "Format", null); serializer.EndAttributes(pos); pos = serializer.BeginContent(); if (!this.IsNull("Elements")) this.elements.Serialize(serializer); serializer.EndContent(pos); } /// <summary> /// Allows the visitor object to visit the document object and it's child objects. /// </summary> void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren) { visitor.VisitFootnote(this); if (visitChildren && this.elements != null) ((IVisitable)this.elements).AcceptVisitor(visitor, visitChildren); } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (meta == null) meta = new Meta(typeof(Footnote)); return meta; } } static Meta meta; #endregion } }
namespace Orleans.CodeGeneration { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Orleans.CodeGenerator; using Orleans.Serialization; using Orleans.Runtime; /// <summary> /// Generates factory, grain reference, and invoker classes for grain interfaces. /// Generates state object classes for grain implementation classes. /// </summary> public class GrainClientGenerator : MarshalByRefObject { [Serializable] internal class CodeGenOptions { public FileInfo InputLib; public bool LanguageConflict; public Language? TargetLanguage; public List<string> ReferencedAssemblies = new List<string>(); public string CodeGenFile; public string SourcesDir; } [Serializable] internal class GrainClientGeneratorFlags { internal static bool Verbose = false; internal static bool FailOnPathNotFound = false; } private static readonly int[] suppressCompilerWarnings = { 162, // CS0162 - Unreachable code detected. 219, // CS0219 - The variable 'V' is assigned but its value is never used. 414, // CS0414 - The private field 'F' is assigned but its value is never used. 649, // CS0649 - Field 'F' is never assigned to, and will always have its default value. 693, // CS0693 - Type parameter 'type parameter' has the same name as the type parameter from outer type 'T' 1591, // CS1591 - Missing XML comment for publicly visible type or member 'Type_or_Member' 1998 // CS1998 - This async method lacks 'await' operators and will run synchronously }; /// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { AppDomain appDomain = null; try { var assembly = typeof (GrainClientGenerator).GetTypeInfo().Assembly; // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( assembly.FullName, typeof(GrainClientGenerator).FullName); // Call a method return generator.CreateGrainClient(options); } finally { if (appDomain != null) AppDomain.Unload(appDomain); // Unload the AppDomain } } /// <summary> /// Generate one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private bool CreateGrainClient(CodeGenOptions options) { PlacementStrategy.Initialize(); // Load input assembly // special case Orleans.dll because there is a circular dependency. var assemblyName = AssemblyName.GetAssemblyName(options.InputLib.FullName); var grainAssembly = (Path.GetFileName(options.InputLib.FullName) != "Orleans.dll") ? Assembly.LoadFrom(options.InputLib.FullName) : Assembly.Load(assemblyName); // Create sources directory if (!Directory.Exists(options.SourcesDir)) Directory.CreateDirectory(options.SourcesDir); // Generate source var outputFileName = Path.Combine( options.SourcesDir, Path.GetFileNameWithoutExtension(options.InputLib.Name) + ".codegen.cs"); ConsoleText.WriteStatus("Orleans-CodeGen - Generating file {0}", outputFileName); var codeGenerator = RoslynCodeGenerator.Instance; SerializationManager.RegisterBuiltInSerializers(); using (var sourceWriter = new StreamWriter(outputFileName)) { sourceWriter.WriteLine("#if !EXCLUDE_CODEGEN"); DisableWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine(codeGenerator.GenerateSourceForAssembly(grainAssembly)); RestoreWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine("#endif"); } ConsoleText.WriteStatus("Orleans-CodeGen - Generated file written {0}", outputFileName); // Copy intermediate file to permanent location, if newer. ConsoleText.WriteStatus( "Orleans-CodeGen - Updating IntelliSense file {0} -> {1}", outputFileName, options.CodeGenFile); UpdateIntellisenseFile(options.CodeGenFile, outputFileName); return true; } private static void DisableWarnings(TextWriter sourceWriter, IEnumerable<int> warnings) { foreach (var warningNum in warnings) sourceWriter.WriteLine("#pragma warning disable {0}", warningNum); } private static void RestoreWarnings(TextWriter sourceWriter, IEnumerable<int> warnings) { foreach (var warningNum in warnings) sourceWriter.WriteLine("#pragma warning restore {0}", warningNum); } /// <summary> /// Updates the source file in the project if required. /// </summary> /// <param name="sourceFileToBeUpdated">Path to file to be updated.</param> /// <param name="outputFileGenerated">File that was updated.</param> private static void UpdateIntellisenseFile(string sourceFileToBeUpdated, string outputFileGenerated) { if (string.IsNullOrEmpty(sourceFileToBeUpdated)) throw new ArgumentNullException("sourceFileToBeUpdated", "Output file must not be blank"); if (string.IsNullOrEmpty(outputFileGenerated)) throw new ArgumentNullException("outputFileGenerated", "Generated file must already exist"); var sourceToUpdateFileInfo = new FileInfo(sourceFileToBeUpdated); var generatedFileInfo = new FileInfo(outputFileGenerated); if (!generatedFileInfo.Exists) throw new Exception("Generated file must already exist"); if (File.Exists(sourceFileToBeUpdated)) { bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo); if (filesMatch) { ConsoleText.WriteStatus( "Orleans-CodeGen - No changes to the generated file {0}", sourceFileToBeUpdated); return; } // we come here only if files don't match sourceToUpdateFileInfo.Attributes = sourceToUpdateFileInfo.Attributes & (~FileAttributes.ReadOnly); // remove read only attribute ConsoleText.WriteStatus( "Orleans-CodeGen - copying file {0} to {1}", outputFileGenerated, sourceFileToBeUpdated); File.Copy(outputFileGenerated, sourceFileToBeUpdated, true); filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo); ConsoleText.WriteStatus( "Orleans-CodeGen - After copying file {0} to {1} Matchs={2}", outputFileGenerated, sourceFileToBeUpdated, filesMatch); } else { var dir = Path.GetDirectoryName(sourceFileToBeUpdated); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); ConsoleText.WriteStatus( "Orleans-CodeGen - copying file {0} to {1}", outputFileGenerated, sourceFileToBeUpdated); File.Copy(outputFileGenerated, sourceFileToBeUpdated, true); bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo); ConsoleText.WriteStatus( "Orleans-CodeGen - After copying file {0} to {1} Matchs={2}", outputFileGenerated, sourceFileToBeUpdated, filesMatch); } } private static bool CheckFilesMatch(FileInfo file1, FileInfo file2) { bool isMatching; long len1 = -1; long len2 = -1; if (file1.Exists) len1 = file1.Length; if (file2.Exists) len2 = file2.Length; if (len1 <= 0 || len2 <= 0) { isMatching = false; } else if (len1 != len2) { isMatching = false; } else { byte[] arr1 = File.ReadAllBytes(file1.FullName); byte[] arr2 = File.ReadAllBytes(file2.FullName); isMatching = true; // initially assume files match for (int i = 0; i < arr1.Length; i++) { if (arr1[i] != arr2[i]) { isMatching = false; // unless we know they don't match break; } } } if (GrainClientGeneratorFlags.Verbose) ConsoleText.WriteStatus( "Orleans-CodeGen - CheckFilesMatch = {0} File1 = {1} Len = {2} File2 = {3} Len = {4}", isMatching, file1, len1, file2, len2); return isMatching; } private static readonly string CodeGenFileRelativePathCSharp = Path.Combine("Properties", "orleans.codegen.cs"); public int RunMain(string[] args) { ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine); if (args.Length < 1) { Console.WriteLine( "Usage: ClientGenerator.exe <grain interface dll path> [<client dll path>] [<key file>] [<referenced assemblies>]"); Console.WriteLine( " ClientGenerator.exe /server <grain dll path> [<factory dll path>] [<key file>] [<referenced assemblies>]"); return 1; } try { var options = new CodeGenOptions(); // STEP 1 : Parse parameters if (args.Length == 1 && args[0].StartsWith("@")) { // Read command line args from file string arg = args[0]; string argsFile = arg.Trim('"').Substring(1).Trim('"'); Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile); AssertWellFormed(argsFile, true); args = File.ReadAllLines(argsFile); } int i = 1; foreach (string a in args) { string arg = a.Trim('"').Trim().Trim('"'); if (GrainClientGeneratorFlags.Verbose) Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg); if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg)) continue; if (arg.StartsWith("/")) { if (arg.StartsWith("/reference:") || arg.StartsWith("/r:")) { // list of references passed from from project file. separator =';' string refstr = arg.Substring(arg.IndexOf(':') + 1); string[] references = refstr.Split(';'); foreach (string rp in references) { AssertWellFormed(rp, true); options.ReferencedAssemblies.Add(rp); } } else if (arg.StartsWith("/in:")) { var infile = arg.Substring(arg.IndexOf(':') + 1); AssertWellFormed(infile); options.InputLib = new FileInfo(infile); } else if (arg.StartsWith("/bootstrap") || arg.StartsWith("/boot")) { // special case for building circular dependecy in preprocessing: // Do not build the input assembly, assume that some other build step options.CodeGenFile = Path.GetFullPath(CodeGenFileRelativePathCSharp); if (GrainClientGeneratorFlags.Verbose) { Console.WriteLine( "Orleans-CodeGen - Set CodeGenFile={0} from bootstrap", options.CodeGenFile); } } else if (arg.StartsWith("/sources:") || arg.StartsWith("/src:")) { var sourcesStr = arg.Substring(arg.IndexOf(':') + 1); string[] sources = sourcesStr.Split(';'); foreach (var source in sources) { HandleSourceFile(source, options); } } } else { HandleSourceFile(arg, options); } } if (options.TargetLanguage != Language.CSharp) { ConsoleText.WriteLine( "ERROR: Compile-time code generation is supported for C# only. " + "Remove code generation from your project in order to use run-time code generation."); return 2; } // STEP 2 : Validate and calculate unspecified parameters if (options.InputLib == null) { Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified."); return 2; } if (string.IsNullOrEmpty(options.CodeGenFile)) { Console.WriteLine( "ERROR: No codegen file. Add a file '{0}' to your project", Path.Combine("Properties", "orleans.codegen.cs")); return 2; } options.SourcesDir = Path.Combine(options.InputLib.DirectoryName, "Generated"); // STEP 3 : Dump useful info for debugging Console.WriteLine( "Orleans-CodeGen - Options " + Environment.NewLine + "\tInputLib={0} " + Environment.NewLine + "\tCodeGenFile={1}", options.InputLib.FullName, options.CodeGenFile); if (options.ReferencedAssemblies != null) { Console.WriteLine("Orleans-CodeGen - Using referenced libraries:"); foreach (string assembly in options.ReferencedAssemblies) Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly); } // STEP 5 : Finally call code generation if (!CreateGrainClientAssembly(options)) return -1; // DONE! return 0; } catch (Exception ex) { File.WriteAllText("error.txt", ex.Message + Environment.NewLine + ex.StackTrace); Console.WriteLine("-- Code-gen FAILED -- \n{0}", TraceLogger.PrintException(ex)); return 3; } } private static void HandleSourceFile(string arg, CodeGenOptions options) { AssertWellFormed(arg, true); SetLanguageIfMatchNoConflict(arg, ".cs", Language.CSharp, ref options.TargetLanguage, ref options.LanguageConflict); SetLanguageIfMatchNoConflict(arg, ".vb", Language.VisualBasic, ref options.TargetLanguage, ref options.LanguageConflict); SetLanguageIfMatchNoConflict(arg, ".fs", Language.FSharp, ref options.TargetLanguage, ref options.LanguageConflict); if (arg.EndsWith(CodeGenFileRelativePathCSharp, StringComparison.InvariantCultureIgnoreCase)) { options.CodeGenFile = Path.GetFullPath(arg); if (GrainClientGeneratorFlags.Verbose) { Console.WriteLine("Orleans-CodeGen - Set CodeGenFile={0} from {1}", options.CodeGenFile, arg); } } } private static void SetLanguageIfMatchNoConflict( string arg, string extension, Language value, ref Language? language, ref bool conflict) { if (conflict) return; if (arg.EndsWith(extension, StringComparison.InvariantCultureIgnoreCase)) { if (language.HasValue && language != value) { language = null; conflict = true; } else { language = value; } } } private static void AssertWellFormed(string path, bool mustExist = false) { CheckPathNotStartWith(path, ":"); CheckPathNotStartWith(path, "\""); CheckPathNotEndsWith(path, "\""); CheckPathNotEndsWith(path, "/"); CheckPath(path, p => !string.IsNullOrWhiteSpace(p), "Empty path string"); bool exists = FileExists(path); if (mustExist && GrainClientGeneratorFlags.FailOnPathNotFound) CheckPath(path, p => exists, "Path not exists"); } private static bool FileExists(string path) { bool exists = File.Exists(path) || Directory.Exists(path); if (!exists) Console.WriteLine("MISSING: Path not exists: {0}", path); return exists; } private static void CheckPathNotStartWith(string path, string str) { CheckPath(path, p => !p.StartsWith(str), string.Format("Cannot start with '{0}'", str)); } private static void CheckPathNotEndsWith(string path, string str) { CheckPath( path, p => !p.EndsWith(str, StringComparison.InvariantCultureIgnoreCase), string.Format("Cannot end with '{0}'", str)); } private static void CheckPath(string path, Func<string, bool> condition, string what) { if (condition(path)) return; var errMsg = string.Format("Bad path {0} Reason = {1}", path, what); Console.WriteLine("CODEGEN-ERROR: " + errMsg); throw new ArgumentException("FAILED: " + errMsg); } /// <summary> /// Simple class that loads the reference assemblies upon the AppDomain.AssemblyResolve /// </summary> [Serializable] internal class ReferenceResolver { /// <summary> /// Dictionary : Assembly file name without extension -> full path /// </summary> private Dictionary<string, string> referenceAssemblyPaths = new Dictionary<string, string>(); /// <summary> /// Needs to be public so can be serialized accross the the app domain. /// </summary> public Dictionary<string, string> ReferenceAssemblyPaths { get { return referenceAssemblyPaths; } set { referenceAssemblyPaths = value; } } /// <summary> /// Inits the resolver /// </summary> /// <param name="referencedAssemblies">Full paths of referenced assemblies</param> public ReferenceResolver(IEnumerable<string> referencedAssemblies) { if (null == referencedAssemblies) return; foreach (var assemblyPath in referencedAssemblies) referenceAssemblyPaths[Path.GetFileNameWithoutExtension(assemblyPath)] = assemblyPath; } /// <summary> /// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The event data.</param> /// <returns>The assembly that resolves the type, assembly, or resource; /// or null if theassembly cannot be resolved. /// </returns> public Assembly ResolveAssembly(object sender, ResolveEventArgs args) { Assembly assembly = null; string path; var asmName = new AssemblyName(args.Name); if (referenceAssemblyPaths.TryGetValue(asmName.Name, out path)) assembly = Assembly.LoadFrom(path); else ConsoleText.WriteStatus("Could not resolve {0}:", asmName.Name); return assembly; } } } }
// 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 Xunit; namespace System.Numerics.Tests { public class StackCalc { public string[] input; public Stack<BigInteger> myCalc; public Stack<BigInteger> snCalc; public Queue<string> operators; private BigInteger _snOut = 0; private BigInteger _myOut = 0; public StackCalc(string _input) { myCalc = new Stack<System.Numerics.BigInteger>(); snCalc = new Stack<System.Numerics.BigInteger>(); string delimStr = " "; char[] delimiter = delimStr.ToCharArray(); input = _input.Split(delimiter); operators = new Queue<string>(input); } public bool DoNextOperation() { string op = ""; bool ret = false; bool checkValues = false; BigInteger snnum1 = 0; BigInteger snnum2 = 0; BigInteger snnum3 = 0; BigInteger mynum1 = 0; BigInteger mynum2 = 0; BigInteger mynum3 = 0; if (operators.Count == 0) { return false; } op = operators.Dequeue(); if (op.StartsWith("u")) { checkValues = true; snnum1 = snCalc.Pop(); snCalc.Push(DoUnaryOperatorSN(snnum1, op)); mynum1 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoUnaryOperatorMine(mynum1, op)); ret = true; } else if (op.StartsWith("b")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snCalc.Push(DoBinaryOperatorSN(snnum1, snnum2, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoBinaryOperatorMine(mynum1, mynum2, op)); ret = true; } else if (op.StartsWith("t")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snnum3 = snCalc.Pop(); snCalc.Push(DoTertanaryOperatorSN(snnum1, snnum2, snnum3, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); mynum3 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoTertanaryOperatorMine(mynum1, mynum2, mynum3, op)); ret = true; } else { if (op.Equals("make")) { snnum1 = DoConstruction(); snCalc.Push(snnum1); myCalc.Push(snnum1); } else if (op.Equals("Corruption")) { snCalc.Push(-33); myCalc.Push(-555); } else if (BigInteger.TryParse(op, out snnum1)) { snCalc.Push(snnum1); myCalc.Push(snnum1); } else { Console.WriteLine("Failed to parse string {0}", op); } ret = true; } if (checkValues) { if ((snnum1 != mynum1) || (snnum2 != mynum2) || (snnum3 != mynum3)) { operators.Enqueue("Corruption"); } } return ret; } private BigInteger DoConstruction() { List<byte> bytes = new List<byte>(); BigInteger ret = new BigInteger(0); string op = operators.Dequeue(); while (String.CompareOrdinal(op, "endmake") != 0) { bytes.Add(byte.Parse(op)); op = operators.Dequeue(); } return new BigInteger(bytes.ToArray()); } private BigInteger DoUnaryOperatorSN(BigInteger num1, string op) { switch (op) { case "uSign": return new BigInteger(num1.Sign); case "u~": return (~(num1)); case "uLog10": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(num1)); case "uLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1)); case "uAbs": return BigInteger.Abs(num1); case "uNegate": return BigInteger.Negate(num1); case "u--": return (--(num1)); case "u++": return (++(num1)); case "u-": return (-(num1)); case "u+": return (+(num1)); case "uMultiply": return BigInteger.Multiply(num1, num1); case "u*": return num1 * num1; default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op) { switch (op) { case "bMin": return BigInteger.Min(num1, num2); case "bMax": return BigInteger.Max(num1, num2); case "b>>": return num1 >> (int)num2; case "b<<": return num1 << (int)num2; case "b^": return num1 ^ num2; case "b|": return num1 | num2; case "b&": return num1 & num2; case "b%": return num1 % num2; case "b/": return num1 / num2; case "b*": return num1 * num2; case "b-": return num1 - num2; case "b+": return num1 + num2; case "bLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1, (double)num2)); case "bGCD": return BigInteger.GreatestCommonDivisor(num1, num2); case "bPow": int arg2 = (int)num2; return BigInteger.Pow(num1, arg2); case "bDivRem": BigInteger num3; BigInteger ret = BigInteger.DivRem(num1, num2, out num3); SetSNOutCheck(num3); return ret; case "bRemainder": return BigInteger.Remainder(num1, num2); case "bDivide": return BigInteger.Divide(num1, num2); case "bMultiply": return BigInteger.Multiply(num1, num2); case "bSubtract": return BigInteger.Subtract(num1, num2); case "bAdd": return BigInteger.Add(num1, num2); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private BigInteger DoTertanaryOperatorSN(BigInteger num1, BigInteger num2, BigInteger num3, string op) { switch (op) { case "tModPow": return BigInteger.ModPow(num1, num2, num3); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private void SetSNOutCheck(BigInteger value) { _snOut = value; } public void VerifyOutParameter() { Assert.True(_snOut == MyBigIntImp.outParam, "Out parameters not matching"); _snOut = 0; MyBigIntImp.outParam = 0; } private static String Print(byte[] bytes) { return MyBigIntImp.PrintFormatX(bytes); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // Signature.cs // // 21 [....] 2000 // namespace System.Security.Cryptography.Xml { using System; using System.Collections; using System.Xml; [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public class Signature { private string m_id; private SignedInfo m_signedInfo; private byte[] m_signatureValue; private string m_signatureValueId; private KeyInfo m_keyInfo; private IList m_embeddedObjects; private CanonicalXmlNodeList m_referencedItems; private SignedXml m_signedXml = null; internal SignedXml SignedXml { get { return m_signedXml; } set { m_signedXml = value; } } // // public constructors // public Signature() { m_embeddedObjects = new ArrayList(); m_referencedItems = new CanonicalXmlNodeList(); } // // public properties // public string Id { get { return m_id; } set { m_id = value; } } public SignedInfo SignedInfo { get { return m_signedInfo; } set { m_signedInfo = value; if (this.SignedXml != null && m_signedInfo != null) m_signedInfo.SignedXml = this.SignedXml; } } public byte[] SignatureValue { get { return m_signatureValue; } set { m_signatureValue = value; } } public KeyInfo KeyInfo { get { if (m_keyInfo == null) m_keyInfo = new KeyInfo(); return m_keyInfo; } set { m_keyInfo = value; } } public IList ObjectList { get { return m_embeddedObjects; } set { m_embeddedObjects = value; } } internal CanonicalXmlNodeList ReferencedItems { get { return m_referencedItems; } } // // public methods // public XmlElement GetXml() { XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; return GetXml(document); } internal XmlElement GetXml (XmlDocument document) { // Create the Signature XmlElement signatureElement = (XmlElement)document.CreateElement("Signature", SignedXml.XmlDsigNamespaceUrl); if (!String.IsNullOrEmpty(m_id)) signatureElement.SetAttribute("Id", m_id); // Add the SignedInfo if (m_signedInfo == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignedInfoRequired")); signatureElement.AppendChild(m_signedInfo.GetXml(document)); // Add the SignatureValue if (m_signatureValue == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureValueRequired")); XmlElement signatureValueElement = document.CreateElement("SignatureValue", SignedXml.XmlDsigNamespaceUrl); signatureValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(m_signatureValue))); if (!String.IsNullOrEmpty(m_signatureValueId)) signatureValueElement.SetAttribute("Id", m_signatureValueId); signatureElement.AppendChild(signatureValueElement); // Add the KeyInfo if (this.KeyInfo.Count > 0) signatureElement.AppendChild(this.KeyInfo.GetXml(document)); // Add the Objects foreach (Object obj in m_embeddedObjects) { DataObject dataObj = obj as DataObject; if (dataObj != null) { signatureElement.AppendChild(dataObj.GetXml(document)); } } return signatureElement; } public void LoadXml(XmlElement value) { // Make sure we don't get passed null if (value == null) throw new ArgumentNullException("value"); // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature"); // Id attribute -- optional m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); // SignedInfo XmlElement signedInfoElement = signatureElement.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement; if (signedInfoElement == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo"); this.SignedInfo = new SignedInfo(); this.SignedInfo.LoadXml(signedInfoElement); // SignatureValue XmlElement signatureValueElement = signatureElement.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement; if (signatureValueElement == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo/SignatureValue"); m_signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); m_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); m_keyInfo = new KeyInfo(); if (keyInfoNodes != null) { foreach(XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) m_keyInfo.LoadXml(keyInfoElement); } } XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); m_embeddedObjects.Clear(); if (objectNodes != null) { foreach(XmlNode node in objectNodes) { XmlElement objectElement = node as XmlElement; if (objectElement != null) { DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); m_embeddedObjects.Add(dataObj); } } } // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) { m_referencedItems.Add(node); } } } public void AddObject(DataObject dataObject) { m_embeddedObjects.Add(dataObject); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.Collections; using System.IO; using NUnit.Framework; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.POIFS.Storage; using NPOI.POIFS.Properties; namespace TestCases.POIFS.FileSystem { /** * Class to Test POIFSDocumentPath functionality * * @author Marc Johnson */ [TestFixture] public class TestPOIFSDocumentPath { /** * Constructor TestPOIFSDocumentPath * * @param name */ public TestPOIFSDocumentPath() { } /** * Test default constructor */ [Test] public void TestDefaultConstructor() { POIFSDocumentPath path = new POIFSDocumentPath(); Assert.AreEqual(0, path.Length); } /** * Test full path constructor */ [Test] public void TestFullPathConstructor() { string[] components = { "foo", "bar", "foobar", "fubar" }; for (int j = 0; j < components.Length; j++) { string[] pms = new string[j]; for (int k = 0; k < j; k++) { pms[k] = components[k]; } POIFSDocumentPath path = new POIFSDocumentPath(pms); Assert.AreEqual(j, path.Length); for (int k = 0; k < j; k++) { Assert.AreEqual(components[k], path.GetComponent(k)); } if (j == 0) Assert.IsNull(path.Parent); else { POIFSDocumentPath parent = path.Parent; Assert.IsNotNull(parent); Assert.AreEqual(j - 1, parent.Length); for (int k = 0; k < j - 1; k++) Assert.AreEqual(components[k], parent.GetComponent(k)); } } // Test weird variants Assert.AreEqual(0, new POIFSDocumentPath(null).Length); try { new POIFSDocumentPath(new string[] { "fu", "" }); Assert.Fail("Should have caught IllegalArgumentException"); } catch (ArgumentException) { } try { new POIFSDocumentPath(new string[] { "fu", null }); Assert.Fail("Should have caught IllegalArgumentException"); } catch (ArgumentException) { } } /** * Test relative path constructor */ [Test] public void TestRelativePathConstructor() { string[] initialComponents = { "a", "b", "c" }; for (int n = 0; n < initialComponents.Length; n++) { String[] initialParams = new String[n]; for (int k = 0; k < n; k++) initialParams[k] = initialComponents[k]; POIFSDocumentPath b = new POIFSDocumentPath(initialParams); string[] components = { "foo", "bar", "foobar", "fubar" }; for (int j = 0; j < components.Length; j++) { String[] params1 = new String[j]; for (int k = 0; k < j; k++) { params1[k] = components[k]; } POIFSDocumentPath path = new POIFSDocumentPath(b, params1); Assert.AreEqual(j + n, path.Length); for (int k = 0; k < n; k++) { Assert.AreEqual(initialComponents[k], path.GetComponent(k)); } for (int k = 0; k < j; k++) { Assert.AreEqual(components[k], path.GetComponent(k + n)); } if ((j + n) == 0) { Assert.IsNull(path.Parent); } else { POIFSDocumentPath parent = path.Parent; Assert.IsNotNull(parent); Assert.AreEqual(j + n - 1, parent.Length); for (int k = 0; k < (j + n - 1); k++) { Assert.AreEqual(path.GetComponent(k), parent.GetComponent(k)); } } } Assert.AreEqual(n, new POIFSDocumentPath(b, null).Length); //this one is allowed. new POIFSDocumentPath(b, new string[] { "fu", "" }); //this one is allowed too new POIFSDocumentPath(b, new string[] { "", "fu" }); //this one is not allowed. try { new POIFSDocumentPath(b, new string[] { "fu", null }); Assert.Fail("should have caught ArgumentException"); } catch (ArgumentException) { } try { new POIFSDocumentPath(b, new string[] { "fu", null }); Assert.Fail("should have caught ArgumentException"); } catch (ArgumentException) { } } } /** * Test equality */ [Test] public void TestEquality() { POIFSDocumentPath a1 = new POIFSDocumentPath(); POIFSDocumentPath a2 = new POIFSDocumentPath(null); POIFSDocumentPath a3 = new POIFSDocumentPath(new String[0]); POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null); POIFSDocumentPath a5 = new POIFSDocumentPath(a1, new string[0]); POIFSDocumentPath[] paths = { a1, a2, a3, a4, a5 }; for (int j = 0; j < paths.Length; j++) { for (int k = 0; k < paths.Length; k++) Assert.AreEqual(paths[j], paths[k], j + "<>" + k); } a2 = new POIFSDocumentPath(a1, new string[] { "foo" }); a3 = new POIFSDocumentPath(a2, new string[] { "bar" }); a4 = new POIFSDocumentPath(a3, new string[] { "fubar" }); a5 = new POIFSDocumentPath(a4, new string[] { "foobar" }); POIFSDocumentPath[] builtUpPaths = { a1, a2, a3, a4, a5 }; POIFSDocumentPath[] fullPaths = { new POIFSDocumentPath(), new POIFSDocumentPath(new string[]{"foo"}), new POIFSDocumentPath(new string[]{"foo", "bar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "fubar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "fubar", "foobar"}) }; for (int k = 0; k < builtUpPaths.Length; k++) { for (int j = 0; j < fullPaths.Length; j++) { if (k == j) Assert.AreEqual(fullPaths[j], builtUpPaths[k], j + "<>" + k); else Assert.IsTrue(!(fullPaths[j].Equals(builtUpPaths[k])), j + "<>" + k); } } POIFSDocumentPath[] badPaths = { new POIFSDocumentPath(new string[]{"_foo"}), new POIFSDocumentPath(new string[]{"foo", "_bar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "_fubar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "fubar", "_foobar"}) }; for (int k = 0; k < builtUpPaths.Length; k++) { for (int j = 0; j < badPaths.Length; j++) Assert.IsTrue(!(fullPaths[k].Equals(badPaths[j])), j + "<>" + k); } } } }
using System; using System.Collections; using System.Globalization; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdOrgStaffTypes : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private String Id; private int Seq; private int Curr; private int SalPeriod; private int GetIndexOfCurr (string s) { return (lstCurr.Items.IndexOf (lstCurr.Items.FindByValue(s))); } protected void Page_Load(object sender, System.EventArgs e) { Id=Request.Params["Id"]; lblOrg.Text=(Session["OrgName"]).ToString(); lblContent1.Text=Request.Params["btnAction"] + " Staff Type"; if (!IsPostBack) { loadCurr(); btnAction.Text= Request.Params["btnAction"]; if (Request.Params["btnAction"] == "Update") { loadData(); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="hrs_RetrieveOrgStaffType"; cmd.Parameters.Add("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Request.Params["Id"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"OST"); if (ds.Tables["OST"].Rows.Count == 1) { if (ds.Tables["OST"].Rows[0][0].ToString() == "") { lblStaffTypeName.Text=""; } else { lblStaffTypeName.Text=ds.Tables["OST"].Rows[0][0].ToString(); } if (ds.Tables["OST"].Rows[0][1].ToString() == "1") { ckbStatus.Checked=true; } else { ckbStatus.Checked=false; } if (ds.Tables["OST"].Rows[0][2].ToString() != "") { Curr=Int32.Parse(ds.Tables["OST"].Rows[0][2].ToString()); } else { Curr=0; } if (ds.Tables["OST"].Rows[0][3].ToString() != "") { SalPeriod=Int32.Parse(ds.Tables["OST"].Rows[0][3].ToString()); } else { SalPeriod=0; } if (ds.Tables["OST"].Rows[0][4].ToString() == "") { Seq=0; } else { Seq=int.Parse(ds.Tables["OST"].Rows[0][4].ToString()); } if (ds.Tables["OST"].Rows[0][1].ToString() == "1") { ckbTimesheet.Checked=true; } else { ckbTimesheet.Checked=false; } lstCurr.SelectedIndex = GetIndexOfCurr(Curr.ToString()); lstSalPeriod.SelectedIndex = SalPeriod; txtSeq.Text=Seq.ToString(); } else { lblContent1.Text="Error. Please Contact System Administrator."; } } private void loadCurr() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveCurrencies"; /*cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();*/ DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Currencies"); lstCurr.DataSource = ds; lstCurr.DataMember= "Currencies"; lstCurr.DataTextField = "Name"; lstCurr.DataValueField = "Id"; lstCurr.DataBind(); } protected void btnAction_Click(object sender, System.EventArgs e) { if (btnAction.Text == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="hrs_UpdateOrgStaffType"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Int32.Parse(Id); cmd.Parameters.Add ("@CurrenciesId",SqlDbType.Int); cmd.Parameters["@CurrenciesId"].Value=lstCurr.SelectedItem.Value; cmd.Parameters.Add ("@SalPeriod",SqlDbType.Int); cmd.Parameters["@SalPeriod"].Value=lstSalPeriod.SelectedItem.Value; cmd.Parameters.Add ("@Seq",SqlDbType.Int); if (txtSeq.Text != "") { cmd.Parameters["@Seq"].Value=int.Parse(txtSeq.Text); } cmd.Parameters.Add ("@Status",SqlDbType.Int); if (ckbStatus.Checked) { cmd.Parameters["@Status"].Value=1; } else { cmd.Parameters["@Status"].Value=null; } cmd.Parameters.Add ("@PaymentBasis",SqlDbType.Int); if (ckbTimesheet.Checked) { cmd.Parameters["@PaymentBasis"].Value=1; } else { cmd.Parameters["@PaymentBasis"].Value=null; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } /*else if (btnAction.Text == "Add") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="hrs_AddOrgStaffType"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value= lblStaffTypeName.Text; cmd.Parameters.Add ("@OrgStaffTypesId",SqlDbType.Int); cmd.Parameters["@OrgStaffTypesId"].Value=Session["OrgSTId"].ToString(); cmd.Parameters.Add ("@CurrenciesId",SqlDbType.Int); cmd.Parameters["@CurrenciesId"].Value=lstCurr.SelectedItem.Value; cmd.Parameters.Add ("@SalPeriod",SqlDbType.Int); cmd.Parameters["@SalPeriod"].Value=lstSalPeriod.SelectedItem.Value; cmd.Parameters.Add ("@SalMax",SqlDbType.Decimal); if (txtSalMax.Text != "") { cmd.Parameters["@SalMax"].Value=decimal.Parse(txtSalMax.Text, NumberStyles.Any); } cmd.Parameters.Add ("@SalMin",SqlDbType.Decimal); if (txtSalMin.Text != "") { cmd.Parameters["@SalMin"].Value=decimal.Parse(txtSalMin.Text, NumberStyles.Any); } cmd.Parameters.Add ("@SalAve",SqlDbType.Decimal); if (txtSalAve.Text != "") { cmd.Parameters["@SalAve"].Value=decimal.Parse(txtSalAve.Text, NumberStyles.Any); } cmd.Parameters.Add ("@Ovt",SqlDbType.Decimal); if (txtOvt.Text != "") { cmd.Parameters["@Ovt"].Value=decimal.Parse(txtOvt.Text, NumberStyles.Any); } cmd.Parameters.Add ("@Status",SqlDbType.Int); if (ckbStatus.Checked) { cmd.Parameters["@Status"].Value=1; } else { cmd.Parameters["@Status"].Value=null; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); }*/ Done(); } private void Done() { Response.Redirect (strURL + Session["CUpdOST"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } } }
using PublicApiGeneratorTests.Examples; using System; using System.Collections.Generic; using System.IO; using Xunit; namespace PublicApiGeneratorTests { // Tests for https://github.com/PublicApiGenerator/PublicApiGenerator/issues/54 // See also https://github.com/dotnet/roslyn/blob/master/docs/features/nullable-reference-types.md [Trait("NRT", "Nullable Reference Types")] public class NullableTests : ApiGeneratorTestsBase { [Fact] public void Should_Annotate_ReturnType() { AssertPublicApi<ReturnType>( @"namespace PublicApiGeneratorTests.Examples { public class ReturnType { public ReturnType() { } public string? ReturnProperty { get; set; } } }"); } [Fact] public void Should_Annotate_VoidReturn() { AssertPublicApi(typeof(VoidReturn), @"namespace PublicApiGeneratorTests.Examples { public static class VoidReturn { public static void ShouldBeEquivalentTo(this object? actual, object? expected) { } } }"); } [Fact] public void Should_Annotate_Derived_ReturnType() { AssertPublicApi<ReturnArgs>( @"namespace PublicApiGeneratorTests.Examples { public class ReturnArgs : System.EventArgs { public ReturnArgs() { } public string? Target { get; set; } } }"); } [Fact] public void Should_Annotate_Ctor_Args() { AssertPublicApi<NullableCtor>( @"namespace PublicApiGeneratorTests.Examples { public class NullableCtor { public NullableCtor(string? nullableLabel, string nope) { } } }"); } [Fact] public void Should_Not_Annotate_Obsolete_Attribute() { AssertPublicApi<ClassWithObsolete>( @"namespace PublicApiGeneratorTests.Examples { [System.Obsolete(""Foo"")] public class ClassWithObsolete { [System.Obsolete(""Bar"")] public ClassWithObsolete(string? nullableLabel) { } [System.Obsolete(""Bar"")] public ClassWithObsolete(string? nullableLabel, string? nullableLabel2) { } } }"); } [Fact] public void Should_Annotate_Generic_Event() { AssertPublicApi<GenericEvent>( @"namespace PublicApiGeneratorTests.Examples { public class GenericEvent { public GenericEvent() { } public event System.EventHandler<PublicApiGeneratorTests.Examples.ReturnArgs?> ReturnEvent; } }"); } [Fact] public void Should_Annotate_Delegate_Declaration() { AssertPublicApi<DelegateDeclaration>( @"namespace PublicApiGeneratorTests.Examples { public class DelegateDeclaration { public DelegateDeclaration() { } public delegate string? OnNullableReturn(object sender, PublicApiGeneratorTests.Examples.ReturnArgs? args); public delegate string OnReturn(object sender, PublicApiGeneratorTests.Examples.ReturnArgs? args); } }"); } [Fact] public void Should_Annotate_Nullable_Array() { AssertPublicApi<NullableArray>( @"namespace PublicApiGeneratorTests.Examples { public class NullableArray { public NullableArray() { } public PublicApiGeneratorTests.Examples.ReturnType[]? NullableMethod1() { } public PublicApiGeneratorTests.Examples.ReturnType[]?[]? NullableMethod2() { } } }"); } [Fact] public void Should_Annotate_Nullable_Enumerable() { AssertPublicApi<NullableEnumerable>( @"namespace PublicApiGeneratorTests.Examples { public class NullableEnumerable { public NullableEnumerable() { } public System.Collections.Generic.IEnumerable<PublicApiGeneratorTests.Examples.ReturnType?>? Enumerable() { } } }"); } [Fact] public void Should_Annotate_Generic_Method() { AssertPublicApi<GenericMethod>( @"namespace PublicApiGeneratorTests.Examples { public class GenericMethod { public GenericMethod() { } public PublicApiGeneratorTests.Examples.ReturnType? NullableGenericMethod<T1, T2, T3>(T1? t1, T2 t2, T3? t3) where T1 : class where T2 : class where T3 : class { } } }"); } [Fact] public void Should_Annotate_Skeet_Examples() { AssertPublicApi<SkeetExamplesClass>( @"namespace PublicApiGeneratorTests.Examples { public class SkeetExamplesClass { public System.Collections.Generic.Dictionary<System.Collections.Generic.List<string?>, string[]?> SkeetExample; public System.Collections.Generic.Dictionary<System.Collections.Generic.List<string?>, string?[]> SkeetExample2; public System.Collections.Generic.Dictionary<System.Collections.Generic.List<string?>, string?[]?> SkeetExample3; public SkeetExamplesClass() { } } }"); } [Fact] public void Should_Annotate_By_Ref() { AssertPublicApi<ByRefClass>( @"namespace PublicApiGeneratorTests.Examples { public class ByRefClass { public ByRefClass() { } public bool ByRefNullableReferenceParam(PublicApiGeneratorTests.Examples.ReturnType rt1, ref PublicApiGeneratorTests.Examples.ReturnType? rt2, PublicApiGeneratorTests.Examples.ReturnType rt3, PublicApiGeneratorTests.Examples.ReturnType? rt4, out PublicApiGeneratorTests.Examples.ReturnType? rt5, PublicApiGeneratorTests.Examples.ReturnType rt6) { } } }"); } [Fact] public void Should_Annotate_Different_API() { AssertPublicApi<NullableApi>( @"namespace PublicApiGeneratorTests.Examples { public class NullableApi { public PublicApiGeneratorTests.Examples.ReturnType NonNullField; public PublicApiGeneratorTests.Examples.ReturnType? NullableField; public NullableApi() { } public System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<int, int?>?>>? ComplicatedDictionary { get; set; } public PublicApiGeneratorTests.Examples.ReturnType NonNullProperty { get; set; } public PublicApiGeneratorTests.Examples.ReturnType? NullableProperty { get; set; } public string? Convert(string source) { } public override bool Equals(object? obj) { } public override int GetHashCode() { } public PublicApiGeneratorTests.Examples.ReturnType? NullableParamAndReturnMethod(string? nullableParam, string nonNullParam, int? nullableValueType) { } public PublicApiGeneratorTests.Examples.ReturnType NullableParamMethod(string? nullableParam, string nonNullParam, int? nullableValueType) { } public PublicApiGeneratorTests.Examples.Data<string> NullableStruct1(PublicApiGeneratorTests.Examples.Data<string> param) { } public PublicApiGeneratorTests.Examples.Data<string>? NullableStruct2(PublicApiGeneratorTests.Examples.Data<string>? param) { } public PublicApiGeneratorTests.Examples.Data<System.Collections.Generic.KeyValuePair<string, string?>> NullableStruct3(PublicApiGeneratorTests.Examples.Data<System.Collections.Generic.KeyValuePair<string, string?>> param) { } public PublicApiGeneratorTests.Examples.Data<System.Collections.Generic.KeyValuePair<string, string?>?> NullableStruct4(PublicApiGeneratorTests.Examples.Data<System.Collections.Generic.KeyValuePair<string, string?>?> param) { } public PublicApiGeneratorTests.Examples.Data<System.Collections.Generic.KeyValuePair<string, string?>?>? NullableStruct5(PublicApiGeneratorTests.Examples.Data<System.Collections.Generic.KeyValuePair<string, string?>?>? param) { } } }"); } [Fact] public void Should_Annotate_System_Nullable() { AssertPublicApi<SystemNullable>( @"namespace PublicApiGeneratorTests.Examples { public class SystemNullable { public readonly int? Age; public SystemNullable() { } public System.DateTime? Birth { get; set; } public float? Calc(double? first, decimal? second) { } public System.Collections.Generic.List<System.Guid?> GetSecrets(System.Collections.Generic.Dictionary<int?, System.Collections.Generic.Dictionary<bool?, byte?>> data) { } } }"); } [Fact] public void Should_Annotate_Generics() { AssertPublicApi<Generics>( @"namespace PublicApiGeneratorTests.Examples { public class Generics { public Generics() { } public System.Collections.Generic.List<string?> GetSecretData0() { } public System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<int?>> GetSecretData1() { } public System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<int?>?> GetSecretData2() { } public System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string?, System.Collections.Generic.List<int>?>>> GetSecretData3(System.Collections.Generic.Dictionary<int?, System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.List<int?>>>>? value) { } public System.Collections.Generic.Dictionary<int?, string>? GetSecretData4(System.Collections.Generic.Dictionary<int?, string>? value) { } } }"); } [Fact] public void Should_Annotate_Structs() { AssertPublicApi<Structs>( @"namespace PublicApiGeneratorTests.Examples { public class Structs { public System.Collections.Generic.KeyValuePair<string?, int?> field; public Structs() { } } }"); } [Fact] public void Should_Annotate_Tuples() { AssertPublicApi<Tuples>( @"namespace PublicApiGeneratorTests.Examples { public class Tuples { public Tuples() { } public System.Tuple<string, string?, int, int?> Tuple1(System.Tuple<string, string?, int, int?>? tuple) { } public System.ValueTuple<string, string?, int, int?> Tuple2(System.ValueTuple<string, string?, int, int?>? tuple) { } } }"); } [Fact] public void Should_Annotate_Constraints() { AssertPublicApi<Constraints>( @"namespace PublicApiGeneratorTests.Examples { public class Constraints { public Constraints() { } public void Print1<T>(T val) where T : class { } public void Print2<T>(T val) where T : class? { } public static void Print3<T>() where T : System.IO.Stream { } public static void Print4<T>() where T : System.IDisposable { } } }"); } [Fact] public void Should_Annotate_Nullable_Constraints() { AssertPublicApi(typeof(Constraints2<,>), @"namespace PublicApiGeneratorTests.Examples { public class Constraints2<X, Y> where X : System.IComparable<X> where Y : class? { public Constraints2() { } public T Convert<T>(T data) where T : System.IComparable<string?> { } public static void Print1<T>() where T : System.IO.Stream? { } public static void Print2<T>() where T : System.IDisposable? { } } }"); } [Fact] public void Should_Annotate_BaseType() { AssertPublicApi<NullableComparable>( @"namespace PublicApiGeneratorTests.Examples { public class NullableComparable : System.Collections.Generic.List<string?>, System.IComparable<string?> { public NullableComparable() { } public int CompareTo(string? other) { } } }"); } [Fact] public void Should_Annotate_OpenGeneric() { AssertPublicApi(typeof(StringNullableList<,>), @"namespace PublicApiGeneratorTests.Examples { public class StringNullableList<T, U> : System.Collections.Generic.List<T?>, System.IComparable<U> where T : struct where U : class { public StringNullableList() { } public int CompareTo(U other) { } } }"); } [Fact] public void Should_Annotate_NotNull_Constraint() { AssertPublicApi(typeof(IDoStuff1<,>), @"namespace PublicApiGeneratorTests.Examples { public interface IDoStuff1<TIn, TOut> where TIn : notnull where TOut : notnull { TOut DoStuff(TIn input); } }"); } [Fact] public void Should_Annotate_NotNull_And_Null_Constraint() { AssertPublicApi(typeof(IDoStuff2<,>), @"namespace PublicApiGeneratorTests.Examples { public interface IDoStuff2<TIn, TOut> where TIn : class? where TOut : notnull { TOut DoStuff(TIn input); } }"); } [Fact] public void Should_Annotate_Without_Explicit_Constraints() { AssertPublicApi(typeof(IDoStuff3<,>), @"namespace PublicApiGeneratorTests.Examples { public interface IDoStuff3<TIn, TOut> { TOut DoStuff(TIn input); } }"); } [Fact] public void Should_Annotate_NotNull_And_Null_Class_Constraint() { AssertPublicApi(typeof(IDoStuff4<,>), @"namespace PublicApiGeneratorTests.Examples { public interface IDoStuff4<TIn, TOut> where TIn : class? where TOut : class { TOut DoStuff(TIn input); } }"); } [Fact] public void Should_Annotate_Nullable_Class_And_Struct_Constraint() { AssertPublicApi(typeof(IDoStuff5<,>), @"namespace PublicApiGeneratorTests.Examples { public interface IDoStuff5<TIn, TOut> where TIn : class? where TOut : struct { TOut DoStuff(TIn input); } }"); } [Fact] public void Should_Annotate_Unmanaged_Constraint() { AssertPublicApi(typeof(IDoStuff6<,>), @"namespace PublicApiGeneratorTests.Examples { public interface IDoStuff6<TIn, TOut> where TIn : notnull where TOut : unmanaged { TOut DoStuff(TIn input); } }"); } } // ReSharper disable ClassNeverInstantiated.Global namespace Examples { public class ReturnType { public string? ReturnProperty { get; set; } } public static class VoidReturn { public static void ShouldBeEquivalentTo(this object? actual, object? expected) { } } public class ReturnArgs : EventArgs { public string? Target { get; set; } } public class NullableCtor { public NullableCtor(string? nullableLabel, string nope) { } } [Obsolete("Foo")] public class ClassWithObsolete { [Obsolete("Bar")] public ClassWithObsolete(string? nullableLabel) { } [Obsolete("Bar")] public ClassWithObsolete(string? nullableLabel, string? nullableLabel2) { } } public class GenericEvent { public event EventHandler<ReturnArgs?> ReturnEvent { add { } remove { } } } public class DelegateDeclaration { protected delegate string OnReturn(object sender, ReturnArgs? args); protected delegate string? OnNullableReturn(object sender, ReturnArgs? args); } public class Structs { public KeyValuePair<string?, int?> field; } public struct Data<T> { public T Value { get; } } public class Generics { public List<string?> GetSecretData0() => null; public Dictionary<int, List<int?>> GetSecretData1() => null; public Dictionary<int, List<int?>?> GetSecretData2() => null; public Dictionary<int, List<KeyValuePair<string?, List<int>?>>> GetSecretData3(Dictionary<int?, List<KeyValuePair<string, List<int?>>>>? value) { return null; } public Dictionary<int?, string>? GetSecretData4(Dictionary<int?, string>? value) { return null; } } public class NullableArray { public ReturnType[]? NullableMethod1() { return null; } public ReturnType[]?[]? NullableMethod2() { return null; } } public class NullableEnumerable { public IEnumerable<ReturnType?>? Enumerable() { return null; } } public class GenericMethod { public ReturnType? NullableGenericMethod<T1, T2, T3>(T1? t1, T2 t2, T3? t3) where T1 : class where T2 : class where T3 : class { return null; } } public class SkeetExamplesClass { public Dictionary<List<string?>, string[]?> SkeetExample = new Dictionary<List<string?>, string[]?>(); public Dictionary<List<string?>, string?[]> SkeetExample2 = new Dictionary<List<string?>, string?[]>(); public Dictionary<List<string?>, string?[]?> SkeetExample3 = new Dictionary<List<string?>, string?[]?>(); } public class ByRefClass { public bool ByRefNullableReferenceParam(ReturnType rt1, ref ReturnType? rt2, ReturnType rt3, ReturnType? rt4, out ReturnType? rt5, ReturnType rt6) { rt5 = null; return false; } } public class NullableApi { public ReturnType NonNullField = new ReturnType(); public ReturnType? NullableField; public ReturnType NonNullProperty { get; protected set; } = new ReturnType(); public ReturnType? NullableProperty { get; set; } public ReturnType NullableParamMethod(string? nullableParam, string nonNullParam, int? nullableValueType) { return new ReturnType(); } public ReturnType? NullableParamAndReturnMethod(string? nullableParam, string nonNullParam, int? nullableValueType) { return default; } public Dictionary<string, Dictionary<string, Dictionary<int, int?>?>>? ComplicatedDictionary { get; set; } public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); public string? Convert(string source) => source; public Data<string> NullableStruct1(Data<string> param) => default; public Data<string>? NullableStruct2(Data<string>? param) => default; public Data<KeyValuePair<string, string?>> NullableStruct3(Data<KeyValuePair<string, string?>> param) => default; public Data<KeyValuePair<string, string?>?> NullableStruct4(Data<KeyValuePair<string, string?>?> param) => default; public Data<KeyValuePair<string, string?>?>? NullableStruct5(Data<KeyValuePair<string, string?>?>? param) => default; } public class SystemNullable { public readonly int? Age; public DateTime? Birth { get; set; } public float? Calc(double? first, decimal? second) { return null; } public List<Guid?> GetSecrets(Dictionary<int?, Dictionary<bool?, byte?>> data) => null; } public class Tuples { public Tuple<string, string?, int, int?> Tuple1(Tuple<string, string?, int, int?>? tuple) => default; public ValueTuple<string, string?, int, int?> Tuple2(ValueTuple<string, string?, int, int?>? tuple) => default; } public class Constraints { public void Print1<T>(T val) where T : class { val.ToString(); } public void Print2<T>(T val) where T : class? { if (val != null) val.ToString(); } public static void Print3<T>() where T : Stream { } public static void Print4<T>() where T : IDisposable { } } public class Constraints2<X, Y> where X: IComparable<X> where Y : class? { public T Convert<T>(T data) where T : IComparable<string?> => default; public static void Print1<T>() where T : Stream? { } public static void Print2<T>() where T : IDisposable? { } } public class NullableComparable : List<string?>, IComparable<string?> { public int CompareTo(string? other) { throw new NotImplementedException(); } } public class StringNullableList<T,U> : List<T?>, IComparable<U> where T : struct where U : class { public int CompareTo(U other) => 0; } public interface IDoStuff1<TIn, TOut> where TIn : notnull where TOut : notnull { TOut DoStuff(TIn input); } public interface IDoStuff2<TIn, TOut> where TIn : class? where TOut : notnull { TOut DoStuff(TIn input); } public interface IDoStuff3<TIn, TOut> { TOut DoStuff(TIn input); } public interface IDoStuff4<TIn, TOut> where TIn : class? where TOut : class { TOut DoStuff(TIn input); } public interface IDoStuff5<TIn, TOut> where TIn : class? where TOut : struct { TOut DoStuff(TIn input); } public interface IDoStuff6<TIn, TOut> where TIn : notnull where TOut : unmanaged { TOut DoStuff(TIn input); } } // ReSharper restore ClassNeverInstantiated.Global // ReSharper restore UnusedMember.Global }
using System; using System.Diagnostics; using System.Linq; using System.IO; using System.Reflection; using System.Security.Cryptography; using NetSparkleUpdater.Enums; using NetSparkleUpdater.Interfaces; namespace NetSparkleUpdater.SignatureVerifiers { /// <summary> /// Class that allows you to verify a DSA signature of /// some text, a file, or some other item based on a /// DSA public key /// </summary> public class DSAChecker : ISignatureVerifier { private DSACryptoServiceProvider _cryptoProvider; /// <inheritdoc/> public bool HasValidKeyInformation() { return _cryptoProvider != null; } /// <summary> /// Create a DSAChecker object from the given parameters /// </summary> /// <param name="mode">The <see cref="SecurityMode"/> of the validator. Controls what needs to be set in order to validate /// an app cast and its items.</param> /// <param name="publicKey">the DSA public key as a string (will be used instead of the file if available, non-null, and not blank)</param> /// <param name="publicKeyFile">the public key file name (including extension)</param> public DSAChecker(SecurityMode mode, string publicKey = null, string publicKeyFile = "NetSparkle_DSA.pub") { SecurityMode = mode; string key = publicKey; if (string.IsNullOrEmpty(key)) { Stream data = TryGetResourceStream(publicKeyFile); if (data == null) { data = TryGetFileResource(publicKeyFile); } if (data != null) { using (StreamReader reader = new StreamReader(data)) { key = reader.ReadToEnd(); } } } if (!string.IsNullOrEmpty(key)) { try { _cryptoProvider = new DSACryptoServiceProvider(); _cryptoProvider.FromXmlString(key); } catch { _cryptoProvider = null; } } } /// <inheritdoc/> public SecurityMode SecurityMode { get; set; } private bool CheckSecurityMode(string signature, ref ValidationResult result) { var hasValidKeyInformation = HasValidKeyInformation(); var isSignatureValid = !string.IsNullOrWhiteSpace(signature); switch (SecurityMode) { case SecurityMode.UseIfPossible: // if we have a DSA key, we only accept non-null signatures if (hasValidKeyInformation && !isSignatureValid) { result = ValidationResult.Invalid; return false; } // if we don't have an dsa key, we accept any signature if (!hasValidKeyInformation) { result = ValidationResult.Unchecked; return false; } break; case SecurityMode.Strict: // only accept if we have both a public key and a non-null signature if (!hasValidKeyInformation || !isSignatureValid) { result = ValidationResult.Invalid; return false; } break; case SecurityMode.Unsafe: // always accept anything // If we don't have a signature, make sure to note this as "Unchecked" since we // didn't end up checking anything due to a lack of public key/signature if (!hasValidKeyInformation || !isSignatureValid) { result = ValidationResult.Unchecked; return false; } break; case SecurityMode.OnlyVerifySoftwareDownloads: // If we don't have a signature, make sure to note this as "Unchecked" since we // didn't end up checking anything due to a lack of public key/signature if (!hasValidKeyInformation || !isSignatureValid) { result = ValidationResult.Unchecked; return false; } break; } return true; } /// <inheritdoc/> public ValidationResult VerifySignature(string signature, byte[] dataToVerify) { ValidationResult res = ValidationResult.Invalid; if (!CheckSecurityMode(signature, ref res)) { return res; } // convert signature byte[] bHash = Convert.FromBase64String(signature); // verify return _cryptoProvider.VerifyData(dataToVerify, bHash) ? ValidationResult.Valid : ValidationResult.Invalid; } /// <inheritdoc/> public ValidationResult VerifySignatureOfFile(string signature, string binaryPath) { using (Stream inputStream = File.OpenRead(binaryPath)) { return VerifySignature(signature, Utilities.ConvertStreamToByteArray(inputStream)); } } /// <inheritdoc/> public ValidationResult VerifySignatureOfString(string signature, string data) { // creating stream from string using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { writer.Write(data); writer.Flush(); stream.Position = 0; return VerifySignature(signature, Utilities.ConvertStreamToByteArray(stream)); } } /// <summary> /// Gets a file resource based on a public key at a given path /// </summary> /// <param name="publicKey">the file name of the public key</param> /// <returns>the data stream of the file resource if the file exists; null otherwise</returns> private static Stream TryGetFileResource(string publicKey) { Stream data = null; if (File.Exists(publicKey)) { data = File.OpenRead(publicKey); } return data; } /// <summary> /// Get a resource stream based on the public key /// </summary> /// <param name="publicKey">the public key resource name</param> /// <returns>a stream that contains the public key if found; null otherwise</returns> private static Stream TryGetResourceStream(string publicKey) { Stream data = null; foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { string[] resources; try { resources = asm.GetManifestResourceNames(); } catch (NotSupportedException) { continue; } var resourceName = resources.FirstOrDefault(s => s.IndexOf(publicKey, StringComparison.OrdinalIgnoreCase) > -1); if (!string.IsNullOrEmpty(resourceName)) { data = asm.GetManifestResourceStream(resourceName); if (data != null) { break; } } } return data; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookTableRequest. /// </summary> public partial class WorkbookTableRequest : BaseRequest, IWorkbookTableRequest { /// <summary> /// Constructs a new WorkbookTableRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookTableRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookTable using POST. /// </summary> /// <param name="workbookTableToCreate">The WorkbookTable to create.</param> /// <returns>The created WorkbookTable.</returns> public System.Threading.Tasks.Task<WorkbookTable> CreateAsync(WorkbookTable workbookTableToCreate) { return this.CreateAsync(workbookTableToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookTable using POST. /// </summary> /// <param name="workbookTableToCreate">The WorkbookTable to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookTable.</returns> public async System.Threading.Tasks.Task<WorkbookTable> CreateAsync(WorkbookTable workbookTableToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookTable>(workbookTableToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookTable. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookTable. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookTable>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookTable. /// </summary> /// <returns>The WorkbookTable.</returns> public System.Threading.Tasks.Task<WorkbookTable> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookTable. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookTable.</returns> public async System.Threading.Tasks.Task<WorkbookTable> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookTable>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookTable using PATCH. /// </summary> /// <param name="workbookTableToUpdate">The WorkbookTable to update.</param> /// <returns>The updated WorkbookTable.</returns> public System.Threading.Tasks.Task<WorkbookTable> UpdateAsync(WorkbookTable workbookTableToUpdate) { return this.UpdateAsync(workbookTableToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookTable using PATCH. /// </summary> /// <param name="workbookTableToUpdate">The WorkbookTable to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookTable.</returns> public async System.Threading.Tasks.Task<WorkbookTable> UpdateAsync(WorkbookTable workbookTableToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookTable>(workbookTableToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableRequest Expand(Expression<Func<WorkbookTable, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableRequest Select(Expression<Func<WorkbookTable, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookTableToInitialize">The <see cref="WorkbookTable"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookTable workbookTableToInitialize) { if (workbookTableToInitialize != null && workbookTableToInitialize.AdditionalData != null) { if (workbookTableToInitialize.Columns != null && workbookTableToInitialize.Columns.CurrentPage != null) { workbookTableToInitialize.Columns.AdditionalData = workbookTableToInitialize.AdditionalData; object nextPageLink; workbookTableToInitialize.AdditionalData.TryGetValue("columns@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { workbookTableToInitialize.Columns.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (workbookTableToInitialize.Rows != null && workbookTableToInitialize.Rows.CurrentPage != null) { workbookTableToInitialize.Rows.AdditionalData = workbookTableToInitialize.AdditionalData; object nextPageLink; workbookTableToInitialize.AdditionalData.TryGetValue("rows@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { workbookTableToInitialize.Rows.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Globalization; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Dom; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Core.Handlers; using TheArtOfDev.HtmlRenderer.Core.Utils; namespace TheArtOfDev.HtmlRenderer.Core.Parse { /// <summary> /// Handle css DOM tree generation from raw html and stylesheet. /// </summary> internal sealed class DomParser { #region Fields and Consts /// <summary> /// Parser for CSS /// </summary> private readonly CssParser _cssParser; #endregion /// <summary> /// Init. /// </summary> public DomParser(CssParser cssParser) { ArgChecker.AssertArgNotNull(cssParser, "cssParser"); _cssParser = cssParser; } /// <summary> /// Generate css tree by parsing the given html and applying the given css style data on it. /// </summary> /// <param name="html">the html to parse</param> /// <param name="htmlContainer">the html container to use for reference resolve</param> /// <param name="cssData">the css data to use</param> /// <returns>the root of the generated tree</returns> public CssBox GenerateCssTree(string html, HtmlContainerInt htmlContainer, ref CssData cssData) { var root = HtmlParser.ParseDocument(html); if (root != null) { root.HtmlContainer = htmlContainer; bool cssDataChanged = false; CascadeParseStyles(root, htmlContainer, ref cssData, ref cssDataChanged); CascadeApplyStyles(root, cssData); SetTextSelectionStyle(htmlContainer, cssData); CorrectTextBoxes(root); CorrectImgBoxes(root); bool followingBlock = true; CorrectLineBreaksBlocks(root, ref followingBlock); CorrectInlineBoxesParent(root); CorrectBlockInsideInline(root); CorrectInlineBoxesParent(root); } return root; } #region Private methods /// <summary> /// Read styles defined inside the dom structure in links and style elements.<br/> /// If the html tag is "style" tag parse it content and add to the css data for all future tags parsing.<br/> /// If the html tag is "link" that point to style data parse it content and add to the css data for all future tags parsing.<br/> /// </summary> /// <param name="box">the box to parse style data in</param> /// <param name="htmlContainer">the html container to use for reference resolve</param> /// <param name="cssData">the style data to fill with found styles</param> /// <param name="cssDataChanged">check if the css data has been modified by the handled html not to change the base css data</param> private void CascadeParseStyles(CssBox box, HtmlContainerInt htmlContainer, ref CssData cssData, ref bool cssDataChanged) { if (box.HtmlTag != null) { // Check for the <link rel=stylesheet> tag if (box.HtmlTag.Name.Equals("link", StringComparison.CurrentCultureIgnoreCase) && box.GetAttribute("rel", string.Empty).Equals("stylesheet", StringComparison.CurrentCultureIgnoreCase)) { CloneCssData(ref cssData, ref cssDataChanged); string stylesheet; CssData stylesheetData; StylesheetLoadHandler.LoadStylesheet(htmlContainer, box.GetAttribute("href", string.Empty), box.HtmlTag.Attributes, out stylesheet, out stylesheetData); if (stylesheet != null) _cssParser.ParseStyleSheet(cssData, stylesheet); else if (stylesheetData != null) cssData.Combine(stylesheetData); } // Check for the <style> tag if (box.HtmlTag.Name.Equals("style", StringComparison.CurrentCultureIgnoreCase) && box.Boxes.Count > 0) { CloneCssData(ref cssData, ref cssDataChanged); foreach (var child in box.Boxes) _cssParser.ParseStyleSheet(cssData, child.Text.CutSubstring()); } } foreach (var childBox in box.Boxes) { CascadeParseStyles(childBox, htmlContainer, ref cssData, ref cssDataChanged); } } /// <summary> /// Applies style to all boxes in the tree.<br/> /// If the html tag has style defined for each apply that style to the css box of the tag.<br/> /// If the html tag has "class" attribute and the class name has style defined apply that style on the tag css box.<br/> /// If the html tag has "style" attribute parse it and apply the parsed style on the tag css box.<br/> /// </summary> /// <param name="box">the box to apply the style to</param> /// <param name="cssData">the style data for the html</param> private void CascadeApplyStyles(CssBox box, CssData cssData) { box.InheritStyle(); if (box.HtmlTag != null) { // try assign style using all wildcard AssignCssBlocks(box, cssData, "*"); // try assign style using the html element tag AssignCssBlocks(box, cssData, box.HtmlTag.Name); // try assign style using the "class" attribute of the html element if (box.HtmlTag.HasAttribute("class")) { AssignClassCssBlocks(box, cssData); } // try assign style using the "id" attribute of the html element if (box.HtmlTag.HasAttribute("id")) { var id = box.HtmlTag.TryGetAttribute("id"); AssignCssBlocks(box, cssData, "#" + id); } TranslateAttributes(box.HtmlTag, box); // Check for the style="" attribute if (box.HtmlTag.HasAttribute("style")) { var block = _cssParser.ParseCssBlock(box.HtmlTag.Name, box.HtmlTag.TryGetAttribute("style")); if (block != null) AssignCssBlock(box, block); } } // cascade text decoration only to boxes that actually have text so it will be handled correctly. if (box.TextDecoration != String.Empty && box.Text == null) { foreach (var childBox in box.Boxes) childBox.TextDecoration = box.TextDecoration; box.TextDecoration = string.Empty; } foreach (var childBox in box.Boxes) { CascadeApplyStyles(childBox, cssData); } } /// <summary> /// Set the selected text style (selection text color and background color). /// </summary> /// <param name="htmlContainer"> </param> /// <param name="cssData">the style data</param> private void SetTextSelectionStyle(HtmlContainerInt htmlContainer, CssData cssData) { htmlContainer.SelectionForeColor = RColor.Empty; htmlContainer.SelectionBackColor = RColor.Empty; if (cssData.ContainsCssBlock("::selection")) { var blocks = cssData.GetCssBlock("::selection"); foreach (var block in blocks) { if (block.Properties.ContainsKey("color")) htmlContainer.SelectionForeColor = _cssParser.ParseColor(block.Properties["color"]); if (block.Properties.ContainsKey("background-color")) htmlContainer.SelectionBackColor = _cssParser.ParseColor(block.Properties["background-color"]); } } } /// <summary> /// Assigns the given css classes to the given css box checking if matching.<br/> /// Support multiple classes in single attribute separated by whitespace. /// </summary> /// <param name="box">the css box to assign css to</param> /// <param name="cssData">the css data to use to get the matching css blocks</param> private static void AssignClassCssBlocks(CssBox box, CssData cssData) { var classes = box.HtmlTag.TryGetAttribute("class"); var startIdx = 0; while (startIdx < classes.Length) { while (startIdx < classes.Length && classes[startIdx] == ' ') startIdx++; if (startIdx < classes.Length) { var endIdx = classes.IndexOf(' ', startIdx); if (endIdx < 0) endIdx = classes.Length; var cls = "." + classes.Substring(startIdx, endIdx - startIdx); AssignCssBlocks(box, cssData, cls); AssignCssBlocks(box, cssData, box.HtmlTag.Name + cls); startIdx = endIdx + 1; } } } /// <summary> /// Assigns the given css style blocks to the given css box checking if matching. /// </summary> /// <param name="box">the css box to assign css to</param> /// <param name="cssData">the css data to use to get the matching css blocks</param> /// <param name="className">the class selector to search for css blocks</param> private static void AssignCssBlocks(CssBox box, CssData cssData, string className) { var blocks = cssData.GetCssBlock(className); foreach (var block in blocks) { if (IsBlockAssignableToBox(box, block)) { AssignCssBlock(box, block); } } } /// <summary> /// Check if the given css block is assignable to the given css box.<br/> /// the block is assignable if it has no hierarchical selectors or if the hierarchy matches.<br/> /// Special handling for ":hover" pseudo-class.<br/> /// </summary> /// <param name="box">the box to check assign to</param> /// <param name="block">the block to check assign of</param> /// <returns>true - the block is assignable to the box, false - otherwise</returns> private static bool IsBlockAssignableToBox(CssBox box, CssBlock block) { bool assignable = true; if (block.Selectors != null) { assignable = IsBlockAssignableToBoxWithSelector(box, block); } else if (box.HtmlTag.Name.Equals("a", StringComparison.OrdinalIgnoreCase) && block.Class.Equals("a", StringComparison.OrdinalIgnoreCase) && !box.HtmlTag.HasAttribute("href")) { assignable = false; } if (assignable && block.Hover) { box.HtmlContainer.AddHoverBox(box, block); assignable = false; } return assignable; } /// <summary> /// Check if the given css block is assignable to the given css box by validating the selector.<br/> /// </summary> /// <param name="box">the box to check assign to</param> /// <param name="block">the block to check assign of</param> /// <returns>true - the block is assignable to the box, false - otherwise</returns> private static bool IsBlockAssignableToBoxWithSelector(CssBox box, CssBlock block) { foreach (var selector in block.Selectors) { bool matched = false; while (!matched) { box = box.ParentBox; while (box != null && box.HtmlTag == null) box = box.ParentBox; if (box == null) return false; if (box.HtmlTag.Name.Equals(selector.Class, StringComparison.InvariantCultureIgnoreCase)) matched = true; if (!matched && box.HtmlTag.HasAttribute("class")) { var className = box.HtmlTag.TryGetAttribute("class"); if (selector.Class.Equals("." + className, StringComparison.InvariantCultureIgnoreCase) || selector.Class.Equals(box.HtmlTag.Name + "." + className, StringComparison.InvariantCultureIgnoreCase)) matched = true; } if (!matched && box.HtmlTag.HasAttribute("id")) { var id = box.HtmlTag.TryGetAttribute("id"); if (selector.Class.Equals("#" + id, StringComparison.InvariantCultureIgnoreCase)) matched = true; } if (!matched && selector.DirectParent) return false; } } return true; } /// <summary> /// Assigns the given css style block properties to the given css box. /// </summary> /// <param name="box">the css box to assign css to</param> /// <param name="block">the css block to assign</param> private static void AssignCssBlock(CssBox box, CssBlock block) { foreach (var prop in block.Properties) { var value = prop.Value; if (prop.Value == CssConstants.Inherit && box.ParentBox != null) { value = CssUtils.GetPropertyValue(box.ParentBox, prop.Key); } if (IsStyleOnElementAllowed(box, prop.Key, value)) { CssUtils.SetPropertyValue(box, prop.Key, value); } } } /// <summary> /// Check if the given style is allowed to be set on the given css box.<br/> /// Used to prevent invalid CssBoxes creation like table with inline display style. /// </summary> /// <param name="box">the css box to assign css to</param> /// <param name="key">the style key to cehck</param> /// <param name="value">the style value to check</param> /// <returns>true - style allowed, false - not allowed</returns> private static bool IsStyleOnElementAllowed(CssBox box, string key, string value) { if (box.HtmlTag != null && key == HtmlConstants.Display) { switch (box.HtmlTag.Name) { case HtmlConstants.Table: return value == CssConstants.Table; case HtmlConstants.Tr: return value == CssConstants.TableRow; case HtmlConstants.Tbody: return value == CssConstants.TableRowGroup; case HtmlConstants.Thead: return value == CssConstants.TableHeaderGroup; case HtmlConstants.Tfoot: return value == CssConstants.TableFooterGroup; case HtmlConstants.Col: return value == CssConstants.TableColumn; case HtmlConstants.Colgroup: return value == CssConstants.TableColumnGroup; case HtmlConstants.Td: case HtmlConstants.Th: return value == CssConstants.TableCell; case HtmlConstants.Caption: return value == CssConstants.TableCaption; } } return true; } /// <summary> /// Clone css data if it has not already been cloned.<br/> /// Used to preserve the base css data used when changed by style inside html. /// </summary> private static void CloneCssData(ref CssData cssData, ref bool cssDataChanged) { if (!cssDataChanged) { cssDataChanged = true; cssData = cssData.Clone(); } } /// <summary> /// /// </summary> /// <param name="tag"></param> /// <param name="box"></param> private void TranslateAttributes(HtmlTag tag, CssBox box) { if (tag.HasAttributes()) { foreach (string att in tag.Attributes.Keys) { string value = tag.Attributes[att]; switch (att) { case HtmlConstants.Align: if (value == HtmlConstants.Left || value == HtmlConstants.Center || value == HtmlConstants.Right || value == HtmlConstants.Justify) box.TextAlign = value.ToLower(); else box.VerticalAlign = value.ToLower(); break; case HtmlConstants.Background: box.BackgroundImage = value.ToLower(); break; case HtmlConstants.Bgcolor: box.BackgroundColor = value.ToLower(); break; case HtmlConstants.Border: if (!string.IsNullOrEmpty(value) && value != "0") box.BorderLeftStyle = box.BorderTopStyle = box.BorderRightStyle = box.BorderBottomStyle = CssConstants.Solid; box.BorderLeftWidth = box.BorderTopWidth = box.BorderRightWidth = box.BorderBottomWidth = TranslateLength(value); if (tag.Name == HtmlConstants.Table) { if (value != "0") ApplyTableBorder(box, "1px"); } else { box.BorderTopStyle = box.BorderLeftStyle = box.BorderRightStyle = box.BorderBottomStyle = CssConstants.Solid; } break; case HtmlConstants.Bordercolor: box.BorderLeftColor = box.BorderTopColor = box.BorderRightColor = box.BorderBottomColor = value.ToLower(); break; case HtmlConstants.Cellspacing: box.BorderSpacing = TranslateLength(value); break; case HtmlConstants.Cellpadding: ApplyTablePadding(box, value); break; case HtmlConstants.Color: box.Color = value.ToLower(); break; case HtmlConstants.Dir: box.Direction = value.ToLower(); break; case HtmlConstants.Face: box.FontFamily = _cssParser.ParseFontFamily(value); break; case HtmlConstants.Height: box.Height = TranslateLength(value); break; case HtmlConstants.Hspace: box.MarginRight = box.MarginLeft = TranslateLength(value); break; case HtmlConstants.Nowrap: box.WhiteSpace = CssConstants.NoWrap; break; case HtmlConstants.Size: if (tag.Name.Equals(HtmlConstants.Hr, StringComparison.OrdinalIgnoreCase)) box.Height = TranslateLength(value); else if (tag.Name.Equals(HtmlConstants.Font, StringComparison.OrdinalIgnoreCase)) box.FontSize = value; break; case HtmlConstants.Valign: box.VerticalAlign = value.ToLower(); break; case HtmlConstants.Vspace: box.MarginTop = box.MarginBottom = TranslateLength(value); break; case HtmlConstants.Width: box.Width = TranslateLength(value); break; } } } } /// <summary> /// Converts an HTML length into a Css length /// </summary> /// <param name="htmlLength"></param> /// <returns></returns> private static string TranslateLength(string htmlLength) { CssLength len = new CssLength(htmlLength); if (len.HasError) { return string.Format(NumberFormatInfo.InvariantInfo, "{0}px", htmlLength); } return htmlLength; } /// <summary> /// Cascades to the TD's the border spacified in the TABLE tag. /// </summary> /// <param name="table"></param> /// <param name="border"></param> private static void ApplyTableBorder(CssBox table, string border) { SetForAllCells(table, cell => { cell.BorderLeftStyle = cell.BorderTopStyle = cell.BorderRightStyle = cell.BorderBottomStyle = CssConstants.Solid; cell.BorderLeftWidth = cell.BorderTopWidth = cell.BorderRightWidth = cell.BorderBottomWidth = border; }); } /// <summary> /// Cascades to the TD's the border spacified in the TABLE tag. /// </summary> /// <param name="table"></param> /// <param name="padding"></param> private static void ApplyTablePadding(CssBox table, string padding) { var length = TranslateLength(padding); SetForAllCells(table, cell => cell.PaddingLeft = cell.PaddingTop = cell.PaddingRight = cell.PaddingBottom = length); } /// <summary> /// Execute action on all the "td" cells of the table.<br/> /// Handle if there is "theader" or "tbody" exists. /// </summary> /// <param name="table">the table element</param> /// <param name="action">the action to execute</param> private static void SetForAllCells(CssBox table, ActionInt<CssBox> action) { foreach (var l1 in table.Boxes) { foreach (var l2 in l1.Boxes) { if (l2.HtmlTag != null && l2.HtmlTag.Name == "td") { action(l2); } else { foreach (var l3 in l2.Boxes) { action(l3); } } } } } /// <summary> /// Go over all the text boxes (boxes that have some text that will be rendered) and /// remove all boxes that have only white-spaces but are not 'preformatted' so they do not effect /// the rendered html. /// </summary> /// <param name="box">the current box to correct its sub-tree</param> private static void CorrectTextBoxes(CssBox box) { for (int i = box.Boxes.Count - 1; i >= 0; i--) { var childBox = box.Boxes[i]; if (childBox.Text != null) { // is the box has text var keepBox = !childBox.Text.IsEmptyOrWhitespace(); // is the box is pre-formatted keepBox = keepBox || childBox.WhiteSpace == CssConstants.Pre || childBox.WhiteSpace == CssConstants.PreWrap; // is the box is only one in the parent keepBox = keepBox || box.Boxes.Count == 1; // is it a whitespace between two inline boxes keepBox = keepBox || (i > 0 && i < box.Boxes.Count - 1 && box.Boxes[i - 1].IsInline && box.Boxes[i + 1].IsInline); // is first/last box where is in inline box and it's next/previous box is inline keepBox = keepBox || (i == 0 && box.Boxes.Count > 1 && box.Boxes[1].IsInline && box.IsInline) || (i == box.Boxes.Count - 1 && box.Boxes.Count > 1 && box.Boxes[i - 1].IsInline && box.IsInline); if (keepBox) { // valid text box, parse it to words childBox.ParseToWords(); } else { // remove text box that has no childBox.ParentBox.Boxes.RemoveAt(i); } } else { // recursive CorrectTextBoxes(childBox); } } } /// <summary> /// Go over all image boxes and if its display style is set to block, put it inside another block but set the image to inline. /// </summary> /// <param name="box">the current box to correct its sub-tree</param> private static void CorrectImgBoxes(CssBox box) { for (int i = box.Boxes.Count - 1; i >= 0; i--) { var childBox = box.Boxes[i]; if (childBox is CssBoxImage && childBox.Display == CssConstants.Block) { var block = CssBox.CreateBlock(childBox.ParentBox, null, childBox); childBox.ParentBox = block; childBox.Display = CssConstants.Inline; } else { // recursive CorrectImgBoxes(childBox); } } } /// <summary> /// Correct the DOM tree recursively by replacing "br" html boxes with anonymous blocks that respect br spec.<br/> /// If the "br" tag is after inline box then the anon block will have zero height only acting as newline, /// but if it is after block box then it will have min-height of the font size so it will create empty line. /// </summary> /// <param name="box">the current box to correct its sub-tree</param> /// <param name="followingBlock">used to know if the br is following a box so it should create an empty line or not so it only /// move to a new line</param> private static void CorrectLineBreaksBlocks(CssBox box, ref bool followingBlock) { followingBlock = followingBlock || box.IsBlock; foreach (var childBox in box.Boxes) { CorrectLineBreaksBlocks(childBox, ref followingBlock); followingBlock = childBox.Words.Count == 0 && (followingBlock || childBox.IsBlock); } int lastBr = -1; CssBox brBox; do { brBox = null; for (int i = 0; i < box.Boxes.Count && brBox == null; i++) { if (i > lastBr && box.Boxes[i].IsBrElement) { brBox = box.Boxes[i]; lastBr = i; } else if (box.Boxes[i].Words.Count > 0) { followingBlock = false; } else if (box.Boxes[i].IsBlock) { followingBlock = true; } } if (brBox != null) { brBox.Display = CssConstants.Block; if (followingBlock) brBox.Height = ".95em"; // TODO:a check the height to min-height when it is supported } } while (brBox != null); } /// <summary> /// Correct DOM tree if there is block boxes that are inside inline blocks.<br/> /// Need to rearrange the tree so block box will be only the child of other block box. /// </summary> /// <param name="box">the current box to correct its sub-tree</param> private static void CorrectBlockInsideInline(CssBox box) { try { if (DomUtils.ContainsInlinesOnly(box) && !ContainsInlinesOnlyDeep(box)) { var tempRightBox = CorrectBlockInsideInlineImp(box); while (tempRightBox != null) { // loop on the created temp right box for the fixed box until no more need (optimization remove recursion) CssBox newTempRightBox = null; if (DomUtils.ContainsInlinesOnly(tempRightBox) && !ContainsInlinesOnlyDeep(tempRightBox)) newTempRightBox = CorrectBlockInsideInlineImp(tempRightBox); tempRightBox.ParentBox.SetAllBoxes(tempRightBox); tempRightBox.ParentBox = null; tempRightBox = newTempRightBox; } } if (!DomUtils.ContainsInlinesOnly(box)) { foreach (var childBox in box.Boxes) { CorrectBlockInsideInline(childBox); } } } catch (Exception ex) { box.HtmlContainer.ReportError(HtmlRenderErrorType.HtmlParsing, "Failed in block inside inline box correction", ex); } } /// <summary> /// Rearrange the DOM of the box to have block box with boxes before the inner block box and after. /// </summary> /// <param name="box">the box that has the problem</param> private static CssBox CorrectBlockInsideInlineImp(CssBox box) { if (box.Display == CssConstants.Inline) box.Display = CssConstants.Block; if (box.Boxes.Count > 1 || box.Boxes[0].Boxes.Count > 1) { var leftBlock = CssBox.CreateBlock(box); while (ContainsInlinesOnlyDeep(box.Boxes[0])) box.Boxes[0].ParentBox = leftBlock; leftBlock.SetBeforeBox(box.Boxes[0]); var splitBox = box.Boxes[1]; splitBox.ParentBox = null; CorrectBlockSplitBadBox(box, splitBox, leftBlock); // remove block that did not get any inner elements if (leftBlock.Boxes.Count < 1) leftBlock.ParentBox = null; int minBoxes = leftBlock.ParentBox != null ? 2 : 1; if (box.Boxes.Count > minBoxes) { // create temp box to handle the tail elements and then get them back so no deep hierarchy is created var tempRightBox = CssBox.CreateBox(box, null, box.Boxes[minBoxes]); while (box.Boxes.Count > minBoxes + 1) box.Boxes[minBoxes + 1].ParentBox = tempRightBox; return tempRightBox; } } else if (box.Boxes[0].Display == CssConstants.Inline) { box.Boxes[0].Display = CssConstants.Block; } return null; } /// <summary> /// Split bad box that has inline and block boxes into two parts, the left - before the block box /// and right - after the block box. /// </summary> /// <param name="parentBox">the parent box that has the problem</param> /// <param name="badBox">the box to split into different boxes</param> /// <param name="leftBlock">the left block box that is created for the split</param> private static void CorrectBlockSplitBadBox(CssBox parentBox, CssBox badBox, CssBox leftBlock) { CssBox leftbox = null; while (badBox.Boxes[0].IsInline && ContainsInlinesOnlyDeep(badBox.Boxes[0])) { if (leftbox == null) { // if there is no elements in the left box there is no reason to keep it leftbox = CssBox.CreateBox(leftBlock, badBox.HtmlTag); leftbox.InheritStyle(badBox, true); } badBox.Boxes[0].ParentBox = leftbox; } var splitBox = badBox.Boxes[0]; if (!ContainsInlinesOnlyDeep(splitBox)) { CorrectBlockSplitBadBox(parentBox, splitBox, leftBlock); splitBox.ParentBox = null; } else { splitBox.ParentBox = parentBox; } if (badBox.Boxes.Count > 0) { CssBox rightBox; if (splitBox.ParentBox != null || parentBox.Boxes.Count < 3) { rightBox = CssBox.CreateBox(parentBox, badBox.HtmlTag); rightBox.InheritStyle(badBox, true); if (parentBox.Boxes.Count > 2) rightBox.SetBeforeBox(parentBox.Boxes[1]); if (splitBox.ParentBox != null) splitBox.SetBeforeBox(rightBox); } else { rightBox = parentBox.Boxes[2]; } rightBox.SetAllBoxes(badBox); } else if (splitBox.ParentBox != null && parentBox.Boxes.Count > 1) { splitBox.SetBeforeBox(parentBox.Boxes[1]); if (splitBox.HtmlTag != null && splitBox.HtmlTag.Name == "br" && (leftbox != null || leftBlock.Boxes.Count > 1)) splitBox.Display = CssConstants.Inline; } } /// <summary> /// Makes block boxes be among only block boxes and all inline boxes have block parent box.<br/> /// Inline boxes should live in a pool of Inline boxes only so they will define a single block.<br/> /// At the end of this process a block box will have only block siblings and inline box will have /// only inline siblings. /// </summary> /// <param name="box">the current box to correct its sub-tree</param> private static void CorrectInlineBoxesParent(CssBox box) { if (ContainsVariantBoxes(box)) { for (int i = 0; i < box.Boxes.Count; i++) { if (box.Boxes[i].IsInline) { var newbox = CssBox.CreateBlock(box, null, box.Boxes[i++]); while (i < box.Boxes.Count && box.Boxes[i].IsInline) { box.Boxes[i].ParentBox = newbox; } } } } if (!DomUtils.ContainsInlinesOnly(box)) { foreach (var childBox in box.Boxes) { CorrectInlineBoxesParent(childBox); } } } /// <summary> /// Check if the given box contains only inline child boxes in all subtree. /// </summary> /// <param name="box">the box to check</param> /// <returns>true - only inline child boxes, false - otherwise</returns> private static bool ContainsInlinesOnlyDeep(CssBox box) { foreach (var childBox in box.Boxes) { if (!childBox.IsInline || !ContainsInlinesOnlyDeep(childBox)) { return false; } } return true; } /// <summary> /// Check if the given box contains inline and block child boxes. /// </summary> /// <param name="box">the box to check</param> /// <returns>true - has variant child boxes, false - otherwise</returns> private static bool ContainsVariantBoxes(CssBox box) { bool hasBlock = false; bool hasInline = false; for (int i = 0; i < box.Boxes.Count && (!hasBlock || !hasInline); i++) { var isBlock = !box.Boxes[i].IsInline; hasBlock = hasBlock || isBlock; hasInline = hasInline || !isBlock; } return hasBlock && hasInline; } #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.Diagnostics; using System.Reflection; using System.Text; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.TypeSystem.NativeFormat; using Internal.TypeSystem.NoMetadata; namespace Internal.Runtime.TypeLoader { internal struct NativeLayoutInfo { public uint Offset; public NativeFormatModuleInfo Module; public NativeReader Reader; public NativeLayoutInfoLoadContext LoadContext; } // // TypeBuilder per-Type state. It is attached to each TypeDesc that gets involved in type building. // internal class TypeBuilderState { internal class VTableLayoutInfo { public uint VTableSlot; public RuntimeSignature MethodSignature; public bool IsSealedVTableSlot; } internal class VTableSlotMapper { private int[] _slotMap; private IntPtr[] _dictionarySlots; private int _numMappingsAssigned; public VTableSlotMapper(int numVtableSlotsInTemplateType) { _slotMap = new int[numVtableSlotsInTemplateType]; _dictionarySlots = new IntPtr[numVtableSlotsInTemplateType]; _numMappingsAssigned = 0; for (int i = 0; i < numVtableSlotsInTemplateType; i++) { _slotMap[i] = -1; _dictionarySlots[i] = IntPtr.Zero; } } public void AddMapping(int vtableSlotInTemplateType, int vtableSlotInTargetType, IntPtr dictionaryValueInSlot) { Debug.Assert(_numMappingsAssigned < _slotMap.Length); _slotMap[vtableSlotInTemplateType] = vtableSlotInTargetType; _dictionarySlots[vtableSlotInTemplateType] = dictionaryValueInSlot; _numMappingsAssigned++; } public int GetVTableSlotInTargetType(int vtableSlotInTemplateType) { Debug.Assert(vtableSlotInTemplateType < _slotMap.Length); return _slotMap[vtableSlotInTemplateType]; } public bool IsDictionarySlot(int vtableSlotInTemplateType, out IntPtr dictionaryPtrValue) { Debug.Assert(vtableSlotInTemplateType < _dictionarySlots.Length); dictionaryPtrValue = _dictionarySlots[vtableSlotInTemplateType]; return _dictionarySlots[vtableSlotInTemplateType] != IntPtr.Zero; } public int NumSlotMappings { get { return _numMappingsAssigned; } } } public TypeBuilderState(TypeDesc typeBeingBuilt) { TypeBeingBuilt = typeBeingBuilt; } public readonly TypeDesc TypeBeingBuilt; // // We cache and try to reuse the most recently used TypeSystemContext. The TypeSystemContext is used by not just type builder itself, // but also in several random other places in reflection. There can be multiple ResolutionContexts in flight at any given moment. // This check ensures that the RuntimeTypeHandle cache in the current resolution context is refreshed in case there were new // types built using a different TypeSystemContext in the meantime. // NOTE: For correctness, this value must be recomputed every time the context is recycled. This requires flushing the TypeBuilderState // from each type that has one if context is recycled. // public bool AttemptedAndFailedToRetrieveTypeHandle = false; public bool NeedsTypeHandle; public bool HasBeenPrepared; public RuntimeTypeHandle HalfBakedRuntimeTypeHandle; public IntPtr HalfBakedDictionary; public IntPtr HalfBakedSealedVTable; private bool _templateComputed; private bool _nativeLayoutTokenComputed; private TypeDesc _templateType; public TypeDesc TemplateType { get { if (!_templateComputed) { // Multidimensional arrays and szarrays of pointers don't implement generic interfaces and are special cases. They use // typeof(object[,]) as their template. if (TypeBeingBuilt.IsMdArray || (TypeBeingBuilt.IsSzArray && ((ArrayType)TypeBeingBuilt).ElementType.IsPointer)) { _templateType = TypeBeingBuilt.Context.ResolveRuntimeTypeHandle(typeof(object[,]).TypeHandle); _templateTypeLoaderNativeLayout = false; _nativeLayoutComputed = _nativeLayoutTokenComputed = _templateComputed = true; return _templateType; } // Locate the template type and native layout info _templateType = TypeBeingBuilt.Context.TemplateLookup.TryGetTypeTemplate(TypeBeingBuilt, ref _nativeLayoutInfo); Debug.Assert(_templateType == null || !_templateType.RuntimeTypeHandle.IsNull()); _templateTypeLoaderNativeLayout = true; _templateComputed = true; if ((_templateType != null) && !_templateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) _nativeLayoutTokenComputed = true; } return _templateType; } } private bool _nativeLayoutComputed = false; private bool _templateTypeLoaderNativeLayout = false; private bool _readyToRunNativeLayout = false; private NativeLayoutInfo _nativeLayoutInfo; private NativeLayoutInfo _r2rnativeLayoutInfo; private void EnsureNativeLayoutInfoComputed() { if (!_nativeLayoutComputed) { if (!_nativeLayoutTokenComputed) { if (!_templateComputed) { // Attempt to compute native layout through as a non-ReadyToRun template object temp = this.TemplateType; } if (!_nativeLayoutTokenComputed) { TypeBeingBuilt.Context.TemplateLookup.TryGetMetadataNativeLayout(TypeBeingBuilt, out _r2rnativeLayoutInfo.Module, out _r2rnativeLayoutInfo.Offset); if (_r2rnativeLayoutInfo.Module != null) _readyToRunNativeLayout = true; } _nativeLayoutTokenComputed = true; } if (_nativeLayoutInfo.Module != null) { FinishInitNativeLayoutInfo(TypeBeingBuilt, ref _nativeLayoutInfo); } if (_r2rnativeLayoutInfo.Module != null) { FinishInitNativeLayoutInfo(TypeBeingBuilt, ref _r2rnativeLayoutInfo); } _nativeLayoutComputed = true; } } /// <summary> /// Initialize the Reader and LoadContext fields of the native layout info /// </summary> /// <param name="type"></param> /// <param name="nativeLayoutInfo"></param> private static void FinishInitNativeLayoutInfo(TypeDesc type, ref NativeLayoutInfo nativeLayoutInfo) { var nativeLayoutInfoLoadContext = new NativeLayoutInfoLoadContext(); nativeLayoutInfoLoadContext._typeSystemContext = type.Context; nativeLayoutInfoLoadContext._module = nativeLayoutInfo.Module; if (type is DefType) { nativeLayoutInfoLoadContext._typeArgumentHandles = ((DefType)type).Instantiation; } else if (type is ArrayType) { nativeLayoutInfoLoadContext._typeArgumentHandles = new Instantiation(new TypeDesc[] { ((ArrayType)type).ElementType }); } else { Debug.Assert(false); } nativeLayoutInfoLoadContext._methodArgumentHandles = new Instantiation(null); nativeLayoutInfo.Reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(nativeLayoutInfo.Module.Handle); nativeLayoutInfo.LoadContext = nativeLayoutInfoLoadContext; } public NativeLayoutInfo NativeLayoutInfo { get { EnsureNativeLayoutInfoComputed(); return _nativeLayoutInfo; } } public NativeLayoutInfo R2RNativeLayoutInfo { get { EnsureNativeLayoutInfoComputed(); return _r2rnativeLayoutInfo; } } public NativeParser GetParserForNativeLayoutInfo() { EnsureNativeLayoutInfoComputed(); if (_templateTypeLoaderNativeLayout) return new NativeParser(_nativeLayoutInfo.Reader, _nativeLayoutInfo.Offset); else return default(NativeParser); } public NativeParser GetParserForReadyToRunNativeLayoutInfo() { EnsureNativeLayoutInfoComputed(); if (_readyToRunNativeLayout) return new NativeParser(_r2rnativeLayoutInfo.Reader, _r2rnativeLayoutInfo.Offset); else return default(NativeParser); } public NativeParser GetParserForUniversalNativeLayoutInfo(out NativeLayoutInfoLoadContext universalLayoutLoadContext, out NativeLayoutInfo universalLayoutInfo) { universalLayoutInfo = new NativeLayoutInfo(); universalLayoutLoadContext = null; TypeDesc universalTemplate = TypeBeingBuilt.Context.TemplateLookup.TryGetUniversalTypeTemplate(TypeBeingBuilt, ref universalLayoutInfo); if (universalTemplate == null) return new NativeParser(); FinishInitNativeLayoutInfo(TypeBeingBuilt, ref universalLayoutInfo); universalLayoutLoadContext = universalLayoutInfo.LoadContext; return new NativeParser(universalLayoutInfo.Reader, universalLayoutInfo.Offset); } // RuntimeInterfaces is the full list of interfaces that the type implements. It can include private internal implementation // detail interfaces that nothing is known about. public DefType[] RuntimeInterfaces { get { // Generic Type Definitions have no runtime interfaces if (TypeBeingBuilt.IsGenericDefinition) return null; return TypeBeingBuilt.RuntimeInterfaces; } } private bool? _hasDictionarySlotInVTable; private bool ComputeHasDictionarySlotInVTable() { if (!TypeBeingBuilt.IsGeneric() && !(TypeBeingBuilt is ArrayType)) return false; // Generic interfaces always have a dictionary slot if (TypeBeingBuilt.IsInterface) return true; return TypeBeingBuilt.CanShareNormalGenericCode(); } public bool HasDictionarySlotInVTable { get { if (_hasDictionarySlotInVTable == null) { _hasDictionarySlotInVTable = ComputeHasDictionarySlotInVTable(); } return _hasDictionarySlotInVTable.Value; } } private bool? _hasDictionaryInVTable; private bool ComputeHasDictionaryInVTable() { if (!HasDictionarySlotInVTable) return false; if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible()) { // Type was already constructed return TypeBeingBuilt.RuntimeTypeHandle.GetDictionary() != IntPtr.Zero; } else { // Type is being newly constructed if (TemplateType != null) { NativeParser parser = GetParserForNativeLayoutInfo(); // Template type loader case #if GENERICS_FORCE_USG bool isTemplateUniversalCanon = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup); if (isTemplateUniversalCanon && type.CanShareNormalGenericCode()) { TypeBuilderState tempState = new TypeBuilderState(); tempState.NativeLayoutInfo = new NativeLayoutInfo(); tempState.TemplateType = type.Context.TemplateLookup.TryGetNonUniversalTypeTemplate(type, ref tempState.NativeLayoutInfo); if (tempState.TemplateType != null) { Debug.Assert(!tempState.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup)); parser = GetNativeLayoutInfoParser(type, ref tempState.NativeLayoutInfo); } } #endif var dictionaryLayoutParser = parser.GetParserForBagElementKind(BagElementKind.DictionaryLayout); return !dictionaryLayoutParser.IsNull; } else { NativeParser parser = GetParserForReadyToRunNativeLayoutInfo(); // ReadyToRun case // Dictionary is directly encoded instead of the NativeLayout being a collection of bags if (parser.IsNull) return false; // First unsigned value in the native layout is the number of dictionary entries return parser.GetUnsigned() != 0; } } } public bool HasDictionaryInVTable { get { if (_hasDictionaryInVTable == null) _hasDictionaryInVTable = ComputeHasDictionaryInVTable(); return _hasDictionaryInVTable.Value; } } private ushort? _numVTableSlots; private ushort ComputeNumVTableSlots() { if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible()) { unsafe { return TypeBeingBuilt.RuntimeTypeHandle.ToEETypePtr()->NumVtableSlots; } } else { TypeDesc templateType = TypeBeingBuilt.ComputeTemplate(false); if (templateType != null) { // Template type loader case if (VTableSlotsMapping != null) { return checked((ushort)VTableSlotsMapping.NumSlotMappings); } else { unsafe { if (TypeBeingBuilt.IsMdArray || (TypeBeingBuilt.IsSzArray && ((ArrayType)TypeBeingBuilt).ElementType.IsPointer)) { // MDArray types and pointer arrays have the same vtable as the System.Array type they "derive" from. // They do not implement the generic interfaces that make this interesting for normal arrays. return TypeBeingBuilt.BaseType.GetRuntimeTypeHandle().ToEETypePtr()->NumVtableSlots; } else { // This should only happen for non-universal templates Debug.Assert(TypeBeingBuilt.IsTemplateCanonical()); // Canonical template type loader case return templateType.GetRuntimeTypeHandle().ToEETypePtr()->NumVtableSlots; } } } } else { // Metadata based type loading. // Generic Type Definitions have no actual vtable entries if (TypeBeingBuilt.IsGenericDefinition) return 0; // We have at least as many slots as exist on the base type. ushort numVTableSlots = 0; checked { if (TypeBeingBuilt.BaseType != null) { numVTableSlots = TypeBeingBuilt.BaseType.GetOrCreateTypeBuilderState().NumVTableSlots; } else { // Generic interfaces have a dictionary slot if (TypeBeingBuilt.IsInterface && TypeBeingBuilt.HasInstantiation) numVTableSlots = 1; } // Interfaces have actual vtable slots if (TypeBeingBuilt.IsInterface) return numVTableSlots; foreach (MethodDesc method in TypeBeingBuilt.GetMethods()) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING if (LazyVTableResolver.MethodDefinesVTableSlot(method)) numVTableSlots++; #else Environment.FailFast("metadata type loader required"); #endif } if (HasDictionarySlotInVTable) numVTableSlots++; } return numVTableSlots; } } } public ushort NumVTableSlots { get { if (_numVTableSlots == null) _numVTableSlots = ComputeNumVTableSlots(); return _numVTableSlots.Value; } } public GenericTypeDictionary Dictionary; public int NonGcDataSize { get { DefType defType = TypeBeingBuilt as DefType; // The NonGCStatic fields hold the class constructor data if it exists in the negative space // of the memory region. The ClassConstructorOffset is negative, so it must be negated to // determine the extra space that is used. if (defType != null) { return defType.NonGCStaticFieldSize.AsInt - (HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0); } else { return -(HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0); } } } public int GcDataSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null) { return defType.GCStaticFieldSize.AsInt; } else { return 0; } } } public int ThreadDataSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null && !defType.IsGenericDefinition) { return defType.ThreadStaticFieldSize.AsInt; } else { // Non-DefType's and GenericEETypeDefinitions do not have static fields of any form return 0; } } } public bool HasStaticConstructor { get { return TypeBeingBuilt.HasStaticConstructor; } } public IntPtr? ClassConstructorPointer; public IntPtr GcStaticDesc; public IntPtr GcStaticEEType; public IntPtr ThreadStaticDesc; public bool AllocatedStaticGCDesc; public bool AllocatedThreadStaticGCDesc; public uint ThreadStaticOffset; public uint NumSealedVTableEntries; public int[] GenericVarianceFlags; // Sentinel static to allow us to initializae _instanceLayout to something // and then detect that InstanceGCLayout should return null private static LowLevelList<bool> s_emptyLayout = new LowLevelList<bool>(); private LowLevelList<bool> _instanceGCLayout; /// <summary> /// The instance gc layout of a dynamically laid out type. /// null if one of the following is true /// 1) For an array type: /// - the type is a reference array /// 2) For a generic type: /// - the type has no GC instance fields /// - the type already has a type handle /// - the type has a non-universal canonical template /// - the type has already been constructed /// /// If the type is a valuetype array, this is the layout of the valuetype held in the array if the type has GC reference fields /// Otherwise, it is the layout of the fields in the type. /// </summary> public LowLevelList<bool> InstanceGCLayout { get { if (_instanceGCLayout == null) { LowLevelList<bool> instanceGCLayout = null; if (TypeBeingBuilt is ArrayType) { if (!IsArrayOfReferenceTypes) { ArrayType arrayType = (ArrayType)TypeBeingBuilt; TypeBuilder.GCLayout elementGcLayout = GetFieldGCLayout(arrayType.ElementType); if (!elementGcLayout.IsNone) { instanceGCLayout = new LowLevelList<bool>(); elementGcLayout.WriteToBitfield(instanceGCLayout, 0); _instanceGCLayout = instanceGCLayout; } } else { // Array of reference type returns null _instanceGCLayout = s_emptyLayout; } } else if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible() || TypeBeingBuilt.IsTemplateCanonical() || (TypeBeingBuilt is PointerType) || (TypeBeingBuilt is ByRefType)) { _instanceGCLayout = s_emptyLayout; } else { // Generic Type Definitions have no gc layout if (!(TypeBeingBuilt.IsGenericDefinition)) { // Copy in from base type if (!TypeBeingBuilt.IsValueType && (TypeBeingBuilt.BaseType != null)) { DefType baseType = TypeBeingBuilt.BaseType; // Capture the gc layout from the base type TypeBuilder.GCLayout baseTypeLayout = GetInstanceGCLayout(baseType); if (!baseTypeLayout.IsNone) { instanceGCLayout = new LowLevelList<bool>(); baseTypeLayout.WriteToBitfield(instanceGCLayout, IntPtr.Size /* account for the EEType pointer */); } } foreach (FieldDesc field in GetFieldsForGCLayout()) { if (field.IsStatic) continue; if (field.IsLiteral) continue; TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType); if (!fieldGcLayout.IsNone) { if (instanceGCLayout == null) instanceGCLayout = new LowLevelList<bool>(); fieldGcLayout.WriteToBitfield(instanceGCLayout, field.Offset.AsInt); } } if ((instanceGCLayout != null) && instanceGCLayout.HasSetBits()) { // When bits are set in the instance GC layout, it implies that the type contains GC refs, // which implies that the type size is pointer-aligned. In this case consumers assume that // the type size can be computed by multiplying the bitfield size by the pointer size. If // necessary, expand the bitfield to ensure that this invariant holds. // Valuetypes with gc fields must be aligned on at least pointer boundaries Debug.Assert(!TypeBeingBuilt.IsValueType || (FieldAlignment.Value >= TypeBeingBuilt.Context.Target.PointerSize)); // Valuetypes with gc fields must have a type size which is aligned on an IntPtr boundary. Debug.Assert(!TypeBeingBuilt.IsValueType || ((TypeSize.Value & (IntPtr.Size - 1)) == 0)); int impliedBitCount = (TypeSize.Value + IntPtr.Size - 1) / IntPtr.Size; Debug.Assert(instanceGCLayout.Count <= impliedBitCount); instanceGCLayout.Expand(impliedBitCount); Debug.Assert(instanceGCLayout.Count == impliedBitCount); } } if (instanceGCLayout == null) _instanceGCLayout = s_emptyLayout; else _instanceGCLayout = instanceGCLayout; } } if (_instanceGCLayout == s_emptyLayout) return null; else return _instanceGCLayout; } } public LowLevelList<bool> StaticGCLayout; public LowLevelList<bool> ThreadStaticGCLayout; private bool _staticGCLayoutPrepared; /// <summary> /// Prepare the StaticGCLayout/ThreadStaticGCLayout/GcStaticDesc/ThreadStaticDesc fields by /// reading native layout or metadata as appropriate. This method should only be called for types which /// are actually to be created. /// </summary> public void PrepareStaticGCLayout() { if (!_staticGCLayoutPrepared) { _staticGCLayoutPrepared = true; DefType defType = TypeBeingBuilt as DefType; if (defType == null) { // Array/pointer types do not have static fields } else if (defType.IsTemplateCanonical()) { // Canonical templates get their layout directly from the NativeLayoutInfo. // Parse it and pull that info out here. NativeParser typeInfoParser = GetParserForNativeLayoutInfo(); BagElementKind kind; while ((kind = typeInfoParser.GetBagElementKind()) != BagElementKind.End) { switch (kind) { case BagElementKind.GcStaticDesc: GcStaticDesc = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.ThreadStaticDesc: ThreadStaticDesc = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.GcStaticEEType: GcStaticEEType = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; default: typeInfoParser.SkipInteger(); break; } } } else { // Compute GC layout boolean array from field information. IEnumerable<FieldDesc> fields = GetFieldsForGCLayout(); LowLevelList<bool> threadStaticLayout = null; LowLevelList<bool> gcStaticLayout = null; foreach (FieldDesc field in fields) { if (!field.IsStatic) continue; if (field.IsLiteral) continue; LowLevelList<bool> gcLayoutInfo = null; if (field.IsThreadStatic) { if (threadStaticLayout == null) threadStaticLayout = new LowLevelList<bool>(); gcLayoutInfo = threadStaticLayout; } else if (field.HasGCStaticBase) { if (gcStaticLayout == null) gcStaticLayout = new LowLevelList<bool>(); gcLayoutInfo = gcStaticLayout; } else { // Non-GC static no need to record information continue; } TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType); fieldGcLayout.WriteToBitfield(gcLayoutInfo, field.Offset.AsInt); } if (gcStaticLayout != null && gcStaticLayout.Count > 0) StaticGCLayout = gcStaticLayout; if (threadStaticLayout != null && threadStaticLayout.Count > 0) ThreadStaticGCLayout = threadStaticLayout; } } } /// <summary> /// Get an enumerable list of the fields used for dynamic gc layout calculation. /// </summary> private IEnumerable<FieldDesc> GetFieldsForGCLayout() { DefType defType = (DefType)TypeBeingBuilt; IEnumerable<FieldDesc> fields; if (defType.ComputeTemplate(false) != null) { // we have native layout and a template. Use the NativeLayoutFields as that is the only complete // description of the fields available. (There may be metadata fields, but those aren't guaranteed // to be a complete set of fields due to reflection reduction. NativeLayoutFieldAlgorithm.EnsureFieldLayoutLoadedForGenericType(defType); fields = defType.NativeLayoutFields; } else { // The metadata case. We're loading the type from regular metadata, so use the regular metadata fields fields = defType.GetFields(); } return fields; } // Get the GC layout of a type. Handles pre-created, universal template, and non-universal template cases // Only to be used for getting the instance layout of non-valuetypes. /// <summary> /// Get the GC layout of a type. Handles pre-created, universal template, and non-universal template cases /// Only to be used for getting the instance layout of non-valuetypes that are used as base types /// </summary> /// <param name="type"></param> /// <returns></returns> private unsafe TypeBuilder.GCLayout GetInstanceGCLayout(TypeDesc type) { Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Any)); Debug.Assert(!type.IsValueType); if (type.RetrieveRuntimeTypeHandleIfPossible()) { return new TypeBuilder.GCLayout(type.RuntimeTypeHandle); } if (type.IsTemplateCanonical()) { var templateType = type.ComputeTemplate(); bool success = templateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(success && !templateType.RuntimeTypeHandle.IsNull()); return new TypeBuilder.GCLayout(templateType.RuntimeTypeHandle); } else { TypeBuilderState state = type.GetOrCreateTypeBuilderState(); if (state.InstanceGCLayout == null) return TypeBuilder.GCLayout.None; else return new TypeBuilder.GCLayout(state.InstanceGCLayout, true); } } /// <summary> /// Get the GC layout of a type when used as a field. /// NOTE: if the fieldtype is a reference type, this function will return GCLayout.None /// Consumers of the api must handle that special case. /// </summary> private unsafe TypeBuilder.GCLayout GetFieldGCLayout(TypeDesc fieldType) { if (!fieldType.IsValueType) { if (fieldType.IsPointer) return TypeBuilder.GCLayout.None; else return TypeBuilder.GCLayout.SingleReference; } // Is this a type that already exists? If so, get its gclayout from the EEType directly if (fieldType.RetrieveRuntimeTypeHandleIfPossible()) { return new TypeBuilder.GCLayout(fieldType.RuntimeTypeHandle); } // The type of the field must be a valuetype that is dynamically being constructed if (fieldType.IsTemplateCanonical()) { // Pull the GC Desc from the canonical instantiation TypeDesc templateType = fieldType.ComputeTemplate(); bool success = templateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(success); return new TypeBuilder.GCLayout(templateType.RuntimeTypeHandle); } else { // Use the type builder state's computed InstanceGCLayout var instanceGCLayout = fieldType.GetOrCreateTypeBuilderState().InstanceGCLayout; if (instanceGCLayout == null) return TypeBuilder.GCLayout.None; return new TypeBuilder.GCLayout(instanceGCLayout, false /* Always represents a valuetype as the reference type case is handled above with the GCLayout.SingleReference return */); } } public bool IsArrayOfReferenceTypes { get { ArrayType typeAsArrayType = TypeBeingBuilt as ArrayType; if (typeAsArrayType != null) return !typeAsArrayType.ParameterType.IsValueType && !typeAsArrayType.ParameterType.IsPointer; else return false; } } // Rank for arrays, -1 is used for an SzArray, and a positive number for a multidimensional array. public int? ArrayRank { get { if (!TypeBeingBuilt.IsArray) return null; else if (TypeBeingBuilt.IsSzArray) return -1; else { Debug.Assert(TypeBeingBuilt.IsMdArray); return ((ArrayType)TypeBeingBuilt).Rank; } } } public int? BaseTypeSize { get { if (TypeBeingBuilt.BaseType == null) { return null; } else { return TypeBeingBuilt.BaseType.InstanceByteCountUnaligned.AsInt; } } } public int? TypeSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null) { // Generic Type Definition EETypes do not have size if (defType.IsGenericDefinition) return null; if (defType.IsValueType) { return defType.InstanceFieldSize.AsInt; } else { if (defType.IsInterface) return IntPtr.Size; return defType.InstanceByteCountUnaligned.AsInt; } } else if (TypeBeingBuilt is ArrayType) { int basicArraySize = TypeBeingBuilt.BaseType.InstanceByteCountUnaligned.AsInt; if (TypeBeingBuilt.IsMdArray) { // MD Arrays are arranged like normal arrays, but they also have 2 int's per rank for the individual dimension loBounds and range. basicArraySize += ((ArrayType)TypeBeingBuilt).Rank * sizeof(int) * 2; } return basicArraySize; } else { return null; } } } public int? UnalignedTypeSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null) { return defType.InstanceByteCountUnaligned.AsInt; } else if (TypeBeingBuilt is ArrayType) { // Arrays use the same algorithm for TypeSize as for UnalignedTypeSize return TypeSize; } else { return 0; } } } public int? FieldAlignment { get { if (TypeBeingBuilt is DefType) { return checked((ushort)((DefType)TypeBeingBuilt).InstanceFieldAlignment.AsInt); } else if (TypeBeingBuilt is ArrayType) { ArrayType arrayType = (ArrayType)TypeBeingBuilt; if (arrayType.ElementType is DefType) { return checked((ushort)((DefType)arrayType.ElementType).InstanceFieldAlignment.AsInt); } else { return (ushort)arrayType.Context.Target.PointerSize; } } else if (TypeBeingBuilt is PointerType || TypeBeingBuilt is ByRefType) { return (ushort)TypeBeingBuilt.Context.Target.PointerSize; } else { return null; } } } public ushort? ComponentSize { get { ArrayType arrayType = TypeBeingBuilt as ArrayType; if (arrayType != null) { if (arrayType.ElementType is DefType) { uint size = (uint)((DefType)arrayType.ElementType).InstanceFieldSize.AsInt; if (size > ArrayTypesConstants.MaxSizeForValueClassInArray && arrayType.ElementType.IsValueType) ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadValueClassTooLarge, arrayType.ElementType); return checked((ushort)size); } else { return (ushort)arrayType.Context.Target.PointerSize; } } else { return null; } } } public uint NullableValueOffset { get { if (!TypeBeingBuilt.IsNullable) return 0; if (TypeBeingBuilt.IsTemplateCanonical()) { // Pull the GC Desc from the canonical instantiation TypeDesc templateType = TypeBeingBuilt.ComputeTemplate(); bool success = templateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(success); unsafe { return templateType.RuntimeTypeHandle.ToEETypePtr()->NullableValueOffset; } } else { int fieldCount = 0; uint nullableValueOffset = 0; foreach (FieldDesc f in GetFieldsForGCLayout()) { if (fieldCount == 1) { nullableValueOffset = checked((uint)f.Offset.AsInt); } fieldCount++; } // Nullable<T> only has two fields. HasValue and Value Debug.Assert(fieldCount == 2); return nullableValueOffset; } } } public bool IsHFA { get { #if ARM if (TypeBeingBuilt is DefType) { return ((DefType)TypeBeingBuilt).IsHfa; } else { return false; } #else // On Non-ARM platforms, HFA'ness is not encoded in the EEType as it doesn't effect ABI return false; #endif } } public VTableLayoutInfo[] VTableMethodSignatures; public int NumSealedVTableMethodSignatures; public VTableSlotMapper VTableSlotsMapping; #if GENERICS_FORCE_USG public TypeDesc NonUniversalTemplateType; public int NonUniversalInstanceGCDescSize; public IntPtr NonUniversalInstanceGCDesc; public IntPtr NonUniversalStaticGCDesc; public IntPtr NonUniversalThreadStaticGCDesc; #endif } }
// // Obstacle.cs // MSAGL Obstacle class for Rectilinear Edge Routing. // // Copyright Microsoft Corporation. using System; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing.Rectilinear { // Defines routing information for each obstacle in the graph. internal class Obstacle { internal const int FirstSentinelOrdinal = 1; internal const int FirstNonSentinelOrdinal = 10; /// <summary> /// Only public to make the compiler happy about the "where TPoly : new" constraint. /// Will be populated by caller. /// </summary> public Obstacle(Shape shape, bool makeRect, double padding) { if (makeRect) { #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=369 there are no structs in js var paddedBox = shape.BoundingBox.Clone(); #else var paddedBox = shape.BoundingBox; #endif paddedBox.Pad(padding); this.PaddedPolyline = Curve.PolyFromBox(paddedBox); } else { this.PaddedPolyline = InteractiveObstacleCalculator.PaddedPolylineBoundaryOfNode(shape.BoundaryCurve, padding); #if TEST_MSAGL || VERIFY_MSAGL // This throws if the polyline is nonconvex. VisibilityGraph.CheckThatPolylineIsConvex(this.PaddedPolyline); #endif // TEST || VERIFY } RoundVertices(this.PaddedPolyline); this.IsRectangle = this.IsPolylineRectangle(); if (!this.IsRectangle) { this.ConvertToRectangleIfClose(); } InputShape = shape; Ports = new Set<Port>(InputShape.Ports); } // From CreateSentinel only Obstacle(Point a, Point b, int scanlineOrdinal) { PaddedPolyline = new Polyline(ApproximateComparer.Round(a), ApproximateComparer.Round(b)) {Closed = true}; this.Ordinal = scanlineOrdinal; } internal LowObstacleSide ActiveLowSide { get; set; } internal HighObstacleSide ActiveHighSide { get; set; } internal Shape InputShape { get; set; } internal bool IsRectangle { get; private set; } /// <summary> /// The padded polyline that is tight to the input shape. /// </summary> internal Polyline PaddedPolyline { get; private set; } /// <summary> /// The polyline that is either the PaddedPolyline or a convex hull for multiple overlapping obstacles. /// </summary> internal Polyline VisibilityPolyline { get { return (this.ConvexHull != null) ? this.ConvexHull.Polyline : this.PaddedPolyline; } } /// <summary> /// The visibility polyline that is used for intersection comparisons and group obstacle avoidance. /// </summary> internal Polyline LooseVisibilityPolyline { get { if (this.looseVisibilityPolyline == null) { this.looseVisibilityPolyline = CreateLoosePolyline(this.VisibilityPolyline); } return this.looseVisibilityPolyline; } } internal static Polyline CreateLoosePolyline(Polyline polyline) { var loosePolyline = InteractiveObstacleCalculator.CreatePaddedPolyline(polyline, ApproximateComparer.IntersectionEpsilon * 10); RoundVertices(loosePolyline); return loosePolyline; } private Polyline looseVisibilityPolyline; internal Rectangle PaddedBoundingBox { get { return PaddedPolyline.BoundingBox; } } internal Rectangle VisibilityBoundingBox { get { return VisibilityPolyline.BoundingBox; } } internal bool IsGroup { get { return (null != InputShape) && InputShape.IsGroup; } } internal bool IsTransparentAncestor { get { return InputShape == null ? false : InputShape.IsTransparent; } set { if (InputShape == null) throw new InvalidOperationException(); InputShape.IsTransparent = value; } } // The ScanLine uses this as a final tiebreaker. It is set on InitializeEventQueue rather than in // AddObstacle to avoid a possible wraparound issue if a lot of obstacles are added/removed. // For sentinels, 1/2 are left/right, 3/4 are top/bottom. 0 is invalid during scanline processing. internal int Ordinal { get; set; } /// <summary> /// For overlapping obstacle management; this is just some arbitrary obstacle in the clump. /// </summary> internal Clump Clump { get; set; } internal bool IsOverlapped { get { Debug.Assert((this.Clump == null) || !this.IsGroup, "Groups should not be considered overlapped"); Debug.Assert((this.Clump == null) || (this.ConvexHull == null), "Clumped obstacles should not have overlapped convex hulls"); return (this.Clump != null); } } public bool IsInSameClump(Obstacle other) { return this.IsOverlapped && (this.Clump == other.Clump); } /// <summary> /// For sparseVg, the obstacle has a group corner inside it. /// </summary> internal bool OverlapsGroupCorner { get; set; } // A single convex hull is shared by all obstacles contained by it and we only want one occurrence of that // convex hull's polyline in the visibility graph generation. internal bool IsPrimaryObstacle { get { return (this.ConvexHull == null) || (this == this.ConvexHull.PrimaryObstacle); } } internal OverlapConvexHull ConvexHull { get; private set; } internal bool IsInConvexHull { get { return this.ConvexHull != null; } } // Note there is no !IsGroup check internal void SetConvexHull(OverlapConvexHull hull) { // This obstacle may have been in a rectangular obstacle or clump that was now found to overlap with a non-rectangular obstacle. this.Clump = null; this.IsRectangle = false; this.ConvexHull = hull; this.looseVisibilityPolyline = null; } // Cloned from InputShape and held to test for Port-membership changes. internal Set<Port> Ports { get; private set; } internal bool IsSentinel { get { return null == InputShape; } } // Set the initial ActiveLowSide and ActiveHighSide of the obstacle starting at this point. internal void CreateInitialSides(PolylinePoint startPoint, ScanDirection scanDir) { Debug.Assert((null == ActiveLowSide) && (null == ActiveHighSide) , "Cannot call SetInitialSides when sides are already set"); ActiveLowSide = new LowObstacleSide(this, startPoint, scanDir); ActiveHighSide = new HighObstacleSide(this, startPoint, scanDir); if (scanDir.IsFlat(ActiveHighSide)) { // No flat sides in the scanline; we'll do lookahead processing in the scanline to handle overlaps // with existing segments, and normal neighbor handling will take care of collinear OpenVertexEvents. ActiveHighSide = new HighObstacleSide(this, ActiveHighSide.EndVertex, scanDir); } } // Called when we've processed the HighestVertexEvent and closed the object. internal void Close() { ActiveLowSide = null; ActiveHighSide = null; } internal static Obstacle CreateSentinel(Point a, Point b, ScanDirection scanDir, int scanlineOrdinal) { var sentinel = new Obstacle(a, b, scanlineOrdinal); sentinel.CreateInitialSides(sentinel.PaddedPolyline.StartPoint, scanDir); return sentinel; } internal static void RoundVertices(Polyline polyline) { // Following creation of the padded border, round off the vertices for consistency // in later operations (intersections and event ordering). PolylinePoint ppt = polyline.StartPoint; do { ppt.Point = ApproximateComparer.Round(ppt.Point); ppt = ppt.NextOnPolyline; } while (ppt != polyline.StartPoint); RemoveCloseAndCollinearVerticesInPlace(polyline); // We've modified the points so the BoundingBox may have changed; force it to be recalculated. polyline.RequireInit(); // Verify that the polyline is still clockwise. Debug.Assert(polyline.IsClockwise(), "Polyline is not clockwise after RoundVertices"); } internal static Polyline RemoveCloseAndCollinearVerticesInPlace(Polyline polyline) { var epsilon = ApproximateComparer.IntersectionEpsilon * 10; for (PolylinePoint pp = polyline.StartPoint.Next; pp != null; pp = pp.Next) { if (ApproximateComparer.Close(pp.Prev.Point, pp.Point, epsilon)) { if (pp.Next == null) { polyline.RemoveEndPoint(); } else { pp.Prev.Next = pp.Next; pp.Next.Prev = pp.Prev; } } } if (ApproximateComparer.Close(polyline.Start, polyline.End, epsilon)) { polyline.RemoveStartPoint(); } InteractiveEdgeRouter.RemoveCollinearVertices(polyline); if ((polyline.EndPoint.Prev != null) && (Point.GetTriangleOrientation(polyline.EndPoint.Prev.Point, polyline.End, polyline.Start) == TriangleOrientation.Collinear)) { polyline.RemoveEndPoint(); } if ((polyline.StartPoint.Next != null) && (Point.GetTriangleOrientation(polyline.End, polyline.Start, polyline.StartPoint.Next.Point) == TriangleOrientation.Collinear)) { polyline.RemoveStartPoint(); } return polyline; } private bool IsPolylineRectangle () { if (this.PaddedPolyline.PolylinePoints.Count() != 4) { return false; } var ppt = this.PaddedPolyline.StartPoint; var nextPpt = ppt.NextOnPolyline; var dir = CompassVector.DirectionsFromPointToPoint(ppt.Point, nextPpt.Point); if (!CompassVector.IsPureDirection(dir)) { return false; } do { ppt = nextPpt; nextPpt = ppt.NextOnPolyline; var nextDir = CompassVector.DirectionsFromPointToPoint(ppt.Point, nextPpt.Point); // We know the polyline is clockwise. if (nextDir != CompassVector.RotateRight(dir)) { return false; } dir = nextDir; } while (ppt != this.PaddedPolyline.StartPoint); return true; } // Internal for testing internal void ConvertToRectangleIfClose() { if (this.PaddedPolyline.PolylinePoints.Count() != 4) { return; } // We're not a rectangle now but that may be due to rounding error, so we may be close to one. // First check that it's close to an axis. var ppt = this.PaddedPolyline.StartPoint; var nextPpt = ppt.NextOnPolyline; var testPoint = ppt.Point - nextPpt.Point; var slope = ((testPoint.X == 0) || (testPoint.Y == 0)) ? 0 : Math.Abs(testPoint.Y / testPoint.X); const double factor = 1000.0; if ((slope < factor) && (slope > (1.0/factor))) { return; } const double radian90 = 90.0 * (Math.PI/180.0); const double maxAngleDiff = radian90/factor; // Now check angles. do { var nextNextPpt = nextPpt.NextOnPolyline; var angle = Point.Angle(ppt.Point, nextPpt.Point, nextNextPpt.Point); if (Math.Abs(radian90 - angle) > maxAngleDiff) { return; } ppt = nextPpt; nextPpt = nextNextPpt; } while (ppt != this.PaddedPolyline.StartPoint); this.PaddedPolyline = Curve.PolyFromBox(this.PaddedPolyline.BoundingBox); this.IsRectangle = true; Debug.Assert(this.IsPolylineRectangle(), "PaddedPolyline is not rectangular"); return; } // Return whether there were any port changes, and if so which were added and removed. internal bool GetPortChanges(out Set<Port> addedPorts, out Set<Port> removedPorts) { addedPorts = InputShape.Ports - Ports; removedPorts = Ports - InputShape.Ports; if ((0 == addedPorts.Count) && (0 == removedPorts.Count)) { return false; } Ports = new Set<Port>(InputShape.Ports); return true; } /// <summary> /// </summary> /// <returns></returns> public override string ToString() { string typeString = GetType().ToString(); int lastDotLoc = typeString.LastIndexOf('.'); if (lastDotLoc >= 0) { typeString = typeString.Substring(lastDotLoc + 1); } return typeString + " [" + InputShape + "]"; } } }
#region Header /** * Lexer.cs * JSON lexer implementation based on a finite state machine. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LitJson2 { internal class FsmContext { public bool Return; public int NextState; public Lexer L; public int StateStack; } internal class Lexer { #region Fields private delegate bool StateHandler (FsmContext ctx); private static int[] fsm_return_table; private static StateHandler[] fsm_handler_table; private bool allow_comments; private bool allow_single_quoted_strings; private bool end_of_input; private FsmContext fsm_context; private int input_buffer; private int input_char; private TextReader reader; private int state; private StringBuilder string_buffer; private string string_value; private int token; private int unichar; #endregion #region Properties public bool AllowComments { get { return allow_comments; } set { allow_comments = value; } } public bool AllowSingleQuotedStrings { get { return allow_single_quoted_strings; } set { allow_single_quoted_strings = value; } } public bool EndOfInput { get { return end_of_input; } } public int Token { get { return token; } } public string StringValue { get { return string_value; } } #endregion #region Constructors static Lexer () { PopulateFsmTables (); } public Lexer (TextReader reader) { allow_comments = true; allow_single_quoted_strings = true; input_buffer = 0; string_buffer = new StringBuilder (128); state = 1; end_of_input = false; this.reader = reader; fsm_context = new FsmContext (); fsm_context.L = this; } #endregion #region Static Methods private static int HexValue (int digit) { switch (digit) { case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return digit - '0'; } } private static void PopulateFsmTables () { // See section A.1. of the manual for details of the finite // state machine. fsm_handler_table = new StateHandler[28] { State1, State2, State3, State4, State5, State6, State7, State8, State9, State10, State11, State12, State13, State14, State15, State16, State17, State18, State19, State20, State21, State22, State23, State24, State25, State26, State27, State28 }; fsm_return_table = new int[28] { (int) ParserToken.Char, 0, (int) ParserToken.Number, (int) ParserToken.Number, 0, (int) ParserToken.Number, 0, (int) ParserToken.Number, 0, 0, (int) ParserToken.True, 0, 0, 0, (int) ParserToken.False, 0, 0, (int) ParserToken.Null, (int) ParserToken.CharSeq, (int) ParserToken.Char, 0, 0, (int) ParserToken.CharSeq, (int) ParserToken.Char, 0, 0, 0, 0 }; } private static char ProcessEscChar (int esc_char) { switch (esc_char) { case '"': case '\'': case '\\': case '/': return Convert.ToChar (esc_char); case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'b': return '\b'; case 'f': return '\f'; default: // Unreachable return '?'; } } private static bool State1 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') continue; if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 3; return true; } switch (ctx.L.input_char) { case '"': ctx.NextState = 19; ctx.Return = true; return true; case ',': case ':': case '[': case ']': case '{': case '}': ctx.NextState = 1; ctx.Return = true; return true; case '-': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 2; return true; case '0': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 4; return true; case 'f': ctx.NextState = 12; return true; case 'n': ctx.NextState = 16; return true; case 't': ctx.NextState = 9; return true; case '\'': if (! ctx.L.allow_single_quoted_strings) return false; ctx.L.input_char = '"'; ctx.NextState = 23; ctx.Return = true; return true; case '/': if (! ctx.L.allow_comments) return false; ctx.NextState = 25; return true; default: return false; } } return true; } private static bool State2 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 3; return true; } switch (ctx.L.input_char) { case '0': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 4; return true; default: return false; } } private static bool State3 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; case '.': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 5; return true; case 'e': case 'E': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } return true; } private static bool State4 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; case '.': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 5; return true; case 'e': case 'E': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } private static bool State5 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 6; return true; } return false; } private static bool State6 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; case 'e': case 'E': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } return true; } private static bool State7 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 8; return true; } switch (ctx.L.input_char) { case '+': case '-': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 8; return true; default: return false; } } private static bool State8 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } return true; } private static bool State9 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'r': ctx.NextState = 10; return true; default: return false; } } private static bool State10 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'u': ctx.NextState = 11; return true; default: return false; } } private static bool State11 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'e': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State12 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'a': ctx.NextState = 13; return true; default: return false; } } private static bool State13 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'l': ctx.NextState = 14; return true; default: return false; } } private static bool State14 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 's': ctx.NextState = 15; return true; default: return false; } } private static bool State15 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'e': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State16 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'u': ctx.NextState = 17; return true; default: return false; } } private static bool State17 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'l': ctx.NextState = 18; return true; default: return false; } } private static bool State18 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'l': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State19 (FsmContext ctx) { while (ctx.L.GetChar ()) { switch (ctx.L.input_char) { case '"': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 20; return true; case '\\': ctx.StateStack = 19; ctx.NextState = 21; return true; default: ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } } return true; } private static bool State20 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case '"': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State21 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'u': ctx.NextState = 22; return true; case '"': case '\'': case '/': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': ctx.L.string_buffer.Append ( ProcessEscChar (ctx.L.input_char)); ctx.NextState = ctx.StateStack; return true; default: return false; } } private static bool State22 (FsmContext ctx) { int counter = 0; int mult = 4096; ctx.L.unichar = 0; while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' || ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' || ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') { ctx.L.unichar += HexValue (ctx.L.input_char) * mult; counter++; mult /= 16; if (counter == 4) { ctx.L.string_buffer.Append ( Convert.ToChar (ctx.L.unichar)); ctx.NextState = ctx.StateStack; return true; } continue; } return false; } return true; } private static bool State23 (FsmContext ctx) { while (ctx.L.GetChar ()) { switch (ctx.L.input_char) { case '\'': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 24; return true; case '\\': ctx.StateStack = 23; ctx.NextState = 21; return true; default: ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } } return true; } private static bool State24 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case '\'': ctx.L.input_char = '"'; ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State25 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case '*': ctx.NextState = 27; return true; case '/': ctx.NextState = 26; return true; default: return false; } } private static bool State26 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == '\n') { ctx.NextState = 1; return true; } } return true; } private static bool State27 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == '*') { ctx.NextState = 28; return true; } } return true; } private static bool State28 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == '*') continue; if (ctx.L.input_char == '/') { ctx.NextState = 1; return true; } ctx.NextState = 27; return true; } return true; } #endregion private bool GetChar () { if ((input_char = NextChar ()) != -1) return true; end_of_input = true; return false; } private int NextChar () { if (input_buffer != 0) { int tmp = input_buffer; input_buffer = 0; return tmp; } return reader.Read (); } public bool NextToken () { StateHandler handler; fsm_context.Return = false; while (true) { handler = fsm_handler_table[state - 1]; if (! handler (fsm_context)) throw new JsonException (input_char); if (end_of_input) return false; if (fsm_context.Return) { string_value = string_buffer.ToString (); string_buffer.Remove (0, string_buffer.Length); token = fsm_return_table[state - 1]; if (token == (int) ParserToken.Char) token = input_char; state = fsm_context.NextState; return true; } state = fsm_context.NextState; } } private void UngetChar () { input_buffer = input_char; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Globalization; using System.ComponentModel; using System.Windows.Forms; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization { public partial class Dimension { /// <summary> /// Returns the textual representation of a dimension object. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the Dimension object. /// </returns> public override string ToString() { StringBuilder sb = new StringBuilder(); if (this.xSpecified) { sb.Append(this.x); } if (this.xSpecified || this.ySpecified) { sb.Append(';'); } if (this.ySpecified) { sb.Append(this.y); } if (sb.Length > 0) sb.Append(' '); AbsDimension absDimension = this.Item as AbsDimension; if (absDimension != null) { sb.Append(String.Format("Abs {0};{1}", absDimension.x, absDimension.y)); } RelDimension relDimension = this.Item as RelDimension; if (relDimension != null) { sb.Append(String.Format(CultureInfo.InvariantCulture, "Rel {0};{1}", relDimension.x, relDimension.y)); } return sb.ToString(); } /// <summary> /// Creates a new Dimension of a given type from the string argument. /// </summary> /// <typeparam name="TDimension">The type of the dimension.</typeparam> /// <param name="textValue">The text value.</param> /// <returns>The dimension object</returns> public static TDimension FromString<TDimension>(string textValue) where TDimension: Dimension, new() { TDimension dimension = new TDimension(); if (String.IsNullOrEmpty(textValue)) return null; textValue = textValue.Replace(" ", ""); if (textValue.Length == 0) return dimension; Regex regEx = new Regex(@"(([-+]?\d+)?;([-+]?\d+)?)?((Rel|Abs)([-+]?\d+(.\d+)?);([-+]?\d+(.\d+)?))?"); Match match = regEx.Match(textValue); if (!match.Success) throw new ArgumentException("Please use the following BNF format: {{<x>};{<y>}} {(Rel|Abs}<x>;<y>}"); if (!match.Groups[1].Success && !match.Groups[4].Success) throw new ArgumentException("Either x;y attributes or Abs/Rel x;y items should be completed!"); // optional x attribute if (match.Groups[2].Success) { dimension.x = Int32.Parse(match.Groups[2].Value); dimension.xSpecified = true; } // optional y attribute if (match.Groups[3].Success) { dimension.y = Int32.Parse(match.Groups[3].Value); dimension.ySpecified = true; } // dimension modifier (abs or rel) and both values are specified if (match.Groups[5].Success && match.Groups[6].Success && match.Groups[8].Success) { switch (match.Groups[5].Value) { case "Rel": RelDimension relDimension = new RelDimension(); relDimension.x = float.Parse(match.Groups[6].Value, CultureInfo.InvariantCulture); relDimension.y = float.Parse(match.Groups[8].Value, CultureInfo.InvariantCulture); dimension.Item = relDimension; break; case "Abs": default: // only if there are no decimals (absolute coordinates are integers) if (match.Groups[7].Success || match.Groups[9].Success) throw new ArgumentException("Absolute coordinates should be integers!"); AbsDimension absDimension = new AbsDimension(); absDimension.x = Int32.Parse(match.Groups[6].Value); absDimension.y = Int32.Parse(match.Groups[8].Value); dimension.Item = absDimension; break; } } return dimension; } /// <summary> /// Extension method of Dimension. Retrieves the size in pixels. /// </summary> /// <param name="dimension">The dimension.</param> /// <returns>Size in pixels</returns> public System.Drawing.Size GetSize() { var size = System.Drawing.Size.Empty; if (this.xSpecified) size.Width = this.x; if (this.ySpecified) size.Height = this.y; AbsDimension absDimension = this.Item as AbsDimension; if (absDimension != null) size = new System.Drawing.Size(absDimension.x, absDimension.y); RelDimension relDimension = this.Item as RelDimension; if (relDimension != null) { var screenSize = Screen.PrimaryScreen.Bounds.Size; size = new System.Drawing.Size( (int)(screenSize.Width * relDimension.x), (int)(screenSize.Height * relDimension.y)); } return size; } public void Update(int? x, int? y) { if (this.Item == null) { if (x.HasValue) { this.x = x.Value; this.xSpecified = true; } if (y.HasValue) { this.y = y.Value; this.yFieldSpecified = true; } } AbsDimension absDimension = this.Item as AbsDimension; if (absDimension != null) { if (x.HasValue) absDimension.x = x.Value; if (y.HasValue) absDimension.y = y.Value; } RelDimension relDimension = this.Item as RelDimension; if (relDimension != null) { var screenSize = Screen.PrimaryScreen.Bounds.Size; if (x.HasValue) relDimension.x = (float) x.Value / screenSize.Width; if (y.HasValue) relDimension.y = (float)y.Value / screenSize.Height; } if (absDimension == null && relDimension == null) { this.Item = new AbsDimension(); (this.Item as AbsDimension).x = x.Value; (this.Item as AbsDimension).y = y.Value; } } public static TDimension FromSize<TDimension>(System.Drawing.Size size) where TDimension: Dimension, new() { TDimension dimension = new TDimension(); dimension.Update(size.Width, size.Height); return dimension; } #region ICloneable Members public static TDimension Clone<TDimension>(TDimension original) where TDimension: Dimension { if (original == null) return null; BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { bf.Serialize(stream, original); stream.Position = 0; return bf.Deserialize(stream) as TDimension; } } #endregion #region Equals public override bool Equals(object obj) { if (obj == null) return false; return this.ToString().Equals(obj.ToString()); } public override int GetHashCode() { return this.ToString().GetHashCode(); } public static bool Equals(Dimension one, Dimension two) { if (one == null) return two == null; return one.Equals(two); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Text; namespace System.Reflection.Metadata { /// <summary> /// Reads metadata as defined byte the ECMA 335 CLI specification. /// </summary> public sealed partial class MetadataReader { internal readonly NamespaceCache NamespaceCache; internal readonly MemoryBlock Block; // A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference). internal readonly int WinMDMscorlibRef; private readonly MetadataReaderOptions _options; private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> _lazyNestedTypesMap; #region Constructors /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// </remarks> public unsafe MetadataReader(byte* metadata, int length) : this(metadata, length, MetadataReaderOptions.Default, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options) : this(metadata, length, options, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain /// metadata from a PE image. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is not positive.</exception> /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception> /// <exception cref="ArgumentException">The encoding of <paramref name="utf8Decoder"/> is not <see cref="UTF8Encoding"/>.</exception> /// <exception cref="PlatformNotSupportedException">The current platform is big-endian.</exception> /// <exception cref="BadImageFormatException">Bad metadata header.</exception> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder) { // Do not throw here when length is 0. We'll throw BadImageFormatException later on, so that the caller doesn't need to // worry about the image (stream) being empty and can handle all image errors by catching BadImageFormatException. if (length < 0) { Throw.ArgumentOutOfRange(nameof(length)); } if (metadata == null) { Throw.ArgumentNull(nameof(metadata)); } if (utf8Decoder == null) { utf8Decoder = MetadataStringDecoder.DefaultUTF8; } if (!(utf8Decoder.Encoding is UTF8Encoding)) { Throw.InvalidArgument(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder)); } Block = new MemoryBlock(metadata, length); _options = options; UTF8Decoder = utf8Decoder; var headerReader = new BlobReader(Block); ReadMetadataHeader(ref headerReader, out _versionString); _metadataKind = GetMetadataKind(_versionString); var streamHeaders = ReadStreamHeaders(ref headerReader); // storage header and stream headers: InitializeStreamReaders(Block, streamHeaders, out _metadataStreamKind, out var metadataTableStream, out var pdbStream); int[] externalTableRowCountsOpt; if (pdbStream.Length > 0) { int pdbStreamOffset = (int)(pdbStream.Pointer - metadata); ReadStandalonePortablePdbStream(pdbStream, pdbStreamOffset, out _debugMetadataHeader, out externalTableRowCountsOpt); } else { externalTableRowCountsOpt = null; } var tableReader = new BlobReader(metadataTableStream); ReadMetadataTableHeader(ref tableReader, out var heapSizes, out var metadataTableRowCounts, out _sortedTables); InitializeTableReaders(tableReader.GetMemoryBlockAt(0, tableReader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCountsOpt); // This previously could occur in obfuscated assemblies but a check was added to prevent // it getting to this point Debug.Assert(AssemblyTable.NumberOfRows <= 1); // Although the specification states that the module table will have exactly one row, // the native metadata reader would successfully read files containing more than one row. // Such files exist in the wild and may be produced by obfuscators. if (pdbStream.Length == 0 && ModuleTable.NumberOfRows < 1) { throw new BadImageFormatException(SR.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows)); } // read NamespaceCache = new NamespaceCache(this); if (_metadataKind != MetadataKind.Ecma335) { WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection(); } } #endregion #region Metadata Headers private readonly string _versionString; private readonly MetadataKind _metadataKind; private readonly MetadataStreamKind _metadataStreamKind; private readonly DebugMetadataHeader _debugMetadataHeader; internal StringHeap StringHeap; internal BlobHeap BlobHeap; internal GuidHeap GuidHeap; internal UserStringHeap UserStringHeap; /// <summary> /// True if the metadata stream has minimal delta format. Used for EnC. /// </summary> /// <remarks> /// The metadata stream has minimal delta format if "#JTD" stream is present. /// Minimal delta format uses large size (4B) when encoding table/heap references. /// The heaps in minimal delta only contain data of the delta, /// there is no padding at the beginning of the heaps that would align them /// with the original full metadata heaps. /// </remarks> internal bool IsMinimalDelta; /// <summary> /// Looks like this function reads beginning of the header described in /// ECMA-335 24.2.1 Metadata root /// </summary> private void ReadMetadataHeader(ref BlobReader memReader, out string versionString) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader) { throw new BadImageFormatException(SR.MetadataHeaderTooSmall); } uint signature = memReader.ReadUInt32(); if (signature != COR20Constants.COR20MetadataSignature) { throw new BadImageFormatException(SR.MetadataSignature); } // major version memReader.ReadUInt16(); // minor version memReader.ReadUInt16(); // reserved: memReader.ReadUInt32(); int versionStringSize = memReader.ReadInt32(); if (memReader.RemainingBytes < versionStringSize) { throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString); } int numberOfBytesRead; versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, UTF8Decoder, out numberOfBytesRead, '\0'); memReader.Offset += versionStringSize; } private MetadataKind GetMetadataKind(string versionString) { // Treat metadata as CLI raw metadata if the client doesn't want to see projections. if ((_options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0) { return MetadataKind.Ecma335; } if (!versionString.Contains("WindowsRuntime")) { return MetadataKind.Ecma335; } else if (versionString.Contains("CLR")) { return MetadataKind.ManagedWindowsMetadata; } else { return MetadataKind.WindowsMetadata; } } /// <summary> /// Reads stream headers described in ECMA-335 24.2.2 Stream header /// </summary> private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) { // storage header: memReader.ReadUInt16(); int streamCount = memReader.ReadInt16(); var streamHeaders = new StreamHeader[streamCount]; for (int i = 0; i < streamHeaders.Length; i++) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader) { throw new BadImageFormatException(SR.StreamHeaderTooSmall); } streamHeaders[i].Offset = memReader.ReadUInt32(); streamHeaders[i].Size = memReader.ReadInt32(); streamHeaders[i].Name = memReader.ReadUtf8NullTerminated(); bool aligned = memReader.TryAlign(4); if (!aligned || memReader.RemainingBytes == 0) { throw new BadImageFormatException(SR.NotEnoughSpaceForStreamHeaderName); } } return streamHeaders; } private void InitializeStreamReaders( in MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MetadataStreamKind metadataStreamKind, out MemoryBlock metadataTableStream, out MemoryBlock standalonePdbStream) { metadataTableStream = default; standalonePdbStream = default; metadataStreamKind = MetadataStreamKind.Illegal; foreach (StreamHeader streamHeader in streamHeaders) { switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForStringStream); } this.StringHeap = new StringHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.BlobStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.BlobHeap = new BlobHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.GUIDStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForGUIDStream); } this.GuidHeap = new GuidHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.UserStringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.UserStringHeap = new UserStringHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.CompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Compressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.UncompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Uncompressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.MinimalDeltaMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } // the content of the stream is ignored this.IsMinimalDelta = true; break; case COR20Constants.StandalonePdbStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; default: // Skip unknown streams. Some obfuscators insert invalid streams. continue; } } if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed) { throw new BadImageFormatException(SR.InvalidMetadataStreamFormat); } } #endregion #region Tables and Heaps private readonly TableMask _sortedTables; /// <summary> /// A row count for each possible table. May be indexed by <see cref="TableIndex"/>. /// </summary> internal int[] TableRowCounts; internal ModuleTableReader ModuleTable; internal TypeRefTableReader TypeRefTable; internal TypeDefTableReader TypeDefTable; internal FieldPtrTableReader FieldPtrTable; internal FieldTableReader FieldTable; internal MethodPtrTableReader MethodPtrTable; internal MethodTableReader MethodDefTable; internal ParamPtrTableReader ParamPtrTable; internal ParamTableReader ParamTable; internal InterfaceImplTableReader InterfaceImplTable; internal MemberRefTableReader MemberRefTable; internal ConstantTableReader ConstantTable; internal CustomAttributeTableReader CustomAttributeTable; internal FieldMarshalTableReader FieldMarshalTable; internal DeclSecurityTableReader DeclSecurityTable; internal ClassLayoutTableReader ClassLayoutTable; internal FieldLayoutTableReader FieldLayoutTable; internal StandAloneSigTableReader StandAloneSigTable; internal EventMapTableReader EventMapTable; internal EventPtrTableReader EventPtrTable; internal EventTableReader EventTable; internal PropertyMapTableReader PropertyMapTable; internal PropertyPtrTableReader PropertyPtrTable; internal PropertyTableReader PropertyTable; internal MethodSemanticsTableReader MethodSemanticsTable; internal MethodImplTableReader MethodImplTable; internal ModuleRefTableReader ModuleRefTable; internal TypeSpecTableReader TypeSpecTable; internal ImplMapTableReader ImplMapTable; internal FieldRVATableReader FieldRvaTable; internal EnCLogTableReader EncLogTable; internal EnCMapTableReader EncMapTable; internal AssemblyTableReader AssemblyTable; internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused internal AssemblyOSTableReader AssemblyOSTable; // unused internal AssemblyRefTableReader AssemblyRefTable; internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused internal FileTableReader FileTable; internal ExportedTypeTableReader ExportedTypeTable; internal ManifestResourceTableReader ManifestResourceTable; internal NestedClassTableReader NestedClassTable; internal GenericParamTableReader GenericParamTable; internal MethodSpecTableReader MethodSpecTable; internal GenericParamConstraintTableReader GenericParamConstraintTable; // debug tables internal DocumentTableReader DocumentTable; internal MethodDebugInformationTableReader MethodDebugInformationTable; internal LocalScopeTableReader LocalScopeTable; internal LocalVariableTableReader LocalVariableTable; internal LocalConstantTableReader LocalConstantTable; internal ImportScopeTableReader ImportScopeTable; internal StateMachineMethodTableReader StateMachineMethodTable; internal CustomDebugInformationTableReader CustomDebugInformationTable; private void ReadMetadataTableHeader(ref BlobReader reader, out HeapSizes heapSizes, out int[] metadataTableRowCounts, out TableMask sortedTables) { if (reader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader) { throw new BadImageFormatException(SR.MetadataTableHeaderTooSmall); } // reserved (shall be ignored): reader.ReadUInt32(); // major version (shall be ignored): reader.ReadByte(); // minor version (shall be ignored): reader.ReadByte(); // heap sizes: heapSizes = (HeapSizes)reader.ReadByte(); // reserved (shall be ignored): reader.ReadByte(); ulong presentTables = reader.ReadUInt64(); sortedTables = (TableMask)reader.ReadUInt64(); // According to ECMA-335, MajorVersion and MinorVersion have fixed values and, // based on recommendation in 24.1 Fixed fields: When writing these fields it // is best that they be set to the value indicated, on reading they should be ignored. // We will not be checking version values. We will continue checking that the set of // present tables is within the set we understand. ulong validTables = (ulong)(TableMask.TypeSystemTables | TableMask.DebugTables); if ((presentTables & ~validTables) != 0) { throw new BadImageFormatException(SR.Format(SR.UnknownTables, presentTables)); } if (_metadataStreamKind == MetadataStreamKind.Compressed) { // In general Ptr tables and EnC tables are not allowed in a compressed stream. // However when asked for a snapshot of the current metadata after an EnC change has been applied // the CLR includes the EnCLog table into the snapshot. We need to be able to read the image, // so we'll allow the table here but pretend it's empty later. if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0) { throw new BadImageFormatException(SR.IllegalTablesInCompressedMetadataStream); } } metadataTableRowCounts = ReadMetadataTableRowCounts(ref reader, presentTables); if ((heapSizes & HeapSizes.ExtraData) == HeapSizes.ExtraData) { // Skip "extra data" used by some obfuscators. Although it is not mentioned in the CLI spec, // it is honored by the native metadata reader. reader.ReadUInt32(); } } private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask) { ulong currentTableBit = 1; var rowCounts = new int[MetadataTokens.TableCount]; for (int i = 0; i < rowCounts.Length; i++) { if ((presentTableMask & currentTableBit) != 0) { if (memReader.RemainingBytes < sizeof(uint)) { throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall); } uint rowCount = memReader.ReadUInt32(); if (rowCount > TokenTypeIds.RIDMask) { throw new BadImageFormatException(SR.Format(SR.InvalidRowCount, rowCount)); } rowCounts[i] = (int)rowCount; } currentTableBit <<= 1; } return rowCounts; } // internal for testing internal static void ReadStandalonePortablePdbStream(MemoryBlock pdbStreamBlock, int pdbStreamOffset, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts) { var reader = new BlobReader(pdbStreamBlock); const int PdbIdSize = 20; byte[] pdbId = reader.ReadBytes(PdbIdSize); // ECMA-335 15.4.1.2: // The entry point to an application shall be static. // This entry point method can be a global method or it can appear inside a type. // The entry point method shall either accept no arguments or a vector of strings. // The return type of the entry point method shall be void, int32, or unsigned int32. // The entry point method cannot be defined in a generic class. uint entryPointToken = reader.ReadUInt32(); int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask); if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0)) { throw new BadImageFormatException(string.Format(SR.InvalidEntryPointToken, entryPointToken)); } ulong externalTableMask = reader.ReadUInt64(); // EnC & Ptr tables can't be referenced from standalone PDB metadata: const ulong validTables = (ulong)TableMask.ValidPortablePdbExternalTables; if ((externalTableMask & ~validTables) != 0) { throw new BadImageFormatException(string.Format(SR.UnknownTables, externalTableMask)); } externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask); debugMetadataHeader = new DebugMetadataHeader( ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref pdbId), MethodDefinitionHandle.FromRowId(entryPointRowId), idStartOffset: pdbStreamOffset); } private const int SmallIndexSize = 2; private const int LargeIndexSize = 4; private int GetReferenceSize(int[] rowCounts, TableIndex index) { return (rowCounts[(int)index] < MetadataStreamConstants.LargeTableRowCount && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize; } private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapSizes heapSizes, int[] rowCounts, int[] externalRowCountsOpt) { // Size of reference tags in each table. this.TableRowCounts = rowCounts; // TODO (https://github.com/dotnet/corefx/issues/2061): // Shouldn't XxxPtr table be always the same size or smaller than the corresponding Xxx table? // Compute ref sizes for tables that can have pointer tables int fieldRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.FieldPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Field); int methodRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.MethodPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.MethodDef); int paramRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.ParamPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Param); int eventRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.EventPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Event); int propertyRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.PropertyPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Property); // Compute the coded token ref sizes int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced); int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced); int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced); int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced); int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced); int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced); int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced); int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced); int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced); int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced); int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced); int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced); int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced); // Compute HeapRef Sizes int stringHeapRefSize = (heapSizes & HeapSizes.StringHeapLarge) == HeapSizes.StringHeapLarge ? LargeIndexSize : SmallIndexSize; int guidHeapRefSize = (heapSizes & HeapSizes.GuidHeapLarge) == HeapSizes.GuidHeapLarge ? LargeIndexSize : SmallIndexSize; int blobHeapRefSize = (heapSizes & HeapSizes.BlobHeapLarge) == HeapSizes.BlobHeapLarge ? LargeIndexSize : SmallIndexSize; // Populate the Table blocks int totalRequiredSize = 0; this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleTable.Block.Length; this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeRefTable.Block.Length; this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSizeSorted, methodRefSizeSorted, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeDefTable.Block.Length; this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldPtrTable.Block.Length; this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldTable.Block.Length; this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], GetReferenceSize(rowCounts, TableIndex.MethodDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodPtrTable.Block.Length; this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSizeSorted, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDefTable.Block.Length; this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], GetReferenceSize(rowCounts, TableIndex.Param), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamPtrTable.Block.Length; this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamTable.Block.Length; this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.InterfaceImplTable.Block.Length; this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MemberRefTable.Block.Length; this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ConstantTable.Block.Length; this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute], IsDeclaredSorted(TableMask.CustomAttribute), hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomAttributeTable.Block.Length; this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldMarshalTable.Block.Length; this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DeclSecurityTable.Block.Length; this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ClassLayoutTable.Block.Length; this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldLayoutTable.Block.Length; this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StandAloneSigTable.Block.Length; this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), eventRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventMapTable.Block.Length; this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], GetReferenceSize(rowCounts, TableIndex.Event), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventPtrTable.Block.Length; this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventTable.Block.Length; this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), propertyRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyMapTable.Block.Length; this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], GetReferenceSize(rowCounts, TableIndex.Property), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyPtrTable.Block.Length; this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyTable.Block.Length; this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), GetReferenceSize(rowCounts, TableIndex.MethodDef), hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSemanticsTable.Block.Length; this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodImplTable.Block.Length; this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleRefTable.Block.Length; this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeSpecTable.Block.Length; this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), GetReferenceSize(rowCounts, TableIndex.ModuleRef), memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImplMapTable.Block.Length; this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldRvaTable.Block.Length; this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, _metadataStreamKind); totalRequiredSize += this.EncLogTable.Block.Length; this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EncMapTable.Block.Length; this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyTable.Block.Length; this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyProcessorTable.Block.Length; this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyOSTable.Block.Length; this.AssemblyRefTable = new AssemblyRefTableReader(rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, _metadataKind); totalRequiredSize += this.AssemblyRefTable.Block.Length; this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length; this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefOSTable.Block.Length; this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FileTable.Block.Length; this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ExportedTypeTable.Block.Length; this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ManifestResourceTable.Block.Length; this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.NestedClassTable.Block.Length; this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamTable.Block.Length; this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSpecTable.Block.Length; this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), GetReferenceSize(rowCounts, TableIndex.GenericParam), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamConstraintTable.Block.Length; // debug tables: // Type-system metadata tables may be stored in a separate (external) metadata file. // We need to use the row counts of the external tables when referencing them. // Debug tables are local to the current metadata image and type system metadata tables are external and precede all debug tables. var combinedRowCounts = (externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, firstLocalTableIndex: TableIndex.Document) : rowCounts; int methodRefSizeCombined = GetReferenceSize(combinedRowCounts, TableIndex.MethodDef); int hasCustomDebugInformationRefSizeCombined = ComputeCodedTokenSize(HasCustomDebugInformationTag.LargeRowSize, combinedRowCounts, HasCustomDebugInformationTag.TablesReferenced); this.DocumentTable = new DocumentTableReader(rowCounts[(int)TableIndex.Document], guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DocumentTable.Block.Length; this.MethodDebugInformationTable = new MethodDebugInformationTableReader(rowCounts[(int)TableIndex.MethodDebugInformation], GetReferenceSize(rowCounts, TableIndex.Document), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDebugInformationTable.Block.Length; this.LocalScopeTable = new LocalScopeTableReader(rowCounts[(int)TableIndex.LocalScope], IsDeclaredSorted(TableMask.LocalScope), methodRefSizeCombined, GetReferenceSize(rowCounts, TableIndex.ImportScope), GetReferenceSize(rowCounts, TableIndex.LocalVariable), GetReferenceSize(rowCounts, TableIndex.LocalConstant), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalScopeTable.Block.Length; this.LocalVariableTable = new LocalVariableTableReader(rowCounts[(int)TableIndex.LocalVariable], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalVariableTable.Block.Length; this.LocalConstantTable = new LocalConstantTableReader(rowCounts[(int)TableIndex.LocalConstant], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalConstantTable.Block.Length; this.ImportScopeTable = new ImportScopeTableReader(rowCounts[(int)TableIndex.ImportScope], GetReferenceSize(rowCounts, TableIndex.ImportScope), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImportScopeTable.Block.Length; this.StateMachineMethodTable = new StateMachineMethodTableReader(rowCounts[(int)TableIndex.StateMachineMethod], IsDeclaredSorted(TableMask.StateMachineMethod), methodRefSizeCombined, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StateMachineMethodTable.Block.Length; this.CustomDebugInformationTable = new CustomDebugInformationTableReader(rowCounts[(int)TableIndex.CustomDebugInformation], IsDeclaredSorted(TableMask.CustomDebugInformation), hasCustomDebugInformationRefSizeCombined, guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomDebugInformationTable.Block.Length; if (totalRequiredSize > metadataTablesMemoryBlock.Length) { throw new BadImageFormatException(SR.MetadataTablesTooSmall); } } private static int[] CombineRowCounts(int[] local, int[] external, TableIndex firstLocalTableIndex) { Debug.Assert(local.Length == external.Length); var rowCounts = new int[local.Length]; for (int i = 0; i < (int)firstLocalTableIndex; i++) { rowCounts[i] = external[i]; } for (int i = (int)firstLocalTableIndex; i < rowCounts.Length; i++) { rowCounts[i] = local[i]; } return rowCounts; } private int ComputeCodedTokenSize(int largeRowSize, int[] rowCounts, TableMask tablesReferenced) { if (IsMinimalDelta) { return LargeIndexSize; } bool isAllReferencedTablesSmall = true; ulong tablesReferencedMask = (ulong)tablesReferenced; for (int tableIndex = 0; tableIndex < MetadataTokens.TableCount; tableIndex++) { if ((tablesReferencedMask & 1) != 0) { isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCounts[tableIndex] < largeRowSize); } tablesReferencedMask >>= 1; } return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize; } private bool IsDeclaredSorted(TableMask index) { return (_sortedTables & index) != 0; } #endregion #region Helpers internal bool UseFieldPtrTable => FieldPtrTable.NumberOfRows > 0; internal bool UseMethodPtrTable => MethodPtrTable.NumberOfRows > 0; internal bool UseParamPtrTable => ParamPtrTable.NumberOfRows > 0; internal bool UseEventPtrTable => EventPtrTable.NumberOfRows > 0; internal bool UsePropertyPtrTable => PropertyPtrTable.NumberOfRows > 0; internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId) { int typeDefRowId = typeDef.RowId; firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId); if (firstFieldRowId == 0) { firstFieldRowId = 1; lastFieldRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows; } else { lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1; } } internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId) { int typeDefRowId = typeDef.RowId; firstMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId); if (firstMethodRowId == 0) { firstMethodRowId = 1; lastMethodRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastMethodRowId = (this.UseMethodPtrTable) ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows; } else { lastMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1; } } internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId) { int eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef); if (eventMapRowId == 0) { firstEventRowId = 1; lastEventRowId = 0; return; } firstEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId); if (eventMapRowId == this.EventMapTable.NumberOfRows) { lastEventRowId = this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows; } else { lastEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1; } } internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId) { int propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef); if (propertyMapRowId == 0) { firstPropertyRowId = 1; lastPropertyRowId = 0; return; } firstPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId); if (propertyMapRowId == this.PropertyMapTable.NumberOfRows) { lastPropertyRowId = (this.UsePropertyPtrTable) ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows; } else { lastPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1; } } internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId) { int rid = methodDef.RowId; firstParamRowId = this.MethodDefTable.GetParamStart(rid); if (firstParamRowId == 0) { firstParamRowId = 1; lastParamRowId = 0; } else if (rid == this.MethodDefTable.NumberOfRows) { lastParamRowId = (this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows); } else { lastParamRowId = this.MethodDefTable.GetParamStart(rid + 1) - 1; } } internal void GetLocalVariableRange(LocalScopeHandle scope, out int firstVariableRowId, out int lastVariableRowId) { int scopeRowId = scope.RowId; firstVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId); if (firstVariableRowId == 0) { firstVariableRowId = 1; lastVariableRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastVariableRowId = this.LocalVariableTable.NumberOfRows; } else { lastVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId + 1) - 1; } } internal void GetLocalConstantRange(LocalScopeHandle scope, out int firstConstantRowId, out int lastConstantRowId) { int scopeRowId = scope.RowId; firstConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId); if (firstConstantRowId == 0) { firstConstantRowId = 1; lastConstantRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastConstantRowId = this.LocalConstantTable.NumberOfRows; } else { lastConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId + 1) - 1; } } #endregion #region Public APIs /// <summary> /// Pointer to the underlying data. /// </summary> public unsafe byte* MetadataPointer => Block.Pointer; /// <summary> /// Length of the underlying data. /// </summary> public int MetadataLength => Block.Length; /// <summary> /// Options passed to the constructor. /// </summary> public MetadataReaderOptions Options => _options; /// <summary> /// Version string read from metadata header. /// </summary> public string MetadataVersion => _versionString; /// <summary> /// Information decoded from #Pdb stream, or null if the stream is not present. /// </summary> public DebugMetadataHeader DebugMetadataHeader => _debugMetadataHeader; /// <summary> /// The kind of the metadata (plain ECMA335, WinMD, etc.). /// </summary> public MetadataKind MetadataKind => _metadataKind; /// <summary> /// Comparer used to compare strings stored in metadata. /// </summary> public MetadataStringComparer StringComparer => new MetadataStringComparer(this); /// <summary> /// The decoder used by the reader to produce <see cref="string"/> instances from UTF8 encoded byte sequences. /// </summary> public MetadataStringDecoder UTF8Decoder { get; } /// <summary> /// Returns true if the metadata represent an assembly. /// </summary> public bool IsAssembly => AssemblyTable.NumberOfRows == 1; public AssemblyReferenceHandleCollection AssemblyReferences => new AssemblyReferenceHandleCollection(this); public TypeDefinitionHandleCollection TypeDefinitions => new TypeDefinitionHandleCollection(TypeDefTable.NumberOfRows); public TypeReferenceHandleCollection TypeReferences => new TypeReferenceHandleCollection(TypeRefTable.NumberOfRows); public CustomAttributeHandleCollection CustomAttributes => new CustomAttributeHandleCollection(this); public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes => new DeclarativeSecurityAttributeHandleCollection(this); public MemberReferenceHandleCollection MemberReferences => new MemberReferenceHandleCollection(MemberRefTable.NumberOfRows); public ManifestResourceHandleCollection ManifestResources => new ManifestResourceHandleCollection(ManifestResourceTable.NumberOfRows); public AssemblyFileHandleCollection AssemblyFiles => new AssemblyFileHandleCollection(FileTable.NumberOfRows); public ExportedTypeHandleCollection ExportedTypes => new ExportedTypeHandleCollection(ExportedTypeTable.NumberOfRows); public MethodDefinitionHandleCollection MethodDefinitions => new MethodDefinitionHandleCollection(this); public FieldDefinitionHandleCollection FieldDefinitions => new FieldDefinitionHandleCollection(this); public EventDefinitionHandleCollection EventDefinitions => new EventDefinitionHandleCollection(this); public PropertyDefinitionHandleCollection PropertyDefinitions => new PropertyDefinitionHandleCollection(this); public DocumentHandleCollection Documents => new DocumentHandleCollection(this); public MethodDebugInformationHandleCollection MethodDebugInformation => new MethodDebugInformationHandleCollection(this); public LocalScopeHandleCollection LocalScopes => new LocalScopeHandleCollection(this, 0); public LocalVariableHandleCollection LocalVariables => new LocalVariableHandleCollection(this, default(LocalScopeHandle)); public LocalConstantHandleCollection LocalConstants => new LocalConstantHandleCollection(this, default(LocalScopeHandle)); public ImportScopeCollection ImportScopes => new ImportScopeCollection(this); public CustomDebugInformationHandleCollection CustomDebugInformation => new CustomDebugInformationHandleCollection(this); public AssemblyDefinition GetAssemblyDefinition() { if (!IsAssembly) { throw new InvalidOperationException(SR.MetadataImageDoesNotRepresentAnAssembly); } return new AssemblyDefinition(this); } public string GetString(StringHandle handle) { return StringHeap.GetString(handle, UTF8Decoder); } public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringHeap.GetString(handle.GetFullName(), UTF8Decoder); } return NamespaceCache.GetFullName(handle); } public byte[] GetBlobBytes(BlobHandle handle) { return BlobHeap.GetBytes(handle); } public ImmutableArray<byte> GetBlobContent(BlobHandle handle) { // TODO: We can skip a copy for virtual blobs. byte[] bytes = GetBlobBytes(handle); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetBlobReader(BlobHandle handle) { return BlobHeap.GetBlobReader(handle); } public BlobReader GetBlobReader(StringHandle handle) { return StringHeap.GetBlobReader(handle); } public string GetUserString(UserStringHandle handle) { return UserStringHeap.GetString(handle); } public Guid GetGuid(GuidHandle handle) { return GuidHeap.GetGuid(handle); } public ModuleDefinition GetModuleDefinition() { if (_debugMetadataHeader != null) { throw new InvalidOperationException(SR.StandaloneDebugMetadataImageDoesNotContainModuleTable); } return new ModuleDefinition(this); } public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle) { return new AssemblyReference(this, handle.Value); } public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle)); } public NamespaceDefinition GetNamespaceDefinitionRoot() { NamespaceData data = NamespaceCache.GetRootNamespace(); return new NamespaceDefinition(data); } public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) { NamespaceData data = NamespaceCache.GetNamespaceData(handle); return new NamespaceDefinition(data); } private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeDefTreatmentAndRowId(handle); } public TypeReference GetTypeReference(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle)); } private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeRefTreatmentAndRowId(handle); } public ExportedType GetExportedType(ExportedTypeHandle handle) { return new ExportedType(this, handle.RowId); } public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle) { return new CustomAttributeHandleCollection(this, handle); } public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle)); } private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId); } public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new DeclarativeSecurityAttribute(this, handle.RowId); } public Constant GetConstant(ConstantHandle handle) { return new Constant(this, handle.RowId); } public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle)); } private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMethodDefTreatmentAndRowId(handle); } public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle)); } private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateFieldDefTreatmentAndRowId(handle); } public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle) { return new PropertyDefinition(this, handle); } public EventDefinition GetEventDefinition(EventDefinitionHandle handle) { return new EventDefinition(this, handle); } public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle) { return new MethodImplementation(this, handle); } public MemberReference GetMemberReference(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle)); } private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMemberRefTreatmentAndRowId(handle); } public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle) { return new MethodSpecification(this, handle); } public Parameter GetParameter(ParameterHandle handle) { return new Parameter(this, handle); } public GenericParameter GetGenericParameter(GenericParameterHandle handle) { return new GenericParameter(this, handle); } public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle) { return new GenericParameterConstraint(this, handle); } public ManifestResource GetManifestResource(ManifestResourceHandle handle) { return new ManifestResource(this, handle); } public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle) { return new AssemblyFile(this, handle); } public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle) { return new StandaloneSignature(this, handle); } public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle) { return new TypeSpecification(this, handle); } public ModuleReference GetModuleReference(ModuleReferenceHandle handle) { return new ModuleReference(this, handle); } public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle) { return new InterfaceImplementation(this, handle); } internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef) { int methodRowId; if (UseMethodPtrTable) { methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId); } else { methodRowId = methodDef.RowId; } return TypeDefTable.FindTypeContainingMethod(methodRowId, MethodDefTable.NumberOfRows); } internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef) { int fieldRowId; if (UseFieldPtrTable) { fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId); } else { fieldRowId = fieldDef.RowId; } return TypeDefTable.FindTypeContainingField(fieldRowId, FieldTable.NumberOfRows); } private static readonly ObjectPool<StringBuilder> s_stringBuilderPool = new ObjectPool<StringBuilder>(() => new StringBuilder()); public string GetString(DocumentNameBlobHandle handle) { return BlobHeap.GetDocumentName(handle); } public Document GetDocument(DocumentHandle handle) { return new Document(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDebugInformationHandle handle) { return new MethodDebugInformation(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDefinitionHandle handle) { return new MethodDebugInformation(this, MethodDebugInformationHandle.FromRowId(handle.RowId)); } public LocalScope GetLocalScope(LocalScopeHandle handle) { return new LocalScope(this, handle); } public LocalVariable GetLocalVariable(LocalVariableHandle handle) { return new LocalVariable(this, handle); } public LocalConstant GetLocalConstant(LocalConstantHandle handle) { return new LocalConstant(this, handle); } public ImportScope GetImportScope(ImportScopeHandle handle) { return new ImportScope(this, handle); } public CustomDebugInformation GetCustomDebugInformation(CustomDebugInformationHandle handle) { return new CustomDebugInformation(this, handle); } public CustomDebugInformationHandleCollection GetCustomDebugInformation(EntityHandle handle) { return new CustomDebugInformationHandleCollection(this, handle); } public LocalScopeHandleCollection GetLocalScopes(MethodDefinitionHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } public LocalScopeHandleCollection GetLocalScopes(MethodDebugInformationHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } #endregion #region Nested Types private void InitializeNestedTypesMap() { var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>(); int numberOfNestedTypes = NestedClassTable.NumberOfRows; ImmutableArray<TypeDefinitionHandle>.Builder builder = null; TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle); for (int i = 1; i <= numberOfNestedTypes; i++) { TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i); Debug.Assert(!enclosingClass.IsNil); if (enclosingClass != previousEnclosingClass) { if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder)) { builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); groupedNestedTypes.Add(enclosingClass, builder); } previousEnclosingClass = enclosingClass; } else { Debug.Assert(builder == groupedNestedTypes[enclosingClass]); } builder.Add(NestedClassTable.GetNestedClass(i)); } var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>(); foreach (var group in groupedNestedTypes) { nestedTypesMap.Add(group.Key, group.Value.ToImmutable()); } _lazyNestedTypesMap = nestedTypesMap; } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef) { if (_lazyNestedTypesMap == null) { InitializeNestedTypesMap(); } ImmutableArray<TypeDefinitionHandle> nestedTypes; if (_lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes)) { return nestedTypes; } return ImmutableArray<TypeDefinitionHandle>.Empty; } #endregion } }
namespace DockSample { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.mainMenu = new System.Windows.Forms.MenuStrip(); this.menuItemFile = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemNew = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemOpen = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemClose = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemCloseAll = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemCloseAllButThisOne = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemExit = new System.Windows.Forms.ToolStripMenuItem(); this.exitWithoutSavingLayout = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemView = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSolutionExplorer = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemPropertyWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemToolbox = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemOutputWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemTaskList = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemToolBar = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemStatusBar = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemLayoutByCode = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemLayoutByXml = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemTools = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemLockLayout = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemShowDocumentIcon = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemSchemaVS2005 = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2003 = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem6 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemDockingMdi = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemDockingSdi = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemDockingWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSystemMdi = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.showRightToLeft = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemNewWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemHelp = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemAbout = new System.Windows.Forms.ToolStripMenuItem(); this.statusBar = new System.Windows.Forms.StatusStrip(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.toolBar = new System.Windows.Forms.ToolStrip(); this.toolBarButtonNew = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonOpen = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolBarButtonSolutionExplorer = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonPropertyWindow = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonToolbox = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonOutputWindow = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonTaskList = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolBarButtonLayoutByCode = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonLayoutByXml = new System.Windows.Forms.ToolStripButton(); this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel(); this.mainMenu.SuspendLayout(); this.toolBar.SuspendLayout(); this.SuspendLayout(); // // mainMenu // this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemFile, this.menuItemView, this.menuItemTools, this.menuItemWindow, this.menuItemHelp}); this.mainMenu.Location = new System.Drawing.Point(0, 0); this.mainMenu.MdiWindowListItem = this.menuItemWindow; this.mainMenu.Name = "mainMenu"; this.mainMenu.Size = new System.Drawing.Size(579, 24); this.mainMenu.TabIndex = 7; // // menuItemFile // this.menuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemNew, this.menuItemOpen, this.menuItemClose, this.menuItemCloseAll, this.menuItemCloseAllButThisOne, this.menuItem4, this.menuItemExit, this.exitWithoutSavingLayout}); this.menuItemFile.Name = "menuItemFile"; this.menuItemFile.Size = new System.Drawing.Size(37, 20); this.menuItemFile.Text = "&File"; this.menuItemFile.DropDownOpening += new System.EventHandler(this.menuItemFile_Popup); // // menuItemNew // this.menuItemNew.Name = "menuItemNew"; this.menuItemNew.Size = new System.Drawing.Size(215, 22); this.menuItemNew.Text = "&New"; this.menuItemNew.Click += new System.EventHandler(this.menuItemNew_Click); // // menuItemOpen // this.menuItemOpen.Name = "menuItemOpen"; this.menuItemOpen.Size = new System.Drawing.Size(215, 22); this.menuItemOpen.Text = "&Open..."; this.menuItemOpen.Click += new System.EventHandler(this.menuItemOpen_Click); // // menuItemClose // this.menuItemClose.Name = "menuItemClose"; this.menuItemClose.Size = new System.Drawing.Size(215, 22); this.menuItemClose.Text = "&Close"; this.menuItemClose.Click += new System.EventHandler(this.menuItemClose_Click); // // menuItemCloseAll // this.menuItemCloseAll.Name = "menuItemCloseAll"; this.menuItemCloseAll.Size = new System.Drawing.Size(215, 22); this.menuItemCloseAll.Text = "Close &All"; this.menuItemCloseAll.Click += new System.EventHandler(this.menuItemCloseAll_Click); // // menuItemCloseAllButThisOne // this.menuItemCloseAllButThisOne.Name = "menuItemCloseAllButThisOne"; this.menuItemCloseAllButThisOne.Size = new System.Drawing.Size(215, 22); this.menuItemCloseAllButThisOne.Text = "Close All &But This One"; this.menuItemCloseAllButThisOne.Click += new System.EventHandler(this.menuItemCloseAllButThisOne_Click); // // menuItem4 // this.menuItem4.Name = "menuItem4"; this.menuItem4.Size = new System.Drawing.Size(212, 6); // // menuItemExit // this.menuItemExit.Name = "menuItemExit"; this.menuItemExit.Size = new System.Drawing.Size(215, 22); this.menuItemExit.Text = "&Exit"; this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click); // // exitWithoutSavingLayout // this.exitWithoutSavingLayout.Name = "exitWithoutSavingLayout"; this.exitWithoutSavingLayout.Size = new System.Drawing.Size(215, 22); this.exitWithoutSavingLayout.Text = "Exit &Without Saving Layout"; this.exitWithoutSavingLayout.Click += new System.EventHandler(this.exitWithoutSavingLayout_Click); // // menuItemView // this.menuItemView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemSolutionExplorer, this.menuItemPropertyWindow, this.menuItemToolbox, this.menuItemOutputWindow, this.menuItemTaskList, this.menuItem1, this.menuItemToolBar, this.menuItemStatusBar, this.menuItem2, this.menuItemLayoutByCode, this.menuItemLayoutByXml}); this.menuItemView.MergeIndex = 1; this.menuItemView.Name = "menuItemView"; this.menuItemView.Size = new System.Drawing.Size(44, 20); this.menuItemView.Text = "&View"; // // menuItemSolutionExplorer // this.menuItemSolutionExplorer.Name = "menuItemSolutionExplorer"; this.menuItemSolutionExplorer.Size = new System.Drawing.Size(185, 22); this.menuItemSolutionExplorer.Text = "&Solution Explorer"; this.menuItemSolutionExplorer.Click += new System.EventHandler(this.menuItemSolutionExplorer_Click); // // menuItemPropertyWindow // this.menuItemPropertyWindow.Name = "menuItemPropertyWindow"; this.menuItemPropertyWindow.ShortcutKeys = System.Windows.Forms.Keys.F4; this.menuItemPropertyWindow.Size = new System.Drawing.Size(185, 22); this.menuItemPropertyWindow.Text = "&Property Window"; this.menuItemPropertyWindow.Click += new System.EventHandler(this.menuItemPropertyWindow_Click); // // menuItemToolbox // this.menuItemToolbox.Name = "menuItemToolbox"; this.menuItemToolbox.Size = new System.Drawing.Size(185, 22); this.menuItemToolbox.Text = "&Toolbox"; this.menuItemToolbox.Click += new System.EventHandler(this.menuItemToolbox_Click); // // menuItemOutputWindow // this.menuItemOutputWindow.Name = "menuItemOutputWindow"; this.menuItemOutputWindow.Size = new System.Drawing.Size(185, 22); this.menuItemOutputWindow.Text = "&Output Window"; this.menuItemOutputWindow.Click += new System.EventHandler(this.menuItemOutputWindow_Click); // // menuItemTaskList // this.menuItemTaskList.Name = "menuItemTaskList"; this.menuItemTaskList.Size = new System.Drawing.Size(185, 22); this.menuItemTaskList.Text = "Task &List"; this.menuItemTaskList.Click += new System.EventHandler(this.menuItemTaskList_Click); // // menuItem1 // this.menuItem1.Name = "menuItem1"; this.menuItem1.Size = new System.Drawing.Size(182, 6); // // menuItemToolBar // this.menuItemToolBar.Checked = true; this.menuItemToolBar.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemToolBar.Name = "menuItemToolBar"; this.menuItemToolBar.Size = new System.Drawing.Size(185, 22); this.menuItemToolBar.Text = "Tool &Bar"; this.menuItemToolBar.Click += new System.EventHandler(this.menuItemToolBar_Click); // // menuItemStatusBar // this.menuItemStatusBar.Checked = true; this.menuItemStatusBar.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemStatusBar.Name = "menuItemStatusBar"; this.menuItemStatusBar.Size = new System.Drawing.Size(185, 22); this.menuItemStatusBar.Text = "Status B&ar"; this.menuItemStatusBar.Click += new System.EventHandler(this.menuItemStatusBar_Click); // // menuItem2 // this.menuItem2.Name = "menuItem2"; this.menuItem2.Size = new System.Drawing.Size(182, 6); // // menuItemLayoutByCode // this.menuItemLayoutByCode.Name = "menuItemLayoutByCode"; this.menuItemLayoutByCode.Size = new System.Drawing.Size(185, 22); this.menuItemLayoutByCode.Text = "Layout By &Code"; this.menuItemLayoutByCode.Click += new System.EventHandler(this.menuItemLayoutByCode_Click); // // menuItemLayoutByXml // this.menuItemLayoutByXml.Name = "menuItemLayoutByXml"; this.menuItemLayoutByXml.Size = new System.Drawing.Size(185, 22); this.menuItemLayoutByXml.Text = "Layout By &XML"; this.menuItemLayoutByXml.Click += new System.EventHandler(this.menuItemLayoutByXml_Click); // // menuItemTools // this.menuItemTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemLockLayout, this.menuItemShowDocumentIcon, this.menuItem3, this.menuItemSchemaVS2005, this.menuItemSchemaVS2003, this.menuItem6, this.menuItemDockingMdi, this.menuItemDockingSdi, this.menuItemDockingWindow, this.menuItemSystemMdi, this.menuItem5, this.showRightToLeft}); this.menuItemTools.MergeIndex = 2; this.menuItemTools.Name = "menuItemTools"; this.menuItemTools.Size = new System.Drawing.Size(48, 20); this.menuItemTools.Text = "&Tools"; this.menuItemTools.DropDownOpening += new System.EventHandler(this.menuItemTools_Popup); // // menuItemLockLayout // this.menuItemLockLayout.Name = "menuItemLockLayout"; this.menuItemLockLayout.Size = new System.Drawing.Size(255, 22); this.menuItemLockLayout.Text = "&Lock Layout"; this.menuItemLockLayout.Click += new System.EventHandler(this.menuItemLockLayout_Click); // // menuItemShowDocumentIcon // this.menuItemShowDocumentIcon.Name = "menuItemShowDocumentIcon"; this.menuItemShowDocumentIcon.Size = new System.Drawing.Size(255, 22); this.menuItemShowDocumentIcon.Text = "&Show Document Icon"; this.menuItemShowDocumentIcon.Click += new System.EventHandler(this.menuItemShowDocumentIcon_Click); // // menuItem3 // this.menuItem3.Name = "menuItem3"; this.menuItem3.Size = new System.Drawing.Size(252, 6); // // menuItemSchemaVS2005 // this.menuItemSchemaVS2005.Checked = true; this.menuItemSchemaVS2005.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemSchemaVS2005.Name = "menuItemSchemaVS2005"; this.menuItemSchemaVS2005.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2005.Text = "Schema: VS200&5"; this.menuItemSchemaVS2005.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2003 // this.menuItemSchemaVS2003.Name = "menuItemSchemaVS2003"; this.menuItemSchemaVS2003.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2003.Text = "Schema: VS200&3"; this.menuItemSchemaVS2003.Click += new System.EventHandler(this.SetSchema); // // menuItem6 // this.menuItem6.Name = "menuItem6"; this.menuItem6.Size = new System.Drawing.Size(252, 6); // // menuItemDockingMdi // this.menuItemDockingMdi.Checked = true; this.menuItemDockingMdi.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemDockingMdi.Name = "menuItemDockingMdi"; this.menuItemDockingMdi.Size = new System.Drawing.Size(255, 22); this.menuItemDockingMdi.Text = "Document Style: Docking &MDI"; this.menuItemDockingMdi.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItemDockingSdi // this.menuItemDockingSdi.Name = "menuItemDockingSdi"; this.menuItemDockingSdi.Size = new System.Drawing.Size(255, 22); this.menuItemDockingSdi.Text = "Document Style: Docking &SDI"; this.menuItemDockingSdi.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItemDockingWindow // this.menuItemDockingWindow.Name = "menuItemDockingWindow"; this.menuItemDockingWindow.Size = new System.Drawing.Size(255, 22); this.menuItemDockingWindow.Text = "Document Style: Docking &Window"; this.menuItemDockingWindow.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItemSystemMdi // this.menuItemSystemMdi.Name = "menuItemSystemMdi"; this.menuItemSystemMdi.Size = new System.Drawing.Size(255, 22); this.menuItemSystemMdi.Text = "Document Style: S&ystem MDI"; this.menuItemSystemMdi.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItem5 // this.menuItem5.Name = "menuItem5"; this.menuItem5.Size = new System.Drawing.Size(252, 6); // // showRightToLeft // this.showRightToLeft.Name = "showRightToLeft"; this.showRightToLeft.Size = new System.Drawing.Size(255, 22); this.showRightToLeft.Text = "Show &Right-To-Left"; this.showRightToLeft.Click += new System.EventHandler(this.showRightToLeft_Click); // // menuItemWindow // this.menuItemWindow.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemNewWindow}); this.menuItemWindow.MergeIndex = 2; this.menuItemWindow.Name = "menuItemWindow"; this.menuItemWindow.Size = new System.Drawing.Size(63, 20); this.menuItemWindow.Text = "&Window"; // // menuItemNewWindow // this.menuItemNewWindow.Name = "menuItemNewWindow"; this.menuItemNewWindow.Size = new System.Drawing.Size(145, 22); this.menuItemNewWindow.Text = "&New Window"; this.menuItemNewWindow.Click += new System.EventHandler(this.menuItemNewWindow_Click); // // menuItemHelp // this.menuItemHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemAbout}); this.menuItemHelp.MergeIndex = 3; this.menuItemHelp.Name = "menuItemHelp"; this.menuItemHelp.Size = new System.Drawing.Size(44, 20); this.menuItemHelp.Text = "&Help"; // // menuItemAbout // this.menuItemAbout.Name = "menuItemAbout"; this.menuItemAbout.Size = new System.Drawing.Size(185, 22); this.menuItemAbout.Text = "&About DockSample..."; this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 387); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(579, 22); this.statusBar.TabIndex = 4; // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, ""); this.imageList.Images.SetKeyName(1, ""); this.imageList.Images.SetKeyName(2, ""); this.imageList.Images.SetKeyName(3, ""); this.imageList.Images.SetKeyName(4, ""); this.imageList.Images.SetKeyName(5, ""); this.imageList.Images.SetKeyName(6, ""); this.imageList.Images.SetKeyName(7, ""); this.imageList.Images.SetKeyName(8, ""); // // toolBar // this.toolBar.ImageList = this.imageList; this.toolBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolBarButtonNew, this.toolBarButtonOpen, this.toolBarButtonSeparator1, this.toolBarButtonSolutionExplorer, this.toolBarButtonPropertyWindow, this.toolBarButtonToolbox, this.toolBarButtonOutputWindow, this.toolBarButtonTaskList, this.toolBarButtonSeparator2, this.toolBarButtonLayoutByCode, this.toolBarButtonLayoutByXml}); this.toolBar.Location = new System.Drawing.Point(0, 24); this.toolBar.Name = "toolBar"; this.toolBar.Size = new System.Drawing.Size(579, 25); this.toolBar.TabIndex = 6; this.toolBar.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolBar_ButtonClick); // // toolBarButtonNew // this.toolBarButtonNew.ImageIndex = 0; this.toolBarButtonNew.Name = "toolBarButtonNew"; this.toolBarButtonNew.Size = new System.Drawing.Size(23, 22); this.toolBarButtonNew.ToolTipText = "Show Layout From XML"; // // toolBarButtonOpen // this.toolBarButtonOpen.ImageIndex = 1; this.toolBarButtonOpen.Name = "toolBarButtonOpen"; this.toolBarButtonOpen.Size = new System.Drawing.Size(23, 22); this.toolBarButtonOpen.ToolTipText = "Open"; // // toolBarButtonSeparator1 // this.toolBarButtonSeparator1.Name = "toolBarButtonSeparator1"; this.toolBarButtonSeparator1.Size = new System.Drawing.Size(6, 25); // // toolBarButtonSolutionExplorer // this.toolBarButtonSolutionExplorer.ImageIndex = 2; this.toolBarButtonSolutionExplorer.Name = "toolBarButtonSolutionExplorer"; this.toolBarButtonSolutionExplorer.Size = new System.Drawing.Size(23, 22); this.toolBarButtonSolutionExplorer.ToolTipText = "Solution Explorer"; // // toolBarButtonPropertyWindow // this.toolBarButtonPropertyWindow.ImageIndex = 3; this.toolBarButtonPropertyWindow.Name = "toolBarButtonPropertyWindow"; this.toolBarButtonPropertyWindow.Size = new System.Drawing.Size(23, 22); this.toolBarButtonPropertyWindow.ToolTipText = "Property Window"; // // toolBarButtonToolbox // this.toolBarButtonToolbox.ImageIndex = 4; this.toolBarButtonToolbox.Name = "toolBarButtonToolbox"; this.toolBarButtonToolbox.Size = new System.Drawing.Size(23, 22); this.toolBarButtonToolbox.ToolTipText = "Tool Box"; // // toolBarButtonOutputWindow // this.toolBarButtonOutputWindow.ImageIndex = 5; this.toolBarButtonOutputWindow.Name = "toolBarButtonOutputWindow"; this.toolBarButtonOutputWindow.Size = new System.Drawing.Size(23, 22); this.toolBarButtonOutputWindow.ToolTipText = "Output Window"; // // toolBarButtonTaskList // this.toolBarButtonTaskList.ImageIndex = 6; this.toolBarButtonTaskList.Name = "toolBarButtonTaskList"; this.toolBarButtonTaskList.Size = new System.Drawing.Size(23, 22); this.toolBarButtonTaskList.ToolTipText = "Task List"; // // toolBarButtonSeparator2 // this.toolBarButtonSeparator2.Name = "toolBarButtonSeparator2"; this.toolBarButtonSeparator2.Size = new System.Drawing.Size(6, 25); // // toolBarButtonLayoutByCode // this.toolBarButtonLayoutByCode.ImageIndex = 7; this.toolBarButtonLayoutByCode.Name = "toolBarButtonLayoutByCode"; this.toolBarButtonLayoutByCode.Size = new System.Drawing.Size(23, 22); this.toolBarButtonLayoutByCode.ToolTipText = "Show Layout By Code"; // // toolBarButtonLayoutByXml // this.toolBarButtonLayoutByXml.ImageIndex = 8; this.toolBarButtonLayoutByXml.Name = "toolBarButtonLayoutByXml"; this.toolBarButtonLayoutByXml.Size = new System.Drawing.Size(23, 22); this.toolBarButtonLayoutByXml.ToolTipText = "Show layout by predefined XML file"; // // dockPanel // this.dockPanel.ActiveAutoHideContent = null; this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.dockPanel.DockBackColor = System.Drawing.SystemColors.AppWorkspace; this.dockPanel.DockBottomPortion = 150; this.dockPanel.DockLeftPortion = 200; this.dockPanel.DockRightPortion = 200; this.dockPanel.DockTopPortion = 150; this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, ((byte)(0))); this.dockPanel.Location = new System.Drawing.Point(0, 49); this.dockPanel.Name = "dockPanel"; this.dockPanel.RightToLeftLayout = true; this.dockPanel.Size = new System.Drawing.Size(579, 338); this.dockPanel.TabIndex = 0; // // MainForm // this.ClientSize = new System.Drawing.Size(579, 409); this.Controls.Add(this.dockPanel); this.Controls.Add(this.toolBar); this.Controls.Add(this.mainMenu); this.Controls.Add(this.statusBar); this.IsMdiContainer = true; this.MainMenuStrip = this.mainMenu; this.Name = "MainForm"; this.Text = "DockSample"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.MainForm_Load); this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); this.mainMenu.ResumeLayout(false); this.mainMenu.PerformLayout(); this.toolBar.ResumeLayout(false); this.toolBar.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel; private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.ToolStrip toolBar; private System.Windows.Forms.ToolStripButton toolBarButtonNew; private System.Windows.Forms.ToolStripButton toolBarButtonOpen; private System.Windows.Forms.ToolStripSeparator toolBarButtonSeparator1; private System.Windows.Forms.ToolStripButton toolBarButtonSolutionExplorer; private System.Windows.Forms.ToolStripButton toolBarButtonPropertyWindow; private System.Windows.Forms.ToolStripButton toolBarButtonToolbox; private System.Windows.Forms.ToolStripButton toolBarButtonOutputWindow; private System.Windows.Forms.ToolStripButton toolBarButtonTaskList; private System.Windows.Forms.ToolStripSeparator toolBarButtonSeparator2; private System.Windows.Forms.ToolStripButton toolBarButtonLayoutByCode; private System.Windows.Forms.ToolStripButton toolBarButtonLayoutByXml; private System.Windows.Forms.MenuStrip mainMenu; private System.Windows.Forms.ToolStripMenuItem menuItemFile; private System.Windows.Forms.ToolStripMenuItem menuItemNew; private System.Windows.Forms.ToolStripMenuItem menuItemOpen; private System.Windows.Forms.ToolStripMenuItem menuItemClose; private System.Windows.Forms.ToolStripMenuItem menuItemCloseAll; private System.Windows.Forms.ToolStripMenuItem menuItemCloseAllButThisOne; private System.Windows.Forms.ToolStripSeparator menuItem4; private System.Windows.Forms.ToolStripMenuItem menuItemExit; private System.Windows.Forms.ToolStripMenuItem menuItemView; private System.Windows.Forms.ToolStripMenuItem menuItemSolutionExplorer; private System.Windows.Forms.ToolStripMenuItem menuItemPropertyWindow; private System.Windows.Forms.ToolStripMenuItem menuItemToolbox; private System.Windows.Forms.ToolStripMenuItem menuItemOutputWindow; private System.Windows.Forms.ToolStripMenuItem menuItemTaskList; private System.Windows.Forms.ToolStripSeparator menuItem1; private System.Windows.Forms.ToolStripMenuItem menuItemToolBar; private System.Windows.Forms.ToolStripMenuItem menuItemStatusBar; private System.Windows.Forms.ToolStripSeparator menuItem2; private System.Windows.Forms.ToolStripMenuItem menuItemLayoutByCode; private System.Windows.Forms.ToolStripMenuItem menuItemLayoutByXml; private System.Windows.Forms.ToolStripMenuItem menuItemTools; private System.Windows.Forms.ToolStripMenuItem menuItemLockLayout; private System.Windows.Forms.ToolStripSeparator menuItem3; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2005; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2003; private System.Windows.Forms.ToolStripSeparator menuItem6; private System.Windows.Forms.ToolStripMenuItem menuItemDockingMdi; private System.Windows.Forms.ToolStripMenuItem menuItemDockingSdi; private System.Windows.Forms.ToolStripMenuItem menuItemDockingWindow; private System.Windows.Forms.ToolStripMenuItem menuItemSystemMdi; private System.Windows.Forms.ToolStripSeparator menuItem5; private System.Windows.Forms.ToolStripMenuItem menuItemShowDocumentIcon; private System.Windows.Forms.ToolStripMenuItem menuItemWindow; private System.Windows.Forms.ToolStripMenuItem menuItemNewWindow; private System.Windows.Forms.ToolStripMenuItem menuItemHelp; private System.Windows.Forms.ToolStripMenuItem menuItemAbout; private System.Windows.Forms.StatusStrip statusBar; private System.Windows.Forms.ToolStripMenuItem showRightToLeft; private System.Windows.Forms.ToolStripMenuItem exitWithoutSavingLayout; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Culture-specific collection of resources. ** ** ===========================================================*/ using System; using System.Collections; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Resources { // A ResourceSet stores all the resources defined in one particular CultureInfo. // // The method used to load resources is straightforward - this class // enumerates over an IResourceReader, loading every name and value, and // stores them in a hash table. Custom IResourceReaders can be used. // [Serializable] public class ResourceSet : IDisposable, IEnumerable { [NonSerialized] protected IResourceReader Reader; private Dictionary<object, object> _table; private Dictionary<object, object> _caseInsensitiveTable; // For case-insensitive lookups. protected ResourceSet() { // To not inconvenience people subclassing us, we should allocate a new // hashtable here just so that Table is set to something. CommonInit(); } // For RuntimeResourceSet, ignore the Table parameter - it's a wasted // allocation. internal ResourceSet(bool junk) { } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to open & read from a file // on disk. // public ResourceSet(String fileName) { Reader = new ResourceReader(fileName); CommonInit(); ReadResources(); } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to read from an open stream // of data. // public ResourceSet(Stream stream) { Reader = new ResourceReader(stream); CommonInit(); ReadResources(); } public ResourceSet(IResourceReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); ReadResources(); } private void CommonInit() { _table = new Dictionary<object, object>(); } // Closes and releases any resources used by this ResourceSet, if any. // All calls to methods on the ResourceSet after a call to close may // fail. Close is guaranteed to be safely callable multiple times on a // particular ResourceSet, and all subclasses must support these semantics. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { // Close the Reader in a thread-safe way. IResourceReader copyOfReader = Reader; Reader = null; if (copyOfReader != null) copyOfReader.Close(); } Reader = null; _caseInsensitiveTable = null; _table = null; } public void Dispose() { Dispose(true); } // Returns the preferred IResourceReader class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultReader() { return typeof(ResourceReader); } // Returns the preferred IResourceWriter class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultWriter() { Assembly resourceWriterAssembly = Assembly.Load("System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); return resourceWriterAssembly.GetType("System.Resources.ResourceWriter", true); } public virtual IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { Dictionary<object, object> copyOfTable = _table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable.GetEnumerator(); } // Look up a string value for a resource given its name. // public virtual String GetString(String name) { Object obj = GetObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } } public virtual String GetString(String name, bool ignoreCase) { Object obj; String s; // Case-sensitive lookup obj = GetObjectInternal(name); try { s = (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } // case-sensitive lookup succeeded if (s != null || !ignoreCase) { return s; } // Try doing a case-insensitive lookup obj = GetCaseInsensitiveObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } } // Look up an object value for a resource given its name. // public virtual Object GetObject(String name) { return GetObjectInternal(name); } public virtual Object GetObject(String name, bool ignoreCase) { Object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; return GetCaseInsensitiveObjectInternal(name); } protected virtual void ReadResources() { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { Object value = en.Value; _table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } private Object GetObjectInternal(String name) { if (name == null) throw new ArgumentNullException("name"); Contract.EndContractBlock(); Dictionary<object, object> copyOfTable = _table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); object value; copyOfTable.TryGetValue(name, out value); return value; } private Object GetCaseInsensitiveObjectInternal(String name) { Dictionary<object, object> copyOfTable = _table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); Dictionary<object, object> caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { caseTable = new Dictionary<object, object>(CaseInsensitiveStringObjectComparer.Instance); IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) { caseTable.Add(en.Key, en.Value); } _caseInsensitiveTable = caseTable; } object value; caseTable.TryGetValue(name, out value); return value; } /// <summary> /// Adapter for StringComparer.OrdinalIgnoreCase to allow it to be used with Dictionary /// </summary> private class CaseInsensitiveStringObjectComparer : IEqualityComparer<object> { public static CaseInsensitiveStringObjectComparer Instance { get; } = new CaseInsensitiveStringObjectComparer(); private CaseInsensitiveStringObjectComparer() { } public new bool Equals(object x, object y) { return ((IEqualityComparer)StringComparer.OrdinalIgnoreCase).Equals(x, y); } public int GetHashCode(object obj) { return ((IEqualityComparer)StringComparer.OrdinalIgnoreCase).GetHashCode(obj); } } } }
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) Lead Pipe Software. All rights reserved. // Licensed under the MIT License. Please see the LICENSE file in the project root for full license information. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.Serialization; namespace LeadPipe.Net { /// <summary> /// The enumeration supertype. /// </summary> /// <remarks><para> /// A frequent problem with standard enumerations is that they often lead to gnarly switch statements. For example: /// </para> /// <code> /// public class Employee /// { /// public EmployeeType Type { get; set; } /// } /// public enum EmployeeType /// { /// FullTime, /// PartTime, /// Contract /// } /// public void ApplyBonus(Employee employee) /// { /// switch(employee.Type) /// { /// case EmployeeType.FullTime: /// employee.Bonus = 1000m; /// break; /// case EmployeeType.PartTime: /// employee.Bonus = 1.0m; /// case EmployeeType.Contract: /// employee.Bonus = 0.01m; /// default: /// throw new ArgumentOutOfRangeException(); /// } /// } /// </code> /// <para> /// The trouble is that behavior related to the enumeration will often become scattered throughout the application /// and simple activities such as adding a new enumeration get messy. Using this class we can do this instead: /// </para> /// <code> /// public class EmployeeType : Enumeration /// { /// public static readonly EmployeeType FullTime = new EmployeeType(0, "Full Time"); /// public static readonly EmployeeType PartTime = new EmployeeType(1, "Part Time"); /// public static readonly EmployeeType Contract = new EmployeeType(2, "Contract"); /// private EmployeeType () /// { /// } /// private EmployeeType(int value, string displayName) : base(value, displayName) /// { /// } /// } /// </code> /// <para> /// The actual enumeration doesn't look any different in code. You can still do this: /// </para> /// <code> /// gregMajor.Type = EmployeeType.FullTime; /// </code> /// <para> /// Ah, but now we have a place to put behavior associated with the enumeration which means we can do this: /// </para> /// <code> /// public void ApplyBonus(Employee employee) /// { /// employee.Bonus = employee.Type.BonusSize; /// } /// </code> /// <para> /// See what happened there? The entire switch statement got dropped to a single line of code. How did we do that? /// Well, we could have simply assigned the enum's BonusSize value somewhere. We could have also done this: /// </para> /// <code> /// public abstract class EmployeeType : Enumeration /// { /// public static readonly EmployeeType FullTime = new FullTimeEmployeeType(); /// protected EmployeeType() /// { /// } /// protected EmployeeType(int value, string displayName) : base(value, displayName) /// { /// } /// public abstract decimal BonusSize { get; } /// public override decimal BonusSize /// { /// get { return 1000m; } /// } /// } /// </code> /// <para> /// Pretty cool, huh? Now we can zero in on implementation without having to hunt all over our code for references /// to the enumeration. This is basically just the Strategy pattern applied to the enumeration class idea. Props to /// Jimmy Bogard (http://lostechies.com/jimmybogard) for laying this one out. /// </para></remarks> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")] [Serializable] [DebuggerDisplay("{DisplayName} - {Value}")] public abstract class Enumeration<TEnumeration> : Enumeration<TEnumeration, int> where TEnumeration : Enumeration<TEnumeration> { protected Enumeration(int value, string displayName) : base(value, displayName) { } public static TEnumeration FromInt32(int value) { return FromValue(value); } public static bool TryFromInt32(int listItemValue, out TEnumeration result) { return TryParse(listItemValue, out result); } } [Serializable] [DebuggerDisplay("{DisplayName} - {Value}")] [DataContract(Namespace = "https://github.com/LeadPipeSoftware/LeadPipe.Net")] public abstract class Enumeration<TEnumeration, TValue> : IComparable<TEnumeration>, IEquatable<TEnumeration> where TEnumeration : Enumeration<TEnumeration, TValue> where TValue : IComparable { private static Lazy<TEnumeration[]> enumerations = new Lazy<TEnumeration[]>(GetEnumerations); [DataMember(Order = 1)] private readonly string displayName; [DataMember(Order = 0)] private readonly TValue value; protected Enumeration(TValue value, string displayName) { this.value = value; this.displayName = displayName; } public string DisplayName { get { return displayName; } } public TValue Value { get { return value; } } public static TEnumeration FromValue(TValue value) { return Parse(value, "value", item => item.Value.Equals(value)); } public static TEnumeration[] GetAll() { return enumerations.Value; } public static bool operator !=(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) { return !Equals(left, right); } public static bool operator ==(Enumeration<TEnumeration, TValue> left, Enumeration<TEnumeration, TValue> right) { return Equals(left, right); } public static TEnumeration Parse(string displayName) { return Parse(displayName, "display name", item => item.DisplayName == displayName); } public static bool TryParse(TValue value, out TEnumeration result) { return TryParse(e => e.Value.Equals(value), out result); } public static bool TryParse(string displayName, out TEnumeration result) { return TryParse(e => e.DisplayName == displayName, out result); } public int CompareTo(TEnumeration other) { return Value.CompareTo(other.Value); } public override bool Equals(object obj) { return Equals(obj as TEnumeration); } public bool Equals(TEnumeration other) { return other != null && Value.Equals(other.Value); } public override int GetHashCode() { return Value.GetHashCode(); } public sealed override string ToString() { return DisplayName; } private static TEnumeration[] GetEnumerations() { var enumerationType = typeof(TEnumeration); return enumerationType .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) .Where(info => enumerationType.IsAssignableFrom(info.FieldType)) .Select(info => info.GetValue(null)) .Cast<TEnumeration>() .ToArray(); } private static TEnumeration Parse(object value, string description, Func<TEnumeration, bool> predicate) { TEnumeration result; if (!TryParse(predicate, out result)) { string message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(TEnumeration)); throw new ArgumentException(message, "value"); } return result; } private static bool TryParse(Func<TEnumeration, bool> predicate, out TEnumeration result) { result = GetAll().FirstOrDefault(predicate); return result != null; } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents an attachment to an item. /// </summary> public abstract class Attachment : ComplexProperty { private Item owner; private string id; private string name; private string contentType; private string contentId; private string contentLocation; private int size; private DateTime lastModifiedTime; private bool isInline; private ExchangeService service; /// <summary> /// Initializes a new instance of the <see cref="Attachment"/> class. /// </summary> /// <param name="owner">The owner.</param> internal Attachment(Item owner) { this.owner = owner; if (owner != null) { this.service = this.owner.Service; } } /// <summary> /// Initializes a new instance of the <see cref="Attachment"/> class. /// </summary> /// <param name="service">The service.</param> internal Attachment(ExchangeService service) { this.service = service; } /// <summary> /// Throws exception if this is not a new service object. /// </summary> internal void ThrowIfThisIsNotNew() { if (!this.IsNew) { throw new InvalidOperationException(Strings.AttachmentCannotBeUpdated); } } /// <summary> /// Sets value of field. /// </summary> /// <remarks> /// We override the base implementation. Attachments cannot be modified so any attempts /// the change a property on an existing attachment is an error. /// </remarks> /// <typeparam name="T">Field type.</typeparam> /// <param name="field">The field.</param> /// <param name="value">The value.</param> internal override void SetFieldValue<T>(ref T field, T value) { this.ThrowIfThisIsNotNew(); base.SetFieldValue<T>(ref field, value); } /// <summary> /// Gets the Id of the attachment. /// </summary> public string Id { get { return this.id; } internal set { this.id = value; } } /// <summary> /// Gets or sets the name of the attachment. /// </summary> public string Name { get { return this.name; } set { this.SetFieldValue<string>(ref this.name, value); } } /// <summary> /// Gets or sets the content type of the attachment. /// </summary> public string ContentType { get { return this.contentType; } set { this.SetFieldValue<string>(ref this.contentType, value); } } /// <summary> /// Gets or sets the content Id of the attachment. ContentId can be used as a custom way to identify /// an attachment in order to reference it from within the body of the item the attachment belongs to. /// </summary> public string ContentId { get { return this.contentId; } set { this.SetFieldValue<string>(ref this.contentId, value); } } /// <summary> /// Gets or sets the content location of the attachment. ContentLocation can be used to associate /// an attachment with a Url defining its location on the Web. /// </summary> public string ContentLocation { get { return this.contentLocation; } set { this.SetFieldValue<string>(ref this.contentLocation, value); } } /// <summary> /// Gets the size of the attachment. /// </summary> public int Size { get { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "Size"); return this.size; } internal set { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "Size"); this.SetFieldValue<int>(ref this.size, value); } } /// <summary> /// Gets the date and time when this attachment was last modified. /// </summary> public DateTime LastModifiedTime { get { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "LastModifiedTime"); return this.lastModifiedTime; } internal set { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "LastModifiedTime"); this.SetFieldValue<DateTime>(ref this.lastModifiedTime, value); } } /// <summary> /// Gets or sets a value indicating whether this is an inline attachment. /// Inline attachments are not visible to end users. /// </summary> public bool IsInline { get { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "IsInline"); return this.isInline; } set { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "IsInline"); this.SetFieldValue<bool>(ref this.isInline, value); } } /// <summary> /// True if the attachment has not yet been saved, false otherwise. /// </summary> internal bool IsNew { get { return string.IsNullOrEmpty(this.Id); } } /// <summary> /// Gets the owner of the attachment. /// </summary> internal Item Owner { get { return this.owner; } } /// <summary> /// Gets the related exchange service. /// </summary> internal ExchangeService Service { get { return this.service; } } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name.</returns> internal abstract string GetXmlElementName(); /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.AttachmentId: this.id = reader.ReadAttributeValue(XmlAttributeNames.Id); if (this.Owner != null) { string rootItemChangeKey = reader.ReadAttributeValue(XmlAttributeNames.RootItemChangeKey); if (!string.IsNullOrEmpty(rootItemChangeKey)) { this.Owner.RootItemId.ChangeKey = rootItemChangeKey; } } reader.ReadEndElementIfNecessary(XmlNamespace.Types, XmlElementNames.AttachmentId); return true; case XmlElementNames.Name: this.name = reader.ReadElementValue(); return true; case XmlElementNames.ContentType: this.contentType = reader.ReadElementValue(); return true; case XmlElementNames.ContentId: this.contentId = reader.ReadElementValue(); return true; case XmlElementNames.ContentLocation: this.contentLocation = reader.ReadElementValue(); return true; case XmlElementNames.Size: this.size = reader.ReadElementValue<int>(); return true; case XmlElementNames.LastModifiedTime: this.lastModifiedTime = reader.ReadElementValueAsDateTime().Value; return true; case XmlElementNames.IsInline: this.isInline = reader.ReadElementValue<bool>(); return true; default: return false; } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Name, this.Name); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ContentType, this.ContentType); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ContentId, this.ContentId); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ContentLocation, this.ContentLocation); if (writer.Service.RequestedServerVersion > ExchangeVersion.Exchange2007_SP1) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.IsInline, this.IsInline); } } /// <summary> /// Load the attachment. /// </summary> /// <param name="bodyType">Type of the body.</param> /// <param name="additionalProperties">The additional properties.</param> internal void InternalLoad(BodyType? bodyType, IEnumerable<PropertyDefinitionBase> additionalProperties) { this.service.GetAttachment( this, bodyType, additionalProperties); } /// <summary> /// Validates this instance. /// </summary> /// <param name="attachmentIndex">Index of this attachment.</param> internal virtual void Validate(int attachmentIndex) { } /// <summary> /// Loads the attachment. Calling this method results in a call to EWS. /// </summary> public void Load() { this.InternalLoad(null, null); } } }
/* * This sample is based on the "Skinnable App" from * http://mattgemmell.com/2008/02/24/skinnable-cocoa-ui-with-webkit-and-css * See http://mattgemmell.com/license for license on the original code. * * Ported by Maxi Combina <maxi.combina@passwordbank.com> or <maxi.combina@gmail.com> * * ----------------------------------------------------------------------------------- * * This is a simple Mono/MonoMac application showing how to use an embedded * MonoMac.WebKit.WebView to "skin" you application using standard loadable * CSS files, and how to exchange data between your C# code and the HTML document. * * The project shows you: * - How to switch CSS themes dynamically * - how to add content into the WebView from C# * - how to retrieve data from inside the HTML document * - how to replace existing content in the HTML document * - how to detect clicks in an HTML button end execute C# code (button "Show Message") * - how to allow HTML controls (like form elements, or links) to call methods in C# objects (button "Show JavaScript Message") * */ using System; using System.IO; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.WebKit; namespace SkinnableApp { public class ShowMessageClickListener : DomEventListener { // The user just clicked the Show Message NSButton, so we show him/her // a greeting. This code shows you how to execute C# code when a click is done in // and HTML button. public override void HandleEvent (DomEvent evt) { var alert = new NSAlert () { MessageText = "Hello there", InformativeText = "Saying hello from C# code. Event type: " + evt.Type }; alert.RunModal(); } } public partial class MainWindowController : MonoMac.AppKit.NSWindowController { private System.Collections.Generic.List<NSMenuItem> nsItemList = new System.Collections.Generic.List<NSMenuItem>(); // Workaround bug #661500 public SkinnableApp.ShowMessageClickListener clickListener = new ShowMessageClickListener (); public MainWindowController (IntPtr handle) : base(handle) { } // Called when created directly from a XIB file [Export("initWithCoder:")] public MainWindowController (NSCoder coder) : base(coder) { } // Call to load from the XIB/NIB file public MainWindowController () : base("MainWindow") { } /* * Auto generated code ends here. Let's have some fun! */ public override void AwakeFromNib() { // Set up delegates for the relevant events webView.FinishedLoad += delegate { loadTitle(); installClickHandlers(); }; webView.UIGetContextMenuItems = (sender, forElements, defaultItems) => { // Disable contextual (right click) menu for the webView return null; }; webView.DrawsBackground = false; // Configure webView to let JavaScript talk to this object. webView.WindowScriptObject.SetValueForKey(this, new NSString("MainWindowController")); // can be any unique name you want /* Notes: 1. In JavaScript, you can now talk to this object using "window.MainWindowController". 2. You must explicitly allow methods to be called from JavaScript; See the "public static bool IsSelectorExcludedFromWebScript(MonoMac.ObjCRuntime.Selector aSelector)" method below for an example. 3. The method on this class which we call from JavaScript is showMessage: To call it from JavaScript, we use window.AppController.showMessage_() <-- NOTE colon becomes underscore! For more on method-name translation, see: http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html# */ // Load the HTML document var htmlPath = Path.Combine (NSBundle.MainBundle.ResourcePath, "index.html"); webView.MainFrame.LoadRequest(new NSUrlRequest (new NSUrl (htmlPath))); // Setup the theme chooser themeChooser.RemoveAllItems (); DirectoryInfo resourceDir = new DirectoryInfo (NSBundle.MainBundle.ResourcePath); FileInfo[] cssFiles = resourceDir.GetFiles("*.css"); Array.Sort (cssFiles, delegate (FileInfo f1, FileInfo f2) { // Sort by name, GetFiles does not seem to use naming order. return f1.Name.CompareTo(f2.Name); }); foreach (var cssFile in cssFiles){ var themeName = cssFile.Name.Substring(0, cssFile.Name.IndexOf(".css")); var nsItem = new NSMenuItem (themeName, "", delegate { changeTheme (null); }) { RepresentedObject = new NSString(cssFile.Name) }; nsItemList.Add(nsItem); // Workaround bug #661500 if (themeName == "Default") nsItem.State = NSCellStateValue.On; themeChooser.Menu.AddItem(nsItem); } themeChooser.SelectItem("Default"); } // The user just clicked the Add Content NSButton, so we'll add a new P tag // and a new I tag to the HTML, with some default content. // This shows you how to add content into an HTML document without reloading the page. partial void addContent (MonoMac.AppKit.NSButton sender) { var document = webView.MainFrameDocument; var paraBlock = document.GetElementById("main_content"); var newPara = document.CreateElement("p"); var newItal = document.CreateElement("i"); var newText = document.CreateTextNode("Some new italic content"); newPara.AppendChild (newItal); newItal.AppendChild (newText); paraBlock.AppendChild (newPara); // This is a different way to change the whole text. // Useful for replacing the ".InnerText = some string" used by Internet Explorer engine //paraBlock.TextContent = "Text replaced from Mono"; } // The user clicked the Set Title button, so we'll take whatever text is in // the titleText NSTextField and replace the current content of the 'contentTitle' // H1 tag in the HTML with the new text. This shows you how to replace some HTML // content with new content. partial void setTitle (MonoMac.AppKit.NSButton sender) { var document = webView.MainFrame.DomDocument; DomText newText = document.CreateTextNode(titleText.StringValue); var contentTitle = document.GetElementById("contentTitle"); contentTitle.ReplaceChild(newText, contentTitle.FirstChild); } // The user just chose a theme in the NSPopUpButton, so we replace the HTML // document's CSS file using JavaScript. partial void changeTheme (MonoMac.AppKit.NSPopUpButton sender) { WebScriptObject scriptObject = webView.WindowScriptObject; NSString theme = (NSString) themeChooser.SelectedItem.RepresentedObject; scriptObject.EvaluateWebScript("document.getElementById('ss').href = '" + (string)theme + "'"); } // Grab the 'contentTitle' H1 tag, and put it in the titleText NSTextField // This code shows you how to get a value from the HTML document public void loadTitle () { var document = webView.MainFrame.DomDocument; var contentTitle = document.GetElementById("contentTitle"); titleText.StringValue = contentTitle.FirstChild.Value; } // Install the click handler for the Show Message HTML button public void installClickHandlers() { var dom = webView.MainFrameDocument; var element = dom.GetElementById ("message_button"); element.AddEventListener ("click", clickListener, true); } // This shows you how to expose an Objective-C function that is not present. // The function isSelectorExcludedFromWebScript: is part of the WebScripting Protocol [Export ("isSelectorExcludedFromWebScript:")] public static bool IsSelectorExcludedFromWebScript(MonoMac.ObjCRuntime.Selector aSelector) { // For security, you must explicitly allow a selector to be called from JavaScript. if (aSelector.Name == "showMessage:") return false; // i.e. showMessage: is NOT _excluded_ from scripting, so it can be called. if (aSelector.Name == "alert:") return false; return true; // disallow everything else } [Export("showMessage:")] public void ShowMessage(NSString message){ MonoMac.AppKit.NSAlert alert = new MonoMac.AppKit.NSAlert(); alert.MessageText = "Message from JavaScript"; alert.InformativeText = (String) message; alert.RunModal(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Jal.Router.AzureServiceBus.Standard.Model; using Jal.Router.Interface; using Jal.Router.Model; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Management; namespace Jal.Router.AzureServiceBus.Standard.Impl { public class AzureServiceBusQueue : AzureServiceBus, IPointToPointChannel { private QueueClient _client; public void Open(SenderContext sendercontext) { _client = new QueueClient(sendercontext.Channel.ConnectionString, sendercontext.Channel.Path); var connection = Get(sendercontext.Channel); if(connection.TimeoutInSeconds>0) { _client.ServiceBusConnection.OperationTimeout = TimeSpan.FromSeconds(connection.TimeoutInSeconds); } } public async Task<string> Send(SenderContext sendercontext, object message) { var sbmessage = message as Microsoft.Azure.ServiceBus.Message; if (sbmessage != null) { await _client.SendAsync(sbmessage).ConfigureAwait(false); return sbmessage.MessageId; } return string.Empty; } public void Open(ListenerContext listenercontext) { _client = new QueueClient(listenercontext.Channel.ConnectionString, listenercontext.Channel.Path); } public bool IsActive(ListenerContext listenercontext) { return !_client.IsClosedOrClosing; } public bool IsActive(SenderContext sendercontext) { return !_client.IsClosedOrClosing; } public Task Close(SenderContext sendercontext) { return _client.CloseAsync(); } public void Listen(ListenerContext listenercontext) { var options = CreateOptions(listenercontext); var sessionoptions = CreateSessionOptions(listenercontext); if (listenercontext.Channel.UsePartition) { _client.RegisterSessionHandler(async (ms, message, token) => { var context = await listenercontext.Read(message).ConfigureAwait(false); Logger.Log($"Message {context.Id} arrived to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} route {listenercontext.Route?.Name}"); try { await listenercontext.Dispatch(context).ConfigureAwait(false); await ms.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false); if (listenercontext.Channel.ClosePartitionCondition!=null && listenercontext.Channel.ClosePartitionCondition(context)) { await ms.CloseAsync().ConfigureAwait(false); } } catch (Exception ex) { Logger.Log($"Message {context.Id} failed to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} route {listenercontext.Route?.Name} {ex}"); } finally { Logger.Log($"Message {context.Id} completed to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} route {listenercontext.Route?.Name}"); } }, sessionoptions); } else { _client.RegisterMessageHandler(async (message, token) => { var context = await listenercontext.Read(message).ConfigureAwait(false); Logger.Log($"Message {context.Id} arrived to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} route {listenercontext.Route?.Name}"); try { await listenercontext.Dispatch(context).ConfigureAwait(false); await _client.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false); } catch (Exception ex) { Logger.Log($"Message {context.Id} failed to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} route {listenercontext.Route?.Name} {ex}"); } finally { Logger.Log($"Message {context.Id} completed to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} route {listenercontext.Route?.Name}"); } }, options); } } public Task Close(ListenerContext context) { return _client.CloseAsync(); } public async Task<bool> CreateIfNotExist(Channel channel) { var client = new ManagementClient(channel.ConnectionString); if (!await client.QueueExistsAsync(channel.Path).ConfigureAwait(false)) { var description = new QueueDescription(channel.Path); var properties = new AzureServiceBusChannelProperties(channel.Properties); description.DefaultMessageTimeToLive = TimeSpan.FromDays(properties.DefaultMessageTtlInDays); description.LockDuration = TimeSpan.FromSeconds(properties.MessageLockDurationInSeconds); if (properties.DuplicateMessageDetectionInMinutes>0) { description.RequiresDuplicateDetection = true; description.DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(properties.DuplicateMessageDetectionInMinutes); } if (properties.SessionEnabled!=null) { description.RequiresSession = properties.SessionEnabled.Value; } if (properties.PartitioningEnabled!=null) { description.EnablePartitioning = properties.PartitioningEnabled.Value; } await client.CreateQueueAsync(description).ConfigureAwait(false); return true; } return false; } public async Task<Statistic> GetStatistic(Channel channel) { var client = new ManagementClient(channel.ConnectionString); if (await client.QueueExistsAsync(channel.Path).ConfigureAwait(false)) { var info = await client.GetQueueRuntimeInfoAsync(channel.Path).ConfigureAwait(false); var statistics = new Statistic(channel.Path); statistics.Properties.Add("DeadLetterMessageCount", info.MessageCountDetails.DeadLetterMessageCount.ToString()); statistics.Properties.Add("ActiveMessageCount", info.MessageCountDetails.ActiveMessageCount.ToString()); statistics.Properties.Add("ScheduledMessageCount", info.MessageCountDetails.ScheduledMessageCount.ToString()); statistics.Properties.Add("CurrentSizeInBytes", info.SizeInBytes.ToString()); return statistics; } return null; } public async Task<bool> DeleteIfExist(Channel channel) { var client = new ManagementClient(channel.ConnectionString); if (await client.QueueExistsAsync(channel.Path).ConfigureAwait(false)) { await client.DeleteQueueAsync(channel.Path).ConfigureAwait(false); return true; } return false; } public async Task<MessageContext> Read(SenderContext sendercontext, MessageContext context, IMessageAdapter adapter) { var client = default(SessionClient); if(sendercontext.Channel.ReplyChannel.ChannelType== ChannelType.PointToPoint) { client = new SessionClient(sendercontext.Channel.ReplyChannel.ConnectionString, sendercontext.Channel.ReplyChannel.Path); } else { var entity = EntityNameHelper.FormatSubscriptionPath(sendercontext.Channel.ReplyChannel.Path, sendercontext.Channel.ReplyChannel.Subscription); client = new SessionClient(sendercontext.Channel.ReplyChannel.ConnectionString, entity); } var messagesession = await client.AcceptMessageSessionAsync(context.TracingContext.ReplyToRequestId).ConfigureAwait(false); var message = sendercontext.Channel.ReplyTimeOut != 0 ? await messagesession.ReceiveAsync(TimeSpan.FromSeconds(sendercontext.Channel.ReplyTimeOut)).ConfigureAwait(false) : await messagesession.ReceiveAsync().ConfigureAwait(false); MessageContext outputcontext = null; if (message != null) { outputcontext = await adapter.ReadFromPhysicalMessage(message, sendercontext).ConfigureAwait(false); await messagesession.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false); } await messagesession.CloseAsync().ConfigureAwait(false); await client.CloseAsync().ConfigureAwait(false); return outputcontext; } public AzureServiceBusQueue(IComponentFactoryFacade factory, ILogger logger, IParameterProvider provider) : base(factory, logger, provider) { } } }
// 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.Collections; /// <summary> /// ValueCollection.System.Collections.ICollection.CopyTo(Array,Int32) /// </summary> public class ValueCollectionICollectionCopyTo { private const int SIZE = 10; public static int Main() { ValueCollectionICollectionCopyTo valCollectICollectCopyTo = new ValueCollectionICollectionCopyTo(); TestLibrary.TestFramework.BeginTestCase("ValueCollectionICollectionCopyTo"); if (valCollectICollectCopyTo.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method CopyTo in ValueCollection ICollection 1"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str2", "Test2"); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; icollect.CopyTo(TVals, 0); string strVals = null; for (int i = 0; i < TVals.Length; i++) { if (TVals[i] != null) { strVals += TVals[i].ToString(); } } if (TVals[0].ToString() != "Test1" || TVals[1].ToString() != "Test2" || strVals != "Test1Test2") { TestLibrary.TestFramework.LogError("001", "the ExpecResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method CopyTo in ValueCollection ICollection 2"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str2", "Test2"); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; icollect.CopyTo(TVals, 5); string strVals = null; for (int i = 0; i < TVals.Length; i++) { if (TVals[i] != null) { strVals += TVals[i].ToString(); } } if (TVals[5].ToString() != "Test1" || TVals[6].ToString() != "Test2" || strVals != "Test1Test2") { TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method CopyTo in ValueCollection ICollection 3"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; icollect.CopyTo(TVals, 0); for (int i = 0; i < TVals.Length; i++) { if (TVals[i] != null) { TestLibrary.TestFramework.LogError("005", "the ExpecResult is not the ActualResult"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The argument array is null"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = null; icollect.CopyTo(TVals, 0); TestLibrary.TestFramework.LogError("N001", "The argument array is null but not throw exception"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2:The argument index is less than zero"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; int index = -1; icollect.CopyTo(TVals, index); TestLibrary.TestFramework.LogError("N003", "The argument index is less than zero but not throw exception"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3:The argument index is larger than array length"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; int index = SIZE + 1; icollect.CopyTo(TVals, index); TestLibrary.TestFramework.LogError("N005", "The argument index is larger than array length but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4:The number of elements in the source ICollection is greater than the available space from index to the end of the destination array"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str1", "Test1"); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; int index = SIZE - 1; icollect.CopyTo(TVals, index); TestLibrary.TestFramework.LogError("N007", "The ExpectResult should throw exception but the ActualResult not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5:The type of ICollection not cast automatically to the type of array"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); int[] TVals = new int[SIZE]; icollect.CopyTo(TVals, 0); TestLibrary.TestFramework.LogError("N009", "The type of ICollection not cast automatically to the type of array but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N010", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6:The array is multidimentional"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); ICollection icollect = (ICollection)new Dictionary<string, string>.ValueCollection(dic); int[,] TVals = new int[1, 2]; icollect.CopyTo(TVals, 0); TestLibrary.TestFramework.LogError("N011", "The array is multidimentional but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N012", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion }
// 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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class EnumTests : CSharpTestBase { // Common example. (Associated Dev10 errors are indicated for cases // where the underlying type of the enum cannot be determined.) private const string ExampleSource = @"class C { static void F(E e) { } static void Main() { E e = E.A; // Dev10: 'E.A' is not supported by the language F(e); // Dev10: no error F(E.B); // Dev10: 'E.B' is not supported by the language int b = (int)e; // Dev10: cannot convert 'E' to 'int' e = e + 1; // Dev10: operator '+' cannot be applied to operands of type 'E' and 'int' e = ~e; // Dev10: operator '~' cannot be applied to operand of type 'E' } }"; [ClrOnlyFact] public void EnumWithPrivateInstanceField() { // No errors. CompileWithCustomILSource( ExampleSource, @".class public E extends [mscorlib]System.Enum { .field private specialname rtspecialname int16 _val .field public static literal valuetype E A = int16(31) .field public static literal valuetype E B = int16(32) }"); } [Fact] public void EnumWithNoInstanceFields() { EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public static literal valuetype E A = int32(0) .field public static literal valuetype E B = int32(1) }"); } [Fact] public void EnumWithMultipleInstanceFields() { // Note that Dev10 reports a single error for this case: // "'E' is a type not supported by the language" for "static void F(E e) { }" EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 _val1 .field public specialname rtspecialname int32 _val2 .field public static literal valuetype E A = int32(0) .field public static literal valuetype E B = int32(1) }"); } [Fact] public void EnumWithPrivateLiterals() { CreateCompilationWithCustomILSource( @"class C { static void F(E e) { } static void Main() { F(E.A); F(E.B); F(E.C); } }", @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname int16 _val .field public static literal valuetype E A = int16(0) .field private static literal valuetype E B = int16(1) .field assembly static literal valuetype E C = int16(2) }").VerifyDiagnostics( // (7,13): error CS0117: 'E' does not contain a definition for 'B' // F(E.B); Diagnostic(ErrorCode.ERR_NoSuchMember, "B").WithArguments("E", "B"), // (8,13): error CS0117: 'E' does not contain a definition for 'C' // F(E.C); Diagnostic(ErrorCode.ERR_NoSuchMember, "C").WithArguments("E", "C")); } [Fact] public void EnumUnsupportedUnderlyingType() { // bool EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname bool value__ .field public static literal valuetype E A = bool(false) .field public static literal valuetype E B = bool(true) }"); // char EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname char value__ .field public static literal valuetype E A = char(0) .field public static literal valuetype E B = char(1) }"); // string EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname string _val .field public static literal valuetype E A = int16(0) .field public static literal valuetype E B = int16(1) }"); } private void EnumWithBogusUnderlyingType(string ilSource) { CreateCompilationWithCustomILSource(ExampleSource, ilSource).VerifyDiagnostics( // (6,15): error CS0570: 'E.A' is not supported by the language // E e = E.A; // Dev10: 'E.A' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "E.A").WithArguments("E.A"), // (8,11): error CS0570: 'E.B' is not supported by the language // F(E.B); // Dev10: 'E.B' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "E.B").WithArguments("E.B"), // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'E' and 'int' // e = e + 1; // Dev10: operator '+' cannot be applied to operands of type 'E' and 'int' Diagnostic(ErrorCode.ERR_BadBinaryOps, "e + 1").WithArguments("+", "E", "int"), // (11,13): error CS0023: Operator '~' cannot be applied to operand of type 'E' // e = ~e; // Dev10: operator '~' cannot be applied to operand of type 'E' Diagnostic(ErrorCode.ERR_BadUnaryOp, "~e").WithArguments("~", "E")); } [Fact] public void CycleOneMember() { var source = @"enum E { A = A, }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = A, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void CycleTwoMembers() { var source = @"enum E { A = B + 1, B = A + 1, }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void TwoConnectedCycles() { var source = @"enum E { A = B | C, B = A + 1, C = A + 2, }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B | C, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void CyclesAndConnectedFields() { var source = @"enum E { A = A | B, B = C, C = D, D = D }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = A | B, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5), // (6,5): error CS0110: The evaluation of the constant value for 'E.D' involves a circular definition // D = D Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("E.D").WithLocation(6, 5)); } [Fact] public void DependenciesTwoEnums() { var source = @"enum E { A = F.A, B = F.B + A } enum F { A = 1, B = E.A }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics(); } [Fact] public void MultipleCircularDependencies() { var source = @"enum E { A = B + F.B, B = A + F.A, } enum F { A = E.B + 1, B = A + 1, }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B + F.B, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5), // (4,5): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // B = A + F.A, Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(4, 5)); } [Fact] public void CircularDefinitionManyMembers_Implicit() { // enum E { M0 = Mn + 1, M1, ..., Mn, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~5600 members. var source = GenerateEnum(10000, (i, n) => (i == 0) ? string.Format("M{0} + 1", n - 1) : ""); CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.M0' involves a circular definition // M0 = M5999 + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "M0").WithArguments("E.M0").WithLocation(3, 5)); } [WorkItem(843037, "DevDiv")] [Fact] public void CircularDefinitionManyMembers_Explicit() { // enum E { M0 = Mn + 1, M1 = M0 + 1, ..., Mn = Mn-1 + 1, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~1600 members. var source = GenerateEnum(10000, (i, n) => string.Format("M{0} + 1", (i == 0) ? (n - 1) : (i - 1))); CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.M0' involves a circular definition // M0 = M1999 + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "M0").WithArguments("E.M0").WithLocation(3, 5)); } [WorkItem(843037, "DevDiv")] [Fact] public void InvertedDefinitionManyMembers_Explicit() { // enum E { M0 = M1 - 1, M1 = M2 - 1, ..., Mn = n, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~1500 members. var source = GenerateEnum(10000, (i, n) => (i < n - 1) ? string.Format("M{0} - 1", i + 1) : i.ToString()); CreateCompilationWithMscorlib(source).VerifyDiagnostics(); } /// <summary> /// Generate "enum E { M0 = ..., M1 = ..., ..., Mn = ... }". /// </summary> private static string GenerateEnum(int n, Func<int, int, string> getMemberValue) { var builder = new StringBuilder(); builder.AppendLine("enum E"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.Append(string.Format(" M{0}", i)); var value = getMemberValue(i, n); if (!string.IsNullOrEmpty(value)) { builder.Append(" = "); builder.Append(value); } builder.AppendLine(","); } builder.AppendLine("}"); return builder.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 System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Tools.ServiceModel.Svcutil.Metadata; namespace Microsoft.Tools.ServiceModel.Svcutil { internal class CmdCredentialsProvider : IHttpCredentialsProvider, IClientCertificateProvider, IServerCertificateValidationProvider { #region IHttpCredentialProvider private bool _authMessageShown; public NetworkCredential GetCredentials(Uri serviceUri, WebException webException) { ShowAuthenticationConsent(); string username = null; while (string.IsNullOrWhiteSpace(username)) { username = ReadUserInput(SR.UsernamePrompt); Console.WriteLine(); } username = username.Trim(); var password = ReadUserInput(SR.PasswordPrompt, isPassword: true); Console.WriteLine(); return new NetworkCredential(username, password); } private void ShowAuthenticationConsent() { if (!_authMessageShown) { _authMessageShown = true; Console.WriteLine(); Console.WriteLine(SR.WrnUserBasicCredentialsInClearText); PromptEnterOrEscape(throwOnEscape: true); } } #endregion #region IClientCertificateProvider private const string OidClientAuthValue = "1.3.6.1.5.5.7.3.2"; private X509Certificate2Collection _certificates; private X509Certificate2Collection Certificates { get { if (_certificates == null) { _certificates = GetCertificates(); } return _certificates; } } public X509Certificate2Collection GetCertificates() { X509Certificate2Collection certs = new X509Certificate2Collection(); X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); try { certificateStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); foreach (X509Certificate2 certificate in certificateStore.Certificates) { if (certificate.HasPrivateKey) { bool digitalSignatureUsage = false; bool clientAuthEnhancedUsage = false; bool enhancedKeyUsageSupported = false; foreach (X509Extension extension in certificate.Extensions) { X509KeyUsageExtension keyUsage = extension as X509KeyUsageExtension; if (keyUsage != null) { digitalSignatureUsage = (keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0; } else { X509EnhancedKeyUsageExtension enhancedKeyUsage = extension as X509EnhancedKeyUsageExtension; if (enhancedKeyUsage != null && enhancedKeyUsage.EnhancedKeyUsages != null) { enhancedKeyUsageSupported = true; foreach (var oid in enhancedKeyUsage.EnhancedKeyUsages) { if (oid.Value == OidClientAuthValue) { clientAuthEnhancedUsage = true; break; } } } } } if (digitalSignatureUsage && (!enhancedKeyUsageSupported || clientAuthEnhancedUsage)) { certs.Add(certificate); } } } } finally { certificateStore.Dispose(); } return certs; } public X509Certificate GetCertificate(Uri serviceUri) { X509Certificate2 cert = null; if (this.Certificates.Count > 0) { cert = this.Certificates.Count > 1 ? SelectCertificateFromCollection(this.Certificates, serviceUri) : this.Certificates[0]; } return cert; } private Dictionary<string, X509Certificate> _validatedClientCerts = new Dictionary<string, X509Certificate>(); private X509Certificate2 SelectCertificateFromCollection(X509Certificate2Collection selectedCerts, Uri serviceUri) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, SR.CertificateSelectionMessageFormat, serviceUri.Authority)); PromptEnterOrEscape(throwOnEscape: true); var candidateCerts = new List<X509Certificate2>(); int counter = 1; foreach (var cert in selectedCerts) { var certhash = cert.GetCertHashString(); if (!_validatedClientCerts.Keys.Contains(certhash)) { candidateCerts.Add(cert); var certId = counter++ + "."; Console.WriteLine(FormatCertificate(cert, certId)); } } string idxString; ; int idx = 0; do { idxString = ReadUserInput(SR.CertificateIndexPrompt); Console.WriteLine(); } while (!int.TryParse(idxString, out idx) || idx < 1 || idx > candidateCerts.Count); var selectedCert = candidateCerts[idx - 1]; _validatedClientCerts[selectedCert.GetCertHashString()] = selectedCert; return selectedCert; } #endregion #region IServerCertificateValidationProvider private Uri _serviceUri; public void BeforeServerCertificateValidation(Uri serviceUri) { #if NETCORE10 // NOOP #else System.Diagnostics.Debug.Assert(_serviceUri == null, "provider already started for the specified service URI"); _serviceUri = serviceUri; ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(this.ValidateServerCertificate); #endif } public void AfterServerCertificateValidation(Uri serviceUri) { #if NETCORE10 // NOOP #else System.Diagnostics.Debug.Assert(_serviceUri == serviceUri, "provider not statrted for the specified service URI"); _serviceUri = null; ServicePointManager.ServerCertificateValidationCallback -= new RemoteCertificateValidationCallback(this.ValidateServerCertificate); #endif } private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { bool result = true; HttpWebRequest request = sender as HttpWebRequest; if (request != null && _serviceUri != null && _serviceUri.Authority == request.RequestUri.Authority) { result = sslPolicyErrors == SslPolicyErrors.None ? true : PromptUserOnInvalidCert(cert, sslPolicyErrors); } return result; } private Dictionary<string, bool> _validatedServerCerts = new Dictionary<string, bool>(); private bool PromptUserOnInvalidCert(X509Certificate cert, SslPolicyErrors sslPolicyErrors) { var certhash = cert.GetCertHashString(); if (!_validatedServerCerts.Keys.Contains(certhash)) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, SR.ErrServerCertFailedValidationFormat, sslPolicyErrors, FormatCertificate(cert))); _validatedServerCerts[certhash] = PromptEnterOrEscape(throwOnEscape: false); } return _validatedServerCerts[certhash]; } #endregion #region ICloneable public object Clone() { return new CmdCredentialsProvider(); } #endregion #region common functions private static string FormatCertificate(X509Certificate cert, string certId = null) { var separator = "--------------------------------------------------------"; return separator + Environment.NewLine + certId + cert + separator; } private static bool PromptEnterOrEscape(bool throwOnEscape) { ConsoleKeyInfo keyInfo; do { Console.WriteLine(SR.EnterOrEscapeMessage); keyInfo = Console.ReadKey(intercept: true); } while (keyInfo.Key != ConsoleKey.Enter && keyInfo.Key != ConsoleKey.Escape); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape && throwOnEscape) { throw new OperationCanceledException(); } return keyInfo.Key == ConsoleKey.Enter; } public static string ReadUserInput(string prompt, bool isPassword = false) { ConsoleKeyInfo keyInfo; StringBuilder userInput = new StringBuilder(); Console.Write(prompt); do { keyInfo = System.Console.ReadKey(intercept: true); if (keyInfo.Key == ConsoleKey.Escape) { Console.WriteLine(); throw new OperationCanceledException(); } else if (keyInfo.Key == ConsoleKey.Backspace && userInput.Length > 0) { Console.Write("\b \b"); userInput = userInput.Remove(userInput.Length - 1, 1); } else if (!Char.IsControl(keyInfo.KeyChar)) { userInput.Append(keyInfo.KeyChar); System.Console.Write(isPassword ? '*' : keyInfo.KeyChar); } } while (keyInfo.Key != ConsoleKey.Enter); return userInput.ToString(); } #endregion } internal static class CertificateExtensions { public static string GetCertHashString(this X509Certificate cert) { return Encoding.Unicode.GetString(cert.GetCertHash()); } } }
// $Id: Util.java,v 1.13 2004/07/28 08:14:14 belaban Exp $ using System; using System.IO; using System.Net; using System.Net.Sockets; using Alachisoft.NCache.Common; using System.Text; using Alachisoft.NCache.Serialization.Formatters; using Alachisoft.NCache.Common.DataStructures.Clustered; using System.Collections; using Alachisoft.NGroups.Blocks; namespace Alachisoft.NGroups.Util { /// <summary> Collection of various utility routines that can not be assigned to other classes.</summary> internal class Util { // constants public const int MAX_PORT = 65535; // highest port allocatable /// <summary>Finds first available port starting at start_port and returns server socket </summary> public static System.Net.Sockets.TcpListener createServerSocket(int start_port) { System.Net.Sockets.TcpListener ret = null; while (true) { try { System.Net.Sockets.TcpListener temp_tcpListener; temp_tcpListener = new System.Net.Sockets.TcpListener(start_port); temp_tcpListener.Start(); ret = temp_tcpListener; } catch (System.Net.Sockets.SocketException bind_ex) { start_port++; continue; } catch (System.IO.IOException io_ex) { } break; } return ret; } /// <summary> Returns all members that left between 2 views. All members that are element of old_mbrs but not element of /// new_mbrs are returned. /// </summary> public static System.Collections.ArrayList determineLeftMembers(System.Collections.ArrayList old_mbrs, System.Collections.ArrayList new_mbrs) { System.Collections.ArrayList retval = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); object mbr; if (old_mbrs == null || new_mbrs == null) return retval; for (int i = 0; i < old_mbrs.Count; i++) { mbr = old_mbrs[i]; if (!new_mbrs.Contains(mbr)) retval.Add(mbr); } return retval; } /// <summary>Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted </summary> public static void sleep(long timeout) { System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(timeout)); } internal static IList serializeMessage(Message msg) { int len = 0; byte[] buffie; FlagsByte flags = new FlagsByte(); msg.Dest = null; msg.Dests = null; RequestCorrelator.HDR rqHeader = (RequestCorrelator.HDR)msg.getHeader(HeaderType.REQUEST_COORELATOR); if (rqHeader != null) { rqHeader.serializeFlag = false; } ClusteredMemoryStream stmOut = new ClusteredMemoryStream(); stmOut.Write(Util.WriteInt32(len), 0, 4); stmOut.Write(Util.WriteInt32(len), 0, 4); if (msg.IsUserMsg) { BinaryWriter msgWriter = new BinaryWriter(stmOut, new UTF8Encoding(true)); flags.SetOn(FlagsByte.Flag.TRANS); msgWriter.Write(flags.DataByte); msg.SerializeLocal(msgWriter); } else { flags.SetOff(FlagsByte.Flag.TRANS); stmOut.WriteByte(flags.DataByte); CompactBinaryFormatter.Serialize(stmOut, msg, null, false); } len = (int)stmOut.Position - 4; int payloadLength = 0; // the user payload size. payload is passed on untill finally send on the socket. if (msg.Payload != null) { for (int i = 0; i < msg.Payload.Length; i++) { payloadLength += ((byte[])msg.Payload.GetValue(i)).Length; } len += payloadLength; } stmOut.Position = 0; stmOut.Write(Util.WriteInt32(len), 0, 4); stmOut.Write(Util.WriteInt32(len - 4 - payloadLength), 0, 4); return stmOut.GetInternalBuffer(); } /// <summary> On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will /// sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the /// thread never relinquishes control and therefore the sleep(x) is exactly x ms long. /// </summary> public static void sleep(long msecs, bool busy_sleep) { if (!busy_sleep) { sleep(msecs); return ; } long start = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; long stop = start + msecs; while (stop > start) { start = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; } } /// <summary>Returns a random value in the range [1 - range] </summary> public static long random(long range) { return (long) ((Global.Random.NextDouble() * 100000) % range) + 1; } /// <summary>E.g. 2000,4000,8000</summary> public static long[] parseCommaDelimitedLongs(string s) { if (s == null) return null; string[] v = s.Split(','); if (v.Length == 0) return null; long[] retval = new long[v.Length]; for (int i = 0; i < v.Length; i++) retval[i] = Convert.ToInt64(v[i].Trim()); return retval; } /// <summary> Selects a random subset of members according to subset_percentage and returns them. /// Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. /// </summary> public static System.Collections.ArrayList pickSubset(System.Collections.ArrayList members, double subset_percentage) { System.Collections.ArrayList ret = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)), tmp_mbrs; int num_mbrs = members.Count, subset_size, index; if (num_mbrs == 0) return ret; subset_size = (int) System.Math.Ceiling(num_mbrs * subset_percentage); tmp_mbrs = (System.Collections.ArrayList) members.Clone(); for (int i = subset_size; i > 0 && tmp_mbrs.Count > 0; i--) { index = (int) ((Global.Random.NextDouble() * num_mbrs) % tmp_mbrs.Count); ret.Add(tmp_mbrs[index]); tmp_mbrs.RemoveAt(index); } return ret; } /// <summary>Tries to read an object from the message's buffer and prints it </summary> public static string printMessage(Message msg) { if (msg == null) return ""; if (msg.Length == 0) return null; try { return msg.getObject().ToString(); } catch (System.Exception ex) { //Trace.error("util.printMessage()",ex.Message); // it is not an object return ""; } } public static string printEvent(Event evt) { Message msg; if (evt.Type == Event.MSG) { msg = (Message) evt.Arg; if (msg != null) { if (msg.Length > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.ToString(); } /// <summary>Fragments a byte buffer into smaller fragments of (max.) frag_size. /// Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments /// of 248 bytes each and 1 fragment of 32 bytes. /// </summary> /// <returns> An array of byte buffers (<code>byte[]</code>). /// </returns> public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { byte[][] retval; long total_size = buf.Length; int accumulated_size = 0; byte[] fragment; int tmp_size = 0; int num_frags; int index = 0; num_frags = buf.Length % frag_size == 0?buf.Length / frag_size:buf.Length / frag_size + 1; retval = new byte[num_frags][]; while (accumulated_size < total_size) { if (accumulated_size + frag_size <= total_size) tmp_size = frag_size; else tmp_size = (int) (total_size - accumulated_size); fragment = new byte[tmp_size]; Array.Copy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++] = fragment; accumulated_size += tmp_size; } return retval; } /// <summary> Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and /// return them in a list. Example:<br/> /// Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). /// This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment /// starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length /// of 2 bytes. /// </summary> /// <param name="">frag_size /// </param> /// <returns> List. A List<Range> of offset/length pairs /// </returns> public static System.Collections.IList computeFragOffsets(int offset, int length, int frag_size) { System.Collections.IList retval = new System.Collections.ArrayList(); long total_size = length + offset; int index = offset; int tmp_size = 0; Range r; while (index < total_size) { if (index + frag_size <= total_size) tmp_size = frag_size; else tmp_size = (int) (total_size - index); r = new Range(index, tmp_size); retval.Add(r); index += tmp_size; } return retval; } public static System.Collections.IList computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.Length, frag_size); } /// <summary>Concatenates smaller fragments into entire buffers.</summary> /// <param name="fragments">An array of byte buffers (<code>byte[]</code>) /// </param> /// <returns> A byte buffer /// </returns> public static byte[] defragmentBuffer(byte[][] fragments) { int total_length = 0; byte[] ret; int index = 0; if (fragments == null) return null; for (int i = 0; i < fragments.Length; i++) { if (fragments[i] == null) continue; total_length += fragments[i].Length; } ret = new byte[total_length]; for (int i = 0; i < fragments.Length; i++) { if (fragments[i] == null) continue; Array.Copy(fragments[i], 0, ret, index, fragments[i].Length); index += fragments[i].Length; } return ret; } public static void printFragments(byte[][] frags) { for (int i = 0; i < frags.Length; i++) System.Console.Out.WriteLine('\'' + new string(Global.ToCharArray(frags[i])) + '\''); } public static string shortName(string hostname) { int index; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (hostname == null) return null; index = hostname.IndexOf((System.Char) '.'); if (index > 0 && !System.Char.IsDigit(hostname[0])) sb.Append(hostname.Substring(0, (index) - (0))); else sb.Append(hostname); return sb.ToString(); } /// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary> /// <param name="sourceStream">The source Stream to read from.</param> /// <param name="target">Contains the array of characteres read from the source Stream.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source Stream.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.Net.Sockets.Socket sock, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; int bytesRead,totalBytesRead = 0,buffStart = start; while(true) { try { if (!sock.Connected) throw new ExtSocketException("socket closed"); bytesRead = sock.Receive(target, start, count, SocketFlags.None); if (bytesRead == 0) throw new ExtSocketException("socket closed"); totalBytesRead += bytesRead; if (bytesRead == count) break; else count = count - bytesRead; start = start + bytesRead; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } } if (totalBytesRead == 0) return -1; return totalBytesRead; } public static System.Int32 ReadInput(System.Net.Sockets.Socket sock, byte[] target, int start, int count,int min) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; int bytesRead, totalBytesRead = 0, buffStart = start; while (true) { try { if (!sock.Connected) throw new ExtSocketException("socket closed"); bytesRead = sock.Receive(target, start, count, SocketFlags.None); if (bytesRead == 0) throw new ExtSocketException("socket closed"); totalBytesRead += bytesRead; if (bytesRead == count) break; else count = count - bytesRead; start = start + bytesRead; if (totalBytesRead >min && sock.Available <= 0) break; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } } // Returns -1 if EOF if (totalBytesRead == 0) return -1; return totalBytesRead; } /// <summary> /// Compares the two IP Addresses. Returns 0 if both are equal, 1 if ip1 is greateer than ip2 otherwise -1. /// </summary> /// <param name="ip1"></param> /// <param name="ip1"></param> /// <returns></returns> public static int CompareIP(IPAddress ip1,IPAddress ip2) { uint ipval1,ipval2; ipval1 = IPAddressToLong(ip1); ipval2 = IPAddressToLong(ip2); if(ipval1 == ipval2) return 0; if(ipval1 > ipval2) return 1; else return -1; } static private uint IPAddressToLong(IPAddress IPAddr) { byte[] byteIP=IPAddr.GetAddressBytes(); uint ip=(uint)byteIP[0]<<24; ip+=(uint)byteIP[1]<<16; ip+=(uint)byteIP[2]<<8; ip+=(uint)byteIP[3]; return ip; } //: /// <summary>Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.</summary> /// <param name="sourceTextReader">The source TextReader to read from</param> /// <param name="target">Contains the array of characteres read from the source TextReader.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source TextReader.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for(int index=start; index<start+bytesRead; index++) target[index] = (byte)charArray[index]; return bytesRead; } /// <summary> /// Creates a byte buffer representation of a <c>int32</c> /// </summary> /// <param name="value"><c>int</c> to be converted</param> /// <returns>Byte Buffer representation of a <c>Int32</c></returns> public static byte[] WriteInt32(int value) { byte[] _byteBuffer = new byte[4]; _byteBuffer[0] = (byte)value; _byteBuffer[1] = (byte)(value >> 8); _byteBuffer[2] = (byte)(value >> 16); _byteBuffer[3] = (byte)(value >> 24); return _byteBuffer; } /// <summary> /// Creates a <c>Int32</c> from a byte buffer representation /// </summary> /// <param name="_byteBuffer">Byte Buffer representation of a <c>Int32</c></param> /// <returns></returns> public static int convertToInt32(byte[] _byteBuffer) { return (int)((_byteBuffer[0] & 0xFF) | _byteBuffer[1] << 8 | _byteBuffer[2] << 16 | _byteBuffer[3] << 24); } /// <summary> /// Creates a <c>Int32</c> from a byte buffer representation /// </summary> /// <param name="_byteBuffer">Byte Buffer representation of a <c>Int32</c></param> /// <returns></returns> public static int convertToInt32(byte[] _byteBuffer, int offset) { byte[] temp = new byte[4]; System.Buffer.BlockCopy(_byteBuffer, offset, temp, 0, 4); return convertToInt32(temp); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using System.Xml.Linq; namespace DotSpatial.Plugins.MapWindowProjectFileCompatibility { /// <summary> /// http://mutable.net/blog/archive/2010/07/07/yet-another-take-on-a-dynamicobject-wrapper-for-xml.aspx /// </summary> public class DynamicXMLNode : DynamicObject { #region Fields private readonly XElement _node; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DynamicXMLNode"/> class. /// </summary> /// <param name="node">The node.</param> public DynamicXMLNode(XElement node) { _node = node; } /// <summary> /// Initializes a new instance of the <see cref="DynamicXMLNode"/> class. /// </summary> /// <param name="name">The name.</param> public DynamicXMLNode(string name) { _node = new XElement(name); } /// <summary> /// Initializes a new instance of the <see cref="DynamicXMLNode"/> class. /// </summary> public DynamicXMLNode() { } #endregion #region Methods /// <summary> /// Loads the specified URI. /// </summary> /// <param name="uri">The URI.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(string uri) { return new DynamicXMLNode(XElement.Load(uri)); } /// <summary> /// Loads the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(Stream stream) { return new DynamicXMLNode(XElement.Load(stream)); } /// <summary> /// Loads the specified text reader. /// </summary> /// <param name="textReader">The text reader.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(TextReader textReader) { return new DynamicXMLNode(XElement.Load(textReader)); } /// <summary> /// Loads the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(XmlReader reader) { return new DynamicXMLNode(XElement.Load(reader)); } /// <summary> /// Loads the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <param name="options">The options.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(Stream stream, LoadOptions options) { return new DynamicXMLNode(XElement.Load(stream, options)); } /// <summary> /// Loads the specified URI. /// </summary> /// <param name="uri">The URI.</param> /// <param name="options">The options.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(string uri, LoadOptions options) { return new DynamicXMLNode(XElement.Load(uri, options)); } /// <summary> /// Loads the specified text reader. /// </summary> /// <param name="textReader">The text reader.</param> /// <param name="options">The options.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(TextReader textReader, LoadOptions options) { return new DynamicXMLNode(XElement.Load(textReader, options)); } /// <summary> /// Loads the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="options">The options.</param> /// <returns>The resulting DynamicXMLNode</returns> public static DynamicXMLNode Load(XmlReader reader, LoadOptions options) { return new DynamicXMLNode(XElement.Load(reader, options)); } /// <summary> /// Parses the specified text. /// </summary> /// <param name="text">The text.</param> /// <returns>The parse result.</returns> public static DynamicXMLNode Parse(string text) { return new DynamicXMLNode(XElement.Parse(text)); } /// <summary> /// Parses the specified text. /// </summary> /// <param name="text">The text.</param> /// <param name="options">The options.</param> /// <returns>The parse result.</returns> public static DynamicXMLNode Parse(string text, LoadOptions options) { return new DynamicXMLNode(XElement.Parse(text, options)); } /// <summary> /// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another. /// </summary> /// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param> /// <param name="result">The result of the type conversion operation.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) /// </returns> public override bool TryConvert(ConvertBinder binder, out object result) { if (binder.Type == typeof(XElement)) { result = _node; } else if (binder.Type == typeof(string)) { result = _node.Value; } else { result = false; return false; } return true; } /// <summary> /// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations. /// </summary> /// <param name="binder">Provides information about the operation.</param> /// <param name="indexes">The indexes that are used in the operation. </param> /// <param name="result">The result of the index operation.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.) /// </returns> public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { var s = indexes[0] as string; if (s != null) { XAttribute attr = _node.Attribute(s); if (attr != null) { result = attr.Value; return true; } } result = null; return false; } /// <summary> /// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.) /// </returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { XElement getNode = _node.Element(binder.Name); if (getNode != null) { result = new DynamicXMLNode(getNode); return true; } result = null; return false; } /// <summary> /// Provides the implementation for operations that invoke a member. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as calling a method. /// </summary> /// <param name="binder">Provides information about the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleMethod". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="args">The arguments that are passed to the object member during the invoke operation. </param> /// <param name="result">The result of the member invocation.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) /// </returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { Type xmlType = typeof(XElement); try { // unwrap parameters: if the parameters are DynamicXMLNode then pass in the inner XElement node List<object> newargs = null; var argtypes = args.Select(x => x.GetType()).ToList(); // because GetTypeArray is not supported in Silverlight if (argtypes.Contains(typeof(DynamicXMLNode)) || argtypes.Contains(typeof(DynamicXMLNode[]))) { newargs = new List<object>(); foreach (var arg in args) { if (arg.GetType() == typeof(DynamicXMLNode)) { newargs.Add(((DynamicXMLNode)arg)._node); } else if (arg.GetType() == typeof(DynamicXMLNode[])) { // unwrap array of DynamicXMLNode newargs.Add(((DynamicXMLNode[])arg).Select(x => x._node)); } else { newargs.Add(arg); } } } result = xmlType.InvokeMember(binder.Name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, _node, newargs?.ToArray() ?? args); // wrap return value: if the results are an IEnumerable<XElement>, then return a wrapped collection of DynamicXMLNode if (result != null && typeof(IEnumerable<XElement>).IsAssignableFrom(result.GetType())) { result = ((IEnumerable<XElement>)result).Select(x => new DynamicXMLNode(x)); } // Note: we could wrap single XElement too but nothing returns that return true; } catch { result = null; return false; } } /// <summary> /// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index. /// </summary> /// <param name="binder">Provides information about the operation.</param> /// <param name="indexes">The indexes that are used in the operation.</param> /// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown. /// </returns> public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { var s = indexes[0] as string; if (s != null) { _node.SetAttributeValue(s, value); return true; } return false; } /// <summary> /// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) /// </returns> public override bool TrySetMember(SetMemberBinder binder, object value) { XElement setNode = _node.Element(binder.Name); if (setNode != null) { setNode.SetValue(value); } else { _node.Add(value.GetType() == typeof(DynamicXMLNode) ? new XElement(binder.Name) : new XElement(binder.Name, value)); } return true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.ExceptionServices; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Internal; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.SignalR.Protocol { /// <summary> /// Implements the SignalR Hub Protocol using System.Text.Json. /// </summary> public sealed class JsonHubProtocol : IHubProtocol { private const string ResultPropertyName = "result"; private static readonly JsonEncodedText ResultPropertyNameBytes = JsonEncodedText.Encode(ResultPropertyName); private const string ItemPropertyName = "item"; private static readonly JsonEncodedText ItemPropertyNameBytes = JsonEncodedText.Encode(ItemPropertyName); private const string InvocationIdPropertyName = "invocationId"; private static readonly JsonEncodedText InvocationIdPropertyNameBytes = JsonEncodedText.Encode(InvocationIdPropertyName); private const string StreamIdsPropertyName = "streamIds"; private static readonly JsonEncodedText StreamIdsPropertyNameBytes = JsonEncodedText.Encode(StreamIdsPropertyName); private const string TypePropertyName = "type"; private static readonly JsonEncodedText TypePropertyNameBytes = JsonEncodedText.Encode(TypePropertyName); private const string ErrorPropertyName = "error"; private static readonly JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName); private const string AllowReconnectPropertyName = "allowReconnect"; private static readonly JsonEncodedText AllowReconnectPropertyNameBytes = JsonEncodedText.Encode(AllowReconnectPropertyName); private const string TargetPropertyName = "target"; private static readonly JsonEncodedText TargetPropertyNameBytes = JsonEncodedText.Encode(TargetPropertyName); private const string ArgumentsPropertyName = "arguments"; private static readonly JsonEncodedText ArgumentsPropertyNameBytes = JsonEncodedText.Encode(ArgumentsPropertyName); private const string HeadersPropertyName = "headers"; private static readonly JsonEncodedText HeadersPropertyNameBytes = JsonEncodedText.Encode(HeadersPropertyName); private const string ProtocolName = "json"; private const int ProtocolVersion = 1; /// <summary> /// Gets the serializer used to serialize invocation arguments and return values. /// </summary> private readonly JsonSerializerOptions _payloadSerializerOptions; /// <summary> /// Initializes a new instance of the <see cref="JsonHubProtocol"/> class. /// </summary> public JsonHubProtocol() : this(Options.Create(new JsonHubProtocolOptions())) { } /// <summary> /// Initializes a new instance of the <see cref="JsonHubProtocol"/> class. /// </summary> /// <param name="options">The options used to initialize the protocol.</param> public JsonHubProtocol(IOptions<JsonHubProtocolOptions> options) { _payloadSerializerOptions = options.Value.PayloadSerializerOptions; } /// <inheritdoc /> public string Name => ProtocolName; /// <inheritdoc /> public int Version => ProtocolVersion; /// <inheritdoc /> public TransferFormat TransferFormat => TransferFormat.Text; /// <inheritdoc /> public bool IsVersionSupported(int version) { return version == Version; } /// <inheritdoc /> public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, [NotNullWhen(true)] out HubMessage? message) { if (!TextMessageParser.TryParseMessage(ref input, out var payload)) { message = null; return false; } message = ParseMessage(payload, binder); return message != null; } /// <inheritdoc /> public void WriteMessage(HubMessage message, IBufferWriter<byte> output) { WriteMessageCore(message, output); TextMessageFormatter.WriteRecordSeparator(output); } /// <inheritdoc /> public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message) { return HubProtocolExtensions.GetMessageBytes(this, message); } private HubMessage? ParseMessage(ReadOnlySequence<byte> input, IInvocationBinder binder) { try { // We parse using the Utf8JsonReader directly but this has a problem. Some of our properties are dependent on other properties // and since reading the json might be unordered, we need to store the parsed content as JsonDocument to re-parse when true types are known. // if we're lucky and the state we need to directly parse is available, then we'll use it. int? type = null; string? invocationId = null; string? target = null; string? error = null; var hasItem = false; object? item = null; var hasResult = false; object? result = null; var hasArguments = false; object?[]? arguments = null; string[]? streamIds = null; bool hasArgumentsToken = false; Utf8JsonReader argumentsToken = default; bool hasItemsToken = false; Utf8JsonReader itemsToken = default; bool hasResultToken = false; Utf8JsonReader resultToken = default; ExceptionDispatchInfo? argumentBindingException = null; Dictionary<string, string>? headers = null; var completed = false; var allowReconnect = false; var reader = new Utf8JsonReader(input, isFinalBlock: true, state: default); reader.CheckRead(); // We're always parsing a JSON object reader.EnsureObjectStart(); do { switch (reader.TokenType) { case JsonTokenType.PropertyName: if (reader.ValueTextEquals(TypePropertyNameBytes.EncodedUtf8Bytes)) { type = reader.ReadAsInt32(TypePropertyName); if (type == null) { throw new InvalidDataException($"Expected '{TypePropertyName}' to be of type {JsonTokenType.Number}."); } } else if (reader.ValueTextEquals(InvocationIdPropertyNameBytes.EncodedUtf8Bytes)) { invocationId = reader.ReadAsString(InvocationIdPropertyName); } else if (reader.ValueTextEquals(StreamIdsPropertyNameBytes.EncodedUtf8Bytes)) { reader.CheckRead(); if (reader.TokenType != JsonTokenType.StartArray) { throw new InvalidDataException( $"Expected '{StreamIdsPropertyName}' to be of type {SystemTextJsonExtensions.GetTokenString(JsonTokenType.StartArray)}."); } var newStreamIds = new List<string>(); reader.Read(); while (reader.TokenType != JsonTokenType.EndArray) { newStreamIds.Add(reader.GetString() ?? throw new InvalidDataException($"Null value for '{StreamIdsPropertyName}' is not valid.")); reader.Read(); } streamIds = newStreamIds.ToArray(); } else if (reader.ValueTextEquals(TargetPropertyNameBytes.EncodedUtf8Bytes)) { target = reader.ReadAsString(TargetPropertyName); } else if (reader.ValueTextEquals(ErrorPropertyNameBytes.EncodedUtf8Bytes)) { error = reader.ReadAsString(ErrorPropertyName); } else if (reader.ValueTextEquals(AllowReconnectPropertyNameBytes.EncodedUtf8Bytes)) { allowReconnect = reader.ReadAsBoolean(AllowReconnectPropertyName); } else if (reader.ValueTextEquals(ResultPropertyNameBytes.EncodedUtf8Bytes)) { hasResult = true; reader.CheckRead(); if (string.IsNullOrEmpty(invocationId)) { // If we don't have an invocation id then we need to value copy the reader so we can parse it later hasResultToken = true; resultToken = reader; reader.Skip(); } else { // If we have an invocation id already we can parse the end result var returnType = binder.GetReturnType(invocationId); result = BindType(ref reader, returnType); } } else if (reader.ValueTextEquals(ItemPropertyNameBytes.EncodedUtf8Bytes)) { reader.CheckRead(); hasItem = true; string? id = null; if (!string.IsNullOrEmpty(invocationId)) { id = invocationId; } else { // If we don't have an id yet then we need to value copy the reader so we can parse it later hasItemsToken = true; itemsToken = reader; reader.Skip(); continue; } try { var itemType = binder.GetStreamItemType(id); item = BindType(ref reader, itemType); } catch (Exception ex) { return new StreamBindingFailureMessage(id, ExceptionDispatchInfo.Capture(ex)); } } else if (reader.ValueTextEquals(ArgumentsPropertyNameBytes.EncodedUtf8Bytes)) { reader.CheckRead(); int initialDepth = reader.CurrentDepth; if (reader.TokenType != JsonTokenType.StartArray) { throw new InvalidDataException($"Expected '{ArgumentsPropertyName}' to be of type {SystemTextJsonExtensions.GetTokenString(JsonTokenType.StartArray)}."); } hasArguments = true; if (string.IsNullOrEmpty(target)) { // We don't know the method name yet so just value copy the reader so we can parse it later hasArgumentsToken = true; argumentsToken = reader; reader.Skip(); } else { try { var paramTypes = binder.GetParameterTypes(target); arguments = BindTypes(ref reader, paramTypes); } catch (Exception ex) { argumentBindingException = ExceptionDispatchInfo.Capture(ex); // Could be at any point in argument array JSON when an error is thrown // Read until the end of the argument JSON array while (reader.CurrentDepth == initialDepth && reader.TokenType == JsonTokenType.StartArray || reader.CurrentDepth > initialDepth) { reader.CheckRead(); } } } } else if (reader.ValueTextEquals(HeadersPropertyNameBytes.EncodedUtf8Bytes)) { reader.CheckRead(); headers = ReadHeaders(ref reader); } else { reader.CheckRead(); reader.Skip(); } break; case JsonTokenType.EndObject: completed = true; break; } } while (!completed && reader.CheckRead()); HubMessage message; switch (type) { case HubProtocolConstants.InvocationMessageType: { if (target is null) { throw new InvalidDataException($"Missing required property '{TargetPropertyName}'."); } if (hasArgumentsToken) { // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything. try { var paramTypes = binder.GetParameterTypes(target); arguments = BindTypes(ref argumentsToken, paramTypes); } catch (Exception ex) { argumentBindingException = ExceptionDispatchInfo.Capture(ex); } } message = argumentBindingException != null ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException) : BindInvocationMessage(invocationId, target, arguments, hasArguments, streamIds); } break; case HubProtocolConstants.StreamInvocationMessageType: { if (target is null) { throw new InvalidDataException($"Missing required property '{TargetPropertyName}'."); } if (hasArgumentsToken) { // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything. try { var paramTypes = binder.GetParameterTypes(target); arguments = BindTypes(ref argumentsToken, paramTypes); } catch (Exception ex) { argumentBindingException = ExceptionDispatchInfo.Capture(ex); } } message = argumentBindingException != null ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException) : BindStreamInvocationMessage(invocationId, target, arguments, hasArguments, streamIds); } break; case HubProtocolConstants.StreamItemMessageType: if (invocationId is null) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (hasItemsToken) { try { var returnType = binder.GetStreamItemType(invocationId); item = BindType(ref itemsToken, returnType); } catch (JsonException ex) { message = new StreamBindingFailureMessage(invocationId, ExceptionDispatchInfo.Capture(ex)); break; } } message = BindStreamItemMessage(invocationId, item, hasItem, binder); break; case HubProtocolConstants.CompletionMessageType: if (invocationId is null) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (hasResultToken) { var returnType = binder.GetReturnType(invocationId); result = BindType(ref resultToken, returnType); } message = BindCompletionMessage(invocationId, error, result, hasResult, binder); break; case HubProtocolConstants.CancelInvocationMessageType: message = BindCancelInvocationMessage(invocationId); break; case HubProtocolConstants.PingMessageType: return PingMessage.Instance; case HubProtocolConstants.CloseMessageType: return BindCloseMessage(error, allowReconnect); case null: throw new InvalidDataException($"Missing required property '{TypePropertyName}'."); default: // Future protocol changes can add message types, old clients can ignore them return null; } return ApplyHeaders(message, headers); } catch (JsonException jrex) { throw new InvalidDataException("Error reading JSON.", jrex); } } private static Dictionary<string, string> ReadHeaders(ref Utf8JsonReader reader) { var headers = new Dictionary<string, string>(StringComparer.Ordinal); if (reader.TokenType != JsonTokenType.StartObject) { throw new InvalidDataException($"Expected '{HeadersPropertyName}' to be of type {JsonTokenType.StartObject}."); } while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.PropertyName: var propertyName = reader.GetString()!; reader.CheckRead(); if (reader.TokenType != JsonTokenType.String) { throw new InvalidDataException($"Expected header '{propertyName}' to be of type {JsonTokenType.String}."); } headers[propertyName] = reader.GetString()!; break; case JsonTokenType.Comment: break; case JsonTokenType.EndObject: return headers; } } throw new InvalidDataException("Unexpected end when reading message headers"); } private void WriteMessageCore(HubMessage message, IBufferWriter<byte> stream) { var reusableWriter = ReusableUtf8JsonWriter.Get(stream); try { var writer = reusableWriter.GetJsonWriter(); writer.WriteStartObject(); switch (message) { case InvocationMessage m: WriteMessageType(writer, HubProtocolConstants.InvocationMessageType); WriteHeaders(writer, m); WriteInvocationMessage(m, writer); break; case StreamInvocationMessage m: WriteMessageType(writer, HubProtocolConstants.StreamInvocationMessageType); WriteHeaders(writer, m); WriteStreamInvocationMessage(m, writer); break; case StreamItemMessage m: WriteMessageType(writer, HubProtocolConstants.StreamItemMessageType); WriteHeaders(writer, m); WriteStreamItemMessage(m, writer); break; case CompletionMessage m: WriteMessageType(writer, HubProtocolConstants.CompletionMessageType); WriteHeaders(writer, m); WriteCompletionMessage(m, writer); break; case CancelInvocationMessage m: WriteMessageType(writer, HubProtocolConstants.CancelInvocationMessageType); WriteHeaders(writer, m); WriteCancelInvocationMessage(m, writer); break; case PingMessage _: WriteMessageType(writer, HubProtocolConstants.PingMessageType); break; case CloseMessage m: WriteMessageType(writer, HubProtocolConstants.CloseMessageType); WriteCloseMessage(m, writer); break; default: throw new InvalidOperationException($"Unsupported message type: {message.GetType().FullName}"); } writer.WriteEndObject(); writer.Flush(); Debug.Assert(writer.CurrentDepth == 0); } finally { ReusableUtf8JsonWriter.Return(reusableWriter); } } private static void WriteHeaders(Utf8JsonWriter writer, HubInvocationMessage message) { if (message.Headers != null && message.Headers.Count > 0) { writer.WriteStartObject(HeadersPropertyNameBytes); foreach (var value in message.Headers) { writer.WriteString(value.Key, value.Value); } writer.WriteEndObject(); } } private void WriteCompletionMessage(CompletionMessage message, Utf8JsonWriter writer) { WriteInvocationId(message, writer); if (!string.IsNullOrEmpty(message.Error)) { writer.WriteString(ErrorPropertyNameBytes, message.Error); } else if (message.HasResult) { writer.WritePropertyName(ResultPropertyNameBytes); if (message.Result == null) { writer.WriteNullValue(); } else { JsonSerializer.Serialize(writer, message.Result, message.Result.GetType(), _payloadSerializerOptions); } } } private static void WriteCancelInvocationMessage(CancelInvocationMessage message, Utf8JsonWriter writer) { WriteInvocationId(message, writer); } private void WriteStreamItemMessage(StreamItemMessage message, Utf8JsonWriter writer) { WriteInvocationId(message, writer); writer.WritePropertyName(ItemPropertyNameBytes); if (message.Item == null) { writer.WriteNullValue(); } else { JsonSerializer.Serialize(writer, message.Item, message.Item.GetType(), _payloadSerializerOptions); } } private void WriteInvocationMessage(InvocationMessage message, Utf8JsonWriter writer) { WriteInvocationId(message, writer); writer.WriteString(TargetPropertyNameBytes, message.Target); WriteArguments(message.Arguments, writer); WriteStreamIds(message.StreamIds, writer); } private void WriteStreamInvocationMessage(StreamInvocationMessage message, Utf8JsonWriter writer) { WriteInvocationId(message, writer); writer.WriteString(TargetPropertyNameBytes, message.Target); WriteArguments(message.Arguments, writer); WriteStreamIds(message.StreamIds, writer); } private static void WriteCloseMessage(CloseMessage message, Utf8JsonWriter writer) { if (message.Error != null) { writer.WriteString(ErrorPropertyNameBytes, message.Error); } if (message.AllowReconnect) { writer.WriteBoolean(AllowReconnectPropertyNameBytes, true); } } private void WriteArguments(object?[] arguments, Utf8JsonWriter writer) { writer.WriteStartArray(ArgumentsPropertyNameBytes); foreach (var argument in arguments) { if (argument == null) { writer.WriteNullValue(); } else { JsonSerializer.Serialize(writer, argument, argument.GetType(), _payloadSerializerOptions); } } writer.WriteEndArray(); } private static void WriteStreamIds(string[]? streamIds, Utf8JsonWriter writer) { if (streamIds == null) { return; } writer.WriteStartArray(StreamIdsPropertyNameBytes); foreach (var streamId in streamIds) { writer.WriteStringValue(streamId); } writer.WriteEndArray(); } private static void WriteInvocationId(HubInvocationMessage message, Utf8JsonWriter writer) { if (!string.IsNullOrEmpty(message.InvocationId)) { writer.WriteString(InvocationIdPropertyNameBytes, message.InvocationId); } } private static void WriteMessageType(Utf8JsonWriter writer, int type) { writer.WriteNumber(TypePropertyNameBytes, type); } private static HubMessage BindCancelInvocationMessage(string? invocationId) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } return new CancelInvocationMessage(invocationId); } private static HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (error != null && hasResult) { throw new InvalidDataException("The 'error' and 'result' properties are mutually exclusive."); } if (hasResult) { return new CompletionMessage(invocationId, error, result, hasResult: true); } return new CompletionMessage(invocationId, error, result: null, hasResult: false); } private static HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (!hasItem) { throw new InvalidDataException($"Missing required property '{ItemPropertyName}'."); } return new StreamItemMessage(invocationId, item); } private static HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (!hasArguments) { throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'."); } if (string.IsNullOrEmpty(target)) { throw new InvalidDataException($"Missing required property '{TargetPropertyName}'."); } Debug.Assert(arguments != null); return new StreamInvocationMessage(invocationId, target, arguments, streamIds); } private static HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds) { if (string.IsNullOrEmpty(target)) { throw new InvalidDataException($"Missing required property '{TargetPropertyName}'."); } if (!hasArguments) { throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'."); } Debug.Assert(arguments != null); return new InvocationMessage(invocationId, target, arguments, streamIds); } private object? BindType(ref Utf8JsonReader reader, Type type) { return JsonSerializer.Deserialize(ref reader, type, _payloadSerializerOptions); } private object?[] BindTypes(ref Utf8JsonReader reader, IReadOnlyList<Type> paramTypes) { object?[]? arguments = null; var paramIndex = 0; var paramCount = paramTypes.Count; var depth = reader.CurrentDepth; reader.CheckRead(); while (reader.TokenType != JsonTokenType.EndArray && reader.CurrentDepth > depth) { if (paramIndex < paramCount) { arguments ??= new object?[paramCount]; try { arguments[paramIndex] = BindType(ref reader, paramTypes[paramIndex]); } catch (Exception ex) { throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex); } } else { // Skip extra arguments and throw error after reading them all reader.Skip(); } reader.CheckRead(); paramIndex++; } if (paramIndex != paramCount) { throw new InvalidDataException($"Invocation provides {paramIndex} argument(s) but target expects {paramCount}."); } return arguments ?? Array.Empty<object>(); } private static CloseMessage BindCloseMessage(string? error, bool allowReconnect) { // An empty string is still an error if (error == null && !allowReconnect) { return CloseMessage.Empty; } return new CloseMessage(error, allowReconnect); } private static HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers) { if (headers != null && message is HubInvocationMessage invocationMessage) { invocationMessage.Headers = headers; } return message; } internal static JsonSerializerOptions CreateDefaultSerializerSettings() { return new JsonSerializerOptions() { WriteIndented = false, ReadCommentHandling = JsonCommentHandling.Disallow, AllowTrailingCommas = false, DefaultIgnoreCondition = JsonIgnoreCondition.Never, IgnoreReadOnlyProperties = false, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, MaxDepth = 64, DictionaryKeyPolicy = null, DefaultBufferSize = 16 * 1024, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Collections.Generic; using System.Linq; using Microsoft.PythonTools.Analysis.Analyzer; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Values { class BuiltinInstanceInfo : BuiltinNamespace<IPythonType>, IReferenceableContainer { private readonly BuiltinClassInfo _klass; public BuiltinInstanceInfo(BuiltinClassInfo klass) : base(klass._type, klass.ProjectState) { _klass = klass; } public BuiltinClassInfo ClassInfo { get { return _klass; } } public override IPythonType PythonType { get { return _type; } } public override IAnalysisSet GetInstanceType() { if (_klass.TypeId == BuiltinTypeId.Type) { return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance; } return base.GetInstanceType(); } public override string Description { get { return _klass._type.Name; } } public override string Documentation { get { return _klass.Documentation; } } public override PythonMemberType MemberType { get { switch (_klass.MemberType) { case PythonMemberType.Enum: return PythonMemberType.EnumInstance; case PythonMemberType.Delegate: return PythonMemberType.DelegateInstance; default: return PythonMemberType.Instance; } } } public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) { // Must unconditionally call the base implementation of GetMember var res = base.GetMember(node, unit, name); if (res.Count > 0) { _klass.AddMemberReference(node, unit, name); return res.GetDescriptor(node, this, _klass, unit); } return res; } public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) { var res = base.GetMember(node, unit, name); if (res.Count > 0) { _klass.AddMemberReference(node, unit, name); } } public override IAnalysisSet UnaryOperation(Node node, AnalysisUnit unit, PythonOperator operation) { if (operation == PythonOperator.Not) { return unit.ProjectState.ClassInfos[BuiltinTypeId.Bool].Instance; } string methodName = InstanceInfo.UnaryOpToString(unit.ProjectState, operation); if (methodName != null) { var method = GetMember(node, unit, methodName); if (method.Count > 0) { var res = method.Call( node, unit, new[] { this }, ExpressionEvaluator.EmptyNames ); return res; } } return base.UnaryOperation(node, unit, operation); } public override IAnalysisSet BinaryOperation(Node node, AnalysisUnit unit, PythonOperator operation, IAnalysisSet rhs) { return ConstantInfo.NumericOp(node, this, unit, operation, rhs) ?? NumericOp(node, unit, operation, rhs) ?? AnalysisSet.Empty; } private IAnalysisSet NumericOp(Node node, AnalysisUnit unit, Parsing.PythonOperator operation, IAnalysisSet rhs) { string methodName = InstanceInfo.BinaryOpToString(operation); if (methodName != null) { var method = GetMember(node, unit, methodName); if (method.Count > 0) { var res = method.Call( node, unit, new[] { this, rhs }, ExpressionEvaluator.EmptyNames ); if (res.IsObjectOrUnknown()) { // the type defines the operator, assume it returns // some combination of the input types. return SelfSet.Union(rhs); } return res; } } return base.BinaryOperation(node, unit, operation, rhs); } public override IAnalysisSet GetIndex(Node node, AnalysisUnit unit, IAnalysisSet index) { var getItem = GetMember(node, unit, "__getitem__"); if (getItem.Count > 0) { var res = getItem.Call(node, unit, new[] { index }, ExpressionEvaluator.EmptyNames); if (res.IsObjectOrUnknown() && index.Contains(SliceInfo.Instance)) { // assume slicing returns a type of the same object... return this; } return res; } return AnalysisSet.Empty; } public override IEnumerable<OverloadResult> Overloads { get { IAnalysisSet callRes; if (_klass.GetAllMembers(ProjectState._defaultContext).TryGetValue("__call__", out callRes)) { foreach (var overload in callRes.SelectMany(av => av.Overloads)) { yield return overload.WithNewParameters( overload.Parameters.Skip(1).ToArray() ); } } foreach (var overload in base.Overloads) { yield return overload; } } } public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var res = base.Call(node, unit, args, keywordArgNames); if (Push()) { try { var callRes = GetMember(node, unit, "__call__"); if (callRes.Any()) { res = res.Union(callRes.Call(node, unit, args, keywordArgNames)); } } finally { Pop(); } } return res; } public override IAnalysisSet GetEnumeratorTypes(Node node, AnalysisUnit unit) { if (Push()) { try { var iter = GetIterator(node, unit); if (iter.Any()) { return iter .GetMember(node, unit, unit.ProjectState.LanguageVersion.Is3x() ? "__next__" : "next") .Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames); } } finally { Pop(); } } return base.GetEnumeratorTypes(node, unit); } public override IAnalysisSet GetAsyncEnumeratorTypes(Node node, AnalysisUnit unit) { if (unit.ProjectState.LanguageVersion.Is3x() && Push()) { try { var iter = GetAsyncIterator(node, unit); if (iter.Any()) { return iter .GetMember(node, unit, "__anext__") .Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames) .Await(node, unit); } } finally { Pop(); } } return base.GetAsyncEnumeratorTypes(node, unit); } internal override bool IsOfType(IAnalysisSet klass) { if (klass.Contains(this.ClassInfo)) { return true; } if (TypeId != BuiltinTypeId.NoneType && TypeId != BuiltinTypeId.Type && TypeId != BuiltinTypeId.Function && TypeId != BuiltinTypeId.BuiltinFunction) { return klass.Contains(ProjectState.ClassInfos[BuiltinTypeId.Object]); } return false; } internal override BuiltinTypeId TypeId { get { return ClassInfo.PythonType.TypeId; } } internal override bool UnionEquals(AnalysisValue ns, int strength) { var dict = ProjectState.ClassInfos[BuiltinTypeId.Dict]; if (strength < MergeStrength.IgnoreIterableNode && (this is DictionaryInfo || this == dict.Instance)) { if (ns is DictionaryInfo || ns == dict.Instance) { return true; } var ci = ns as ConstantInfo; if (ci != null && ci.ClassInfo == dict) { return true; } return false; } if (strength >= MergeStrength.ToObject) { if (TypeId == BuiltinTypeId.NoneType || ns.TypeId == BuiltinTypeId.NoneType) { // BII + BII(None) => do not merge // Unless both types are None, since they could be various // combinations of BuiltinInstanceInfo or ConstantInfo that // need to be merged. return TypeId == BuiltinTypeId.NoneType && ns.TypeId == BuiltinTypeId.NoneType; } var func = ProjectState.ClassInfos[BuiltinTypeId.Function]; if (this == func.Instance) { // FI + BII(function) => BII(function) return ns is FunctionInfo || ns is BuiltinFunctionInfo || ns == func.Instance; } else if (ns == func.Instance) { return false; } var type = ProjectState.ClassInfos[BuiltinTypeId.Type]; if (this == type.Instance) { // CI + BII(type) => BII(type) // BCI + BII(type) => BII(type) return ns is ClassInfo || ns is BuiltinClassInfo || ns == type.Instance; } else if (ns == type.Instance) { return false; } /// BII + II => BII(object) /// BII + BII => BII(object) return ns is InstanceInfo || ns is BuiltinInstanceInfo; } else if (strength >= MergeStrength.ToBaseClass) { var bii = ns as BuiltinInstanceInfo; if (bii != null) { return ClassInfo.UnionEquals(bii.ClassInfo, strength); } var ii = ns as InstanceInfo; if (ii != null) { return ClassInfo.UnionEquals(ii.ClassInfo, strength); } } else if (this is ConstantInfo || ns is ConstantInfo) { // ConI + BII => BII if CIs match var bii = ns as BuiltinInstanceInfo; return bii != null && ClassInfo.Equals(bii.ClassInfo); } return base.UnionEquals(ns, strength); } internal override int UnionHashCode(int strength) { return ClassInfo.UnionHashCode(strength); } internal override AnalysisValue UnionMergeTypes(AnalysisValue ns, int strength) { if (strength >= MergeStrength.ToObject) { if (TypeId == BuiltinTypeId.NoneType || ns.TypeId == BuiltinTypeId.NoneType) { // BII + BII(None) => do not merge // Unless both types are None, since they could be various // combinations of BuiltinInstanceInfo or ConstantInfo that // need to be merged. return ProjectState.ClassInfos[BuiltinTypeId.NoneType].Instance; } var func = ProjectState.ClassInfos[BuiltinTypeId.Function]; if (this == func.Instance) { // FI + BII(function) => BII(function) return func.Instance; } var type = ProjectState.ClassInfos[BuiltinTypeId.Type]; if (this == type.Instance) { // CI + BII(type) => BII(type) // BCI + BII(type) => BII(type) return type; } /// BII + II => BII(object) /// BII + BII => BII(object) return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance; } else if (strength >= MergeStrength.ToBaseClass) { var bii = ns as BuiltinInstanceInfo; if (bii != null) { return ClassInfo.UnionMergeTypes(bii.ClassInfo, strength).GetInstanceType().Single(); } var ii = ns as InstanceInfo; if (ii != null) { return ClassInfo.UnionMergeTypes(ii.ClassInfo, strength).GetInstanceType().Single(); } } else if (this is ConstantInfo || ns is ConstantInfo) { return ClassInfo.Instance; } return base.UnionMergeTypes(ns, strength); } #region IReferenceableContainer Members public IEnumerable<IReferenceable> GetDefinitions(string name) { return _klass.GetDefinitions(name); } #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.Net; using System.Security.Principal; using System.Diagnostics; using System.Runtime.InteropServices; using System.ComponentModel; using System.Security.Permissions; using System.IO; namespace System.DirectoryServices.ActiveDirectory { public enum DirectoryContextType { Domain = 0, Forest = 1, DirectoryServer = 2, ConfigurationSet = 3, ApplicationPartition = 4 } public class DirectoryContext { private string _name = null; private DirectoryContextType _contextType; private NetworkCredential _credential = null; internal string serverName = null; internal bool usernameIsNull = false; internal bool passwordIsNull = false; private bool _validated = false; private bool _contextIsValid = false; internal static LoadLibrarySafeHandle ADHandle; internal static LoadLibrarySafeHandle ADAMHandle; #region constructors static DirectoryContext() { // load ntdsapi.dll for AD and ADAM GetLibraryHandle(); } // Internal Constructors internal void InitializeDirectoryContext(DirectoryContextType contextType, string name, string username, string password) { _name = name; _contextType = contextType; _credential = new NetworkCredential(username, password); if (username == null) { usernameIsNull = true; } if (password == null) { passwordIsNull = true; } } internal DirectoryContext(DirectoryContextType contextType, string name, DirectoryContext context) { _name = name; _contextType = contextType; if (context != null) { _credential = context.Credential; this.usernameIsNull = context.usernameIsNull; this.passwordIsNull = context.passwordIsNull; } else { _credential = new NetworkCredential(null, "", null); this.usernameIsNull = true; this.passwordIsNull = true; } } internal DirectoryContext(DirectoryContext context) { _name = context.Name; _contextType = context.ContextType; _credential = context.Credential; this.usernameIsNull = context.usernameIsNull; this.passwordIsNull = context.passwordIsNull; if (context.ContextType != DirectoryContextType.ConfigurationSet) { // // only for configurationset, we select a server, so we should not copy over that // information, for all other types, this is either the same as name of the target or if the target is netbios name // (for domain and forest) it could be the dns name. We should copy over this information. // this.serverName = context.serverName; } } #endregion constructors #region public constructors public DirectoryContext(DirectoryContextType contextType) { // // this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain // since all other types require the name to be specified // if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.OnlyDomainOrForest, "contextType"); } InitializeDirectoryContext(contextType, null, null, null); } public DirectoryContext(DirectoryContextType contextType, string name) { if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition) { throw new InvalidEnumArgumentException("contextType", (int)contextType, typeof(DirectoryContextType)); } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "name"); } InitializeDirectoryContext(contextType, name, null, null); } public DirectoryContext(DirectoryContextType contextType, string username, string password) { // // this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain // since all other types require the name to be specified // if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.OnlyDomainOrForest, "contextType"); } InitializeDirectoryContext(contextType, null, username, password); } public DirectoryContext(DirectoryContextType contextType, string name, string username, string password) { if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition) { throw new InvalidEnumArgumentException("contextType", (int)contextType, typeof(DirectoryContextType)); } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "name"); } InitializeDirectoryContext(contextType, name, username, password); } #endregion public methods #region public properties public string Name => _name; public string UserName => usernameIsNull ? null : _credential.UserName; internal string Password { get => passwordIsNull ? null : _credential.Password; } public DirectoryContextType ContextType => _contextType; internal NetworkCredential Credential => _credential; #endregion public properties #region private methods internal static bool IsContextValid(DirectoryContext context, DirectoryContextType contextType) { bool contextIsValid = false; if ((contextType == DirectoryContextType.Domain) || ((contextType == DirectoryContextType.Forest) && (context.Name == null))) { string tmpTarget = context.Name; if (tmpTarget == null) { // GetLoggedOnDomain returns the dns name of the logged on user's domain context.serverName = GetLoggedOnDomain(); contextIsValid = true; } else { // check for domain int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // try with force rediscovery errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { contextIsValid = false; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } else { Debug.Assert(domainControllerInfo != null); Debug.Assert(domainControllerInfo.DomainName != null); context.serverName = domainControllerInfo.DomainName; contextIsValid = true; } } else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT) { // we can get this error if the target it server:port (not a valid domain) contextIsValid = false; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } else { Debug.Assert(domainControllerInfo != null); Debug.Assert(domainControllerInfo.DomainName != null); context.serverName = domainControllerInfo.DomainName; contextIsValid = true; } } } else if (contextType == DirectoryContextType.Forest) { Debug.Assert(context.Name != null); // check for forest int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // try with force rediscovery errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)((PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired)) | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { contextIsValid = false; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } else { Debug.Assert(domainControllerInfo != null); Debug.Assert(domainControllerInfo.DnsForestName != null); context.serverName = domainControllerInfo.DnsForestName; contextIsValid = true; } } else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT) { // we can get this error if the target it server:port (not a valid forest) contextIsValid = false; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } else { Debug.Assert(domainControllerInfo != null); Debug.Assert(domainControllerInfo.DnsForestName != null); context.serverName = domainControllerInfo.DnsForestName; contextIsValid = true; } } else if (contextType == DirectoryContextType.ApplicationPartition) { Debug.Assert(context.Name != null); // check for application partition int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // try with force rediscovery errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { contextIsValid = false; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } else { contextIsValid = true; } } else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT) { // we can get this error if the target it server:port (not a valid application partition) contextIsValid = false; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } else { contextIsValid = true; } } else if (contextType == DirectoryContextType.DirectoryServer) { // // if the servername contains a port number, then remove that // string tempServerName = null; string portNumber; tempServerName = Utils.SplitServerNameAndPortNumber(context.Name, out portNumber); // // this will validate that the name specified in the context is truely the name of a machine (and not of a domain) // DirectoryEntry de = new DirectoryEntry("WinNT://" + tempServerName + ",computer", context.UserName, context.Password, Utils.DefaultAuthType); try { de.Bind(true); contextIsValid = true; } catch (COMException e) { if ((e.ErrorCode == unchecked((int)0x80070035)) || (e.ErrorCode == unchecked((int)0x80070033)) || (e.ErrorCode == unchecked((int)0x80005000))) { // if this returns bad network path contextIsValid = false; } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { de.Dispose(); } } else { // no special validation for ConfigurationSet contextIsValid = true; } return contextIsValid; } internal bool isRootDomain() { if (_contextType != DirectoryContextType.Forest) return false; if (!_validated) { _contextIsValid = IsContextValid(this, DirectoryContextType.Forest); _validated = true; } return _contextIsValid; } internal bool isDomain() { if (_contextType != DirectoryContextType.Domain) return false; if (!_validated) { _contextIsValid = IsContextValid(this, DirectoryContextType.Domain); _validated = true; } return _contextIsValid; } internal bool isNdnc() { if (_contextType != DirectoryContextType.ApplicationPartition) return false; if (!_validated) { _contextIsValid = IsContextValid(this, DirectoryContextType.ApplicationPartition); _validated = true; } return _contextIsValid; } internal bool isServer() { if (_contextType != DirectoryContextType.DirectoryServer) return false; if (!_validated) { _contextIsValid = IsContextValid(this, DirectoryContextType.DirectoryServer); _validated = true; } return _contextIsValid; } internal bool isADAMConfigSet() { if (_contextType != DirectoryContextType.ConfigurationSet) return false; if (!_validated) { _contextIsValid = IsContextValid(this, DirectoryContextType.ConfigurationSet); _validated = true; } return _contextIsValid; } // // this method is called when the forest name is explicitly specified // and we want to check if that matches the current logged on forest // internal bool isCurrentForest() { bool result = false; Debug.Assert(_name != null); DomainControllerInfo domainControllerInfo = Locator.GetDomainControllerInfo(null, _name, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName)); DomainControllerInfo currentDomainControllerInfo; string loggedOnDomain = GetLoggedOnDomain(); int errorCode = Locator.DsGetDcNameWrapper(null, loggedOnDomain, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName), out currentDomainControllerInfo); if (errorCode == 0) { Debug.Assert(domainControllerInfo.DnsForestName != null); Debug.Assert(currentDomainControllerInfo.DnsForestName != null); result = (Utils.Compare(domainControllerInfo.DnsForestName, currentDomainControllerInfo.DnsForestName) == 0); } // // if there is no forest associated with the logged on domain, then we return false // else if (errorCode != NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } return result; } internal bool useServerBind() { return ((ContextType == DirectoryContextType.DirectoryServer) || (ContextType == DirectoryContextType.ConfigurationSet)); } internal string GetServerName() { if (serverName == null) { switch (_contextType) { case DirectoryContextType.ConfigurationSet: { AdamInstance adamInst = ConfigurationSet.FindAnyAdamInstance(this); try { serverName = adamInst.Name; } finally { adamInst.Dispose(); } break; } case DirectoryContextType.Domain: case DirectoryContextType.Forest: { // // if the target is not specified OR // if the forest name was explicitly specified and the forest is the same as the current forest // we want to find a DC in the current domain // if ((_name == null) || ((_contextType == DirectoryContextType.Forest) && (isCurrentForest()))) { serverName = GetLoggedOnDomain(); } else { serverName = GetDnsDomainName(_name); } break; } case DirectoryContextType.ApplicationPartition: { // if this is an appNC the target should not be null Debug.Assert(_name != null); serverName = _name; break; } case DirectoryContextType.DirectoryServer: { // this should not happen (We should have checks for this earlier itself) Debug.Assert(_name != null); serverName = _name; break; } default: { Debug.Fail("DirectoryContext::GetServerName - Unknown contextType"); break; } } } return serverName; } internal static string GetLoggedOnDomain() { string domainName = null; NegotiateCallerNameRequest requestBuffer = new NegotiateCallerNameRequest(); int requestBufferLength = (int)Marshal.SizeOf(requestBuffer); IntPtr pResponseBuffer = IntPtr.Zero; NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse(); int responseBufferLength; int protocolStatus; int result; LsaLogonProcessSafeHandle lsaHandle; // // since we are using safe handles, we don't need to explicitly call NativeMethods.LsaDeregisterLogonProcess(lsaHandle) // result = NativeMethods.LsaConnectUntrusted(out lsaHandle); if (result == 0) { // // initialize the request buffer // requestBuffer.messageType = NativeMethods.NegGetCallerName; result = NativeMethods.LsaCallAuthenticationPackage(lsaHandle, 0, requestBuffer, requestBufferLength, out pResponseBuffer, out responseBufferLength, out protocolStatus); try { if (result == 0 && protocolStatus == 0) { Marshal.PtrToStructure(pResponseBuffer, responseBuffer); // // callerName is of the form domain\username // Debug.Assert((responseBuffer.callerName != null), "NativeMethods.LsaCallAuthenticationPackage returned null callerName."); int index = responseBuffer.callerName.IndexOf('\\'); Debug.Assert((index != -1), "NativeMethods.LsaCallAuthenticationPackage returned callerName not in domain\\username format."); domainName = responseBuffer.callerName.Substring(0, index); } else { if (result == NativeMethods.STATUS_QUOTA_EXCEEDED) { throw new OutOfMemoryException(); } else if ((result == 0) && (UnsafeNativeMethods.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION)) { // If this is a directory user, extract domain info from username if (!Utils.IsSamUser()) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); int index = identity.Name.IndexOf('\\'); Debug.Assert(index != -1); domainName = identity.Name.Substring(0, index); } } else { throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError((result != 0) ? result : protocolStatus)); } } } finally { if (pResponseBuffer != IntPtr.Zero) { NativeMethods.LsaFreeReturnBuffer(pResponseBuffer); } } } else if (result == NativeMethods.STATUS_QUOTA_EXCEEDED) { throw new OutOfMemoryException(); } else { throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result)); } // If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.), // domainName will be null and we fall back to the machine's domain domainName = GetDnsDomainName(domainName); if (domainName == null) { // // we should never get to this point here since we should have already verified that the context is valid // by the time we get to this point // throw new ActiveDirectoryOperationException(SR.ContextNotAssociatedWithDomain); } return domainName; } internal static string GetDnsDomainName(string domainName) { DomainControllerInfo domainControllerInfo; int errorCode = 0; // // Locator.DsGetDcNameWrapper internally passes the ReturnDNSName flag when calling DsGetDcName // errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // try again with force rediscovery errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)((long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery), out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { return null; } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo != null); Debug.Assert(domainControllerInfo.DomainName != null); return domainControllerInfo.DomainName; } private static void GetLibraryHandle() { // first get AD handle string systemPath = Environment.SystemDirectory; IntPtr tempHandle = UnsafeNativeMethods.LoadLibrary(systemPath + "\\ntdsapi.dll"); if (tempHandle == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } else { ADHandle = new LoadLibrarySafeHandle(tempHandle); } // not get the ADAM handle // got to the windows\adam directory DirectoryInfo windowsDirectory = Directory.GetParent(systemPath); tempHandle = UnsafeNativeMethods.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll"); if (tempHandle == (IntPtr)0) { ADAMHandle = ADHandle; } else { ADAMHandle = new LoadLibrarySafeHandle(tempHandle); } } #endregion private methods } }
using System; using System.Collections; using Server; using Server.Multis; using Server.Items; namespace Knives.TownHouses { public class RentalContract : TownHouseSign { private Mobile c_RentalMaster; private Mobile c_RentalClient; private BaseHouse c_ParentHouse; private bool c_Completed, c_EntireHouse; public BaseHouse ParentHouse{ get{ return c_ParentHouse; } } public Mobile RentalClient{ get{ return c_RentalClient; } set{ c_RentalClient = value; InvalidateProperties(); } } public Mobile RentalMaster{ get{ return c_RentalMaster; } } public bool Completed{ get{ return c_Completed; } set{ c_Completed = value; } } public bool EntireHouse{ get{ return c_EntireHouse; } set{ c_EntireHouse = value; } } public RentalContract() : base() { ItemID = 0x14F0; Movable = true; RentByTime = TimeSpan.FromDays( 1 ); RecurRent = true; MaxZ = MinZ; } public bool HasContractedArea( Rectangle2D rect, int z ) { foreach( Item item in TownHouseSign.AllSigns ) if ( item is RentalContract && item != this && item.Map == Map && c_ParentHouse == ((RentalContract)item).ParentHouse ) foreach( Rectangle2D rect2 in ((RentalContract)item).Blocks ) for( int x = rect.Start.X; x < rect.End.X; ++x ) for( int y = rect.Start.Y; y < rect.End.Y; ++y ) if ( rect2.Contains( new Point2D( x, y ) ) ) if ( ((RentalContract)item).MinZ <= z && ((RentalContract)item).MaxZ >= z ) return true; return false; } public bool HasContractedArea( int z ) { foreach( Item item in TownHouseSign.AllSigns ) if ( item is RentalContract && item != this && item.Map == Map && c_ParentHouse == ((RentalContract)item).ParentHouse ) if ( ((RentalContract)item).MinZ <= z && ((RentalContract)item).MaxZ >= z ) return true; return false; } public void DepositTo( Mobile m ) { if ( m == null ) return; if ( Free ) { m.SendMessage( "Since this home is free, you do not receive the deposit." ); return; } m.BankBox.DropItem( new Gold( Price ) ); m.SendMessage( "You have received a {0} gold deposit from your town house.", Price ); } public override void ValidateOwnership() { if ( c_Completed && c_RentalMaster == null ) { Delete(); return; } if ( c_RentalClient != null && ( c_ParentHouse == null || c_ParentHouse.Deleted ) ) { Delete(); return; } if ( c_RentalClient != null && !Owned ) { Delete(); return; } if ( ParentHouse == null ) return; if ( !ValidateLocSec() ) { if ( DemolishTimer == null ) BeginDemolishTimer( TimeSpan.FromHours( 48 ) ); } else ClearDemolishTimer(); } protected override void DemolishAlert() { if ( ParentHouse == null || c_RentalMaster == null || c_RentalClient == null ) return; c_RentalMaster.SendMessage( "You have begun to use lockdowns reserved for {0}, and their rental unit will collapse in {1}.", c_RentalClient.Name, Math.Round( (DemolishTime-DateTime.Now).TotalHours, 2 ) ); c_RentalClient.SendMessage( "Alert your land lord, {0}, they are using storage reserved for you. They have violated the rental agreement, which will end in {1} if nothing is done.", c_RentalMaster.Name, Math.Round( (DemolishTime-DateTime.Now).TotalHours, 2 ) ); } public void FixLocSec() { int count = 0; if ( (count = General.RemainingSecures( c_ParentHouse )+Secures) < Secures ) Secures = count; if ( (count = General.RemainingLocks( c_ParentHouse )+Locks) < Locks ) Locks = count; } public bool ValidateLocSec() { if ( General.RemainingSecures( c_ParentHouse )+Secures < Secures ) return false; if ( General.RemainingLocks( c_ParentHouse )+Locks < Locks ) return false; return true; } public override void ConvertItems( bool keep ) { if ( House == null || c_ParentHouse == null || c_RentalMaster == null ) return; foreach( BaseDoor door in new ArrayList( c_ParentHouse.Doors ) ) if ( door.Map == House.Map && House.Region.Contains( door.Location ) ) ConvertDoor( door ); foreach( SecureInfo info in new ArrayList( c_ParentHouse.Secures ) ) if ( info.Item.Map == House.Map && House.Region.Contains( info.Item.Location ) ) c_ParentHouse.Release( c_RentalMaster, info.Item ); foreach( Item item in new ArrayList( c_ParentHouse.LockDowns ) ) if ( item.Map == House.Map && House.Region.Contains( item.Location ) ) c_ParentHouse.Release( c_RentalMaster, item ); } public override void UnconvertDoors( ) { if ( House == null || c_ParentHouse == null ) return; foreach( BaseDoor door in new ArrayList( House.Doors ) ) House.Doors.Remove( door ); } protected override void OnRentPaid() { if ( c_RentalMaster == null || c_RentalClient == null ) return; if ( Free ) return; c_RentalMaster.BankBox.DropItem( new Gold( Price ) ); c_RentalMaster.SendMessage( "The bank has transfered your rent from {0}.", c_RentalClient.Name ); } public override void ClearHouse() { if ( !Deleted ) Delete(); base.ClearHouse(); } public override void OnDoubleClick( Mobile m ) { ValidateOwnership(); if ( Deleted ) return; if ( c_RentalMaster == null ) c_RentalMaster = m; BaseHouse house = BaseHouse.FindHouseAt( m ); if ( c_ParentHouse == null ) c_ParentHouse = house; if ( house == null || ( house != c_ParentHouse && house != House ) ) { m.SendMessage( "You must be in the home to view this contract." ); return; } if ( m == c_RentalMaster && !c_Completed && house is TownHouse && ((TownHouse)house).ForSaleSign.PriceType != "Sale" ) { c_ParentHouse = null; m.SendMessage( "You can only rent property you own." ); return; } if ( m == c_RentalMaster && !c_Completed && General.EntireHouseContracted( c_ParentHouse ) ) { m.SendMessage( "This entire house already has a rental contract." ); return; } if ( c_Completed ) new ContractConfirmGump( m, this ); else if ( m == c_RentalMaster ) new ContractSetupGump( m, this ); else m.SendMessage( "This rental contract has not yet been completed." ); } public override void GetProperties( ObjectPropertyList list ) { if ( c_RentalClient != null ) list.Add( "a house rental contract with " + c_RentalClient.Name ); else if ( c_Completed ) list.Add( "a completed house rental contract" ); else list.Add( "an uncompleted house rental contract" ); } public override void Delete() { if ( c_ParentHouse == null ) { base.Delete(); return; } if ( !Owned && !c_ParentHouse.IsFriend( c_RentalClient ) ) { if ( c_RentalClient != null && c_RentalMaster != null ) { c_RentalMaster.SendMessage( "{0} has ended your rental agreement. Because you revoked their access, their last payment will be refunded.", c_RentalMaster.Name ); c_RentalClient.SendMessage( "You have ended your rental agreement with {0}. Because your access was revoked, your last payment is refunded.", c_RentalClient.Name ); } DepositTo( c_RentalClient ); } else if ( Owned ) { if ( c_RentalClient != null && c_RentalMaster != null ) { c_RentalClient.SendMessage( "{0} has ended your rental agreement. Since they broke the contract, your are refunded the last payment.", c_RentalMaster.Name ); c_RentalMaster.SendMessage( "You have ended your rental agreement with {0}. They will be refunded their last payment.", c_RentalClient.Name ); } DepositTo( c_RentalClient ); PackUpHouse(); } else { if ( c_RentalClient != null && c_RentalMaster != null ) { c_RentalMaster.SendMessage( "{0} has ended your rental agreement.", c_RentalClient.Name ); c_RentalClient.SendMessage( "You have ended your rental agreement with {0}.", c_RentalMaster.Name ); } DepositTo( c_RentalMaster ); } ClearRentTimer(); base.Delete(); } public RentalContract( Serial serial ) : base( serial ) { RecurRent = true; } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version // Version 1 writer.Write( c_EntireHouse ); writer.Write( c_RentalMaster ); writer.Write( c_RentalClient ); writer.Write( c_ParentHouse ); writer.Write( c_Completed ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( version >= 1 ) c_EntireHouse = reader.ReadBool(); c_RentalMaster = reader.ReadMobile(); c_RentalClient = reader.ReadMobile(); c_ParentHouse = reader.ReadItem() as BaseHouse; c_Completed = reader.ReadBool(); } } }
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.IO; using NUnit.Framework; using NodaTime; using NodaTime.TimeZones; using NodaTime.ZoneInfoCompiler; using NodaTime.ZoneInfoCompiler.Tzdb; namespace ZoneInfoCompiler.Test { ///<summary> /// This is a test class for containing all of the TzdbZoneInfoParser unit tests. ///</summary> [TestFixture] public class TzdbZoneInfoParserTest { private static readonly string[] MonthNames = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private BufferLog Log { get; set; } private TzdbZoneInfoParser Parser { get; set; } [TestFixtureSetUp] public void Setup() { Log = new BufferLog(); Parser = new TzdbZoneInfoParser(Log); } private static Offset ToOffset(int hours, int minutes, int seconds, int fractions) { return Offset.FromMilliseconds((((((hours * 60) + minutes) * 60) + seconds) * 1000) + fractions); } private static void ValidateCounts(TzdbDatabase database, int ruleSets, int zoneLists, int links) { Assert.AreEqual(ruleSets, database.Rules.Count, "Rules"); Assert.AreEqual(zoneLists, database.Zones.Count, "Zones"); Assert.AreEqual(links, database.Aliases.Count, "Links"); } /* ############################################################################### */ [Test] public void ParseDateTimeOfYear_emptyString() { var tokens = Tokens.Tokenize(string.Empty); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseDateTimeOfYear(tokens)); } [Test] public void ParseDateTimeOfYear_missingAt() { const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseDateTimeOfYear(tokens)); } [Test] public void ParseDateTimeOfYear_missingOn() { const string text = "Mar"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseDateTimeOfYear(tokens)); } [Test] public void ParseDateTimeOfYear_onAfter() { const string text = "Mar Tue>=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)DayOfWeek.Tuesday, true, ToOffset(2, 0, 0, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onBefore() { const string text = "Mar Tue<=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)DayOfWeek.Tuesday, false, ToOffset(2, 0, 0, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onLast() { const string text = "Mar lastTue 2:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)DayOfWeek.Tuesday, false, ToOffset(2, 0, 0, 0)); Assert.AreEqual(expected, actual); } /* ############################################################################### */ [Test] public void ParseLine_comment() { const string line = "# Comment"; var database = new TzdbDatabase(); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_commentWithLeadingWhitespace() { const string line = " # Comment"; var database = new TzdbDatabase(); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_emptyString() { var database = new TzdbDatabase(); Parser.ParseLine(string.Empty, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_link() { const string line = "Link from to"; var database = new TzdbDatabase(); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 1); } [Test] public void ParseLine_whiteSpace() { const string line = " \t\t\n"; var database = new TzdbDatabase(); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_zone() { const string line = "Zone PST 2:00 US P%sT"; var database = new TzdbDatabase(); Parser.ParseLine(line, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.Zones[0].Count, "Zones in set"); } [Test] public void ParseLine_zonePlus() { const string line = "Zone PST 2:00 US P%sT"; var database = new TzdbDatabase(); Parser.ParseLine(line, database); const string line2 = " 3:00 US P%sT"; Parser.ParseLine(line2, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones[0].Count, "Zones in set"); } /* ############################################################################### */ [Test] public void ParseLink_emptyString_exception() { var tokens = Tokens.Tokenize(string.Empty); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseLink(tokens)); } [Test] public void ParseLink_simple() { var tokens = Tokens.Tokenize("from to"); var actual = Parser.ParseLink(tokens); var expected = new ZoneAlias("from", "to"); Assert.AreEqual(expected, actual); } [Test] public void ParseLink_tooFewWords_exception() { var tokens = Tokens.Tokenize("from"); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseLink(tokens)); } [Test] public void ParseMonth_emptyString_default() { Assert.AreEqual(0, TzdbZoneInfoParser.ParseMonth(string.Empty)); } [Test] public void ParseMonth_invalidMonth_default() { const string month = "Able"; Assert.AreEqual(0, TzdbZoneInfoParser.ParseMonth(month)); } [Test] public void ParseMonth_months() { for (int i = 0; i < MonthNames.Length; i++) { var month = MonthNames[i]; Assert.AreEqual(i + 1, TzdbZoneInfoParser.ParseMonth(month)); } } [Test] public void ParseMonth_nullArgument_default() { string month = null; Assert.AreEqual(0, TzdbZoneInfoParser.ParseMonth(month)); } [Test] public void ParseZone_badOffset_exception() { var tokens = Tokens.Tokenize("asd US P%sT 1969 Mar 23 14:53:27.856s"); Assert.Throws(typeof(FormatException), () => Parser.ParseZone(string.Empty, tokens)); } /* ############################################################################### */ [Test] public void ParseZone_emptyString_exception() { var tokens = Tokens.Tokenize(string.Empty); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_optionalRule() { var tokens = Tokens.Tokenize("2:00 - P%sT"); var expected = new Zone(string.Empty, ToOffset(2, 0, 0, 0), null, "P%sT"); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_simple() { var tokens = Tokens.Tokenize("2:00 US P%sT"); var expected = new Zone(string.Empty, ToOffset(2, 0, 0, 0), "US", "P%sT"); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_tooFewWords1_exception() { var tokens = Tokens.Tokenize("2:00 US"); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_tooFewWords2_exception() { var tokens = Tokens.Tokenize("2:00"); Assert.Throws(typeof(TzdbZoneInfoParser.ParseException), () => Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYear() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969"); var expected = new Zone(string.Empty, ToOffset(2, 0, 0, 0), "US", "P%sT", 1969, 1, 1, Offset.Zero, (char)0); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYearMonthDay() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23"); var expected = new Zone(string.Empty, ToOffset(2, 0, 0, 0), "US", "P%sT", 1969, 3, 23, Offset.Zero, (char)0); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYearMonthDayTime() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856"); var expected = new Zone(string.Empty, ToOffset(2, 0, 0, 0), "US", "P%sT", 1969, 3, 23, ToOffset(14, 53, 27, 856), (char)0); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYearMonthDayTimeZone() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856s"); var expected = new Zone(string.Empty, ToOffset(2, 0, 0, 0), "US", "P%sT", 1969, 3, 23, ToOffset(14, 53, 27, 856), 's'); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void Parse_emptyStream() { var reader = new StringReader(string.Empty); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 0, 0, 0); } [Test] public void Parse_threeLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n" + " 3:00 - P%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones[0].Count, "Zones in set"); } [Test] public void Parse_threeLinesWithComment() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones[0].Count, "Zones in set"); } [Test] public void Parse_twoLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.Zones[0].Count, "Zones in set"); } [Test] public void Parse_twoLinks() { const string text = "# First line must be a comment\n" + "Link from to\n" + "Link target source\n"; var reader = new StringReader(text); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 0, 0, 2); } [Test] public void Parse_twoZones() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 0, 2, 0); Assert.AreEqual(2, database.Zones[0].Count, "Zones in set " + database.Zones[0].Name); Assert.AreEqual(3, database.Zones[1].Count, "Zones in set " + database.Zones[1].Name); } [Test] public void Parse_twoZonesTwoRule() { const string text = "# A comment\n" + "Rule US 1987 2006 - Apr Sun>=1 2:00 1:00 D\n" + "Rule US 2007 max - Mar Sun>=8 2:00 1:00 D\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase(); Parser.Parse(reader, database); ValidateCounts(database, 1, 2, 0); Assert.AreEqual(2, database.Zones[0].Count, "Zones in set " + database.Zones[0].Name); Assert.AreEqual(3, database.Zones[1].Count, "Zones in set " + database.Zones[1].Name); } /* ############################################################################### */ [Test] public void Parse_2400_FromDay() { const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens); var expected = new ZoneYearOffset(TransitionMode.Wall, 4, 2, (int)DayOfWeek.Monday, true, ToOffset(0, 0, 0, 0)); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_Last() { const string text = "Mar lastSun 24:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens); var expected = new ZoneYearOffset(TransitionMode.Wall, 4, 1, (int)DayOfWeek.Monday, false, ToOffset(0, 0, 0, 0)); Assert.AreEqual(expected, actual); } } }
/** * 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; using Avro.IO; namespace Avro.Generic { public delegate void Writer<T>(T t); /// <summary> /// A typesafe wrapper around DefaultWriter. While a specific object of DefaultWriter /// allows the client to serialize a generic type, an object of this class allows /// only a single type of object to be serialized through it. /// </summary> /// <typeparam name="T">The type of object to be serialized.</typeparam> public class GenericWriter<T> : DatumWriter<T> { private readonly DefaultWriter writer; public GenericWriter(Schema schema) : this(new DefaultWriter(schema)) { } public Schema Schema { get { return writer.Schema; } } public GenericWriter(DefaultWriter writer) { this.writer = writer; } /// <summary> /// Serializes the given object using this writer's schema. /// </summary> /// <param name="value">The value to be serialized</param> /// <param name="encoder">The encoder to use for serializing</param> public void Write(T value, Encoder encoder) { writer.Write(value, encoder); } } /// <summary> /// A General purpose writer for serializing objects into a Stream using /// Avro. This class implements a default way of serializing objects. But /// one can derive a class from this and override different methods to /// acheive results that are different from the default implementation. /// </summary> public class DefaultWriter { public Schema Schema { get; private set; } /// <summary> /// Constructs a generic writer for the given schema. /// </summary> /// <param name="schema">The schema for the object to be serialized</param> public DefaultWriter(Schema schema) { this.Schema = schema; } public void Write<T>(T value, Encoder encoder) { Write(Schema, value, encoder); } /// <summary> /// Examines the schema and dispatches the actual work to one /// of the other methods of this class. This allows the derived /// classes to override specific methods and get custom results. /// </summary> /// <param name="schema">The schema to use for serializing</param> /// <param name="value">The value to be serialized</param> /// <param name="encoder">The encoder to use during serialization</param> public virtual void Write(Schema schema, object value, Encoder encoder) { switch (schema.Tag) { case Schema.Type.Null: WriteNull(value, encoder); break; case Schema.Type.Boolean: Write<bool>(value, schema.Tag, encoder.WriteBoolean); break; case Schema.Type.Int: Write<int>(value, schema.Tag, encoder.WriteInt); break; case Schema.Type.Long: Write<long>(value, schema.Tag, encoder.WriteLong); break; case Schema.Type.Float: Write<float>(value, schema.Tag, encoder.WriteFloat); break; case Schema.Type.Double: Write<double>(value, schema.Tag, encoder.WriteDouble); break; case Schema.Type.String: Write<string>(value, schema.Tag, encoder.WriteString); break; case Schema.Type.Bytes: Write<byte[]>(value, schema.Tag, encoder.WriteBytes); break; case Schema.Type.Record: case Schema.Type.Error: WriteRecord(schema as RecordSchema, value, encoder); break; case Schema.Type.Enumeration: WriteEnum(schema as EnumSchema, value, encoder); break; case Schema.Type.Fixed: WriteFixed(schema as FixedSchema, value, encoder); break; case Schema.Type.Array: WriteArray(schema as ArraySchema, value, encoder); break; case Schema.Type.Map: WriteMap(schema as MapSchema, value, encoder); break; case Schema.Type.Union: WriteUnion(schema as UnionSchema, value, encoder); break; default: error(schema, value); break; } } /// <summary> /// Serializes a "null" /// </summary> /// <param name="value">The object to be serialized using null schema</param> /// <param name="encoder">The encoder to use while serialization</param> protected virtual void WriteNull(object value, Encoder encoder) { if (value != null) throw TypeMismatch(value, "null", "null"); } /// <summary> /// A generic method to serialize primitive Avro types. /// </summary> /// <typeparam name="S">Type of the C# type to be serialized</typeparam> /// <param name="value">The value to be serialized</param> /// <param name="tag">The schema type tag</param> /// <param name="writer">The writer which should be used to write the given type.</param> protected virtual void Write<S>(object value, Schema.Type tag, Writer<S> writer) { if (!(value is S)) throw TypeMismatch(value, tag.ToString(), typeof(S).ToString()); writer((S)value); } /// <summary> /// Serialized a record using the given RecordSchema. It uses GetField method /// to extract the field value from the given object. /// </summary> /// <param name="schema">The RecordSchema to use for serialization</param> /// <param name="value">The value to be serialized</param> /// <param name="encoder">The Encoder for serialization</param> protected virtual void WriteRecord(RecordSchema schema, object value, Encoder encoder) { EnsureRecordObject(schema, value); foreach (Field field in schema) { try { object obj = GetField(value, field.Name, field.Pos); Write(field.Schema, obj, encoder); } catch (Exception ex) { throw new AvroException(ex.Message + " in field " + field.Name); } } } protected virtual void EnsureRecordObject(RecordSchema s, object value) { if (value == null || !(value is GenericRecord) || !((value as GenericRecord).Schema.Equals(s))) { throw TypeMismatch(value, "record", "GenericRecord"); } } /// <summary> /// Extracts the field value from the given object. In this default implementation, /// value should be of type GenericRecord. /// </summary> /// <param name="value">The record value from which the field needs to be extracted</param> /// <param name="fieldName">The name of the field in the record</param> /// <param name="fieldPos">The position of field in the record</param> /// <returns></returns> protected virtual object GetField(object value, string fieldName, int fieldPos) { GenericRecord d = value as GenericRecord; return d[fieldName]; } /// <summary> /// Serializes an enumeration. The default implementation expectes the value to be string whose /// value is the name of the enumeration. /// </summary> /// <param name="es">The EnumSchema for serialization</param> /// <param name="value">Value to be written</param> /// <param name="encoder">Encoder for serialization</param> protected virtual void WriteEnum(EnumSchema es, object value, Encoder encoder) { if (value == null || !(value is GenericEnum) || !((value as GenericEnum).Schema.Equals(es))) throw TypeMismatch(value, "enum", "GenericEnum"); encoder.WriteEnum(es.Ordinal((value as GenericEnum).Value)); } /// <summary> /// Serialized an array. The default implementation calls EnsureArrayObject() to ascertain that the /// given value is an array. It then calls GetArrayLength() and GetArrayElement() /// to access the members of the array and then serialize them. /// </summary> /// <param name="schema">The ArraySchema for serialization</param> /// <param name="value">The value being serialized</param> /// <param name="encoder">The encoder for serialization</param> protected virtual void WriteArray(ArraySchema schema, object value, Encoder encoder) { EnsureArrayObject(value); long l = GetArrayLength(value); encoder.WriteArrayStart(); encoder.SetItemCount(l); for (long i = 0; i < l; i++) { encoder.StartItem(); Write(schema.ItemSchema, GetArrayElement(value, i), encoder); } encoder.WriteArrayEnd(); } /// <summary> /// Checks if the given object is an array. If it is a valid array, this function returns normally. Otherwise, /// it throws an exception. The default implementation checks if the value is an array. /// </summary> /// <param name="value"></param> protected virtual void EnsureArrayObject(object value) { if (value == null || !(value is Array)) throw TypeMismatch(value, "array", "Array"); } /// <summary> /// Returns the length of an array. The default implementation requires the object /// to be an array of objects and returns its length. The defaul implementation /// gurantees that EnsureArrayObject() has been called on the value before this /// function is called. /// </summary> /// <param name="value">The object whose array length is required</param> /// <returns>The array length of the given object</returns> protected virtual long GetArrayLength(object value) { return (value as Array).Length; } /// <summary> /// Returns the element at the given index from the given array object. The default implementation /// requires that the value is an object array and returns the element in that array. The defaul implementation /// gurantees that EnsureArrayObject() has been called on the value before this /// function is called. /// </summary> /// <param name="value">The array object</param> /// <param name="index">The index to look for</param> /// <returns>The array element at the index</returns> protected virtual object GetArrayElement(object value, long index) { return (value as Array).GetValue(index); } /// <summary> /// Serialized a map. The default implementation first ensure that the value is indeed a map and then uses /// GetMapSize() and GetMapElements() to access the contents of the map. /// </summary> /// <param name="schema">The MapSchema for serialization</param> /// <param name="value">The value to be serialized</param> /// <param name="encoder">The encoder for serialization</param> protected virtual void WriteMap(MapSchema schema, object value, Encoder encoder) { EnsureMapObject(value); IDictionary<string, object> vv = (IDictionary<string, object>)value; encoder.WriteMapStart(); encoder.SetItemCount(GetMapSize(value)); foreach (KeyValuePair<string, object> obj in GetMapValues(vv)) { encoder.StartItem(); encoder.WriteString(obj.Key); Write(schema.ValueSchema, obj.Value, encoder); } encoder.WriteMapEnd(); } /// <summary> /// Checks if the given object is a map. If it is a valid map, this function returns normally. Otherwise, /// it throws an exception. The default implementation checks if the value is an IDictionary<string, object>. /// </summary> /// <param name="value"></param> protected virtual void EnsureMapObject(object value) { if (value == null || !(value is IDictionary<string, object>)) throw TypeMismatch(value, "map", "IDictionary<string, object>"); } /// <summary> /// Returns the size of the map object. The default implementation gurantees that EnsureMapObject has been /// successfully called with the given value. The default implementation requires the value /// to be an IDictionary<string, object> and returns the number of elements in it. /// </summary> /// <param name="value">The map object whose size is desired</param> /// <returns>The size of the given map object</returns> protected virtual long GetMapSize(object value) { return (value as IDictionary<string, object>).Count; } /// <summary> /// Returns the contents of the given map object. The default implementation guarantees that EnsureMapObject /// has been called with the given value. The defualt implementation of this method requires that /// the value is an IDictionary<string, object> and returns its contents. /// </summary> /// <param name="value">The map object whose size is desired</param> /// <returns>The contents of the given map object</returns> protected virtual IEnumerable<KeyValuePair<string, object>> GetMapValues(object value) { return value as IDictionary<string, object>; } /// <summary> /// Resolves the given value against the given UnionSchema and serializes the object against /// the resolved schema member. The default implementation of this method uses /// ResolveUnion to find the member schema within the UnionSchema. /// </summary> /// <param name="us">The UnionSchema to resolve against</param> /// <param name="value">The value to be serialized</param> /// <param name="encoder">The encoder for serialization</param> protected virtual void WriteUnion(UnionSchema us, object value, Encoder encoder) { int index = ResolveUnion(us, value); encoder.WriteUnionIndex(index); Write(us[index], value, encoder); } /// <summary> /// Finds the branch within the given UnionSchema that matches the given object. The default implementation /// calls Matches() method in the order of branches within the UnionSchema. If nothing matches, throws /// an exception. /// </summary> /// <param name="us">The UnionSchema to resolve against</param> /// <param name="obj">The object that should be used in matching</param> /// <returns></returns> protected virtual int ResolveUnion(UnionSchema us, object obj) { for (int i = 0; i < us.Count; i++) { if (Matches(us[i], obj)) return i; } throw new AvroException("Cannot find a match for " + obj.GetType() + " in " + us); } /// <summary> /// Serialized a fixed object. The default implementation requires that the value is /// a GenericFixed object with an identical schema as es. /// </summary> /// <param name="es">The schema for serialization</param> /// <param name="value">The value to be serialized</param> /// <param name="encoder">The encoder for serialization</param> protected virtual void WriteFixed(FixedSchema es, object value, Encoder encoder) { if (value == null || !(value is GenericFixed) || !(value as GenericFixed).Schema.Equals(es)) { throw TypeMismatch(value, "fixed", "GenericFixed"); } GenericFixed ba = (GenericFixed)value; encoder.WriteFixed(ba.Value); } protected AvroException TypeMismatch(object obj, string schemaType, string type) { return new AvroException(type + " required to write against " + schemaType + " schema but found " + (null == obj ? "null" : obj.GetType().ToString()) ); } private void error(Schema schema, Object value) { throw new AvroTypeException("Not a " + schema + ": " + value); } /* * FIXME: This method of determining the Union branch has problems. If the data is IDictionary<string, object> * if there are two branches one with record schema and the other with map, it choose the first one. Similarly if * the data is byte[] and there are fixed and bytes schemas as branches, it choose the first one that matches. * Also it does not recognize the arrays of primitive types. */ protected virtual bool Matches(Schema sc, object obj) { if (obj == null && sc.Tag != Avro.Schema.Type.Null) return false; switch (sc.Tag) { case Schema.Type.Null: return obj == null; case Schema.Type.Boolean: return obj is bool; case Schema.Type.Int: return obj is int; case Schema.Type.Long: return obj is long; case Schema.Type.Float: return obj is float; case Schema.Type.Double: return obj is double; case Schema.Type.Bytes: return obj is byte[]; case Schema.Type.String: return obj is string; case Schema.Type.Record: //return obj is GenericRecord && (obj as GenericRecord).Schema.Equals(s); return obj is GenericRecord && (obj as GenericRecord).Schema.SchemaName.Equals((sc as RecordSchema).SchemaName); case Schema.Type.Enumeration: //return obj is GenericEnum && (obj as GenericEnum).Schema.Equals(s); return obj is GenericEnum && (obj as GenericEnum).Schema.SchemaName.Equals((sc as EnumSchema).SchemaName); case Schema.Type.Array: return obj is Array && !(obj is byte[]); case Schema.Type.Map: return obj is IDictionary<string, object>; case Schema.Type.Union: return false; // Union directly within another union not allowed! case Schema.Type.Fixed: //return obj is GenericFixed && (obj as GenericFixed).Schema.Equals(s); return obj is GenericFixed && (obj as GenericFixed).Schema.SchemaName.Equals((sc as FixedSchema).SchemaName); default: throw new AvroException("Unknown schema type: " + sc.Tag); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CampaignBudget</c> resource.</summary> public sealed partial class CampaignBudgetName : gax::IResourceName, sys::IEquatable<CampaignBudgetName> { /// <summary>The possible contents of <see cref="CampaignBudgetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>. /// </summary> CustomerCampaignBudget = 1, } private static gax::PathTemplate s_customerCampaignBudget = new gax::PathTemplate("customers/{customer_id}/campaignBudgets/{campaign_budget_id}"); /// <summary>Creates a <see cref="CampaignBudgetName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CampaignBudgetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CampaignBudgetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CampaignBudgetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CampaignBudgetName"/> with the pattern /// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CampaignBudgetName"/> constructed from the provided ids.</returns> public static CampaignBudgetName FromCustomerCampaignBudget(string customerId, string campaignBudgetId) => new CampaignBudgetName(ResourceNameType.CustomerCampaignBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignBudgetId, nameof(campaignBudgetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignBudgetName"/> with pattern /// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignBudgetName"/> with pattern /// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>. /// </returns> public static string Format(string customerId, string campaignBudgetId) => FormatCustomerCampaignBudget(customerId, campaignBudgetId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignBudgetName"/> with pattern /// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignBudgetName"/> with pattern /// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>. /// </returns> public static string FormatCustomerCampaignBudget(string customerId, string campaignBudgetId) => s_customerCampaignBudget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(campaignBudgetId, nameof(campaignBudgetId))); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignBudgetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item> /// </list> /// </remarks> /// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CampaignBudgetName"/> if successful.</returns> public static CampaignBudgetName Parse(string campaignBudgetName) => Parse(campaignBudgetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignBudgetName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CampaignBudgetName"/> if successful.</returns> public static CampaignBudgetName Parse(string campaignBudgetName, bool allowUnparsed) => TryParse(campaignBudgetName, allowUnparsed, out CampaignBudgetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CampaignBudgetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item> /// </list> /// </remarks> /// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CampaignBudgetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string campaignBudgetName, out CampaignBudgetName result) => TryParse(campaignBudgetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CampaignBudgetName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CampaignBudgetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string campaignBudgetName, bool allowUnparsed, out CampaignBudgetName result) { gax::GaxPreconditions.CheckNotNull(campaignBudgetName, nameof(campaignBudgetName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignBudget.TryParseName(campaignBudgetName, out resourceName)) { result = FromCustomerCampaignBudget(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(campaignBudgetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CampaignBudgetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignBudgetId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CampaignBudgetId = campaignBudgetId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="CampaignBudgetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param> public CampaignBudgetName(string customerId, string campaignBudgetId) : this(ResourceNameType.CustomerCampaignBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignBudgetId, nameof(campaignBudgetId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>CampaignBudget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string CampaignBudgetId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCampaignBudget: return s_customerCampaignBudget.Expand(CustomerId, CampaignBudgetId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CampaignBudgetName); /// <inheritdoc/> public bool Equals(CampaignBudgetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CampaignBudgetName a, CampaignBudgetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CampaignBudgetName a, CampaignBudgetName b) => !(a == b); } public partial class CampaignBudget { /// <summary> /// <see cref="gagvr::CampaignBudgetName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CampaignBudgetName ResourceNameAsCampaignBudgetName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CampaignBudgetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::CampaignBudgetName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal CampaignBudgetName CampaignBudgetName { get => string.IsNullOrEmpty(Name) ? null : gagvr::CampaignBudgetName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.ModelBinding; using Xunit; namespace Microsoft.AspNetCore.Mvc.Rendering { /// <summary> /// Test the <see cref="HtmlHelperDisplayNameExtensions" /> class. /// </summary> public class HtmlHelperDisplayNameExtensionsTest { [Fact] public void DisplayNameHelpers_ReturnEmptyForModel() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); var enumerableHelper = DefaultTemplatesUtilities.GetHtmlHelper<IEnumerable<DefaultTemplatesUtilities.ObjectTemplateModel>>(model: null); // Act var displayNameResult = helper.DisplayName(expression: string.Empty); var displayNameNullResult = helper.DisplayName(expression: null); // null is another alias for current model var displayNameForResult = helper.DisplayNameFor(m => m); var displayNameForEnumerableModelResult = enumerableHelper.DisplayNameFor(m => m); var displayNameForModelResult = helper.DisplayNameForModel(); // Assert Assert.Empty(displayNameResult); Assert.Empty(displayNameNullResult); Assert.Empty(displayNameForResult); Assert.Empty(displayNameForEnumerableModelResult); Assert.Empty(displayNameForModelResult); } [Fact] public void DisplayNameHelpers_ReturnPropertyName() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); var enumerableHelper = DefaultTemplatesUtilities.GetHtmlHelperForEnumerable(); // Act var displayNameResult = helper.DisplayName("Property1"); var displayNameForResult = helper.DisplayNameFor(m => m.Property1); var displayNameForEnumerableResult = enumerableHelper.DisplayNameFor(m => m.Property1); // Assert Assert.Equal("Property1", displayNameResult); Assert.Equal("Property1", displayNameForResult); Assert.Equal("Property1", displayNameForEnumerableResult); } // If the metadata is for a type (not property), then DisplayName(expression) will evaluate the expression [Fact] public void DisplayNameHelpers_DisplayName_Evaluates_Expression() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); helper.ViewData["value"] = "testvalue"; // Act var displayNameResult = helper.DisplayName(expression: "value"); // Assert Assert.Equal("value", displayNameResult); } [Fact] public void DisplayNameHelpers_ReturnPropertyName_ForNestedProperty() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper<OuterClass>(model: null); var enumerableHelper = DefaultTemplatesUtilities.GetHtmlHelperForEnumerable<OuterClass>(model: null); // Act var displayNameResult = helper.DisplayName("Inner.Id"); var displayNameForResult = helper.DisplayNameFor(m => m.Inner.Id); var displayNameForEnumerableResult = enumerableHelper.DisplayNameFor(m => m.Inner.Id); // Assert Assert.Equal("Id", displayNameResult); Assert.Equal("Id", displayNameForResult); Assert.Equal("Id", displayNameForEnumerableResult); } [Theory] [InlineData("")] // Empty display name wins over non-empty property name. [InlineData("Custom display name from metadata")] public void DisplayNameHelpers_ReturnDisplayName_IfNonNull(string displayName) { // Arrange var provider = new TestModelMetadataProvider(); provider .ForType<DefaultTemplatesUtilities.ObjectTemplateModel>() .DisplayDetails(dd => dd.DisplayName = () => displayName); var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider); var enumerableHelper = DefaultTemplatesUtilities.GetHtmlHelperForEnumerable(provider: provider); // Act var displayNameResult = helper.DisplayName(expression: string.Empty); var displayNameForResult = helper.DisplayNameFor(m => m); var displayNameForEnumerableResult = enumerableHelper.DisplayNameFor((DefaultTemplatesUtilities.ObjectTemplateModel m) => m); var displayNameForModelResult = helper.DisplayNameForModel(); // Assert Assert.Equal(displayName, displayNameResult); Assert.Equal(displayName, displayNameForResult); Assert.Equal(displayName, displayNameForEnumerableResult); Assert.Equal(displayName, displayNameForModelResult); } [Theory] [InlineData("")] [InlineData("Custom display name from metadata")] public void DisplayNameHelpers_ReturnDisplayNameForProperty_IfNonNull(string displayName) { // Arrange var provider = new TestModelMetadataProvider(); provider .ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1") .DisplayDetails(dd => dd.DisplayName = () => displayName); var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider); var enumerableHelper = DefaultTemplatesUtilities.GetHtmlHelperForEnumerable(provider: provider); // Act var displayNameResult = helper.DisplayName("Property1"); var displayNameForResult = helper.DisplayNameFor(m => m.Property1); var displayNameForEnumerableResult = enumerableHelper.DisplayNameFor(m => m.Property1); // Assert Assert.Equal(displayName, displayNameResult); Assert.Equal(displayName, displayNameForResult); Assert.Equal(displayName, displayNameForEnumerableResult); } [Theory] [InlineData("A", "A")] [InlineData("A[23]", "A[23]")] [InlineData("A[0].B", "B")] [InlineData("A.B.C.D", "D")] public void DisplayName_ReturnsRightmostExpressionSegment_IfPropertiesNotFound( string expression, string expectedResult) { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act var result = helper.DisplayName(expression); // Assert // DisplayName() falls back to expression name when DisplayName and PropertyName are null. Assert.Equal(expectedResult, result); } [Fact] public void DisplayNameFor_ThrowsInvalidOperation_IfExpressionUnsupported() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act & Assert var exception = Assert.Throws<InvalidOperationException>( () => helper.DisplayNameFor(model => new { foo = "Bar" })); Assert.Equal( "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.", exception.Message); } [Fact] public void EnumerableDisplayNameFor_ThrowsInvalidOperation_IfExpressionUnsupported() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper<IEnumerable<DefaultTemplatesUtilities.ObjectTemplateModel>>(model: null); // Act & Assert var exception = Assert.Throws<InvalidOperationException>( () => helper.DisplayNameFor(model => new { foo = "Bar" })); Assert.Equal( "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.", exception.Message); } [Fact] public void DisplayNameFor_ReturnsVariableName() { // Arrange var unknownKey = "this is a dummy parameter value"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act var result = helper.DisplayNameFor(model => unknownKey); // Assert Assert.Equal("unknownKey", result); } [Fact] public void EnumerableDisplayNameFor_ReturnsVariableName() { // Arrange var unknownKey = "this is a dummy parameter value"; var helper = DefaultTemplatesUtilities.GetHtmlHelper<IEnumerable<DefaultTemplatesUtilities.ObjectTemplateModel>>(model: null); // Act var result = helper.DisplayNameFor(model => unknownKey); // Assert Assert.Equal("unknownKey", result); } private sealed class InnerClass { public int Id { get; set; } } private sealed class OuterClass { public InnerClass Inner { get; set; } } } }
//Copyright 2017 Spin Services Limited //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Moq; using NUnit.Framework; using SS.Integration.Adapter.Interface; using SS.Integration.Adapter.Actors; using SS.Integration.Adapter.Actors.Messages; using SS.Integration.Adapter.Model; using SS.Integration.Adapter.Model.Enums; using SS.Integration.Adapter.Model.Interfaces; using Akka.Routing; using FluentAssertions; using SportingSolutions.Udapi.Sdk.Interfaces; using SS.Integration.Adapter.Enums; using Settings = SS.Integration.Adapter.Configuration.Settings; namespace SS.Integration.Adapter.Tests { [TestFixture] public class StreamHealthCheckActorTests : AdapterTestKit { #region Constants public const string STREAM_HEALTH_CHECK_ACTOR_CATEGORY = nameof(StreamHealthCheckActor); #endregion #region SetUp [SetUp] public void SetupTest() { PluginMock = new Mock<IAdapterPlugin>(); SettingsMock = new Mock<ISettings>(); SettingsMock.SetupGet(a => a.StateProviderPath).Returns(GetType().Assembly.Location); SettingsMock.SetupGet(a => a.StreamSafetyThreshold).Returns(3); SettingsMock.SetupGet(a => a.FixtureCreationConcurrency).Returns(3); SettingsMock.SetupGet(a => a.FixtureCheckerFrequency).Returns(10000); SettingsMock.SetupGet(a => a.FixturesStateFilePath).Returns(GetType().Assembly.Location); SettingsMock.SetupGet(a => a.FixturesStateAutoStoreInterval).Returns(int.MaxValue); FootabllSportMock = new Mock<IFeature>(); FootabllSportMock.SetupGet(o => o.Name).Returns("Football"); ServiceMock = new Mock<IServiceFacade>(); StateManagerMock = new Mock<IStateManager>(); MarketRulesManagerMock = new Mock<IMarketRulesManager>(); StateProviderMock = new Mock<IStateProvider>(); StoreProviderMock = new Mock<IStoreProvider>(); SuspensionManagerMock = new Mock<ISuspensionManager>(); StreamHealthCheckValidationMock = new Mock<IStreamHealthCheckValidation>(); FixtureValidationMock = new Mock<IFixtureValidation>(); } #endregion #region Test Methods /// <summary> /// This test ensures we move to Streaming State after processing health check message. /// Also Snapshot processing is done twice /// - first snapshot processing is done on initialization due to different sequence numbers between stored and current /// - second snapshot processing is done after we process the health check message due to match status changed /// </summary> [Test] [Category(STREAM_HEALTH_CHECK_ACTOR_CATEGORY)] public void ConnectToStreamingServerAndProcessSnapshot() { // //Arrange // Fixture snapshot; Mock<IResourceFacade> resourceFacadeMock; SetupCommonMockObjects( /*sport*/FootabllSportMock.Object.Name, /*fixtureData*/FixtureSamples.football_setup_snapshot_2, /*storedData*/new { Epoch = 3, Sequence = 1, MatchStatus = MatchStatus.Setup }, out snapshot, out resourceFacadeMock); ServiceMock.Setup(o => o.GetSports()).Returns(new[] { FootabllSportMock.Object }); ServiceMock.Setup(o => o.GetResources(It.Is<string>(s => s.Equals(FootabllSportMock.Object.Name)))) .Returns(new List<IResourceFacade> { resourceFacadeMock.Object }); StreamHealthCheckValidationMock.Setup(a => a.CanConnectToStreamServer( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>())) .Returns(false); SettingsMock.SetupGet(a => a.AllowFixtureStreamingInSetupMode).Returns(false); FixtureValidationMock.Setup(a => a.IsSnapshotNeeded( It.IsAny<IResourceFacade>(), It.IsAny<FixtureState>())) .Returns(true); // //Act // var streamListenerManagerActor = ActorOfAsTestActorRef<StreamListenerManagerActor>( Props.Create(() => new StreamListenerManagerActor( SettingsMock.Object, PluginMock.Object, StateManagerMock.Object, SuspensionManagerMock.Object, StreamHealthCheckValidationMock.Object, FixtureValidationMock.Object)), StreamListenerManagerActor.ActorName); var sportProcessorRouterActor = ActorOfAsTestActorRef<SportProcessorRouterActor>( Props.Create(() => new SportProcessorRouterActor(ServiceMock.Object)) .WithRouter(new SmallestMailboxPool(SettingsMock.Object.FixtureCreationConcurrency)), SportProcessorRouterActor.ActorName); ActorOfAsTestActorRef<SportsProcessorActor>( Props.Create(() => new SportsProcessorActor( SettingsMock.Object, ServiceMock.Object, sportProcessorRouterActor)), SportsProcessorActor.ActorName); sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); Task.Delay(1000).Wait(); IActorRef streamListenerActorRef = null; StreamListenerActor streamListenerActor = null; IActorRef resourceActorRef; IActorRef healthCheckActorRef; //Get child actors instances AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); streamListenerActor = GetUnderlyingActor<StreamListenerActor>(streamListenerActorRef); resourceActorRef = GetChildActorRef(streamListenerActorRef, ResourceActor.ActorName); healthCheckActorRef = GetChildActorRef(streamListenerActorRef, StreamHealthCheckActor.ActorName); Assert.NotNull(streamListenerActorRef); Assert.NotNull(streamListenerActor); Assert.NotNull(resourceActorRef); Assert.NotNull(healthCheckActorRef); Assert.AreEqual(StreamListenerState.Initialized, streamListenerActor.State); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); StreamHealthCheckValidationMock.Reset(); StreamHealthCheckValidationMock.Setup(a => a.CanConnectToStreamServer( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>())) .Returns(true); StreamHealthCheckValidationMock.Setup(a => a.IsSequenceValid( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>(), It.IsAny<int>())) .Returns(true); //This call will trigger health check message sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); Task.Delay(2000).Wait(); // //Assert // AwaitAssert(() => { resourceFacadeMock.Verify(a => a.GetSnapshot(), Times.Exactly(3)); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false), Times.Exactly(3)); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), true), Times.Never); PluginMock.Verify(a => a.ProcessMatchStatus(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), Times.Never); SuspensionManagerMock.Verify(a => a.Unsuspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), Times.Never); SuspensionManagerMock.Verify(a => a.Suspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), SuspensionReason.SUSPENSION), Times.Never); Assert.AreEqual(StreamListenerState.Streaming, streamListenerActor.State); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } /// <summary> /// This test ensures that when trying to connect to the streaming server and that is not responding /// then the Stream Listener Child actor is stopped by the Stream Listener Manager /// </summary> [Test] [Category(STREAM_HEALTH_CHECK_ACTOR_CATEGORY)] public void WhenStartStreamingIsNotRespondingThenStopStreamListener() { // //Arrange // Fixture snapshot; Mock<IResourceFacade> resourceFacadeMock; SetupCommonMockObjects( /*sport*/FootabllSportMock.Object.Name, /*fixtureData*/FixtureSamples.football_inplay_snapshot_2, /*storedData*/new { Epoch = 7, Sequence = 1, MatchStatus = MatchStatus.InRunning }, out snapshot, out resourceFacadeMock); StreamHealthCheckValidationMock.Setup(a => a.CanConnectToStreamServer( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>())) .Returns(true); SettingsMock.SetupGet(o => o.StartStreamingTimeoutInSeconds).Returns(1); SettingsMock.SetupGet(o => o.StartStreamingAttempts).Returns(3); ServiceMock.Setup(o => o.GetResources(It.Is<string>(s => s.Equals(FootabllSportMock.Object.Name)))) .Returns(new List<IResourceFacade> { resourceFacadeMock.Object }); resourceFacadeMock.Reset(); resourceFacadeMock.Setup(o => o.Id).Returns(snapshot.Id); resourceFacadeMock.Setup(o => o.Sport).Returns(FootabllSportMock.Object.Name); resourceFacadeMock.Setup(o => o.MatchStatus).Returns((MatchStatus)Convert.ToInt32(snapshot.MatchStatus)); resourceFacadeMock.Setup(o => o.Content).Returns(new Summary { Id = snapshot.Id, Sequence = snapshot.Sequence, MatchStatus = Convert.ToInt32(snapshot.MatchStatus), StartTime = snapshot.StartTime?.ToString("yyyy-MM-ddTHH:mm:ssZ") }); // //Act // var streamListenerManagerActor = ActorOfAsTestActorRef<StreamListenerManagerActor>( Props.Create(() => new StreamListenerManagerActor( SettingsMock.Object, PluginMock.Object, StateManagerMock.Object, SuspensionManagerMock.Object, StreamHealthCheckValidationMock.Object, FixtureValidationMock.Object)), StreamListenerManagerActor.ActorName); var sportProcessorRouterActor = ActorOfAsTestActorRef<SportProcessorRouterActor>( Props.Create(() => new SportProcessorRouterActor(ServiceMock.Object)) .WithRouter(new SmallestMailboxPool(SettingsMock.Object.FixtureCreationConcurrency)), SportProcessorRouterActor.ActorName); sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); //wait for 5 seconds while the health checks run every second and after 3 attempts the manager kills the actor Task.Delay(5000).Wait(); // //Assert // AwaitAssert(() => { resourceFacadeMock.Verify(a => a.GetSnapshot(), Times.Never); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false), Times.Never); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), true), Times.Never); PluginMock.Verify(a => a.ProcessStreamUpdate(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false), Times.Never); SuspensionManagerMock.Verify(a => a.Unsuspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), Times.Never); SuspensionManagerMock.Verify(a => a.Suspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), SuspensionReason.SUSPENSION), Times.Never); SuspensionManagerMock.Verify(a => a.Suspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), SuspensionReason.FIXTURE_ERRORED), Times.Never); SuspensionManagerMock.Verify(a => a.Suspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), SuspensionReason.DISCONNECT_EVENT), Times.Never); Assert.Throws<AggregateException>(() => { Sys.ActorSelection( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)) .ResolveOne(TimeSpan.FromSeconds(5)).Wait(); }).InnerException.Should().BeOfType<ActorNotFoundException>(); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } /// <summary> /// This test ensures that when we get the heatlh check message, we missed processing sequences for the second time /// and the resource is match over, then: /// - stream listener is stopped as a result of second invalid stream (missing sequences) /// - stream listener is recreated and match over is processed /// Also Snapshot processing is done three times /// - first snapshot processing is done on after start streaming for the first time due to different sequence numbers between stored and current /// - second snapshot processing is done on first health check message when missing sequences are discovered /// - thirs snapshot processing is done due to match over processing after we get the second health check message /// and restart stream listener due to missing sequences for second time in a row /// </summary> [Test] [Category(STREAM_HEALTH_CHECK_ACTOR_CATEGORY)] public void WhenStreamingAndMatchOverUpdateAfterSecondTimeMissingSequencesThenRecreateStreamListenerAndProcessMatchOver() { // //Arrange // Fixture snapshot; Mock<IResourceFacade> resourceFacadeMock; SetupCommonMockObjects( /*sport*/FootabllSportMock.Object.Name, /*fixtureData*/FixtureSamples.football_inplay_snapshot_2, /*storedData*/new { Epoch = 3, Sequence = 1, MatchStatus = MatchStatus.InRunning }, out snapshot, out resourceFacadeMock); ServiceMock.Setup(o => o.GetSports()).Returns(new[] { FootabllSportMock.Object }); ServiceMock.Setup(o => o.GetResources(It.Is<string>(s => s.Equals(FootabllSportMock.Object.Name)))) .Returns(new List<IResourceFacade> { resourceFacadeMock.Object }); StreamHealthCheckValidationMock.Setup(a => a.CanConnectToStreamServer( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>())) .Returns(true); FixtureValidationMock.Setup(a => a.IsSnapshotNeeded( It.IsAny<IResourceFacade>(), It.IsAny<FixtureState>())) .Returns(true); // //Act // var streamListenerManagerActor = ActorOfAsTestActorRef<StreamListenerManagerActor>( Props.Create(() => new StreamListenerManagerActor( SettingsMock.Object, PluginMock.Object, StateManagerMock.Object, SuspensionManagerMock.Object, StreamHealthCheckValidationMock.Object, FixtureValidationMock.Object)), StreamListenerManagerActor.ActorName); var sportProcessorRouterActor = ActorOfAsTestActorRef<SportProcessorRouterActor>( Props.Create(() => new SportProcessorRouterActor(ServiceMock.Object)) .WithRouter(new SmallestMailboxPool(SettingsMock.Object.FixtureCreationConcurrency)), SportProcessorRouterActor.ActorName); sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); Task.Delay(5000).Wait(); IActorRef streamListenerActorRef; StreamListenerActor streamListenerActor = null; IActorRef resourceActorRef; IActorRef healthCheckActorRef; // //Assert // #region 1st processing //first time the stream listeners goes into Streaming State AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); streamListenerActor = GetUnderlyingActor<StreamListenerActor>(streamListenerActorRef); resourceActorRef = GetChildActorRef(streamListenerActorRef, ResourceActor.ActorName); healthCheckActorRef = GetChildActorRef(streamListenerActorRef, StreamHealthCheckActor.ActorName); Assert.NotNull(streamListenerActorRef); Assert.NotNull(streamListenerActor); Assert.NotNull(resourceActorRef); Assert.NotNull(healthCheckActorRef); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); Task.Delay(StreamListenerActor.CONNECT_TO_STREAM_DELAY).Wait(); AwaitAssert(() => { Assert.AreEqual(StreamListenerState.Streaming, streamListenerActor.State); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); #endregion #region 2nd processing //second time the stream is not valid because of missing sequences and the fixture is suspended and snapshot processed StreamHealthCheckValidationMock.Reset(); StreamHealthCheckValidationMock.Setup(a => a.CanConnectToStreamServer( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>())) .Returns(true); StreamHealthCheckValidationMock.Setup(a => a.IsSequenceValid( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>(), It.IsAny<int>())) .Returns(false); //This call will trigger health check message sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); Thread.Sleep((Settings.MinimalHealthcheckInterval + 1) * 1000); sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); Thread.Sleep(10000); sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); // //Assert // AwaitAssert(() => { resourceFacadeMock.Verify(a => a.GetSnapshot(), Times.Once); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false), Times.AtLeast(1)); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), true), Times.Never); PluginMock.Verify(a => a.ProcessMatchStatus(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), Times.Never); SuspensionManagerMock.Verify(a => a.Unsuspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), Times.Never); SuspensionManagerMock.Verify(a => a.Suspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), SuspensionReason.HEALTH_CHECK_FALURE), Times.Once); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); Task.Delay(StreamListenerActor.CONNECT_TO_STREAM_DELAY).Wait(); streamListenerActorRef =GetChildActorRef(streamListenerManagerActor,StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); streamListenerActor = GetUnderlyingActor<StreamListenerActor>(streamListenerActorRef); Thread.Sleep(5000); AwaitAssert(() => { Assert.AreEqual(StreamListenerState.Streaming, streamListenerActor.State); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); #endregion #region 3rd processing //third time the stream is not valid because of missing sequences //and the stream listener is stopped because of second stream invalid detection in a row due to missing sequences //but Resource is Match Over so a new Stream Listener instance is created and Match Over is processed StreamHealthCheckValidationMock.Reset(); StreamHealthCheckValidationMock.Setup(a => a.CanConnectToStreamServer( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>())) .Returns(true); StreamHealthCheckValidationMock.Setup(a => a.IsSequenceValid( It.IsAny<IResourceFacade>(), It.IsAny<StreamListenerState>(), It.IsAny<int>())) .Returns(true); //This call will trigger health check message sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); streamListenerActorRef = null; Task.Delay(5000).Wait(); try { AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); streamListenerActor = GetUnderlyingActor<StreamListenerActor>(streamListenerActorRef); if (streamListenerActor != null) Assert.AreEqual(StreamListenerState.Streaming, streamListenerActor.State); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } catch (Exception) { //exception could be caught here as Stream Listener Actor becomes stopped //and eventually killed before we actually have the chance to assert for Stopped state } streamListenerActorRef = null; try { AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); Assert.NotNull(streamListenerActorRef); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } catch (Exception) { //exception is expected here as Stream Listener Actor should not exist at this time } resourceFacadeMock.Reset(); StateManagerMock.Reset(); StoreProviderMock.Reset(); SetupCommonMockObjects( /*sport*/FootabllSportMock.Object.Name, /*fixtureData*/FixtureSamples.football_matchover_snapshot_2, /*storedData*/new { Epoch = 2, Sequence = 1, MatchStatus = MatchStatus.InRunning }, out snapshot, out resourceFacadeMock); ServiceMock.Reset(); ServiceMock.Setup(o => o.GetResources(It.Is<string>(s => s.Equals(FootabllSportMock.Object.Name)))) .Returns(new List<IResourceFacade> { resourceFacadeMock.Object }); //This call will trigger stream listener actor creation sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); streamListenerActorRef = null; try { AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); streamListenerActor = GetUnderlyingActor<StreamListenerActor>(streamListenerActorRef); if (streamListenerActor != null) Assert.AreEqual(StreamListenerState.Streaming, streamListenerActor.State); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } catch (Exception) { //exception could be caught here as Stream Listener Actor becomes stopped //and eventually killed before we actually have the chance to assert for Stopped state } streamListenerActorRef = null; try { AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); Assert.NotNull(streamListenerActorRef); resourceFacadeMock.Verify(a => a.GetSnapshot(), Times.Never); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false), Times.AtLeast(1)); PluginMock.Verify(a => a.ProcessSnapshot(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), true), Times.Never); PluginMock.Verify(a => a.ProcessMatchStatus(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), Times.Never); //SuspensionManagerMock.Verify(a => // a.Unsuspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))), // Times.AtLeast(1)); SuspensionManagerMock.Verify(a => a.Suspend(It.Is<Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), SuspensionReason.HEALTH_CHECK_FALURE), Times.Once); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } catch (Exception) { //exception is expected here as Stream Listener Actor should not exist at this time } #endregion #region 4th processing //fourth time no Stream Listener is created as Match is already Over and was already processed sportProcessorRouterActor.Tell(new ProcessSportMsg { Sport = FootabllSportMock.Object.Name }); streamListenerActorRef = null; try { AwaitAssert(() => { streamListenerActorRef = GetChildActorRef( streamListenerManagerActor, StreamListenerActor.GetName(resourceFacadeMock.Object.Id)); streamListenerActor = GetUnderlyingActor<StreamListenerActor>(streamListenerActorRef); Assert.NotNull(streamListenerActorRef); Assert.NotNull(streamListenerActor); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); } catch (Exception) { //exception is expected here as Stream Listener Actor should not exist at this time } // //Assert // AwaitAssert(() => { Assert.NotNull(streamListenerActorRef); }, TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT), TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL)); #endregion } #endregion } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using SpatialAnalysis.Interoperability; using SpatialAnalysis.Geometry; namespace SpatialAnalysis.CellularEnvironment { /// <summary> /// Represents a square space in between the grid lines on the floor /// </summary> public class Cell: UV { /// <summary> /// Indices of the visual obstacle edges that pass through this cell /// </summary> public HashSet<int> VisualBarrierEdgeIndices { get; set; } /// <summary> /// Indices of the physical obstacle edges that pass through this cell /// </summary> public HashSet<int> PhysicalBarrierEdgeIndices { get; set; } /// <summary> /// Indices of the field edges that pass through this cell /// </summary> public HashSet<int> FieldBarrierEdgeIndices { get; set; } /// <summary> /// Indices of the field buffer edges that pass through this cell /// </summary> public HashSet<int> BarrierBufferEdgeIndices { get; set; } /// <summary> /// Outside indicates outside visual barriers /// </summary> public OverlapState VisualOverlapState { get; set; } /// <summary> /// Outside indicates outside physical barriers /// </summary> public OverlapState PhysicalOverlapState { get; set; } /// <summary> /// Inside indicates inside field /// </summary> public OverlapState FieldOverlapState { get; set; } /// <summary> /// Inside indicates inside field buffer /// </summary> public OverlapState BarrierBufferOverlapState { get; set; } private int _id; /// <summary> /// The unique ID of the cell /// </summary> public int ID { get { return this._id; } } private readonly Index _cellIndex; /// <summary> /// The index of the cell /// Problem: cell is passed by reference and despite being readonly can have a changed value! /// FIX: make Index class a struct. This asks for many changes in inherited classes /// </summary> public Index CellToIndex { get { return _cellIndex; } } /// <summary> /// Visual Barrier End Points /// </summary> public List<UV> VisualBarrierEndPoints { get; set; } /// <summary> /// Physical Barrier End Points /// </summary> public List<UV> PhysicalBarrierEndPoints { get; set; } /// <summary> /// Field Barrier End Points /// </summary> public List<UV> FieldBarrierEndPoints { get; set; } /// <summary> /// Buffer Barrier End Points /// </summary> public List<UV> BufferBarrierEndPoints { get; set; } /// <summary> /// The constructor of the cell /// </summary> /// <param name="origin">Cell origin</param> /// <param name="id">Cell ID</param> /// <param name="i">Cell index width factor</param> /// <param name="j">Cell index height factor</param> public Cell(UV origin, int id, int i, int j):base(origin) { this._id = id; this.VisualBarrierEdgeIndices = new HashSet<int>(); this.PhysicalBarrierEdgeIndices = new HashSet<int>(); this.FieldBarrierEdgeIndices = new HashSet<int>(); this._cellIndex = new Index(i, j); this.VisualBarrierEndPoints = null; this.PhysicalBarrierEndPoints = null; this.FieldBarrierEndPoints = null; this.BufferBarrierEndPoints = null; } public override int GetHashCode() { //return this._id; return base.GetHashCode(); } public override bool Equals(object obj) { Cell cell = obj as Cell; if (cell != null) { //return this.U == cell.U && this.V == cell.V; //return this._id == cell._id; return this.CellToIndex.I == cell.CellToIndex.I && this.CellToIndex.J == cell.CellToIndex.J; } return false; } /// <summary> /// Determines if the cell include a point /// </summary> /// <param name="p">Point</param> /// <param name="cellSize">Width of cell</param> /// <param name="cellHeight"></param> /// <returns></returns> public bool IncludePoint(UV p, double cellSize) { if (p.U >= this.U && p.U <= (this.U + cellSize)) { if (p.V >= this.V && p.V <= (this.V + cellSize)) { return true; } } return false; } /// <summary> /// Visualize a cell in the BIM target platform /// </summary> /// <param name="visualizer">An instance of the IVisualize interface</param> /// <param name="size">Cell size</param> /// <param name="elevation">Elevation of visualization</param> public void Visualize(I_OSM_To_BIM visualizer, double size, double elevation) { UV[] pnts = new UV[4]; pnts[0] = this; pnts[1] = this + UV.UBase * size; pnts[2] = this + UV.UBase * size + UV.VBase * size; pnts[3] = this + UV.VBase * size; visualizer.VisualizePolygon(pnts, elevation); } /// <summary> /// Cell Center Point /// </summary> /// <param name="cellSize">Cell size</param> /// <returns>Center of cell</returns> public UV GetCenter(double cellSize) { return this + new UV(cellSize / 2, cellSize / 2); } /// <summary> /// Converts a Cell to a collection of lines at its edges /// </summary> /// <returns>A line collection</returns> public HashSet<UVLine> ToUVLines(double size) { HashSet<UVLine> lines = new HashSet<UVLine>(); UV x1 = this + new UV(0, size); UV x2 = this + new UV(size, size); UV x3 = this + new UV(size, 0); lines.Add(new UVLine(this, x1)); lines.Add(new UVLine(x1, x2)); lines.Add(new UVLine(x2, x3)); lines.Add(new UVLine(x3, this)); x1 = null; x2 = null; x3 = null; return lines; } public bool ContainsPoint(UV pnt, double cellSize) { bool widthIncluded = this.U <= pnt.U && pnt.U < (this.U + cellSize); bool heightIncluded = this.V <= pnt.V && pnt.V < (this.V + cellSize); return widthIncluded && heightIncluded; } public List<UV> GetEdgeEndPoint(BarrierType barrierType) { switch (barrierType) { case BarrierType.Visual: return this.VisualBarrierEndPoints; case BarrierType.Physical: return this.PhysicalBarrierEndPoints; case BarrierType.Field: return this.FieldBarrierEndPoints; case BarrierType.BarrierBuffer: return this.BufferBarrierEndPoints; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 MinScalarSingle() { var test = new SimpleBinaryOpTest__MinScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinScalarSingle testClass) { var result = Sse.MinScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.MinScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__MinScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.MinScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.MinScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.MinScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.MinScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.MinScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.MinScalar( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.MinScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.MinScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.MinScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinScalarSingle(); var result = Sse.MinScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MinScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.MinScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.MinScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.MinScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.MinScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.MinScalar( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(Math.Min(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.MinScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using KaoriStudio.Core.Helpers; namespace KaoriStudio.Core.Numerics { using uocto = KaoriStudio.Core.Numerics.UInt128; using socto = KaoriStudio.Core.Numerics.Int128; using System.Diagnostics; using KaoriStudio.Core.Attributes; using System.Linq.Expressions; using System.Runtime.InteropServices; /// <summary> /// An unsigned 128-bit integer (uocto). /// </summary> /// <remarks> /// A signed integer of 64 bits or less with its most significant bit set will always be considered less than this integer. /// Overflows are truncating and bitshifts are logical. /// When a signed number of 64 bits or less with its most significant bit set is converted to this type, the most significant 64 bits will all be set. /// </remarks> [Serializable] [StructLayout(LayoutKind.Sequential)] public partial struct UInt128 { const ulong HiBits = ~0UL << 32; const ulong LoBits = ~0UL >> 32; const ulong OnBits = ~0UL; const ulong MSB = 1UL << 63; [Identifier] ulong lo; [Identifier] ulong hi; /// <summary> /// Represents the smallest possible value of a <see cref="uocto"/>. This value is constant. /// </summary> public static readonly uocto MinValue = new uocto(0, 0); /// <summary> /// Represents the largest possible value of a <see cref="uocto"/>. This value is constant. /// </summary> public static readonly uocto MaxValue = new uocto(~0UL, ~0UL); static readonly uocto maxValueBy10 = MaxValue / 10; static readonly uocto[] maxValueSubtract = { MaxValue - 0, MaxValue - 1, MaxValue - 2, MaxValue - 3, MaxValue - 4, MaxValue - 5, MaxValue - 6, MaxValue - 7, MaxValue - 8, MaxValue - 9 }; #region "Implementations" /// <inheritdoc cref="int.Parse(string)"/> public static uocto Parse(string s) { uocto value = 0; if (s == null) throw new ArgumentNullException("s"); else if (s.Length == 0) throw new FormatException(); foreach (var c in s) { if (value > maxValueBy10) throw new OverflowException(); value *= 10; var v = TextHelper.DecimalDigit(c); if (v == -1) throw new FormatException(); if (value > maxValueSubtract[v]) throw new OverflowException(); value += v; } return value; } /// <inheritdoc cref="int.TryParse(string, out int)"/> public static bool TryParse(string s, out uocto result) { uocto value = 0; if (s == null || s.Length == 0) { result = default(uocto); return false; } foreach (var c in s) { if (value > maxValueBy10) { result = default(uocto); return false; } value *= 10; var v = TextHelper.DecimalDigit(c); if (v == -1 || value > maxValueSubtract[v]) { result = default(uocto); return false; } value += v; } result = value; return true; } /// <inheritdoc/> public override string ToString() { if (lo == 0 && hi == 0) return "0"; var digits = new List<int>(); var x = this; while (x != 0) { uint r; //throw new Exception($"{x.hi:X},{x.lo:X}"); x = DivRem(x, 10U, out r); //throw new Exception($"{x.hi:X},{x.lo:X}"); digits.Add((int)r); } //throw new Exception(digits.Max().ToString()); var sb = new StringBuilder(); for (int i = digits.Count - 1; i >= 0; i--) { sb.Append("0123456789"[digits[i]]); } return sb.ToString(); } /// <inheritdoc/> public override int GetHashCode() => GenericHelper<UInt128>.CompileGetHashCode.Value(this); /// <inheritdoc/> public override bool Equals(object obj) => ObjectHelper.GenerateValueEquals<uocto>(ref this, obj); #endregion #region "Properties" /// <summary> /// The least significant half. /// </summary> public ulong LSH { get { return lo; } set { lo = value; } } /// <summary> /// The most significant half. /// </summary> public ulong MSH { get { return hi; } set { hi = value; } } /// <summary> /// The value of the sign bit. /// </summary> public bool SignBit { get { return (hi & MSB) != 0; } } #endregion /// <summary> /// Creates a new <see cref="uocto"/>. /// </summary> /// <param name="lo">The least significant half.</param> /// <param name="hi">The most sigificant half.</param> public UInt128(ulong lo, ulong hi) { this.lo = lo; this.hi = hi; } /// <summary> /// Creates a new <see cref="uocto"/>. /// </summary> /// <param name="lo">The least significant half.</param> public UInt128(ulong lo) { this.lo = lo; this.hi = 0; } /// <summary> /// Performs a single left shift. /// </summary> public void ShiftLeft() { hi = (hi << 1) | (lo >> 63); lo <<= 1; } /// <summary> /// Performs a single right shift. /// </summary> public void ShiftRight() { lo = (lo >> 1) | (hi << 63); hi >>= 1; } /// <summary> /// Performs a single arithmetic right shift. /// </summary> public void ArithmeticShiftRight() { unchecked { lo = (lo >> 1) | (hi << 63); hi = (ulong)((long)hi >> 1); } } /// <summary> /// Performs an arithmetic right shift. /// </summary> /// <param name="shift">The number of bits to shift right.</param> public void ArithmeticShiftRight(int shift) { unchecked { if (shift == 1) { ArithmeticShiftRight(); return; } if (shift < 0) { this <<= -shift; return; } if (shift == 0) return; if (shift >= 128) { if (SignBit) hi = lo = ~0UL; else hi = lo = 0; return; } if (shift >= 64) { lo = (ulong)((long)hi >> (shift & 63)); hi = (ulong)((long)hi >> 63); return; } lo = (lo >> shift) | (hi << (64 - shift)); hi = (ulong)((long)hi >> shift); } } /// <summary> /// Calculates the quotient of two numbers and also returns the remainder in an output parameter. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <param name="remainder">The remainder.</param> /// <returns>The quotient of the specified numbers.</returns> public static uocto DivRem(uocto numerator, uocto denominator, out uocto remainder) { const int bits = 128; if (denominator == 0) throw new DivideByZeroException(); else { var n = numerator; var d = denominator; var x = (uocto)1; var answer = (uocto)0; while ((n >= d) && (((d >> (bits - 1)) & 1) == 0)) { x <<= 1; d <<= 1; } while (x != 0) { if (n >= d) { n -= d; answer |= x; } x >>= 1; d >>= 1; } remainder = n; return answer; } } /// <summary> /// Calculates the quotient of two numbers and also returns the remainder in an output parameter. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <param name="remainder">The remainder.</param> /// <returns>The quotient of the specified numbers.</returns> public static uocto DivRem(uocto numerator, ulong denominator, out ulong remainder) { uocto r; var q = DivRem(numerator, (uocto)denominator, out r); remainder = (ulong)r; return q; } /// <summary> /// Calculates the quotient of two numbers and also returns the remainder in an output parameter. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <param name="remainder">The remainder.</param> /// <returns>The quotient of the specified numbers.</returns> public static uocto DivRem(uocto numerator, uint denominator, out uint remainder) { uocto r; var q = DivRem(numerator, (uocto)denominator, out r); remainder = (uint)r; return q; } /// <summary> /// Calculates the quotient of two numbers. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <returns>The quotient of the specified numbers.</returns> public static uocto Divide(uocto numerator, uocto denominator) { const int bits = 128; if (denominator == 0) throw new DivideByZeroException(); else { var n = numerator; var d = denominator; var x = (uocto)1; var answer = (uocto)0; while ((n >= d) && (((d >> (bits - 1)) & 1) == 0)) { x <<= 1; d <<= 1; } //throw new Exception($"{x} {d} {n}"); while (x != 0) { if (n >= d) { n -= d; answer |= x; } x >>= 1; d >>= 1; } return answer; } } /// <summary> /// Calculates the quotient of two numbers. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <returns>The quotient of the specified numbers.</returns> public static uocto Divide(uocto numerator, ulong denominator) { return Divide(numerator, (uocto)denominator); } /// <summary> /// Calculates the quotient of two numbers. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <returns>The quotient of the specified numbers.</returns> public static uocto Divide(uocto numerator, uint denominator) { return Divide(numerator, (uocto)denominator); } /// <summary> /// Calculates the remainder of two numbers. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <returns>The remainder of the specified numbers.</returns> public static uocto Remainder(uocto numerator, uocto denominator) { const int bits = 128; //throw new Exception($"{numerator} {denominator}"); if (denominator == 0) throw new DivideByZeroException(); else { var n = numerator; var d = denominator; var x = (uocto)1; //var answer = (uocto)0; while ((n >= d) && (((d >> (bits - 1)) & 1) == 0)) { x <<= 1; d <<= 1; } while (x != 0) { if (n >= d) { n -= d; //answer |= x; } x >>= 1; d >>= 1; } return n; //return answer; } } /// <summary> /// Calculates the remainder of two numbers. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <returns>The remainder of the specified numbers.</returns> public static uocto Remainder(uocto numerator, ulong denominator) { return Remainder(numerator, (uocto)denominator); } /// <summary> /// Calculates the remainder of two numbers. /// </summary> /// <param name="numerator">The dividend.</param> /// <param name="denominator">The divisor.</param> /// <returns>The remainder of the specified numbers.</returns> public static uocto Remainder(uocto numerator, uint denominator) { return Remainder(numerator, (uocto)denominator); } /// <inheritdoc cref="FromBytes(byte[], int, bool)"/> public static uocto FromBytes(byte[] value) => FromBytes(value, 0, true); /// <inheritdoc cref="FromBytes(byte[], int, bool)"/> public static uocto FromBytes(byte[] value, bool isLittleEndian) => FromBytes(value, 0, isLittleEndian); /// <inheritdoc cref="FromBytes(byte[], int, bool)"/> public static uocto FromBytes(byte[] value, int startIndex) => FromBytes(value, startIndex, true); /// <summary> /// Creates a <see cref="uocto"/> from sixteen bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within <paramref name="value"/>.</param> /// <param name="isLittleEndian">Whether <paramref name="value"/> is in little endian format.</param> /// <returns>A <see cref="uocto"/> formed by sixteen bytes beginning at <paramref name="startIndex"/>.</returns> public static uocto FromBytes(byte[] value, int startIndex, bool isLittleEndian) { CollectionHelper.CheckBoundsCopyTo(value, startIndex, 16); ulong lo; ulong hi; if (isLittleEndian) { lo = BitConverter.ToUInt64(value, startIndex); hi = BitConverter.ToUInt64(value, startIndex + 8); } else { hi = BitConverter.ToUInt64(value, startIndex); lo = BitConverter.ToUInt64(value, startIndex + 8); } if (isLittleEndian != BitConverter.IsLittleEndian) { lo = BitHelper.SwapUInt64(lo); hi = BitHelper.SwapUInt64(hi); } return new UInt128(lo, hi); } ///<inheritdoc cref="ToBytes(byte[], int, bool)"/> public void ToBytes(byte[] value) => ToBytes(value, 0, true); ///<inheritdoc cref="ToBytes(byte[], int, bool)"/> public void ToBytes(byte[] value, int startIndex) => ToBytes(value, startIndex, true); ///<inheritdoc cref="ToBytes(byte[], int, bool)"/> public void ToBytes(byte[] value, bool isLittleEndian) => ToBytes(value, 0, isLittleEndian); /// <summary> /// Writes the numeric value of this instance to a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within <paramref name="value"/>.</param> /// <param name="isLittleEndian">Whether <paramref name="value"/> should be written to in little endian format.</param> public void ToBytes(byte[] value, int startIndex, bool isLittleEndian) { CollectionHelper.CheckBoundsCopyTo(value, startIndex, 16); if (isLittleEndian) { value[0] = (byte)((lo >> 8 * 0) & 0xff); value[1] = (byte)((lo >> 8 * 1) & 0xff); value[2] = (byte)((lo >> 8 * 2) & 0xff); value[3] = (byte)((lo >> 8 * 3) & 0xff); value[4] = (byte)((lo >> 8 * 4) & 0xff); value[5] = (byte)((lo >> 8 * 5) & 0xff); value[6] = (byte)((lo >> 8 * 6) & 0xff); value[7] = (byte)((lo >> 8 * 7) & 0xff); value[8] = (byte)((hi >> 8 * 0) & 0xff); value[9] = (byte)((hi >> 8 * 1) & 0xff); value[10] = (byte)((hi >> 8 * 2) & 0xff); value[11] = (byte)((hi >> 8 * 3) & 0xff); value[12] = (byte)((hi >> 8 * 4) & 0xff); value[13] = (byte)((hi >> 8 * 5) & 0xff); value[14] = (byte)((hi >> 8 * 6) & 0xff); value[15] = (byte)((hi >> 8 * 7) & 0xff); } else { value[15] = (byte)((lo >> 8 * 0) & 0xff); value[14] = (byte)((lo >> 8 * 1) & 0xff); value[13] = (byte)((lo >> 8 * 2) & 0xff); value[12] = (byte)((lo >> 8 * 3) & 0xff); value[11] = (byte)((lo >> 8 * 4) & 0xff); value[10] = (byte)((lo >> 8 * 5) & 0xff); value[9] = (byte)((lo >> 8 * 6) & 0xff); value[8] = (byte)((lo >> 8 * 7) & 0xff); value[7] = (byte)((hi >> 8 * 0) & 0xff); value[6] = (byte)((hi >> 8 * 1) & 0xff); value[5] = (byte)((hi >> 8 * 2) & 0xff); value[4] = (byte)((hi >> 8 * 3) & 0xff); value[3] = (byte)((hi >> 8 * 4) & 0xff); value[2] = (byte)((hi >> 8 * 5) & 0xff); value[1] = (byte)((hi >> 8 * 6) & 0xff); value[0] = (byte)((hi >> 8 * 7) & 0xff); } } /// <inheritdoc cref="ToBytes(bool)"/> public byte[] ToBytes() => ToBytes(true); /// <summary> /// Converts the numeric value of this instance to a byte array. /// </summary> /// <param name="isLittleEndian">Whether the array of bytes should be in little endian format.</param> /// <returns>The byte array representation of the value of this instance.</returns> public byte[] ToBytes(bool isLittleEndian) { var value = new byte[16]; ToBytes(value, 0, isLittleEndian); return value; } } }
#if AVALONIA_REMOTE_PROTOCOL namespace Avalonia.Remote.Protocol.Input #else namespace Avalonia.Input #endif { /// <summary> /// Defines the keys available on a keyboard. /// </summary> public enum Key { /// <summary> /// No key pressed. /// </summary> None = 0, /// <summary> /// The Cancel key. /// </summary> Cancel = 1, /// <summary> /// The Back key. /// </summary> Back = 2, /// <summary> /// The Tab key. /// </summary> Tab = 3, /// <summary> /// The Linefeed key. /// </summary> LineFeed = 4, /// <summary> /// The Clear key. /// </summary> Clear = 5, /// <summary> /// The Return key. /// </summary> Return = 6, /// <summary> /// The Enter key. /// </summary> Enter = 6, /// <summary> /// The Pause key. /// </summary> Pause = 7, /// <summary> /// The Caps Lock key. /// </summary> CapsLock = 8, /// <summary> /// The Caps Lock key. /// </summary> Capital = 8, /// <summary> /// The IME Hangul mode key. /// </summary> HangulMode = 9, /// <summary> /// The IME Kana mode key. /// </summary> KanaMode = 9, /// <summary> /// The IME Junja mode key. /// </summary> JunjaMode = 10, /// <summary> /// The IME Final mode key. /// </summary> FinalMode = 11, /// <summary> /// The IME Kanji mode key. /// </summary> KanjiMode = 12, /// <summary> /// The IME Hanja mode key. /// </summary> HanjaMode = 12, /// <summary> /// The Escape key. /// </summary> Escape = 13, /// <summary> /// The IME Convert key. /// </summary> ImeConvert = 14, /// <summary> /// The IME NonConvert key. /// </summary> ImeNonConvert = 15, /// <summary> /// The IME Accept key. /// </summary> ImeAccept = 16, /// <summary> /// The IME Mode change key. /// </summary> ImeModeChange = 17, /// <summary> /// The space bar. /// </summary> Space = 18, /// <summary> /// The Page Up key. /// </summary> PageUp = 19, /// <summary> /// The Page Up key. /// </summary> Prior = 19, /// <summary> /// The Page Down key. /// </summary> PageDown = 20, /// <summary> /// The Page Down key. /// </summary> Next = 20, /// <summary> /// The End key. /// </summary> End = 21, /// <summary> /// The Home key. /// </summary> Home = 22, /// <summary> /// The Left arrow key. /// </summary> Left = 23, /// <summary> /// The Up arrow key. /// </summary> Up = 24, /// <summary> /// The Right arrow key. /// </summary> Right = 25, /// <summary> /// The Down arrow key. /// </summary> Down = 26, /// <summary> /// The Select key. /// </summary> Select = 27, /// <summary> /// The Print key. /// </summary> Print = 28, /// <summary> /// The Execute key. /// </summary> Execute = 29, /// <summary> /// The Print Screen key. /// </summary> Snapshot = 30, /// <summary> /// The Print Screen key. /// </summary> PrintScreen = 30, /// <summary> /// The Insert key. /// </summary> Insert = 31, /// <summary> /// The Delete key. /// </summary> Delete = 32, /// <summary> /// The Help key. /// </summary> Help = 33, /// <summary> /// The 0 key. /// </summary> D0 = 34, /// <summary> /// The 1 key. /// </summary> D1 = 35, /// <summary> /// The 2 key. /// </summary> D2 = 36, /// <summary> /// The 3 key. /// </summary> D3 = 37, /// <summary> /// The 4 key. /// </summary> D4 = 38, /// <summary> /// The 5 key. /// </summary> D5 = 39, /// <summary> /// The 6 key. /// </summary> D6 = 40, /// <summary> /// The 7 key. /// </summary> D7 = 41, /// <summary> /// The 8 key. /// </summary> D8 = 42, /// <summary> /// The 9 key. /// </summary> D9 = 43, /// <summary> /// The A key. /// </summary> A = 44, /// <summary> /// The B key. /// </summary> B = 45, /// <summary> /// The C key. /// </summary> C = 46, /// <summary> /// The D key. /// </summary> D = 47, /// <summary> /// The E key. /// </summary> E = 48, /// <summary> /// The F key. /// </summary> F = 49, /// <summary> /// The G key. /// </summary> G = 50, /// <summary> /// The H key. /// </summary> H = 51, /// <summary> /// The I key. /// </summary> I = 52, /// <summary> /// The J key. /// </summary> J = 53, /// <summary> /// The K key. /// </summary> K = 54, /// <summary> /// The L key. /// </summary> L = 55, /// <summary> /// The M key. /// </summary> M = 56, /// <summary> /// The N key. /// </summary> N = 57, /// <summary> /// The O key. /// </summary> O = 58, /// <summary> /// The P key. /// </summary> P = 59, /// <summary> /// The Q key. /// </summary> Q = 60, /// <summary> /// The R key. /// </summary> R = 61, /// <summary> /// The S key. /// </summary> S = 62, /// <summary> /// The T key. /// </summary> T = 63, /// <summary> /// The U key. /// </summary> U = 64, /// <summary> /// The V key. /// </summary> V = 65, /// <summary> /// The W key. /// </summary> W = 66, /// <summary> /// The X key. /// </summary> X = 67, /// <summary> /// The Y key. /// </summary> Y = 68, /// <summary> /// The Z key. /// </summary> Z = 69, /// <summary> /// The left Windows key. /// </summary> LWin = 70, /// <summary> /// The right Windows key. /// </summary> RWin = 71, /// <summary> /// The Application key. /// </summary> Apps = 72, /// <summary> /// The Sleep key. /// </summary> Sleep = 73, /// <summary> /// The 0 key on the numeric keypad. /// </summary> NumPad0 = 74, /// <summary> /// The 1 key on the numeric keypad. /// </summary> NumPad1 = 75, /// <summary> /// The 2 key on the numeric keypad. /// </summary> NumPad2 = 76, /// <summary> /// The 3 key on the numeric keypad. /// </summary> NumPad3 = 77, /// <summary> /// The 4 key on the numeric keypad. /// </summary> NumPad4 = 78, /// <summary> /// The 5 key on the numeric keypad. /// </summary> NumPad5 = 79, /// <summary> /// The 6 key on the numeric keypad. /// </summary> NumPad6 = 80, /// <summary> /// The 7 key on the numeric keypad. /// </summary> NumPad7 = 81, /// <summary> /// The 8 key on the numeric keypad. /// </summary> NumPad8 = 82, /// <summary> /// The 9 key on the numeric keypad. /// </summary> NumPad9 = 83, /// <summary> /// The Multiply key. /// </summary> Multiply = 84, /// <summary> /// The Add key. /// </summary> Add = 85, /// <summary> /// The Separator key. /// </summary> Separator = 86, /// <summary> /// The Subtract key. /// </summary> Subtract = 87, /// <summary> /// The Decimal key. /// </summary> Decimal = 88, /// <summary> /// The Divide key. /// </summary> Divide = 89, /// <summary> /// The F1 key. /// </summary> F1 = 90, /// <summary> /// The F2 key. /// </summary> F2 = 91, /// <summary> /// The F3 key. /// </summary> F3 = 92, /// <summary> /// The F4 key. /// </summary> F4 = 93, /// <summary> /// The F5 key. /// </summary> F5 = 94, /// <summary> /// The F6 key. /// </summary> F6 = 95, /// <summary> /// The F7 key. /// </summary> F7 = 96, /// <summary> /// The F8 key. /// </summary> F8 = 97, /// <summary> /// The F9 key. /// </summary> F9 = 98, /// <summary> /// The F10 key. /// </summary> F10 = 99, /// <summary> /// The F11 key. /// </summary> F11 = 100, /// <summary> /// The F12 key. /// </summary> F12 = 101, /// <summary> /// The F13 key. /// </summary> F13 = 102, /// <summary> /// The F14 key. /// </summary> F14 = 103, /// <summary> /// The F15 key. /// </summary> F15 = 104, /// <summary> /// The F16 key. /// </summary> F16 = 105, /// <summary> /// The F17 key. /// </summary> F17 = 106, /// <summary> /// The F18 key. /// </summary> F18 = 107, /// <summary> /// The F19 key. /// </summary> F19 = 108, /// <summary> /// The F20 key. /// </summary> F20 = 109, /// <summary> /// The F21 key. /// </summary> F21 = 110, /// <summary> /// The F22 key. /// </summary> F22 = 111, /// <summary> /// The F23 key. /// </summary> F23 = 112, /// <summary> /// The F24 key. /// </summary> F24 = 113, /// <summary> /// The Numlock key. /// </summary> NumLock = 114, /// <summary> /// The Scroll key. /// </summary> Scroll = 115, /// <summary> /// The left Shift key. /// </summary> LeftShift = 116, /// <summary> /// The right Shift key. /// </summary> RightShift = 117, /// <summary> /// The left Ctrl key. /// </summary> LeftCtrl = 118, /// <summary> /// The right Ctrl key. /// </summary> RightCtrl = 119, /// <summary> /// The left Alt key. /// </summary> LeftAlt = 120, /// <summary> /// The right Alt key. /// </summary> RightAlt = 121, /// <summary> /// The browser Back key. /// </summary> BrowserBack = 122, /// <summary> /// The browser Forward key. /// </summary> BrowserForward = 123, /// <summary> /// The browser Refresh key. /// </summary> BrowserRefresh = 124, /// <summary> /// The browser Stop key. /// </summary> BrowserStop = 125, /// <summary> /// The browser Search key. /// </summary> BrowserSearch = 126, /// <summary> /// The browser Favorites key. /// </summary> BrowserFavorites = 127, /// <summary> /// The browser Home key. /// </summary> BrowserHome = 128, /// <summary> /// The Volume Mute key. /// </summary> VolumeMute = 129, /// <summary> /// The Volume Down key. /// </summary> VolumeDown = 130, /// <summary> /// The Volume Up key. /// </summary> VolumeUp = 131, /// <summary> /// The media Next Track key. /// </summary> MediaNextTrack = 132, /// <summary> /// The media Previous Track key. /// </summary> MediaPreviousTrack = 133, /// <summary> /// The media Stop key. /// </summary> MediaStop = 134, /// <summary> /// The media Play/Pause key. /// </summary> MediaPlayPause = 135, /// <summary> /// The Launch Mail key. /// </summary> LaunchMail = 136, /// <summary> /// The Select Media key. /// </summary> SelectMedia = 137, /// <summary> /// The Launch Application 1 key. /// </summary> LaunchApplication1 = 138, /// <summary> /// The Launch Application 2 key. /// </summary> LaunchApplication2 = 139, /// <summary> /// The OEM Semicolon key. /// </summary> OemSemicolon = 140, /// <summary> /// The OEM 1 key. /// </summary> Oem1 = 140, /// <summary> /// The OEM Plus key. /// </summary> OemPlus = 141, /// <summary> /// The OEM Comma key. /// </summary> OemComma = 142, /// <summary> /// The OEM Minus key. /// </summary> OemMinus = 143, /// <summary> /// The OEM Period key. /// </summary> OemPeriod = 144, /// <summary> /// The OEM Question Mark key. /// </summary> OemQuestion = 145, /// <summary> /// The OEM 2 key. /// </summary> Oem2 = 145, /// <summary> /// The OEM Tilde key. /// </summary> OemTilde = 146, /// <summary> /// The OEM 3 key. /// </summary> Oem3 = 146, /// <summary> /// The ABNT_C1 (Brazilian) key. /// </summary> AbntC1 = 147, /// <summary> /// The ABNT_C2 (Brazilian) key. /// </summary> AbntC2 = 148, /// <summary> /// The OEM Open Brackets key. /// </summary> OemOpenBrackets = 149, /// <summary> /// The OEM 4 key. /// </summary> Oem4 = 149, /// <summary> /// The OEM Pipe key. /// </summary> OemPipe = 150, /// <summary> /// The OEM 5 key. /// </summary> Oem5 = 150, /// <summary> /// The OEM Close Brackets key. /// </summary> OemCloseBrackets = 151, /// <summary> /// The OEM 6 key. /// </summary> Oem6 = 151, /// <summary> /// The OEM Quotes key. /// </summary> OemQuotes = 152, /// <summary> /// The OEM 7 key. /// </summary> Oem7 = 152, /// <summary> /// The OEM 8 key. /// </summary> Oem8 = 153, /// <summary> /// The OEM Backslash key. /// </summary> OemBackslash = 154, /// <summary> /// The OEM 3 key. /// </summary> Oem102 = 154, /// <summary> /// A special key masking the real key being processed by an IME. /// </summary> ImeProcessed = 155, /// <summary> /// A special key masking the real key being processed as a system key. /// </summary> System = 156, /// <summary> /// The OEM ATTN key. /// </summary> OemAttn = 157, /// <summary> /// The DBE_ALPHANUMERIC key. /// </summary> DbeAlphanumeric = 157, /// <summary> /// The OEM Finish key. /// </summary> OemFinish = 158, /// <summary> /// The DBE_KATAKANA key. /// </summary> DbeKatakana = 158, /// <summary> /// The DBE_HIRAGANA key. /// </summary> DbeHiragana = 159, /// <summary> /// The OEM Copy key. /// </summary> OemCopy = 159, /// <summary> /// The DBE_SBCSCHAR key. /// </summary> DbeSbcsChar = 160, /// <summary> /// The OEM Auto key. /// </summary> OemAuto = 160, /// <summary> /// The DBE_DBCSCHAR key. /// </summary> DbeDbcsChar = 161, /// <summary> /// The OEM ENLW key. /// </summary> OemEnlw = 161, /// <summary> /// The OEM BackTab key. /// </summary> OemBackTab = 162, /// <summary> /// The DBE_ROMAN key. /// </summary> DbeRoman = 162, /// <summary> /// The DBE_NOROMAN key. /// </summary> DbeNoRoman = 163, /// <summary> /// The ATTN key. /// </summary> Attn = 163, /// <summary> /// The CRSEL key. /// </summary> CrSel = 164, /// <summary> /// The DBE_ENTERWORDREGISTERMODE key. /// </summary> DbeEnterWordRegisterMode = 164, /// <summary> /// The EXSEL key. /// </summary> ExSel = 165, /// <summary> /// The DBE_ENTERIMECONFIGMODE key. /// </summary> DbeEnterImeConfigureMode = 165, /// <summary> /// The ERASE EOF Key. /// </summary> EraseEof = 166, /// <summary> /// The DBE_FLUSHSTRING key. /// </summary> DbeFlushString = 166, /// <summary> /// The Play key. /// </summary> Play = 167, /// <summary> /// The DBE_CODEINPUT key. /// </summary> DbeCodeInput = 167, /// <summary> /// The DBE_NOCODEINPUT key. /// </summary> DbeNoCodeInput = 168, /// <summary> /// The Zoom key. /// </summary> Zoom = 168, /// <summary> /// Reserved for future use. /// </summary> NoName = 169, /// <summary> /// The DBE_DETERMINESTRING key. /// </summary> DbeDetermineString = 169, /// <summary> /// The DBE_ENTERDLGCONVERSIONMODE key. /// </summary> DbeEnterDialogConversionMode = 170, /// <summary> /// The PA1 key. /// </summary> Pa1 = 170, /// <summary> /// The OEM Clear key. /// </summary> OemClear = 171, /// <summary> /// The key is used with another key to create a single combined character. /// </summary> DeadCharProcessed = 172, /// <summary> /// OSX Platform-specific Fn+Left key /// </summary> FnLeftArrow = 10001, /// <summary> /// OSX Platform-specific Fn+Right key /// </summary> FnRightArrow = 10002, /// <summary> /// OSX Platform-specific Fn+Up key /// </summary> FnUpArrow = 10003, /// <summary> /// OSX Platform-specific Fn+Down key /// </summary> FnDownArrow = 10004, } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ConfigService.Model { /// <summary> /// A list that contains detailed configurations of a specified resource. /// /// <note> /// <para> /// Currently, the list does not contain information about non-AWS components (for example, /// applications on your Amazon EC2 instances). /// </para> /// </note> /// </summary> public partial class ConfigurationItem { private string _accountId; private string _arn; private string _availabilityZone; private string _awsRegion; private string _configuration; private DateTime? _configurationItemCaptureTime; private string _configurationItemMD5Hash; private ConfigurationItemStatus _configurationItemStatus; private string _configurationStateId; private List<string> _relatedEvents = new List<string>(); private List<Relationship> _relationships = new List<Relationship>(); private DateTime? _resourceCreationTime; private string _resourceId; private string _resourceName; private ResourceType _resourceType; private Dictionary<string, string> _tags = new Dictionary<string, string>(); private string _version; /// <summary> /// Gets and sets the property AccountId. /// <para> /// The 12 digit AWS account ID associated with the resource. /// </para> /// </summary> public string AccountId { get { return this._accountId; } set { this._accountId = value; } } // Check to see if AccountId property is set internal bool IsSetAccountId() { return this._accountId != null; } /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) of the resource. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The Availability Zone associated with the resource. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property AwsRegion. /// <para> /// The region where the resource resides. /// </para> /// </summary> public string AwsRegion { get { return this._awsRegion; } set { this._awsRegion = value; } } // Check to see if AwsRegion property is set internal bool IsSetAwsRegion() { return this._awsRegion != null; } /// <summary> /// Gets and sets the property Configuration. /// <para> /// The description of the resource configuration. /// </para> /// </summary> public string Configuration { get { return this._configuration; } set { this._configuration = value; } } // Check to see if Configuration property is set internal bool IsSetConfiguration() { return this._configuration != null; } /// <summary> /// Gets and sets the property ConfigurationItemCaptureTime. /// <para> /// The time when the configuration recording was initiated. /// </para> /// </summary> public DateTime ConfigurationItemCaptureTime { get { return this._configurationItemCaptureTime.GetValueOrDefault(); } set { this._configurationItemCaptureTime = value; } } // Check to see if ConfigurationItemCaptureTime property is set internal bool IsSetConfigurationItemCaptureTime() { return this._configurationItemCaptureTime.HasValue; } /// <summary> /// Gets and sets the property ConfigurationItemMD5Hash. /// <para> /// Unique MD5 hash that represents the configuration item's state. /// </para> /// /// <para> /// You can use MD5 hash to compare the states of two or more configuration items that /// are associated with the same resource. /// </para> /// </summary> public string ConfigurationItemMD5Hash { get { return this._configurationItemMD5Hash; } set { this._configurationItemMD5Hash = value; } } // Check to see if ConfigurationItemMD5Hash property is set internal bool IsSetConfigurationItemMD5Hash() { return this._configurationItemMD5Hash != null; } /// <summary> /// Gets and sets the property ConfigurationItemStatus. /// <para> /// The configuration item status. /// </para> /// </summary> public ConfigurationItemStatus ConfigurationItemStatus { get { return this._configurationItemStatus; } set { this._configurationItemStatus = value; } } // Check to see if ConfigurationItemStatus property is set internal bool IsSetConfigurationItemStatus() { return this._configurationItemStatus != null; } /// <summary> /// Gets and sets the property ConfigurationStateId. /// <para> /// An identifier that indicates the ordering of the configuration items of a resource. /// </para> /// </summary> public string ConfigurationStateId { get { return this._configurationStateId; } set { this._configurationStateId = value; } } // Check to see if ConfigurationStateId property is set internal bool IsSetConfigurationStateId() { return this._configurationStateId != null; } /// <summary> /// Gets and sets the property RelatedEvents. /// <para> /// A list of CloudTrail event IDs. /// </para> /// /// <para> /// A populated field indicates that the current configuration was initiated by the events /// recorded in the CloudTrail log. For more information about CloudTrail, see <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html">What /// is AWS CloudTrail?</a>. /// </para> /// /// <para> /// An empty field indicates that the current configuration was not initiated by any event. /// </para> /// </summary> public List<string> RelatedEvents { get { return this._relatedEvents; } set { this._relatedEvents = value; } } // Check to see if RelatedEvents property is set internal bool IsSetRelatedEvents() { return this._relatedEvents != null && this._relatedEvents.Count > 0; } /// <summary> /// Gets and sets the property Relationships. /// <para> /// A list of related AWS resources. /// </para> /// </summary> public List<Relationship> Relationships { get { return this._relationships; } set { this._relationships = value; } } // Check to see if Relationships property is set internal bool IsSetRelationships() { return this._relationships != null && this._relationships.Count > 0; } /// <summary> /// Gets and sets the property ResourceCreationTime. /// <para> /// The time stamp when the resource was created. /// </para> /// </summary> public DateTime ResourceCreationTime { get { return this._resourceCreationTime.GetValueOrDefault(); } set { this._resourceCreationTime = value; } } // Check to see if ResourceCreationTime property is set internal bool IsSetResourceCreationTime() { return this._resourceCreationTime.HasValue; } /// <summary> /// Gets and sets the property ResourceId. /// <para> /// The ID of the resource (for example., <code>sg-xxxxxx</code>). /// </para> /// </summary> public string ResourceId { get { return this._resourceId; } set { this._resourceId = value; } } // Check to see if ResourceId property is set internal bool IsSetResourceId() { return this._resourceId != null; } /// <summary> /// Gets and sets the property ResourceName. /// <para> /// The custom name of the resource, if available. /// </para> /// </summary> public string ResourceName { get { return this._resourceName; } set { this._resourceName = value; } } // Check to see if ResourceName property is set internal bool IsSetResourceName() { return this._resourceName != null; } /// <summary> /// Gets and sets the property ResourceType. /// <para> /// The type of AWS resource. /// </para> /// </summary> public ResourceType ResourceType { get { return this._resourceType; } set { this._resourceType = value; } } // Check to see if ResourceType property is set internal bool IsSetResourceType() { return this._resourceType != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A mapping of key value tags associated with the resource. /// </para> /// </summary> public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property Version. /// <para> /// The version number of the resource configuration. /// </para> /// </summary> public string Version { get { return this._version; } set { this._version = value; } } // Check to see if Version property is set internal bool IsSetVersion() { return this._version != null; } } }
// 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; using System.Collections.Generic; using System.Security; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Threading; namespace System.IO { public static class Directory { public static DirectoryInfo GetParent(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, "path"); Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); String s = Path.GetDirectoryName(fullPath); if (s == null) return null; return new DirectoryInfo(s); } [System.Security.SecuritySafeCritical] public static DirectoryInfo CreateDirectory(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, "path"); Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); FileSystem.Current.CreateDirectory(fullPath); return new DirectoryInfo(fullPath, null); } // Input to this method should already be fullpath. This method will ensure that we append // the trailing slash only when appropriate. internal static String EnsureTrailingDirectorySeparator(string fullPath) { String fullPathWithTrailingDirectorySeparator; if (!PathHelpers.EndsInDirectorySeparator(fullPath)) fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString; else fullPathWithTrailingDirectorySeparator = fullPath; return fullPathWithTrailingDirectorySeparator; } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // [System.Security.SecuritySafeCritical] // auto-generated public static bool Exists(String path) { try { if (path == null) return false; if (path.Length == 0) return false; String fullPath = Path.GetFullPath(path); return FileSystem.Current.DirectoryExists(fullPath); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } public static void SetCreationTime(String path, DateTime creationTime) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true); } public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true); } public static DateTime GetCreationTime(String path) { return File.GetCreationTime(path); } public static DateTime GetCreationTimeUtc(String path) { return File.GetCreationTimeUtc(path); } public static void SetLastWriteTime(String path, DateTime lastWriteTime) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true); } public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true); } public static DateTime GetLastWriteTime(String path) { return File.GetLastWriteTime(path); } public static DateTime GetLastWriteTimeUtc(String path) { return File.GetLastWriteTimeUtc(path); } public static void SetLastAccessTime(String path, DateTime lastAccessTime) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true); } public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) { String fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true); } public static DateTime GetLastAccessTime(String path) { return File.GetLastAccessTime(path); } public static DateTime GetLastAccessTimeUtc(String path) { return File.GetLastAccessTimeUtc(path); } // Returns an array of filenames in the DirectoryInfo specified by path public static String[] GetFiles(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (ie, "*.txt"). public static String[] GetFiles(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (ie, "*.txt") and search option public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (ie, "*.txt") and search option private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption); } // Returns an array of Directories in the current directory. public static String[] GetDirectories(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public static String[] GetDirectories(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<String[]>() != null); return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path public static String[] GetFileSystemEntries(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria public static String[] GetFileSystemEntries(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, searchPattern, searchOption); } private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption); } // Returns fully qualified user path of dirs/files that matches the search parameters. // For recursive search this method will search through all the sub dirs and execute // the given search criteria against every dir. // For all the dirs/files returned, it will then demand path discovery permission for // their parent folders (it will avoid duplicate permission checks) internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(userPathOriginal != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption, (includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0)); return EnumerableHelpers.ToArray(enumerable); } public static IEnumerable<String> EnumerateDirectories(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true); } public static IEnumerable<String> EnumerateFiles(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFiles(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false); } public static IEnumerable<String> EnumerateFileSystemEntries(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true); } private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption, bool includeFiles, bool includeDirs) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption, (includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0)); } [System.Security.SecuritySafeCritical] public static String GetDirectoryRoot(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); return root; } internal static String InternalGetDirectoryRoot(String path) { if (path == null) return null; return path.Substring(0, PathInternal.GetRootLength(path)); } /*===============================CurrentDirectory=============================== **Action: Provides a getter and setter for the current directory. The original ** current DirectoryInfo is the one from which the process was started. **Returns: The current DirectoryInfo (from the getter). Void from the setter. **Arguments: The current DirectoryInfo to which to switch to the setter. **Exceptions: ==============================================================================*/ [System.Security.SecuritySafeCritical] public static String GetCurrentDirectory() { return FileSystem.Current.GetCurrentDirectory(); } [System.Security.SecurityCritical] // auto-generated public static void SetCurrentDirectory(String path) { if (path == null) throw new ArgumentNullException("value"); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, "path"); Contract.EndContractBlock(); if (PathInternal.IsPathTooLong(path)) throw new PathTooLongException(SR.IO_PathTooLong); String fulldestDirName = Path.GetFullPath(path); FileSystem.Current.SetCurrentDirectory(fulldestDirName); } [System.Security.SecuritySafeCritical] public static void Move(String sourceDirName, String destDirName) { if (sourceDirName == null) throw new ArgumentNullException("sourceDirName"); if (sourceDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "sourceDirName"); if (destDirName == null) throw new ArgumentNullException("destDirName"); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName"); Contract.EndContractBlock(); String fullsourceDirName = Path.GetFullPath(sourceDirName); String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName); if (PathInternal.IsDirectoryTooLong(sourcePath)) throw new PathTooLongException(SR.IO_PathTooLong); String fulldestDirName = Path.GetFullPath(destDirName); String destPath = EnsureTrailingDirectorySeparator(fulldestDirName); if (PathInternal.IsDirectoryTooLong(destPath)) throw new PathTooLongException(SR.IO_PathTooLong); StringComparison pathComparison = PathInternal.StringComparison; if (String.Equals(sourcePath, destPath, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(sourcePath); String destinationRoot = Path.GetPathRoot(destPath); if (!String.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName); } [System.Security.SecuritySafeCritical] public static void Delete(String path) { String fullPath = Path.GetFullPath(path); FileSystem.Current.RemoveDirectory(fullPath, false); } [System.Security.SecuritySafeCritical] public static void Delete(String path, bool recursive) { String fullPath = Path.GetFullPath(path); FileSystem.Current.RemoveDirectory(fullPath, recursive); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using mshtml; using OpenLiveWriter.HtmlEditor; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Interop.Windows; namespace OpenLiveWriter.PostEditor.PostHtmlEditing { internal delegate void IHTMLElementCallback(IHTMLElement fromElement); internal class EditableRegionElementBehavior : HtmlEditorElementBehavior { IHTMLElement _nextEditableRegion; IHTMLElement _previousEditableRegion; #region Initialization and Disposal public EditableRegionElementBehavior(IHtmlEditorComponentContext editorContext, IHTMLElement previousEditableRegion, IHTMLElement nextEditableRegion) : base(editorContext) { _nextEditableRegion = nextEditableRegion; _previousEditableRegion = previousEditableRegion; } protected override void OnElementAttached() { if (EditorContext.EditMode) { IHTMLElement3 e3 = HTMLElement as IHTMLElement3; if (!e3.isContentEditable) e3.contentEditable = "true"; } base.OnElementAttached(); SetPaintColors(HTMLElement); EditorContext.PreHandleEvent += new HtmlEditDesignerEventHandler(EditorContext_PreHandleEvent); EditorContext.CommandKey += new KeyEventHandler(EditorContext_CommandKey); EditorContext.KeyDown += new HtmlEventHandler(EditorContext_KeyDown); EditorContext.KeyUp += new HtmlEventHandler(EditorContext_KeyUp); _elementBehaviorAttached = true; } #endregion /// <summary> /// Returns true if the element behavior has been completely attached to element. /// </summary> public bool ElementBehaviorAttached { get { return _elementBehaviorAttached; } } private bool _elementBehaviorAttached; protected override bool QueryElementSelected() { return ElementRange.InRange(EditorContext.Selection.SelectedMarkupRange, false); } protected override void OnSelectedChanged() { Invalidate(); } public virtual string GetEditedHtml(bool useXhtml, bool doCleanup) { try { if (doCleanup || useXhtml) { MshtmlMarkupServices markupServices = new MshtmlMarkupServices(HTMLElement.document as IMarkupServicesRaw); if (doCleanup) { MarkupRange bodyRange = markupServices.CreateMarkupRange(((IHTMLDocument2)HTMLElement.document).body, false); bodyRange.RemoveElementsByTagId(_ELEMENT_TAG_ID.TAGID_FONT, true); } if (useXhtml) { MarkupRange bounds = markupServices.CreateMarkupRange(HTMLElement, false); string xhtml = FormattedHtmlPrinter.ToFormattedHtml(markupServices, bounds); return doCleanup ? CleanupHtml(xhtml, true) : xhtml; } } } catch (Exception e) { // E.g. this failure case: <pre><b></pre></b> Trace.Fail("Exception generating XHTML: " + e.ToString()); } string html = HTMLElement.innerHTML ?? String.Empty; if (doCleanup) return CleanupHtml(html, false); else return html; } /// <summary> /// Converts tag names, attribute names, and style text to lowercase. /// </summary> private string CleanupHtml(string html, bool xml) { bool needsCleanup; do { needsCleanup = false; StringBuilder output = new StringBuilder(html.Length); SimpleHtmlParser htmlParser = new SimpleHtmlParser(html); for (Element el; null != (el = htmlParser.Next()); ) { if (el is BeginTag) { BeginTag bt = (BeginTag)el; if (RemoveMeaninglessTags(htmlParser, bt)) { // Since we are removing a tag, we will want to clean up again, since that might mean // there will be another tag to remove needsCleanup = true; continue; } output.Append("<"); output.Append(bt.Name.ToLower(CultureInfo.InvariantCulture)); foreach (Attr attr in bt.Attributes) { if (attr.NameEquals("contenteditable") || attr.NameEquals("atomicselection") || attr.NameEquals("unselectable")) continue; output.Append(" "); output.Append(attr.Name.ToLower(CultureInfo.InvariantCulture)); if (attr.Value != null) { string attrVal = attr.Value; if (attr.NameEquals("style")) attrVal = LowerCaseCss(attrVal); else if (attr.Name == attr.Value) attrVal = attrVal.ToLower(CultureInfo.InvariantCulture); output.AppendFormat("=\"{0}\"", xml ? HtmlUtils.EscapeEntitiesForXml(attrVal, true) : HtmlUtils.EscapeEntities(attrVal)); } } if (bt.HasResidue) { if (bt.Attributes.Length == 0) output.Append(" "); output.Append(bt.Residue); } if (bt.Complete) output.Append(" /"); output.Append(">"); } else if (el is EndTag) { output.AppendFormat("</{0}>", ((EndTag)el).Name.ToLower(CultureInfo.InvariantCulture)); } else if (el is Text) { string textHtml = HtmlUtils.TidyNbsps(el.RawText); if (xml) textHtml = HtmlUtils.EscapeEntitiesForXml( HtmlUtils.UnEscapeEntities(textHtml, HtmlUtils.UnEscapeMode.NonMarkupText), false); output.Append(textHtml); } else if (el is StyleText) output.Append(el.RawText.ToLower(CultureInfo.InvariantCulture)); else output.Append(el.RawText); } html = output.ToString(); } while (needsCleanup); return html; } /// <summary> /// Is the tag a meaningless tag such as <p></p> or <a href="..."></a> or <a href="...">&nbsp;</a> /// </summary> /// <param name="htmlParser"></param> /// <param name="bt"></param> /// <returns></returns> private static bool RemoveMeaninglessTags(SimpleHtmlParser htmlParser, BeginTag bt) { // Look to see if the tag is a <p> without any attributes if ((bt.NameEquals("p") && bt.Attributes.Length == 0 && !bt.HasResidue)) { Element e = htmlParser.Peek(0); // Look to see if thereis a matching end tag to the element we are looking at if (e != null && e is EndTag && ((EndTag)e).NameEquals("p")) { // eat up the end tag htmlParser.Next(); return true; } } // Look to see if the tag is an <a> without a style/id/name attribute, but has an href... meaning the link is not useful if ((bt.NameEquals("a") && bt.GetAttribute("name") == null && bt.GetAttributeValue("style") == null && bt.GetAttributeValue("id") == null && bt.GetAttributeValue("href") != null)) { bool hadWhiteSpaceText = false; Element e = htmlParser.Peek(0); // Look to see if the a just has whitespace inside of it if (e is Text && HtmlUtils.UnEscapeEntities(e.RawText, HtmlUtils.UnEscapeMode.NonMarkupText).Trim().Length == 0) { e = htmlParser.Peek(1); hadWhiteSpaceText = true; } // Look to see if thereis a matching end tag to the element we are looking at if (e != null && e is EndTag && ((EndTag)e).NameEquals("a")) { // if this was an <a> with whitespace in the middle eat it up if (hadWhiteSpaceText) htmlParser.Next(); // eat up the end tag htmlParser.Next(); return true; } } return false; } private string LowerCaseCss(string val) { StringBuilder output = new StringBuilder(); CssParser parser = new CssParser(val); for (StyleElement el; null != (el = parser.Next()); ) { if (el is StyleText) output.Append(el.RawText.ToLower(CultureInfo.InvariantCulture)); else output.Append(el.RawText); } return output.ToString(); } #region Painting and Drawing public override void GetPainterInfo(ref _HTML_PAINTER_INFO pInfo) { // ensure we paint above everything (including selection handles) pInfo.lFlags = (int)_HTML_PAINTER.HTMLPAINTER_OPAQUE; pInfo.lZOrder = (int)_HTML_PAINT_ZORDER.HTMLPAINT_ZORDER_WINDOW_TOP; // expand to the right to add padding for invalidates pInfo.rcExpand.top += invalidationPadding; pInfo.rcExpand.bottom += invalidationPadding; pInfo.rcExpand.left += invalidationPadding; pInfo.rcExpand.right += invalidationPadding; } protected int invalidationPadding = 3; public override void Draw(RECT rcBounds, RECT rcUpdate, int lDrawFlags, IntPtr hdc, IntPtr pvDrawObject) { drawDepth++; try { if (drawDepth > 1) return; _HTML_PAINTER_INFO pInfo = new _HTML_PAINTER_INFO(); GetPainterInfo(ref pInfo); //adjust the draw bounds to remove our padding for invalidates Rectangle drawBounds = RectangleHelper.Convert(rcBounds); drawBounds.X += invalidationPadding; drawBounds.Y += invalidationPadding; drawBounds.Height -= invalidationPadding * 2; drawBounds.Width -= invalidationPadding * 2; using (Graphics g = Graphics.FromHdc(hdc)) { OnDraw(g, drawBounds, rcBounds, rcUpdate, lDrawFlags, hdc, pvDrawObject); } } finally { drawDepth--; } } int drawDepth; //public virtual void OnDraw(RECT rcBounds, RECT rcUpdate, int lDrawFlags, IntPtr hdc, IntPtr pvDrawObject) public virtual void OnDraw(Graphics g, Rectangle drawBounds, RECT rcBounds, RECT rcUpdate, int lDrawFlags, IntPtr hdc, IntPtr pvDrawObject) { } protected Color PaintRegionBorder { get { return regionBorder; } set { regionBorder = value; } } private Color regionBorder = Color.Transparent; /// <summary> /// Translates a client rectangle into the rectangle defined by the drawing bounds. /// </summary> /// <param name="clientRectangle"></param> /// <param name="rcBounds"></param> /// <returns></returns> protected Rectangle GetPaintRectangle(Rectangle clientRectangle, RECT rcBounds) { POINT globalPoint = new POINT(); globalPoint.x = clientRectangle.Left; globalPoint.y = clientRectangle.Top; POINT localPoint = new POINT(); HTMLPaintSite.TransformGlobalToLocal(globalPoint, ref localPoint); Rectangle converted = new Rectangle(localPoint.x + rcBounds.left, localPoint.y + rcBounds.top, clientRectangle.Right - clientRectangle.Left, clientRectangle.Bottom - clientRectangle.Top); return converted; } #endregion #region Event Handling private int EditorContext_PreHandleEvent(int inEvtDispId, IHTMLEventObj pIEventObj) { if (Attached) { IHTMLElement srcElement = pIEventObj.srcElement; if (srcElement != null && srcElement.sourceIndex == HTMLElement.sourceIndex) { return OnPreHandleEvent(inEvtDispId, pIEventObj); } } return HRESULT.S_FALSE; } protected virtual int OnPreHandleEvent(int inEvtDispId, IHTMLEventObj pIEventObj) { return HRESULT.S_FALSE; } private void EditorContext_CommandKey(object sender, KeyEventArgs e) { if (Selected) { OnCommandKey(sender, e); } } protected virtual void OnCommandKey(object sender, KeyEventArgs e) { if (!e.Shift && !e.Alt && !EditorContext.IsEditFieldSelected) //don't override keyboard navigation when shift or alt are pressed { if (e.KeyCode == Keys.Up) { if (IsCaretWithin(GetFirstLineClientRectangle())) { e.Handled = MoveCaretToNextRegion(MOVE_DIRECTION.UP); } } else if (e.KeyCode == Keys.Down) { if (IsCaretWithin(GetLastLineClientRectangle())) { e.Handled = MoveCaretToNextRegion(MOVE_DIRECTION.DOWN); } } else if (e.KeyCode == Keys.Left) { if (IsCaretWithin(GetFirstLineClientRectangle()) && IsCaretAtLinePosition(LINE_POSITION.START)) { e.Handled = MoveCaretToNextRegion(MOVE_DIRECTION.LEFT); } } else if (e.KeyCode == Keys.Right) { if (IsCaretWithin(GetLastLineClientRectangle()) && IsCaretAtLinePosition(LINE_POSITION.END)) { e.Handled = MoveCaretToNextRegion(MOVE_DIRECTION.RIGHT); } } } } private void EditorContext_KeyDown(object o, HtmlEventArgs e) { if (Selected) { OnKeyDown(o, e); } } protected virtual void OnKeyDown(object o, HtmlEventArgs e) { } private void EditorContext_KeyUp(object o, HtmlEventArgs e) { if (Selected) { OnKeyUp(o, e); } } protected virtual void OnKeyUp(object o, HtmlEventArgs e) { } public event EventHandler EditableRegionFocusChanged; protected virtual void OnEditableRegionFocusChanged(object o, EditableRegionFocusChangedEventArgs e) { if (EditableRegionFocusChanged != null) { EditableRegionFocusChanged(null, e); } } #endregion /// <summary> /// Returns true if there is text to the right of the current position. /// </summary> /// <returns></returns> protected bool hasTextRight(MarkupPointer pointer) { MarkupPointer start = pointer; MarkupPointer end = ElementRange.End; IHTMLTxtRange textRange = EditorContext.MarkupServices.CreateTextRange(start, end); string text = textRange.text; if (text == null || text.Trim().Equals(String.Empty)) return false; else return true; } /// <summary> /// Switches focus to the previous editable region. /// </summary> protected void SelectPreviousRegion() { if (_previousEditableRegion != null) { MarkupRange range = EditorContext.MarkupServices.CreateMarkupRange(_previousEditableRegion, false); range.End.MoveToPointer(range.Start); range.ToTextRange().select(); } } /// <summary> /// Switches focus to the next editable region. /// </summary> protected void SelectNextRegion() { if (_nextEditableRegion != null) { MarkupRange range = EditorContext.MarkupServices.CreateMarkupRange(_nextEditableRegion, false); range.End.MoveToPointer(range.Start); range.ToTextRange().select(); } //Note: this could work if we have to use Focus (which causes scroll) but there is a flicker //HTMLElement.scrollIntoView(false); } private IHTMLElement NextEditableRegion { get { return _nextEditableRegion; } } private IHTMLElement PreviousEditableRegion { get { return _previousEditableRegion; } } protected IHTMLElement2 HTMLElement2 { get { return (IHTMLElement2)HTMLElement; } } #region Caret Helpers /// <summary> /// Navigates the editor's caret to the next editable region. /// </summary> /// <param name="direction"></param> private bool MoveCaretToNextRegion(MOVE_DIRECTION direction) { IHTMLElement nextRegion; _ELEMENT_ADJACENCY nextRegionAdjacency; bool preserveXLocation; if (direction == MOVE_DIRECTION.UP || direction == MOVE_DIRECTION.LEFT) { nextRegion = PreviousEditableRegion; nextRegionAdjacency = _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd; preserveXLocation = direction == MOVE_DIRECTION.UP; } else if (direction == MOVE_DIRECTION.DOWN || direction == MOVE_DIRECTION.RIGHT) { nextRegion = NextEditableRegion; nextRegionAdjacency = _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin; preserveXLocation = direction == MOVE_DIRECTION.DOWN; if (nextRegion == null) return false; MarkupPointer selectRegion = EditorContext.MarkupServices.CreateMarkupPointer(nextRegion, nextRegionAdjacency); MarkupContext mc = selectRegion.Right(false); if (mc.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && mc.Element is IHTMLElement3 && SmartContentSelection.SelectIfSmartContentElement(EditorContext, mc.Element) != null) { return true; } } else throw new ArgumentException("Unsupported move direction detected: " + direction); IDisplayServicesRaw displayServices = (IDisplayServicesRaw)HTMLElement.document; IDisplayPointerRaw displayPointer; displayServices.CreateDisplayPointer(out displayPointer); IHTMLCaretRaw caret = GetCaret(); caret.MoveDisplayPointerToCaret(displayPointer); ILineInfo lineInfo; displayPointer.GetLineInfo(out lineInfo); if (nextRegion != null) { MarkupPointer mp = EditorContext.MarkupServices.CreateMarkupPointer(nextRegion, nextRegionAdjacency); DisplayServices.TraceMoveToMarkupPointer(displayPointer, mp); try { caret.MoveCaretToPointer(displayPointer, true, _CARET_DIRECTION.CARET_DIRECTION_SAME); if (preserveXLocation) { POINT caretLocation; caret.GetLocation(out caretLocation, true); caretLocation.x = lineInfo.x; uint hitTestResults; displayPointer.MoveToPoint(caretLocation, _COORD_SYSTEM.COORD_SYSTEM_GLOBAL, nextRegion, 0, out hitTestResults); caret.MoveCaretToPointer(displayPointer, true, _CARET_DIRECTION.CARET_DIRECTION_SAME); } //BEP: using this line causes scrolling (nextRegion as IHTMLElement2).focus(); (nextRegion as IHTMLElement3).setActive(); return true; } catch (Exception e) { Debug.Fail("Unexpected exception in MoveCaretToNextRegion: " + e.ToString()); } caret.MoveCaretToPointer(displayPointer, true, _CARET_DIRECTION.CARET_DIRECTION_SAME); } return false; } private enum MOVE_DIRECTION { UP, DOWN, LEFT, RIGHT }; /// <summary> /// Returns true if the caret is currently positioned at the specified line position. /// </summary> /// <param name="position"></param> /// <returns></returns> protected bool IsCaretAtLinePosition(LINE_POSITION position) { _DISPLAY_MOVEUNIT moveUnit; if (position == LINE_POSITION.START) moveUnit = _DISPLAY_MOVEUNIT.DISPLAY_MOVEUNIT_CurrentLineStart; else moveUnit = _DISPLAY_MOVEUNIT.DISPLAY_MOVEUNIT_CurrentLineEnd; IDisplayServicesRaw displayServices = (IDisplayServicesRaw)HTMLElement.document; IDisplayPointerRaw displayPointer, displayPointer2; displayServices.CreateDisplayPointer(out displayPointer); displayServices.CreateDisplayPointer(out displayPointer2); IHTMLCaretRaw caret = GetCaret(); caret.MoveDisplayPointerToCaret(displayPointer); displayPointer2.MoveToPointer(displayPointer); displayPointer2.MoveUnit(moveUnit, -1); bool areEqual; displayPointer2.IsEqualTo(displayPointer, out areEqual); return areEqual; } protected enum LINE_POSITION { START, END }; #endregion #region Rectangle Helpers /// <summary> /// Returns the bounds of the first line of text for the element in client-based coordinates. /// </summary> /// <returns></returns> protected Rectangle GetFirstLineClientRectangle() { MarkupPointer pointer = EditorContext.MarkupServices.CreateMarkupPointer(HTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin); return GetLineClientRectangle(pointer); } /// <summary> /// Returns the bounds of the last line of text for the element in client-based coordinates. /// </summary> /// <returns></returns> protected Rectangle GetLastLineClientRectangle() { MarkupPointer pointer = EditorContext.MarkupServices.CreateMarkupPointer(HTMLElement, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); return GetLineClientRectangle(pointer); } /// <summary> /// Returns the bounds of line that the pointer is positioned within in client-based coordinates. /// </summary> /// <param name="pointer"></param> /// <returns></returns> protected Rectangle GetLineClientRectangle(MarkupPointer pointer) { //getting the line associated with a pointer is a little complicated because the //ILineInfo for the pointer position only returns information based on the font //exactly at that position. It does not take the max font height of the line into //account, so we need to that manually. To do this, we get the LineInfo at each //point in the line where the line height may change by moving a markup pointer //in to each element declared on the line. IDisplayServicesRaw displayServices = (IDisplayServicesRaw)HTMLElement.document; //position a display pointer on the same line as the markup pointer IDisplayPointerRaw displayPointer; displayServices.CreateDisplayPointer(out displayPointer); DisplayServices.TraceMoveToMarkupPointer(displayPointer, pointer); //position a markup pointer at the end of the line MarkupPointer pLineEnd = pointer.Clone(); displayPointer.MoveUnit(_DISPLAY_MOVEUNIT.DISPLAY_MOVEUNIT_CurrentLineEnd, 0); displayPointer.PositionMarkupPointer(pLineEnd.PointerRaw); //position a markup pointer at the start of the line MarkupPointer pLineStart = pointer.Clone(); displayPointer.MoveUnit(_DISPLAY_MOVEUNIT.DISPLAY_MOVEUNIT_CurrentLineStart, 0); displayPointer.PositionMarkupPointer(pLineStart.PointerRaw); //calculate the maximum rectangle taken up by any text on this line by walking //the lineStart pointer to the lineEnd pointer and calculating a max rectangle //at each step. Rectangle lineRect = GetLineRect(HTMLElement, displayPointer); pLineStart.Right(true); while (pLineStart.IsLeftOfOrEqualTo(pLineEnd)) { Rectangle dpLineRect; try { displayPointer.MoveToMarkupPointer(pLineStart.PointerRaw, null); dpLineRect = GetLineRect(HTMLElement, displayPointer); } catch (COMException e) { if (e.ErrorCode == IE_CTL_E.INVALIDLINE) { // http://msdn.microsoft.com/en-us/library/aa752674(VS.85).aspx // IDisplayPointer::MoveToMarkupPointer will return an error (CTL_E_INVALIDLINE), // if the markup pointer is in a line whose nearest layout element *is not a flow layout element*. dpLineRect = GetLineRect(pLineStart.CurrentScope); // We also want to skip past the entire current scope... pLineStart.MoveAdjacentToElement(pLineStart.CurrentScope, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); } else { Trace.Fail("Exception thrown in GetLineClientRectangle: " + e.ToString()); throw; } } lineRect.Y = Math.Min(dpLineRect.Y, lineRect.Y); if (lineRect.Bottom < dpLineRect.Bottom) { lineRect.Height += dpLineRect.Bottom - lineRect.Bottom; } pLineStart.Right(true); } //return the line rectangle return lineRect; } // But we need a rectangle based on an element private Rectangle GetLineRect(IHTMLElement nonFlowElement) { Rectangle elementRect = GetClientRectangle(); return new Rectangle(elementRect.X, elementRect.Y - nonFlowElement.offsetHeight, elementRect.Width, nonFlowElement.offsetHeight); } /// <summary> /// Returns the bounds of the element in client-based coordinatates. /// Note: These bounds seem to map to the outer edge of the element's border region. /// </summary> /// <returns></returns> protected Rectangle GetClientRectangle() { return HTMLElementHelper.GetClientRectangle(HTMLElement); } protected enum ELEMENT_REGION { CONTENT, PADDING, BORDER, MARGIN }; protected Rectangle GetClientRectangle(ELEMENT_REGION outerBoundary) { Rectangle elementBounds = GetClientRectangle(); try { if (outerBoundary == ELEMENT_REGION.BORDER) return new Rectangle(elementBounds.Location, elementBounds.Size); int marginTop = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringMarginTop, HTMLElement, null, true); int marginBottom = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringMarginBottom, HTMLElement, null, true); int marginLeft = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringMarginLeft, HTMLElement, null, false); int marginRight = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringMarginRight, HTMLElement, null, false); int paddingTop = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringPaddingTop, HTMLElement, null, true); int paddingBottom = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringPaddingBottom, HTMLElement, null, true); int paddingLeft = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringPaddingLeft, HTMLElement, null, false); int paddingRight = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringPaddingRight, HTMLElement, null, false); int borderTop = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringBorderTop, HTMLElement, null, true); int borderBottom = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringBorderBottom, HTMLElement, null, true); int borderLeft = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringBorderLeft, HTMLElement, null, false); int borderRight = (int)HTMLElementHelper.CSSUnitStringToPointSize(HTMLElementHelper.CSSUnitStringBorderRight, HTMLElement, null, false); int offsetX; int offsetY; int offsetRight; int offsetBottom; if (outerBoundary == ELEMENT_REGION.PADDING) { offsetX = borderLeft; offsetY = borderTop; offsetRight = -borderRight; offsetBottom = -borderBottom; } else if (outerBoundary == ELEMENT_REGION.CONTENT) { offsetX = paddingLeft + borderLeft; offsetY = paddingTop + borderTop; offsetRight = -paddingRight - borderRight; offsetBottom = -paddingBottom - borderBottom; } else if (outerBoundary == ELEMENT_REGION.MARGIN) { offsetX = -marginLeft; offsetY = -marginTop; offsetRight = marginRight; offsetBottom = marginBottom; } else throw new ArgumentException("Unnsupported ELEMENT_REGION: " + outerBoundary.ToString()); Rectangle rect = new Rectangle(elementBounds.Location, elementBounds.Size); rect.X += offsetX; rect.Y += offsetY; rect.Width += offsetRight - offsetX; rect.Height += offsetBottom - offsetY; return rect; } catch (Exception e) { Trace.WriteLine("Error calculating element paint boundary: " + e.ToString()); return new Rectangle(elementBounds.Location, elementBounds.Size); } } #endregion #region Color Management protected virtual void SetPaintColors(IHTMLElement element) { IHTMLElement2 element2 = (element as IHTMLElement2); string textColor = HTMLColorHelper.GetTextColorString(element2); _textColorHex = HTMLColorHelper.ParseColorToHex(textColor); _textColor = HTMLColorHelper.GetColorFromHexColor(_textColorHex, Color.Black); string backgroundColor = HTMLColorHelper.GetBackgroundColorString(element2); _backgroundColorHex = HTMLColorHelper.ParseColorToHex(backgroundColor); _backgroundColor = HTMLColorHelper.GetColorFromHexColor(_backgroundColorHex, Color.White); } private Color _backgroundColor; private string _backgroundColorHex; private Color _textColor; private string _textColorHex; protected Color BackgroundColor { get { return _backgroundColor; } } protected string BackgroundColorHex { get { return _backgroundColorHex; } } protected Color TextColor { get { return _textColor; } } protected string TextColorHex { get { return _textColorHex; } } #endregion protected override void Dispose(bool disposeManagedResources) { if (!_disposed) { if (disposeManagedResources) { Debug.Assert(EditorContext != null); EditorContext.PreHandleEvent -= new HtmlEditDesignerEventHandler(EditorContext_PreHandleEvent); EditorContext.CommandKey -= new KeyEventHandler(EditorContext_CommandKey); EditorContext.KeyDown -= new HtmlEventHandler(EditorContext_KeyDown); EditorContext.KeyUp -= new HtmlEventHandler(EditorContext_KeyUp); } _elementBehaviorAttached = false; _disposed = true; } base.Dispose(disposeManagedResources); } private bool _disposed; } public class EditableRegionFocusChangedEventArgs : EventArgs { public EditableRegionFocusChangedEventArgs(bool Editable) { this.IsFullyEditable = Editable; } public bool IsFullyEditable; } }
/* * 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.Data; using System.Reflection; using System.Threading; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MySQL { /// <summary> /// A MySQL Interface for the Grid Server /// </summary> public class MySQLGridData : GridDataBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MySQLManager m_database; private object m_dbLock = new object(); private string m_connectionString; override public void Initialise() { m_log.Info("[MySQLGridData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException (Name); } /// <summary> /// <para>Initialises Grid interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin</item> /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item> /// <item>Check for migration</item> /// </list> /// </para> /// </summary> /// <param name="connect">connect string.</param> override public void Initialise(string connect) { m_connectionString = connect; m_database = new MySQLManager(connect); // This actually does the roll forward assembly stuff Assembly assem = GetType().Assembly; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { Migration m = new Migration(dbcon, assem, "GridStore"); m.Update(); } } /// <summary> /// Shuts down the grid interface /// </summary> override public void Dispose() { } /// <summary> /// Returns the plugin name /// </summary> /// <returns>Plugin name</returns> override public string Name { get { return "MySql OpenGridData"; } } /// <summary> /// Returns the plugin version /// </summary> /// <returns>Plugin version</returns> override public string Version { get { return "0.1"; } } /// <summary> /// Returns all the specified region profiles within coordates -- coordinates are inclusive /// </summary> /// <param name="xmin">Minimum X coordinate</param> /// <param name="ymin">Minimum Y coordinate</param> /// <param name="xmax">Maximum X coordinate</param> /// <param name="ymax">Maximum Y coordinate</param> /// <returns>Array of sim profiles</returns> override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) { try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?xmin"] = xmin.ToString(); param["?ymin"] = ymin.ToString(); param["?xmax"] = xmax.ToString(); param["?ymax"] = ymax.ToString(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row; List<RegionProfileData> rows = new List<RegionProfileData>(); while ((row = m_database.readSimRow(reader)) != null) rows.Add(row); return rows.ToArray(); } } } } catch (Exception e) { m_log.Error(e.Message, e); return null; } } /// <summary> /// Returns up to maxNum profiles of regions that have a name starting with namePrefix /// </summary> /// <param name="name">The name to match against</param> /// <param name="maxNum">Maximum number of profiles to return</param> /// <returns>A list of sim profiles</returns> override public List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum) { try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?name"] = namePrefix + "%"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE regionName LIKE ?name", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row; List<RegionProfileData> rows = new List<RegionProfileData>(); while (rows.Count < maxNum && (row = m_database.readSimRow(reader)) != null) rows.Add(row); return rows; } } } } catch (Exception e) { m_log.Error(e.Message, e); return null; } } /// <summary> /// Returns a sim profile from it's location /// </summary> /// <param name="handle">Region location handle</param> /// <returns>Sim profile</returns> override public RegionProfileData GetProfileByHandle(ulong handle) { try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?handle"] = handle.ToString(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE regionHandle = ?handle", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row = m_database.readSimRow(reader); return row; } } } } catch (Exception e) { m_log.Error(e.Message, e); return null; } } /// <summary> /// Returns a sim profile from it's UUID /// </summary> /// <param name="uuid">The region UUID</param> /// <returns>The sim profile</returns> override public RegionProfileData GetProfileByUUID(UUID uuid) { try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?uuid"] = uuid.ToString(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE uuid = ?uuid", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row = m_database.readSimRow(reader); return row; } } } } catch (Exception e) { m_log.Error(e.Message, e); return null; } } /// <summary> /// Returns a sim profile from it's Region name string /// </summary> /// <returns>The sim profile</returns> override public RegionProfileData GetProfileByString(string regionName) { if (regionName.Length > 2) { try { Dictionary<string, object> param = new Dictionary<string, object>(); // Add % because this is a like query. param["?regionName"] = regionName + "%"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); // Order by statement will return shorter matches first. Only returns one record or no record. using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row = m_database.readSimRow(reader); return row; } } } } catch (Exception e) { m_log.Error(e.Message, e); return null; } } m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); return null; } /// <summary> /// Adds a new profile to the database /// </summary> /// <param name="profile">The profile to add</param> /// <returns>Successful?</returns> override public DataResponse StoreProfile(RegionProfileData profile) { try { if (m_database.insertRegion(profile)) return DataResponse.RESPONSE_OK; else return DataResponse.RESPONSE_ERROR; } catch { return DataResponse.RESPONSE_ERROR; } } /// <summary> /// Deletes a sim profile from the database /// </summary> /// <param name="uuid">the sim UUID</param> /// <returns>Successful?</returns> //public DataResponse DeleteProfile(RegionProfileData profile) override public DataResponse DeleteProfile(string uuid) { try { if (m_database.deleteRegion(uuid)) return DataResponse.RESPONSE_OK; else return DataResponse.RESPONSE_ERROR; } catch { return DataResponse.RESPONSE_ERROR; } } /// <summary> /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. /// </summary> /// <param name="uuid">The UUID of the challenger</param> /// <param name="handle">The attempted regionHandle of the challenger</param> /// <param name="authkey">The secret</param> /// <returns>Whether the secret and regionhandle match the database entry for UUID</returns> override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) { bool throwHissyFit = false; // Should be true by 1.0 if (throwHissyFit) throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); RegionProfileData data = GetProfileByUUID(uuid); return (handle == data.regionHandle && authkey == data.regionSecret); } /// <summary> /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region /// </summary> /// <remarks>This requires a security audit.</remarks> /// <param name="uuid"></param> /// <param name="handle"></param> /// <param name="authhash"></param> /// <param name="challenge"></param> /// <returns></returns> public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) { // SHA512Managed HashProvider = new SHA512Managed(); // Encoding TextProvider = new UTF8Encoding(); // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); // byte[] hash = HashProvider.ComputeHash(stream); return false; } /// <summary> /// Adds a location reservation /// </summary> /// <param name="x">x coordinate</param> /// <param name="y">y coordinate</param> /// <returns></returns> override public ReservationData GetReservationAtPoint(uint x, uint y) { try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?x"] = x.ToString(); param["?y"] = y.ToString(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", param)) { using (IDataReader reader = result.ExecuteReader()) { ReservationData row = m_database.readReservationRow(reader); return row; } } } } catch (Exception e) { m_log.Error(e.Message, e); return null; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using System.Linq; using System.Threading.Tasks; using Xunit; namespace StreamAnalytics.Tests { public class OutputTests : TestBase { [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_Blob() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); StorageAccount storageAcount = new StorageAccount() { AccountName = TestHelper.AccountName, AccountKey = TestHelper.AccountKey }; Output output = new Output() { Serialization = new CsvSerialization() { FieldDelimiter = ",", Encoding = Encoding.UTF8 }, Datasource = new BlobOutputDataSource() { StorageAccounts = new[] { storageAcount }, Container = TestHelper.Container, PathPattern = "{date}/{time}", DateFormat = "yyyy/MM/dd", TimeFormat = "HH" } }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); storageAcount.AccountKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Serialization = new CsvSerialization() { FieldDelimiter = "|", Encoding = Encoding.UTF8 }, Datasource = new BlobOutputDataSource() { Container = "differentContainer" } }; ((CsvSerialization)putResponse.Body.Serialization).FieldDelimiter = ((CsvSerialization)outputPatch.Serialization).FieldDelimiter; ((BlobOutputDataSource)putResponse.Body.Datasource).Container = ((BlobOutputDataSource)outputPatch.Datasource).Container; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_AzureTable() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); AzureTableOutputDataSource azureTable = new AzureTableOutputDataSource() { AccountName = TestHelper.AccountName, AccountKey = TestHelper.AccountKey, Table = TestHelper.AzureTableName, PartitionKey = "partitionKey", RowKey = "rowKey", ColumnsToRemove = new[] { "column1", "column2" }, BatchSize = 25 }; Output output = new Output() { Datasource = azureTable }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); azureTable.AccountKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Datasource = new AzureTableOutputDataSource() { PartitionKey = "differentPartitionKey" } }; ((AzureTableOutputDataSource)putResponse.Body.Datasource).PartitionKey = ((AzureTableOutputDataSource)outputPatch.Datasource).PartitionKey; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_EventHub() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); EventHubOutputDataSource eventHub = new EventHubOutputDataSource() { ServiceBusNamespace = TestHelper.ServiceBusNamespace, SharedAccessPolicyName = TestHelper.SharedAccessPolicyName, SharedAccessPolicyKey = TestHelper.SharedAccessPolicyKey, EventHubName = TestHelper.EventHubName, PartitionKey = "partitionKey" }; Output output = new Output() { Serialization = new JsonSerialization() { Encoding = Encoding.UTF8, Format = JsonOutputSerializationFormat.Array }, Datasource = eventHub }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); eventHub.SharedAccessPolicyKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Serialization = new JsonSerialization() { Encoding = Encoding.UTF8, Format = JsonOutputSerializationFormat.LineSeparated }, Datasource = new EventHubOutputDataSource() { PartitionKey = "differentPartitionKey" } }; ((JsonSerialization)putResponse.Body.Serialization).Format = ((JsonSerialization)outputPatch.Serialization).Format; ((EventHubOutputDataSource)putResponse.Body.Datasource).PartitionKey = ((EventHubOutputDataSource)outputPatch.Datasource).PartitionKey; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_AzureSqlDatabase() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); AzureSqlDatabaseOutputDataSource azureSqlDatabase = new AzureSqlDatabaseOutputDataSource() { Server = TestHelper.Server, Database = TestHelper.Database, User = TestHelper.User, Password = TestHelper.Password, Table = TestHelper.SqlTableName }; Output output = new Output() { Datasource = azureSqlDatabase }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); azureSqlDatabase.Password = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Datasource = new AzureSqlDatabaseOutputDataSource() { Table = "differentTable" } }; ((AzureSqlDatabaseOutputDataSource)putResponse.Body.Datasource).Table = ((AzureSqlDatabaseOutputDataSource)outputPatch.Datasource).Table; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_DocumentDb() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); DocumentDbOutputDataSource documentDb = new DocumentDbOutputDataSource() { AccountId = TestHelper.DocDbAccountId, AccountKey = TestHelper.DocDbAccountKey, Database = TestHelper.DocDbDatabase, PartitionKey = "key", CollectionNamePattern = "collection", DocumentId = "documentId" }; Output output = new Output() { Datasource = documentDb }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); documentDb.AccountKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Datasource = new DocumentDbOutputDataSource() { PartitionKey = "differentPartitionKey" } }; ((DocumentDbOutputDataSource)putResponse.Body.Datasource).PartitionKey = ((DocumentDbOutputDataSource)outputPatch.Datasource).PartitionKey; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_ServiceBusQueue() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); ServiceBusQueueOutputDataSource serviceBusQueue = new ServiceBusQueueOutputDataSource() { ServiceBusNamespace = TestHelper.ServiceBusNamespace, SharedAccessPolicyName = TestHelper.SharedAccessPolicyName, SharedAccessPolicyKey = TestHelper.SharedAccessPolicyKey, QueueName = TestHelper.QueueName, PropertyColumns = new[] { "column1", "column2" } }; Output output = new Output() { Serialization = new AvroSerialization(), Datasource = serviceBusQueue }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); serviceBusQueue.SharedAccessPolicyKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Serialization = new JsonSerialization() { Encoding = Encoding.UTF8, Format = JsonOutputSerializationFormat.LineSeparated }, Datasource = new ServiceBusQueueOutputDataSource() { QueueName = "differentQueueName" } }; putResponse.Body.Serialization = outputPatch.Serialization; ((ServiceBusQueueOutputDataSource)putResponse.Body.Datasource).QueueName = ((ServiceBusQueueOutputDataSource)outputPatch.Datasource).QueueName; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact(Skip = "ReRecord due to CR change")] public async Task OutputOperationsTest_ServiceBusTopic() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); ServiceBusTopicOutputDataSource serviceBusTopic = new ServiceBusTopicOutputDataSource() { ServiceBusNamespace = TestHelper.ServiceBusNamespace, SharedAccessPolicyName = TestHelper.SharedAccessPolicyName, SharedAccessPolicyKey = TestHelper.SharedAccessPolicyKey, TopicName = TestHelper.TopicName, PropertyColumns = new[] { "column1", "column2" } }; Output output = new Output() { Serialization = new CsvSerialization() { FieldDelimiter = ",", Encoding = Encoding.UTF8 }, Datasource = serviceBusTopic }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); serviceBusTopic.SharedAccessPolicyKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH output var outputPatch = new Output() { Serialization = new CsvSerialization() { FieldDelimiter = "|", Encoding = Encoding.UTF8 }, Datasource = new ServiceBusTopicOutputDataSource() { TopicName = "differentTopicName" } }; ((CsvSerialization)putResponse.Body.Serialization).FieldDelimiter = ((CsvSerialization)outputPatch.Serialization).FieldDelimiter; ((ServiceBusTopicOutputDataSource)putResponse.Body.Datasource).TopicName = ((ServiceBusTopicOutputDataSource)outputPatch.Datasource).TopicName; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact] public async Task OutputOperationsTest_PowerBI() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); PowerBIOutputDataSource powerBI = new PowerBIOutputDataSource() { RefreshToken = "someRefreshToken==", TokenUserPrincipalName = "bobsmith@contoso.com", TokenUserDisplayName = "Bob Smith", Dataset = "someDataset", Table = "someTable", GroupId = "ac40305e-3e8d-43ac-8161-c33799f43e95", GroupName = "MyPowerBIGroup" }; Output output = new Output() { Datasource = powerBI }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); powerBI.RefreshToken = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestFailed", testResult.Status); Assert.NotNull(testResult.Error); Assert.Contains("either expired or is invalid", testResult.Error.Message); // PATCH output var outputPatch = new Output() { Datasource = new PowerBIOutputDataSource() { Dataset = "differentDataset" } }; ((PowerBIOutputDataSource)putResponse.Body.Datasource).Dataset = ((PowerBIOutputDataSource)outputPatch.Datasource).Dataset; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } [Fact] public async Task OutputOperationsTest_AzureDataLakeStore() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string outputName = TestUtilities.GenerateName("output"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedOutputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.OutputsResourceType); string expectedOutputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.OutputsResourceType, outputName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); AzureDataLakeStoreOutputDataSource azureDataLakeStore = new AzureDataLakeStoreOutputDataSource() { RefreshToken = "someRefreshToken==", TokenUserPrincipalName = "bobsmith@contoso.com", TokenUserDisplayName = "Bob Smith", AccountName = "someaccount", TenantId = "cea4e98b-c798-49e7-8c40-4a2b3beb47dd", FilePathPrefix = "{date}/{time}", DateFormat = "yyyy/MM/dd", TimeFormat = "HH" }; Output output = new Output() { Serialization = new CsvSerialization() { FieldDelimiter = ",", Encoding = Encoding.UTF8 }, Datasource = azureDataLakeStore }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // PUT output var putResponse = await streamAnalyticsManagementClient.Outputs.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName); azureDataLakeStore.RefreshToken = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateOutput(output, putResponse.Body, false); Assert.Equal(expectedOutputResourceId, putResponse.Body.Id); Assert.Equal(outputName, putResponse.Body.Name); Assert.Equal(expectedOutputType, putResponse.Body.Type); // Verify GET request returns expected output var getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Output var testResult = streamAnalyticsManagementClient.Outputs.Test(resourceGroupName, jobName, outputName); Assert.Equal("TestFailed", testResult.Status); Assert.NotNull(testResult.Error); Assert.Contains("either expired or is invalid", testResult.Error.Message); // PATCH output var outputPatch = new Output() { Serialization = new CsvSerialization() { FieldDelimiter = "|", Encoding = Encoding.UTF8 }, Datasource = new AzureDataLakeStoreOutputDataSource() { AccountName = "differentaccount" } }; ((CsvSerialization)putResponse.Body.Serialization).FieldDelimiter = ((CsvSerialization)outputPatch.Serialization).FieldDelimiter; ((AzureDataLakeStoreOutputDataSource)putResponse.Body.Datasource).AccountName = ((AzureDataLakeStoreOutputDataSource)outputPatch.Datasource).AccountName; var patchResponse = await streamAnalyticsManagementClient.Outputs.UpdateWithHttpMessagesAsync(outputPatch, resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET output to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Outputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName); ValidationHelper.ValidateOutput(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List output and verify that the output shows up in the list var listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateOutput(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Etag); // Get job with output expanded and verify that the output shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Single(getJobResponse.Outputs); ValidationHelper.ValidateOutput(putResponse.Body, getJobResponse.Outputs.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Outputs.Single().Etag); // Delete output streamAnalyticsManagementClient.Outputs.Delete(resourceGroupName, jobName, outputName); // Verify that list operation returns an empty list after deleting the output listResult = streamAnalyticsManagementClient.Outputs.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with output expanded and verify that there are no outputs after deleting the output getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "outputs"); Assert.Empty(getJobResponse.Outputs); } } } }