context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Machine.Fakes.Sdk { /// <summary> /// Helper class which contains all the helper method needed for reflection. /// </summary> public static class ReflectionExtensions { /// <summary> /// Checks whether the supplied type is one of the machine.fakes /// inline constraint types. /// </summary> /// <param name = "type"> /// Specifies the type to check. /// </param> /// <returns> /// <c>true</c> if it's one of the constraint types. Otherwise not. /// </returns> public static bool IsMFakesConstraint(this Type type) { return type == typeof(Param) || type.ClosesGenericParamType(); } /// <summary> /// Checks whether the supplied type closes the <see cref = "Param{T}" /> class. /// </summary> /// <param name = "type"> /// Specifies the type to be checked. /// </param> /// <returns> /// <c>true</c> if the type closes the <see cref = "Param{T}" /> type. Otherwise <c>false</c>. /// </returns> public static bool ClosesGenericParamType(this Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Param<>); } /// <summary> /// Gets the first generic type argument of the specified type. /// </summary> /// <param name = "type"> /// Specifies the type to extract the type argument from. /// </param> /// <returns> /// The extracted type. /// </returns> public static Type GetFirstTypeArgument(this Type type) { if (!type.GetTypeInfo().IsGenericType) { throw new ArgumentException("Specified type is not a generic type", "type"); } return type.GetGenericArguments()[0]; } /// <summary> /// Gets the first generic type argument of the specified type. /// </summary> /// <param name = "method"> /// Specifies the method to extract the type argument from. /// </param> /// <returns> /// The extracted type. /// </returns> public static Type GetFirstTypeArgument(this MethodInfo method) { if (!method.IsGenericMethod) { throw new ArgumentException("Specified method is not a generic method", "method"); } return method.GetGenericArguments()[0]; } /// <summary> /// Creates a <see cref = "MemberExpression" /> on a public instance property. /// </summary> /// <param name = "targetType"> /// Specifies the target type. /// </param> /// <param name = "property"> /// Specifies the name of the property to be accessed. /// </param> /// <param name = "instanceExpression"> /// Specifies an instance via an <see cref = "Expression" />. /// </param> /// <returns> /// The created <see cref = "MemberExpression" />. /// </returns> public static MemberExpression MakePropertyAccess(this Type targetType, string property, Expression instanceExpression) { Guard.AgainstArgumentNull(targetType, "targetType"); Guard.AgainstArgumentNull(property, "property"); Guard.AgainstArgumentNull(instanceExpression, "instanceExpression"); return MakePropertyAccess( targetType, property, BindingFlags.Public | BindingFlags.Instance, instanceExpression); } /// <summary> /// Creates a <see cref = "MemberExpression" /> on a public static property. /// </summary> /// <param name = "targetType"> /// Specifies the target type. /// </param> /// <param name = "property"> /// Specifies the name of the property to be accessed. /// </param> /// <returns> /// The created <see cref = "MemberExpression" />. /// </returns> public static MemberExpression MakeStaticPropertyAccess(this Type targetType, string property) { Guard.AgainstArgumentNull(targetType, "targetType"); Guard.AgainstArgumentNull(property, "property"); return MakePropertyAccess( targetType, property, BindingFlags.Public | BindingFlags.Static, null); } /// <summary> /// Get all field values of the type specified by <typeparamref name = "TFieldType" />. /// </summary> /// <typeparam name = "TFieldType"> /// Specifies the field type. /// </typeparam> /// <param name = "instance"> /// Specifies the instance to extract the field values from. /// </param> /// <returns> /// A collection of all field values of the specified type. /// </returns> public static IEnumerable<TFieldType> GetFieldValues<TFieldType>(this object instance) { Guard.AgainstArgumentNull(instance, "instance"); var fieldValues = instance .GetType() .GetAllFields() .Where(field => field.FieldType == typeof(TFieldType)) .Select(field => (TFieldType)field.GetValue(instance)) .Where(value => !Equals(value, null)); return fieldValues; } /// <summary> /// Resets the references in the instance specified by <paramref name="instance"/>. /// </summary> /// <param name="instance">The instance.</param> public static void ResetReferences(this object instance) { var fields = instance .GetType() .GetAllFields() .Where(x => !x.FieldType.GetTypeInfo().IsValueType); fields.Each(x => x.SetValue(instance, null)); } static IEnumerable<FieldInfo> GetAllFields(this Type type) { return type .GetFields( BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy) .Where(t => !t.Name.StartsWith("CS$")); } static MemberExpression MakePropertyAccess(this Type targetType, string property, BindingFlags flags, Expression instanceExpression) { Guard.AgainstArgumentNull(targetType, "targetType"); Guard.AgainstArgumentNull(property, "property"); var targetProperty = targetType.GetProperty(property, flags); if (targetProperty == null) { throw new InvalidOperationException( string.Format("Unable to find target property {0} on instance of target type {1}", property, targetType.FullName)); } return Expression.MakeMemberAccess(instanceExpression, targetProperty); } } }
/* ==================================================================== 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 * POI Version: 3.8 beta4 * Date: 2012-02-15 * * ==============================================================*/ namespace NPOI.HSSF.Record { using System; using System.IO; using System.Reflection; using System.Collections; using System.Collections.Generic; using NPOI.HSSF.Record.Chart; using NPOI.HSSF.Record.PivotTable; using NPOI.HSSF.Record.AutoFilter; using NPOI.Util; using System.Globalization; /** * Title: Record Factory * Description: Takes a stream and outputs an array of Record objects. * * @deprecated use {@link org.apache.poi.hssf.eventmodel.EventRecordFactory} instead * @see org.apache.poi.hssf.eventmodel.EventRecordFactory * @author Andrew C. Oliver (acoliver at apache dot org) * @author Marc Johnson (mjohnson at apache dot org) * @author Glen Stampoultzis (glens at apache.org) * @author Csaba Nagy (ncsaba at yahoo dot com) */ public class RecordFactory { private static int NUM_RECORDS = 512; private static Type[] recordClasses; #region inner Record Creater private interface I_RecordCreator { Record Create(RecordInputStream in1); Type GetRecordClass(); } private class ReflectionConstructorRecordCreator : I_RecordCreator { private ConstructorInfo _c; public ReflectionConstructorRecordCreator(ConstructorInfo c) { _c = c; } public Record Create(RecordInputStream in1) { Object[] args = { in1 }; try { return (Record)_c.Invoke(args); } catch (Exception e) { throw new RecordFormatException("Unable to construct record instance", e.InnerException); } } public Type GetRecordClass() { return _c.DeclaringType; } } /** * A "create" method is used instead of the usual constructor if the created record might * be of a different class to the declaring class. */ private class ReflectionMethodRecordCreator : I_RecordCreator { private MethodInfo _m; public ReflectionMethodRecordCreator(MethodInfo m) { _m = m; } public Record Create(RecordInputStream in1) { Object[] args = { in1 }; try { return (Record)_m.Invoke(null, args); } catch (Exception e) { throw new RecordFormatException("Unable to construct record instance", e.InnerException); } } public Type GetRecordClass() { return _m.DeclaringType; } } #endregion private static Type[] CONSTRUCTOR_ARGS = new Type[] { typeof(RecordInputStream), }; static RecordFactory() { recordClasses = new Type[] { typeof(ArrayRecord), typeof(AutoFilterInfoRecord), typeof(BackupRecord), typeof(BlankRecord), typeof(BOFRecord), typeof(BookBoolRecord), typeof(BoolErrRecord), typeof(BottomMarginRecord), typeof(BoundSheetRecord), typeof(CalcCountRecord), typeof(CalcModeRecord), typeof(CFHeaderRecord), typeof(CFRuleRecord), typeof(ChartRecord), typeof(AlRunsRecord), //typeof(CodeNameRecord), typeof(CodepageRecord), typeof(ColumnInfoRecord), typeof(ContinueRecord), typeof(CountryRecord), typeof(CRNCountRecord), typeof(CRNRecord), typeof(DateWindow1904Record), typeof(DBCellRecord), typeof(DConRefRecord), typeof(DefaultColWidthRecord), typeof(DefaultRowHeightRecord), typeof(DeltaRecord), typeof(DimensionsRecord), typeof(DrawingGroupRecord), typeof(DrawingRecord), typeof(DrawingSelectionRecord), typeof(DSFRecord), typeof(DVALRecord), typeof(DVRecord), typeof(EOFRecord), typeof(ExtendedFormatRecord), typeof(ExternalNameRecord), typeof(ExternSheetRecord), typeof(ExtSSTRecord), typeof(FilePassRecord), typeof(FileSharingRecord), typeof(FnGroupCountRecord), typeof(FontRecord), typeof(FooterRecord), typeof(FormatRecord), typeof(FormulaRecord), typeof(GridsetRecord), typeof(GutsRecord), typeof(HCenterRecord), typeof(HeaderRecord), typeof(HeaderFooterRecord), typeof(HideObjRecord), typeof(HorizontalPageBreakRecord), typeof(HyperlinkRecord), typeof(IndexRecord), typeof(InterfaceEndRecord), typeof(InterfaceHdrRecord), typeof(IterationRecord), typeof(LabelRecord), typeof(LabelSSTRecord), typeof(LeftMarginRecord), typeof(MergeCellsRecord), typeof(MMSRecord), typeof(MulBlankRecord), typeof(MulRKRecord), typeof(NameRecord), typeof(NameCommentRecord), typeof(NoteRecord), typeof(NumberRecord), typeof(ObjectProtectRecord), typeof(ObjRecord), typeof(PaletteRecord), typeof(PaneRecord), typeof(PasswordRecord), typeof(PasswordRev4Record), typeof(PrecisionRecord), typeof(PrintGridlinesRecord), typeof(PrintHeadersRecord), typeof(PrintSetupRecord), typeof(PrintSizeRecord), typeof(ProtectionRev4Record), typeof(ProtectRecord), typeof(RecalcIdRecord), typeof(RefModeRecord), typeof(RefreshAllRecord), typeof(RightMarginRecord), typeof(RKRecord), typeof(RowRecord), typeof(SaveRecalcRecord), typeof(ScenarioProtectRecord), typeof(SCLRecord), typeof(SelectionRecord), typeof(SeriesRecord), typeof(SeriesTextRecord), typeof(SharedFormulaRecord), typeof(SSTRecord), typeof(StringRecord), typeof(StyleRecord), typeof(SupBookRecord), typeof(TabIdRecord), typeof(TableRecord), typeof(TableStylesRecord), typeof(TextObjectRecord), typeof(TopMarginRecord), typeof(UncalcedRecord), typeof(UseSelFSRecord), typeof(UserSViewBegin), typeof(UserSViewEnd), typeof(ValueRangeRecord), typeof(VCenterRecord), typeof(VerticalPageBreakRecord), typeof(WindowOneRecord), typeof(WindowProtectRecord), typeof(WindowTwoRecord), typeof(WriteAccessRecord), typeof(WriteProtectRecord), typeof(WSBoolRecord), typeof(SheetExtRecord), // chart records //typeof(AlRunsRecord), typeof(AreaFormatRecord), typeof(AreaRecord), typeof(AttachedLabelRecord), typeof(AxcExtRecord), typeof(AxisLineRecord), typeof(AxisParentRecord), typeof(AxisRecord), typeof(AxesUsedRecord), typeof(BarRecord), typeof(BeginRecord), typeof(BopPopCustomRecord), typeof(BopPopRecord), typeof(BRAIRecord), typeof(CatLabRecord), typeof(CatSerRangeRecord), typeof(Chart3DBarShapeRecord), typeof(Chart3dRecord), typeof(ChartEndObjectRecord), typeof(ChartFormatRecord), typeof(ChartFRTInfoRecord), //typeof(ChartRecord), typeof(ChartStartObjectRecord), typeof(CrtLayout12ARecord), typeof(CrtLayout12Record), typeof(CrtLineRecord), typeof(CrtLinkRecord), typeof(CrtMlFrtContinueRecord), typeof(CrtMlFrtRecord), typeof(DataFormatRecord), typeof(DataLabExtContentsRecord), typeof(DataLabExtRecord), typeof(DatRecord), typeof(DefaultTextRecord), typeof(DropBarRecord), typeof(EndBlockRecord), typeof(EndRecord), typeof(Fbi2Record), typeof(FbiRecord), typeof(FontXRecord), typeof(FrameRecord), typeof(FrtFontListRecord), typeof(GelFrameRecord), typeof(IFmtRecordRecord), typeof(LegendExceptionRecord), typeof(LegendRecord), typeof(LineFormatRecord), typeof(MarkerFormatRecord), typeof(ObjectLinkRecord), typeof(PicFRecord), typeof(PieFormatRecord), typeof(PieRecord), typeof(PlotAreaRecord), typeof(PlotGrowthRecord), typeof(PosRecord), typeof(RadarAreaRecord), typeof(RadarRecord), typeof(RichTextStreamRecord), typeof(ScatterRecord), typeof(SerAuxErrBarRecord), typeof(SerAuxTrendRecord), typeof(SerFmtRecord), typeof(SeriesIndexRecord), typeof(SeriesListRecord), //typeof(SeriesRecord), //typeof(SeriesTextRecord), //typeof(SeriesToChartGroupRecord), typeof(SerParentRecord), typeof(SerToCrtRecord), typeof(ShapePropsStreamRecord), typeof(ShtPropsRecord), typeof(StartBlockRecord), typeof(SurfRecord), typeof(TextPropsStreamRecord), typeof(TextRecord), typeof(TickRecord), typeof(UnitsRecord), //typeof(ValueRangeRecord), typeof(YMultRecord), //typeof(BeginRecord), //typeof(ChartFRTInfoRecord), //typeof(StartBlockRecord), //typeof(EndBlockRecord), //typeof(ChartStartObjectRecord), //typeof(ChartEndObjectRecord), //typeof(CatLabRecord), //typeof(EndRecord), //typeof(PrintSizeRecord), //typeof(AreaFormatRecord), //typeof(AreaRecord), //typeof(AxisLineRecord), //typeof(AxcExtRecord), //typeof(AxisParentRecord), //typeof(AxisRecord), //typeof(Chart3DBarShapeRecord), //typeof(CrtLinkRecord), //typeof(AxisUsedRecord), //typeof(BarRecord), //typeof(CatSerRangeRecord), //typeof(DataFormatRecord), //typeof(DataLabExtRecord), //typeof(DefaultTextRecord), //typeof(FrameRecord), //typeof(LegendRecord), //typeof(FbiRecord), //typeof(FontXRecord), //typeof(LineFormatRecord), //typeof(BRAIRecord), //typeof(IFmtRecordRecord), //typeof(ObjectLinkRecord), //typeof(PlotAreaRecord), //typeof(PlotGrowthRecord), //typeof(PosRecord), //typeof(SCLRecord), //typeof(SerToCrtRecord), ////typeof(SeriesIndexRecord), //typeof(AttachedLabelRecord), //typeof(SeriesListRecord), ////typeof(SeriesToChartGroupRecord), //typeof(ShtPropsRecord), //typeof(TextRecord), //typeof(TickRecord), //typeof(UnitsRecord), //typeof(CrtLayout12Record), //typeof(Chart3dRecord), //typeof(PieRecord), //typeof(PieFormatRecord), //typeof(CrtLayout12ARecord), //typeof(MarkerFormatRecord), //typeof(ChartFormatRecord), //typeof(SeriesIndexRecord), //typeof(GelFrameRecord), //typeof(PicFRecord), //typeof(CrtMlFrtRecord), //typeof(CrtMlFrtContinueRecord), //typeof(ShapePropsStreamRecord), //end // pivot table records typeof(DataItemRecord), typeof(ExtendedPivotTableViewFieldsRecord), typeof(PageItemRecord), typeof(StreamIDRecord), typeof(ViewDefinitionRecord), typeof(ViewFieldsRecord), typeof(ViewSourceRecord), //autofilter typeof(AutoFilterRecord), typeof(FilterModeRecord), typeof(Excel9FileRecord) }; _recordCreatorsById = RecordsToMap(recordClasses); } //private static Hashtable recordsMap; /** * cache of the recordsToMap(); */ private static Dictionary<short, I_RecordCreator> _recordCreatorsById = null;//RecordsToMap(recordClasses); private static short[] _allKnownRecordSIDs; /** * Debug / diagnosis method<br/> * Gets the POI implementation class for a given <tt>sid</tt>. Only a subset of the any BIFF * records are actually interpreted by POI. A few others are known but not interpreted * (see {@link UnknownRecord#getBiffName(int)}). * @return the POI implementation class for the specified record <tt>sid</tt>. * <code>null</code> if the specified record is not interpreted by POI. */ public static Type GetRecordClass(int sid) { I_RecordCreator rc = _recordCreatorsById[(short)sid]; if (rc == null) { return null; } return rc.GetRecordClass(); } /** * Changes the default capacity (10000) to handle larger files */ public static void SetCapacity(int capacity) { NUM_RECORDS = capacity; } /** * Create an array of records from an input stream * * @param in the InputStream from which the records will be * obtained * * @return an array of Records Created from the InputStream * * @exception RecordFormatException on error Processing the * InputStream */ public static List<Record> CreateRecords(Stream in1) { List<Record> records = new List<Record>(NUM_RECORDS); RecordFactoryInputStream recStream = new RecordFactoryInputStream(in1, true); Record record; while ((record = recStream.NextRecord()) != null) { records.Add(record); } return records; } [Obsolete] private static void AddAll(List<Record> destList, Record[] srcRecs) { for (int i = 0; i < srcRecs.Length; i++) { destList.Add(srcRecs[i]); } } public static Record[] CreateRecord(RecordInputStream in1) { Record record = CreateSingleRecord(in1); if (record is DBCellRecord) { // Not needed by POI. Regenerated from scratch by POI when spreadsheet is written return new Record[] { null, }; } if (record is RKRecord) { return new Record[] { ConvertToNumberRecord((RKRecord)record), }; } if (record is MulRKRecord) { return ConvertRKRecords((MulRKRecord)record); } return new Record[] { record, }; } /** * Converts a {@link MulBlankRecord} into an equivalent array of {@link BlankRecord}s */ public static BlankRecord[] ConvertBlankRecords(MulBlankRecord mbk) { BlankRecord[] mulRecs = new BlankRecord[mbk.NumColumns]; for (int k = 0; k < mbk.NumColumns; k++) { BlankRecord br = new BlankRecord(); br.Column = k + mbk.FirstColumn; br.Row = mbk.Row; br.XFIndex = mbk.GetXFAt(k); mulRecs[k] = br; } return mulRecs; } public static Record CreateSingleRecord(RecordInputStream in1) { if (_recordCreatorsById.ContainsKey(in1.Sid)) { I_RecordCreator constructor = _recordCreatorsById[in1.Sid]; return constructor.Create(in1); } else { return new UnknownRecord(in1); } } /// <summary> /// RK record is a slightly smaller alternative to NumberRecord /// POI likes NumberRecord better /// </summary> /// <param name="rk">The rk.</param> /// <returns></returns> public static NumberRecord ConvertToNumberRecord(RKRecord rk) { NumberRecord num = new NumberRecord(); num.Column = (rk.Column); num.Row = (rk.Row); num.XFIndex = (rk.XFIndex); num.Value = (rk.RKNumber); return num; } /// <summary> /// Converts a MulRKRecord into an equivalent array of NumberRecords /// </summary> /// <param name="mrk">The MRK.</param> /// <returns></returns> public static NumberRecord[] ConvertRKRecords(MulRKRecord mrk) { NumberRecord[] mulRecs = new NumberRecord[mrk.NumColumns]; for (int k = 0; k < mrk.NumColumns; k++) { NumberRecord nr = new NumberRecord(); nr.Column = ((short)(k + mrk.FirstColumn)); nr.Row = (mrk.Row); nr.XFIndex = (mrk.GetXFAt(k)); nr.Value = (mrk.GetRKNumberAt(k)); mulRecs[k] = nr; } return mulRecs; } public static short[] GetAllKnownRecordSIDs() { if (_allKnownRecordSIDs == null) { short[] results = new short[_recordCreatorsById.Count]; int i = 0; foreach (KeyValuePair<short, I_RecordCreator> kv in _recordCreatorsById) { results[i++] = kv.Key; } Array.Sort(results); _allKnownRecordSIDs = results; } return (short[])_allKnownRecordSIDs.Clone(); } private static Dictionary<short, I_RecordCreator> RecordsToMap(Type[] records) { Dictionary<short, I_RecordCreator> result = new Dictionary<short, I_RecordCreator>(); Hashtable uniqueRecClasses = new Hashtable(records.Length * 3 / 2); for (int i = 0; i < records.Length; i++) { Type recClass = records[i]; if (!typeof(Record).IsAssignableFrom(recClass)) { throw new Exception("Invalid record sub-class (" + recClass.Name + ")"); } if (recClass.IsAbstract) { throw new Exception("Invalid record class (" + recClass.Name + ") - must not be abstract"); } if (uniqueRecClasses.Contains(recClass)) { throw new Exception("duplicate record class (" + recClass.Name + ")"); } uniqueRecClasses.Add(recClass, recClass); short sid = 0; try { sid = (short)recClass.GetField("sid").GetValue(null); } catch (Exception ArgumentException) { throw new RecordFormatException( "Unable to determine record types", ArgumentException); } if (result.ContainsKey(sid)) { Type prevClass = result[sid].GetRecordClass(); throw new RuntimeException("duplicate record sid 0x" + sid.ToString("X", CultureInfo.CurrentCulture) + " for classes (" + recClass.Name + ") and (" + prevClass.Name + ")"); } result[sid] = GetRecordCreator(recClass); } return result; } [Obsolete] private static void CheckZeros(Stream in1, int avail) { int count = 0; while (true) { int b = (int)in1.ReadByte(); if (b < 0) { break; } if (b != 0) { Console.Error.WriteLine(HexDump.ByteToHex(b)); } count++; } if (avail != count) { Console.Error.WriteLine("avail!=count (" + avail + "!=" + count + ")."); } } private static I_RecordCreator GetRecordCreator(Type recClass) { try { ConstructorInfo constructor; constructor = recClass.GetConstructor(CONSTRUCTOR_ARGS); if (constructor != null) return new ReflectionConstructorRecordCreator(constructor); } catch (Exception) { // fall through and look for other construction methods } try { MethodInfo m = recClass.GetMethod("Create", CONSTRUCTOR_ARGS); return new ReflectionMethodRecordCreator(m); } catch (Exception) { throw new RuntimeException("Failed to find constructor or create method for (" + recClass.Name + ")."); } } } }
// 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.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Internal.Cryptography; using Internal.Cryptography.Pal; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate2 : X509Certificate { public X509Certificate2() : base() { } public X509Certificate2(byte[] rawData) : base(rawData) { } public X509Certificate2(byte[] rawData, string password) : base(rawData, password) { } public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags) { } public X509Certificate2(IntPtr handle) : base(handle) { } internal X509Certificate2(ICertificatePal pal) : base(pal) { } public X509Certificate2(string fileName) : base(fileName) { } public X509Certificate2(string fileName, string password) : base(fileName, password) { } public X509Certificate2(string fileName, string password, X509KeyStorageFlags keyStorageFlags) : base(fileName, password, keyStorageFlags) { } public bool Archived { get { ThrowIfInvalid(); return Pal.Archived; } set { ThrowIfInvalid(); Pal.Archived = value; } } public X509ExtensionCollection Extensions { get { ThrowIfInvalid(); X509ExtensionCollection extensions = _lazyExtensions; if (extensions == null) { extensions = new X509ExtensionCollection(); foreach (X509Extension extension in Pal.Extensions) { X509Extension customExtension = CreateCustomExtensionIfAny(extension.Oid); if (customExtension == null) { extensions.Add(extension); } else { customExtension.CopyFrom(extension); extensions.Add(customExtension); } } _lazyExtensions = extensions; } return extensions; } } public string FriendlyName { get { ThrowIfInvalid(); return Pal.FriendlyName; } set { ThrowIfInvalid(); Pal.FriendlyName = value; } } public bool HasPrivateKey { get { ThrowIfInvalid(); return Pal.HasPrivateKey; } } public X500DistinguishedName IssuerName { get { ThrowIfInvalid(); X500DistinguishedName issuerName = _lazyIssuer; if (issuerName == null) issuerName = _lazyIssuer = Pal.IssuerName; return issuerName; } } public DateTime NotAfter { get { return GetNotAfter(); } } public DateTime NotBefore { get { return GetNotBefore(); } } public PublicKey PublicKey { get { ThrowIfInvalid(); PublicKey publicKey = _lazyPublicKey; if (publicKey == null) { string keyAlgorithmOid = GetKeyAlgorithm(); byte[] parameters = GetKeyAlgorithmParameters(); byte[] keyValue = GetPublicKey(); Oid oid = new Oid(keyAlgorithmOid); publicKey = _lazyPublicKey = new PublicKey(oid, new AsnEncodedData(oid, parameters), new AsnEncodedData(oid, keyValue)); } return publicKey; } } public byte[] RawData { get { ThrowIfInvalid(); byte[] rawData = _lazyRawData; if (rawData == null) { rawData = _lazyRawData = Pal.RawData; } return rawData.CloneByteArray(); } } public string SerialNumber { get { byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); return serialNumber.ToHexStringUpper(); } } public Oid SignatureAlgorithm { get { ThrowIfInvalid(); Oid signatureAlgorithm = _lazySignatureAlgorithm; if (signatureAlgorithm == null) { string oidValue = Pal.SignatureAlgorithm; signatureAlgorithm = _lazySignatureAlgorithm = Oid.FromOidValue(oidValue, OidGroup.SignatureAlgorithm); } return signatureAlgorithm; } } public X500DistinguishedName SubjectName { get { ThrowIfInvalid(); X500DistinguishedName subjectName = _lazySubjectName; if (subjectName == null) subjectName = _lazySubjectName = Pal.SubjectName; return subjectName; } } public string Thumbprint { get { byte[] thumbPrint = GetCertHash(); return thumbPrint.ToHexStringUpper(); } } public int Version { get { ThrowIfInvalid(); int version = _lazyVersion; if (version == 0) version = _lazyVersion = Pal.Version; return version; } } public static X509ContentType GetCertContentType(byte[] rawData) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, "rawData"); return X509Pal.Instance.GetCertContentType(rawData); } public static X509ContentType GetCertContentType(string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); // Desktop compat: The desktop CLR expands the filename to a full path for the purpose of performing a CAS permission check. While CAS is not present here, // we still need to call GetFullPath() so we get the same exception behavior if the fileName is bad. string fullPath = Path.GetFullPath(fileName); return X509Pal.Instance.GetCertContentType(fileName); } public string GetNameInfo(X509NameType nameType, bool forIssuer) { return Pal.GetNameInfo(nameType, forIssuer); } public override string ToString() { return base.ToString(fVerbose: true); } public override string ToString(bool verbose) { if (verbose == false || Pal == null) return ToString(); StringBuilder sb = new StringBuilder(); // Version sb.AppendLine("[Version]"); sb.Append(" V"); sb.Append(Version); // Subject sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Subject]"); sb.Append(" "); sb.Append(SubjectName.Name); string simpleName = GetNameInfo(X509NameType.SimpleName, false); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } string emailName = GetNameInfo(X509NameType.EmailName, false); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } string upnName = GetNameInfo(X509NameType.UpnName, false); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } string dnsName = GetNameInfo(X509NameType.DnsName, false); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Issuer sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.Append(IssuerName.Name); simpleName = GetNameInfo(X509NameType.SimpleName, true); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } emailName = GetNameInfo(X509NameType.EmailName, true); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } upnName = GetNameInfo(X509NameType.UpnName, true); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } dnsName = GetNameInfo(X509NameType.DnsName, true); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Serial Number sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); sb.AppendLine(SerialNumber); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(NotBefore)); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(NotAfter)); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.AppendLine(Thumbprint); // Signature Algorithm sb.AppendLine(); sb.AppendLine("[Signature Algorithm]"); sb.Append(" "); sb.Append(SignatureAlgorithm.FriendlyName); sb.Append('('); sb.Append(SignatureAlgorithm.Value); sb.AppendLine(")"); // Public Key sb.AppendLine(); sb.Append("[Public Key]"); // It could throw if it's some user-defined CryptoServiceProvider try { PublicKey pubKey = PublicKey; sb.AppendLine(); sb.Append(" "); sb.Append("Algorithm: "); sb.Append(pubKey.Oid.FriendlyName); // So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys try { sb.AppendLine(); sb.Append(" "); sb.Append("Length: "); using (RSA pubRsa = this.GetRSAPublicKey()) { if (pubRsa != null) { sb.Append(pubRsa.KeySize); } } } catch (NotSupportedException) { } sb.AppendLine(); sb.Append(" "); sb.Append("Key Blob: "); sb.AppendLine(pubKey.EncodedKeyValue.Format(true)); sb.Append(" "); sb.Append("Parameters: "); sb.Append(pubKey.EncodedParameters.Format(true)); } catch (CryptographicException) { } // Private key Pal.AppendPrivateKeyInfo(sb); // Extensions X509ExtensionCollection extensions = Extensions; if (extensions.Count > 0) { sb.AppendLine(); sb.AppendLine(); sb.Append("[Extensions]"); foreach (X509Extension extension in extensions) { try { sb.AppendLine(); sb.Append("* "); sb.Append(extension.Oid.FriendlyName); sb.Append('('); sb.Append(extension.Oid.Value); sb.Append("):"); sb.AppendLine(); sb.Append(" "); sb.Append(extension.Format(true)); } catch (CryptographicException) { } } } sb.AppendLine(); return sb.ToString(); } private static X509Extension CreateCustomExtensionIfAny(Oid oid) { string oidValue = oid.Value; switch (oidValue) { case Oids.BasicConstraints: return X509Pal.Instance.SupportsLegacyBasicConstraintsExtension ? new X509BasicConstraintsExtension() : null; case Oids.BasicConstraints2: return new X509BasicConstraintsExtension(); case Oids.KeyUsage: return new X509KeyUsageExtension(); case Oids.EnhancedKeyUsage: return new X509EnhancedKeyUsageExtension(); case Oids.SubjectKeyIdentifier: return new X509SubjectKeyIdentifierExtension(); default: return null; } } private volatile byte[] _lazyRawData; private volatile Oid _lazySignatureAlgorithm; private volatile int _lazyVersion; private volatile X500DistinguishedName _lazySubjectName; private volatile X500DistinguishedName _lazyIssuer; private volatile PublicKey _lazyPublicKey; private volatile X509ExtensionCollection _lazyExtensions; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #define CONTRACTS_FULL using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; using System.Runtime.InteropServices; using System.Reflection; namespace PreInference { class StraightLineTests { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(s != null);")] public int StraightForwardNotNull(string s) { return s.Length; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((x + 2) > 0);")] [RegressionOutcome("Consider replacing the expression (x + 2) > 0 with an equivalent, yet not overflowing expression. Fix: x > (0 - 2)")] public void Simplification1(int x) { int z = x + 1; Contract.Assert(z + 1 > 0); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(x > 0);")] public void Simplification2(int x) { int z = x + 1; Contract.Assert(z - 1 > 0); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(x > 0);")] public void Simplification3(int x) { int z = x - 1; Contract.Assert(z + 1 > 0); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((x - 2) > 0);")] public void Simplification4(int x) { int z = x - 1; Contract.Assert(z - 1 > 0); } [RegressionOutcome("Contract.Requires(arr != null);")] [RegressionOutcome("Contract.Requires(2 < arr.Length);")] [ClousotRegressionTest] public void Redundant(byte[] arr) { arr[0] = 10; arr[2] = 123; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(arr != null);")] [RegressionOutcome("Contract.Requires(0 <= k);")] [RegressionOutcome("Contract.Requires((k + 2) < arr.Length);")] public void Redundant(byte[] arr, int k) { arr[k + 0] = 10; arr[k + 2] = 123; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(arr != null);")] [RegressionOutcome("Contract.Requires(0 <= k);")] [RegressionOutcome("Contract.Requires((k + 2) < arr.Length);")] [RegressionOutcome("Possible off-by one: did you meant indexing with k instead of k + 1?. Fix: k")] public void RedundantWithPostfixIncrement(byte[] arr, int k) { arr[k] = 1; var k1 = k + 1; arr[k1] = 123; var k2 = k1 + 1; arr[k2] = 2; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((k + 2) < s.Length);")] public void RedundantWithPreFixIncrementOfParameter(int k, string[] s) { Contract.Requires(s != null); Contract.Requires(k >= 0); s[k] = "1"; s[++k] = "2;"; s[++k] = "3"; } } public class ControlFlowInference { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((x <= 0 || s != null));")] public int Conditional(int x, string s) { if (x > 0) { return s.Length; } return x; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(obj != null);")] public void NotNull(int z, object obj) { if (z > 0) obj.GetHashCode(); obj.GetType(); } // we do not infer the precondition with this system as the propagations stops because of the local // Also no text fix // However we have a suggestion [ClousotRegressionTest] public int WithMethodCall(string s) { var b = Foo(s); if (b) { return s.Length; } else { return s.Length + 1; } } // no precondition to infer [ClousotRegressionTest] //[RegressionOutcome("Contract.Assume(tmp == 29);")] // we moved the some assume suggestions into codefixes [RegressionOutcome("This condition should hold: tmp == 29. Add an assume, a postcondition to method DaysInMonth, or consider a different initialization. Fix: Add (after) Contract.Assume(tmp == 29);")] public int Local(int z) { var tmp = DateTime.DaysInMonth(2012, 12); Contract.Assert(tmp == 29); return tmp; } // infer z == 29: the guard is implied by the precondition [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(z == 29);")] public int Local2(int z, int k) { Contract.Requires(k >= 0); if (k >= -12) { Contract.Assert(z == 29); } return z; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(!(b));")] // if b, the we get an error [RegressionOutcome("Contract.Requires(x > 0);")] // if x <= 0, we get an error no matter what [RegressionOutcome("Consider initializing x with a value other than -123 (e.g., satisfying x > 0). Fix: 1;")] public int Branch(int x, bool b) { if (b) { x = -123; } Contract.Assert(x > 0); return x; } // nothing to infer [ClousotRegressionTest] [RegressionOutcome("Consider initializing x with a value other than 12 (e.g., satisfying x < 0). Fix: -1;")] public void Branch2(int x) { if (Foo("ciao")) { x = -12; } else { x = 12; } Contract.Assert(x < 0); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(s != null);")] public void Branch3(int x, ref int z, string s) { // we need the join here if (x > 0) { z = 11; } else { z = 122; } Contract.Assert(s != null); } // We need a join here in which we get rid of the path [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(s != null);")] public void Branch4(int x, ref int z, string s) { if (x > 0) { z = 11; } else { z = 122; } if (x % 2 == 0) { z += 1; } else { z -= 1; } Contract.Assert(s != null); } [ClousotRegressionTest] // We should not infer "Contract.Requires(((x > 0 || (x % 2) != 0) || s != null));" because this means that simplification failed [RegressionOutcome("Contract.Requires(((x % 2) != 0 || s != null));")] public void Branch5(int x, ref int z, string s) { if (x > 0) { z = 11; } else { z = 122; } if (x % 2 == 0) { z += 1; } else { return; } Contract.Assert(s != null); } public bool Foo(string s) { return s != null; } [ClousotRegressionTest] public void Test_RequiresAnInt_Positive() { RequiresAnInt(12); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(!((" + "@\"12\"" +" as System.Int32)));")] public void Test_RequiresAnInt_Negative() { RequiresAnInt("12"); } [ClousotRegressionTest] // We do not suggest anymore requires from "throw "-> "assert false" transformations // [RegressionOutcome("Contract.Requires(!((s as System.Int32)));")] public void RequiresAnInt(object s) { if ((s is Int32)) { throw new ArgumentException(); } } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((i < 0 || j > 0));")] public int Mixed(int i, int j) { if (i < 0) throw new ArgumentOutOfRangeException("should be >= 0!!!"); Contract.Assert(j > 0); return i * 2; } } public class PreInferenceWithLoops { // infer input <= 0 ==> input == 0 // (equivalent to input >= 0) // Cannot be inferred with precondition over all the paths [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(input >= 0);")] public void Loop(int input) { var j = 0; for (; j < input; j++) { } Contract.Assert(input == j); } // infer x != 0 ==> x > 0 // Cannot be inferred with precondition over all the paths [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(x >= 0);")] public void Loop2(int x) { while (x != 0) { Contract.Assert(x > 0); x--; } } // infer strings.Length > 0 // The other precondition is \exists j \in [0, strings.Length). strings[j] == null, but it is way out of reach at the moment // Cannot be inferred with precondition over all the paths [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(0 < strings.Length);")] public int Loop3(string[] strings) { Contract.Requires(strings != null); int i = 0; while (strings[i] != null) { i++; } return i; } [ClousotRegressionTest] // [RegressionOutcome("Contract.Requires((0 >= m1 || 0 < f));")] // 3/20/2014: Now we infer a better precondition [RegressionOutcome("Contract.Requires((0 >= m1 || m1 <= f));")] public void Loop4(int m1, int f) { int i = 0; while (i < m1) { Contract.Assert(i < f); i++; } } [ClousotRegressionTest] // [RegressionOutcome("Contract.Requires((0 >= m1 || 0 < f));")] // Fixed [RegressionOutcome("Contract.Requires((0 >= m1 || m1 <= f));")] public void Loop4WithPreconditionNotStrongEnough(int m1, int f) { Contract.Requires(m1 >= 0); // as we may have the equality, then we may never execute the loop int i = 0; while (i < m1) { Contract.Assert(i < f); i++; } } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(m1 <= f);")] public void Loop4WithPrecondition(int m1, int f) { Contract.Requires(m1 > 0); // this simplifies the precondition above, as we know now we always execute the loop at least once int i = 0; while (i < m1) { Contract.Assert(i < f); i++; } } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(strs != null);")] [RegressionOutcome("Contract.Requires(0 <= start);")] [RegressionOutcome("Contract.Requires(start < strs.Length);")] public int SearchZero(string[] strs, int start) { while (strs[start] != null) { start++; } return start; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(x == 12);")] public void AfterWhileLoop_ConditionAlwaysTrue(int x, int z) { Contract.Requires(z >= 0); while (z > 0) { z--; } // here z == 0; // uses this information to drop the z <= 0 antecendent if (z == 0) { Contract.Assert(x == 12); } } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(x == 12);")] public void AfterWhileLoop_ConditionAlwaysTrueWithStrongerPrecondition(int x, int z) { Contract.Requires(z > 0); while (z > 0) { z--; } // here z == 0; if (z == 0) { Contract.Assert(x == 12); } } // infers x <0 || y > 0 [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((x < 0 || y > 0));")] public void SrivastavaGulwaniPLDI09(int x, int y) { while (x < 0) { x = x + y; y++; } Contract.Assert(y > 0); } } public class SomeClass { public string[] SomeString; } public class PreconditionOrder { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(((s == null || s.SomeString == null) || 0 <= index));")] [RegressionOutcome("Contract.Requires(((s == null || s.SomeString == null) || index < s.SomeString.Length));")] [RegressionOutcome("Consider strengthening the null check. Fix: Add && index < s.SomeString.Length")] public static string SomeMethod(SomeClass s, int index) { if (s != null) { if (s.SomeString != null) return s.SomeString[index]; } return null; } } } namespace mscorlib { public class MyAppDomainSetup { public string PrivateBinPath; public object DeveloperPath; public string[] Value { get { return new string[0x12]; } } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((blob == null || 0 < blob.Length));")] [RegressionOutcome("Consider strengthening the null check. Fix: Add && 0 < blob.Length")] private static object Deserialize(byte[] blob) { if (blob == null) { return null; } if (blob[0] == 0) { return 1; } return null; } internal void SetupFusionContext(IntPtr fusionContext, MyAppDomainSetup oldInfo) { throw new NotImplementedException(); } } public class AppDomain { // Here we had 2 bugs in the pretty printing: // 1. infer: info != null && info != null && info != null ... // 2. infer (info != null && (info.DeveloperPath != null ==> info != null) // We should only infer info != null // Note: we do not analyze this.Value in the regression run, this is why we get the messages [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(info != null);")] // [RegressionOutcome("Contract.Requires((oldInfo != null || info.Value != null));")] // [RegressionOutcome("Contract.Requires((oldInfo != null || 0 < info.Value.Length));")] // [RegressionOutcome("Contract.Requires((oldInfo != null || 5 < info.Value.Length));")] // [RegressionOutcome("Contract.Assume(info.Value != null);")] // We also infer this assume - we moved the inference of assume to the codefixes // [RegressionOutcome("This condition should hold: info.Value != null. Add an assume, a postcondition, or consider a different initialization. Fix: Add (after) Contract.Assume(info.Value != null);")] [RegressionOutcome("Contract.Requires((oldInfo != null || 5 < ((mscorlib.MyAppDomainSetup)info).Value.Length));")] [RegressionOutcome("Contract.Requires((oldInfo != null || 0 < ((mscorlib.MyAppDomainSetup)info).Value.Length));")] [RegressionOutcome("Contract.Requires((oldInfo != null || ((mscorlib.MyAppDomainSetup)info).Value != null));")] //[RegressionOutcome("This condition should hold: ((mscorlib.MyAppDomainSetup)info).Value != null. Add an assume, a postcondition, or consider a different initialization. Fix: Add (after) Contract.Assume(((mscorlib.MyAppDomainSetup)info).Value != null);")] [RegressionOutcome("This condition should hold: ((mscorlib.MyAppDomainSetup)info).Value != null. Add an assume, a postcondition to method get_Value, or consider a different initialization. Fix: Add (after) Contract.Assume(((mscorlib.MyAppDomainSetup)info).Value != null);")] // When we infer a test strengthening, we check that at least one of the vars in the fix is in the condition. We do not extend this for accesspaths //[RegressionOutcome("Consider strengthening the guard. Fix: Add && 1 < info.Value.Length")] [RegressionOutcome("Possible off-by one: did you meant indexing with 0 instead of 1?. Fix: 0")] private void SetupFusionStore(MyAppDomainSetup info, MyAppDomainSetup oldInfo) { if (oldInfo == null) { if ((info.Value[0] == null) || (info.Value[1] == null)) { // dummy } if (info.Value[5] == null) { info.PrivateBinPath = RuntimeEnvironment.GetRuntimeDirectory(); } if (info.DeveloperPath == null) { info.DeveloperPath = RuntimeEnvironment.GetRuntimeDirectory(); } } IntPtr fusionContext = this.GetFusionContext(); info.SetupFusionContext(fusionContext, oldInfo); } private IntPtr GetFusionContext() { throw new NotImplementedException(); } } public class LinkedStructure { public bool HasElementType; public LinkedStructure next; private LinkedStructure GetElementType() { return next; } // nothing to infer [ClousotRegressionTest] // [RegressionOutcome("Contract.Assume((elementType.GetElementType()) != null);")] // we moved the some assume suggestions into codefixes // Here we build the left argument by ourselves, as the heap analysis does not have a name for it [RegressionOutcome("This condition should hold: elementType.GetElementType() != null. Add an assume, a postcondition to method mscorlib.LinkedStructure.GetElementType(), or consider a different initialization. Fix: Add (after) Contract.Assume(elementType.GetElementType() != null);")] internal string SigToString() { var elementType = this; while (elementType.HasElementType) { elementType = elementType.GetElementType(); } return elementType.ToString(); } } public class Guid { // Here we do not want to generate the trivial precondition hex || !hex || guidChars.Length > ... [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((!(hex) || guidChars != null));")] [RegressionOutcome("Contract.Requires((!(hex) || 0 <= offset));")] [RegressionOutcome("Contract.Requires((!(hex) || offset < guidChars.Length));")] [RegressionOutcome("Contract.Requires((!(hex) || (offset + 1) < guidChars.Length));")] private static int HexsToCharsReduced(char[] guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = 'x'; } if (hex) { guidChars[offset++] = ','; } return offset; } private static char HexToChar(int a) { a &= 15; return ((a > 9) ? ((char)((a - 10) + 0x61)) : ((char)(a + 0x30))); } } public class ActivationAttributeStack { public object[] activationAttributes; public object[] activationTypes; public int freeIndex; /* made the field public to have the precondition inference working */ // it is ok not to infer a precondition on this.activationAttributes, as we do not have boxed expressions for array loads (which appears in the test below) [ClousotRegressionTest] #if CLOUSOT2 [RegressionOutcome("Contract.Requires((this.freeIndex == 0 || this.activationTypes != null));")] [RegressionOutcome("Contract.Requires((this.freeIndex == 0 || 0 <= (this.freeIndex - 1)));")] [RegressionOutcome("Contract.Requires((this.freeIndex == 0 || (this.freeIndex - 1) < this.activationTypes.Length));")] #else [RegressionOutcome("Contract.Requires((!(this.freeIndex) || this.activationTypes != null));")] [RegressionOutcome("Contract.Requires((!(this.freeIndex) || 0 <= (this.freeIndex - 1)));")] [RegressionOutcome("Contract.Requires((!(this.freeIndex) || (this.freeIndex - 1) < this.activationTypes.Length));")] // we infer !(this.freeIndex) instead of (this.freeIndex == 0) because we have some issues with types #endif [RegressionOutcome("Consider strengthening the guard. Fix: Add && (this.freeIndex - 1) < this.activationAttributes.Length")] internal void Pop(Type typ) { #pragma warning disable 252 if ((this.freeIndex != 0) && (this.activationTypes[this.freeIndex - 1] == typ)) { this.freeIndex--; this.activationTypes[this.freeIndex] = null; this.activationAttributes[this.freeIndex] = null; #pragma warning restore 252 } } } public class CustomAttributeData { public object m_namedArgs; public CustomAttributeEncoding[] m_namedParams; public MemberInfo[] m_members; public Type m_scope; // Nothing should be inferred as the assertion depends on a quantified property over the array m_namedParams [ClousotRegressionTest] public virtual IList<object> get_NamedArguments() { if (this.m_namedArgs == null) { if (this.m_namedParams == null) { return null; } int index = 0; int num4 = 0; while (index < this.m_namedParams.Length) { if (this.m_namedParams[index] != CustomAttributeEncoding.Undefined) { Contract.Assert(this.m_members != null); // Cannot prove it num4++; } index++; } } return null; } public enum CustomAttributeEncoding { Array = 29, Boolean = 2, Byte = 5, Char = 3, Double = 13, Enum = 85, Field = 83, Float = 12, Int16 = 6, Int32 = 8, Int64 = 10, Object = 81, Property = 84, SByte = 4, String = 14, Type = 80, UInt16 = 7, UInt32 = 9, UInt64 = 11, Undefined = 0 } } public class SimplificationOfPremises { public int m_RelocFixupCount; [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(0 <= this.m_RelocFixupCount);")] internal int[] GetTokenFixups() { if (this.m_RelocFixupCount == 0) { return null; } int[] destinationArray = new int[this.m_RelocFixupCount]; return destinationArray; } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(z >= 0);")] [RegressionOutcome("Consider replacing z < 0. Fix: 0 <= z")] public int[] WrongArrayInit(int z) { // we were not simplifying the premise if (z < 0) { return new int[z]; } return null; } } public class InferredDisjunction { // Nothing to complain, precondition is proven [ClousotRegressionTest] public void CallFoo() { Foo(null, -1); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((obj == null || z > 0));")] public void Foo(object obj, int z) { if (obj != null) { Contract.Assert(z > 0); } } } public class OverflowTesting { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(elements != null);")] [RegressionOutcome("Contract.Requires((nextFree != elements.Length || 0 <= (elements.Length * 2 + 1)));")] public void Add(int[] elements, int nextFree, int x) { Contract.Requires(0 <= nextFree); Contract.Requires(nextFree <= elements.Length); if (nextFree == elements.Length) { var tmp = new int[nextFree * 2 + 1]; // This may overflow and get negative. We suggest a precondition for that Array.Copy(elements, tmp, elements.Length); elements = tmp; } elements[nextFree] = x; nextFree++; } } public class MoreComplexInference { [ClousotRegressionTest] // [RegressionOutcome("Contract.Requires((length + offset) <= str.Length);")] // Now we have a better requires // This is wrong!!! We should not correct the preconditions for the callers //[RegressionOutcome("Did you meant i <= str.Length instead of i < str.Length?. Fix: i <= str.Length")] [RegressionOutcome("Contract.Requires((offset >= (length + offset) || (length + offset) <= str.Length));")] [RegressionOutcome("Consider adding the assumption (length + offset) <= str.Length. Fix: Add Contract.Assume((length + offset) <= str.Length);")] #if CLOUSOT2 [RegressionOutcome("This condition should hold: i < str.Length. Add an assume, a postcondition to method System.String.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume(i < str.Length);")] [RegressionOutcome("This condition should hold: (length + offset) <= str.Length. Add an assume, a postcondition to method System.String.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume((length + offset) <= str.Length);")] #else [RegressionOutcome("This condition should hold: i < str.Length. Add an assume, a postcondition to method System.String.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume(i < str.Length);")] [RegressionOutcome("This condition should hold: (length + offset) <= str.Length. Add an assume, a postcondition to method System.String.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume((length + offset) <= str.Length);")] #endif public static int GetChar(string str, int offset, int length) { Contract.Requires(str != null); Contract.Requires(offset >= 0); Contract.Requires(length >= 0); Contract.Requires(length < str.Length); Contract.Requires(offset < str.Length); int val = 0; for (int i = offset; i < length + offset; i++) { char c = str[i]; // Method call, not removed by the compiler } return val; } } public class False { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(x != null);")] [RegressionOutcome("Contract.Requires(y >= 0);")] [RegressionOutcome("Contract.Requires(z > y);")] public void Foo(object x, int y, int z) { if(x == null) // x != null Contract.Assert(false); if(y < 0) // infer: x == null || y >= 0 simplified to y >= 0 Contract.Assert(false); if(z <= y) // infer: x == null || y < 0 || z > y simplified to z > y Contract.Assert(false); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(capacity >= 0);")] [RegressionOutcome("Contract.Requires(length >= 0);")] [RegressionOutcome("Contract.Requires(startIndex >= 0);")] [RegressionOutcome("Contract.Requires((value == null || startIndex <= (value.Length - length)));")] [RegressionOutcome("Consider adding the assumption startIndex <= (value.Length - length). Fix: Add Contract.Assume(startIndex <= (value.Length - length));")] #if CLOUSOT2 [RegressionOutcome("This condition should hold: startIndex <= (value.Length - length). Add an assume, a postcondition to method System.String.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume(startIndex <= (value.Length - length));")] #else [RegressionOutcome("This condition should hold: startIndex <= (value.Length - length). Add an assume, a postcondition to method System.String.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume(startIndex <= (value.Length - length));")] #endif public static void StringBuilderSmallRepro(string value, int startIndex, int length, int capacity) { if (capacity < 0) { Contract.Assert(false); } if (length < 0) { Contract.Assert(false); } if (startIndex < 0) { Contract.Assert(false); } if (value == null) { value = string.Empty; } if (startIndex > (value.Length - length)) { Contract.Assert(false); } } } } namespace ReplaceExpressionsByMoreVisibleGetters { public class PublicGetterRepro { private int a, b; public PublicGetterRepro(int a, int b) { this.a = a; this.b = b; } [ClousotRegressionTest] public int Length { get { Contract.Ensures(Contract.Result<int>() == a + b); return a + b; } } [ClousotRegressionTest] // We do not infer it anymore //[RegressionOutcome("Contract.Requires(i <= this.Length);")] #if CLOUSOT2 [RegressionOutcome("This condition should hold: i <= this.Length. Add an assume, a postcondition to method ReplaceExpressionsByMoreVisibleGetters.PublicGetterRepro.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume(i <= this.Length);")] #else [RegressionOutcome("This condition should hold: i <= this.Length. Add an assume, a postcondition to method ReplaceExpressionsByMoreVisibleGetters.PublicGetterRepro.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume(i <= this.Length);")] #endif public int Precondition(int i) { // we should infer i <= this.Length, instead of i <= a + b if (i > this.Length) { throw new ArgumentOutOfRangeException(); } return i + 1; } } } namespace UserRepro { public class RobAshton { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(((a % b) == 0 || a != 0));")] [RegressionOutcome("Contract.Requires((a != Int32.MinValue || b != -1));")] [RegressionOutcome("Contract.Requires(((a % b) == 0 || (b != Int32.MinValue || a != -1)));")] private static bool AreBothWaysDivisibleBy2(int a, int b) { Contract.Requires(b != 0); return a % b == 0 || b % a == 0; } } public class Maf { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(((t as System.Collections.IEnumerable) != null || tabs >= 0));")] [RegressionOutcome("Contract.Requires((!((t as System.String)) || tabs >= 0));")] public void TestInference(object t, int tabs) { var asEnumerable = t as IEnumerable; if (asEnumerable != null && !(t is string)) { // do nothing } else // asNumerable == null || t is string { Contract.Assert(tabs >= 0); } } } } namespace Shuvendu { class Program { [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(0 <= x);")] [RegressionOutcome("Contract.Requires(((x <= 0 || x - 1 != t) || 1 == x));")] public void Foo(int x, int t) { var i = x; var j = 0; while (i > 0) { //Contract.Assert(i + j == x); i--; j++; if (i == t) break; } Contract.Assert(j == x); } } } namespace BugRepro { public class Reactor { public enum State { On, Off} public State state; public Reactor() { this.state = State.Off; } public void turnReactorOn() { Contract.Requires(this.state == State.Off); Contract.Ensures(this.state == State.On); this.state = State.On; } public void SCRAM() { Contract.Requires(this.state == State.On); Contract.Ensures(this.state == State.Off); this.state = State.Off; } } public class Tmp { public readonly Reactor r = new Reactor(); public Reactor.State state; [ClousotRegressionTest] [RegressionOutcome("Contract.Requires((!(restart) || !(wt)));")] [RegressionOutcome("Contract.Requires((restart || wt));")] [RegressionOutcome("Consider initializing this.state with a value other than 1 (e.g., satisfying this.state == 0). Fix: 0;")] [RegressionOutcome("Consider initializing this.state with a value other than 0 (e.g., satisfying this.state == 1). Fix: 1;")] public void SimpleTest(bool wt, bool restart) { Contract.Requires(this.state == Reactor.State.Off); this.state = Reactor.State.On; if (wt) { Contract.Assert(this.state == Reactor.State.On); this.state = Reactor.State.Off; } if (restart) { Contract.Assert(this.state == Reactor.State.On); this.state = Reactor.State.Off; } Contract.Assert(this.state== Reactor.State.Off); } [ClousotRegressionTest] [RegressionOutcome("Contract.Requires(this.r != null);")] [RegressionOutcome("Contract.Requires((!(restart) || !(wt)));")] [RegressionOutcome("Contract.Requires((restart || wt));")] [RegressionOutcome("Consider initializing this.r.state with a value other than 0 (e.g., satisfying this.r.state == 1). Fix: 1;")] public void MoreComplexTest(bool wt, bool restart) { Contract.Requires(this.r.state == Reactor.State.Off); this.r.turnReactorOn(); if(wt) { this.r.SCRAM(); } if(restart) { this.r.SCRAM(); } this.r.turnReactorOn(); this.r.SCRAM(); } } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : ReferenceItem.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 08/20/2008 // Note : Copyright 2006-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a class representing a reference item that can be used // by MRefBuilder to locate assembly dependencies for the assemblies being // documented. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.1.0.0 08/23/2006 EFW Created the code // 1.8.0.0 06/30/2008 EFW Rewrote to support the MSBuild project format //============================================================================= using System; using System.ComponentModel; using System.Drawing.Design; using System.Globalization; using System.IO; using System.Xml; using Microsoft.Build.BuildEngine; using SandcastleBuilder.Utils.Design; namespace SandcastleBuilder.Utils { /// <summary> /// This represents a reference item that can be used by <b>MRefBuilder</b> /// to locate assembly dependencies for the assemblies being documented. /// </summary> public class ReferenceItem : BaseBuildItem, ICustomTypeDescriptor { #region Private data members //===================================================================== // Private data members private FilePath hintPath; #endregion #region Properties //===================================================================== // Properties /// <summary> /// This is used to set or path to the dependency /// </summary> /// <value>For GAC dependencies, this should be null.</value> [Category("Metadata"), Description("The path to the referenced assembly."), Editor(typeof(FilePathObjectEditor), typeof(UITypeEditor)), RefreshProperties(RefreshProperties.All), MergableProperty(false), FileDialog("Select the reference item", "Library and Executable Files (*.dll, *.exe)|*.dll;*.exe|" + "Library Files (*.dll)|*.dll|Executable Files (*.exe)|*.exe|" + "All Files (*.*)|*.*", FileDialogType.FileOpen)] public virtual FilePath HintPath { get { return hintPath; } set { if(value == null || value.Path.Length == 0 || value.Path.IndexOfAny(new char[] { '*', '?' }) != -1) throw new ArgumentException("A hint path must be " + "specified and cannot contain wildcards (* or ?)", "value"); base.ProjectElement.SetMetadata(ProjectElement.HintPath, value.PersistablePath); hintPath = value; hintPath.PersistablePathChanging += new EventHandler( hintPath_PersistablePathChanging); } } /// <summary> /// This is used to get the reference description /// </summary> [Category("Reference"), Description("The reference name")] public virtual string Reference { get { // This will be the filename for file references, a GAC name // for GAC references, or a COM object name for COM references. return base.ProjectElement.Include; } } #endregion #region Designer methods //===================================================================== // Designer methods /// <summary> /// This is used to see if the <see cref="HintPath"/> property should /// be serialized. /// </summary> /// <returns>True to serialize it, false if it matches the default /// and should not be serialized. This property cannot be reset /// as it should always have a value.</returns> private bool ShouldSerializeHintPath() { return (this.HintPath.Path.Length != 0); } #endregion #region Private helper methods //===================================================================== /// <summary> /// This is used to handle changes in the <see cref="HintPath" /> /// properties such that the hint path gets stored in the project file. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void hintPath_PersistablePathChanging(object sender, EventArgs e) { base.ProjectElement.SetMetadata(ProjectElement.HintPath, hintPath.PersistablePath); } #endregion #region Constructor //===================================================================== /// <summary> /// Internal Constructor /// </summary> /// <param name="element">The project element</param> internal ReferenceItem(ProjectElement element) : base(element) { if(base.ProjectElement.HasMetadata(ProjectElement.HintPath)) { hintPath = new FilePath(base.ProjectElement.GetMetadata( ProjectElement.HintPath), base.ProjectElement.Project); hintPath.PersistablePathChanging += new EventHandler( hintPath_PersistablePathChanging); } } #endregion #region Equality and ToString methods //===================================================================== /// <summary> /// See if specified item equals this one by name alone /// </summary> /// <param name="obj">The object to compare to this one</param> /// <returns>True if equal, false if not</returns> public override bool Equals(object obj) { ReferenceItem refItem = obj as ReferenceItem; if(refItem == null) return false; return (this == refItem || (this.Reference == refItem.Reference)); } /// <summary> /// Get a hash code for this item /// </summary> /// <returns>Returns the hash code for the assembly path and /// XML comments path.</returns> public override int GetHashCode() { return this.ToString().GetHashCode(); } /// <summary> /// Return a string representation of the item /// </summary> /// <returns>Returns the assembly path and XML comments path separated /// by a comma.</returns> public override string ToString() { return this.Reference; } #endregion #region ICustomTypeDescriptor Members //===================================================================== /// <inheritdoc /> public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } /// <inheritdoc /> public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } /// <inheritdoc /> public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } /// <inheritdoc /> public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } /// <inheritdoc /> public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } /// <inheritdoc /> public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } /// <inheritdoc /> public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// <inheritdoc /> public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } /// <inheritdoc /> public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } /// <inheritdoc /> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties( this, attributes, true); return this.FilterProperties(pdc); } /// <inheritdoc /> public PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties( this, true); return this.FilterProperties(pdc); } /// <inheritdoc /> public object GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion #region Property filter method //===================================================================== /// <summary> /// This is used to filter out the <see cref="HintPath"/> property if /// not used. /// </summary> /// <param name="pdc">The property descriptor collection to filter</param> /// <returns>The filtered property descriptor collection</returns> private PropertyDescriptorCollection FilterProperties( PropertyDescriptorCollection pdc) { PropertyDescriptorCollection adjustedProps = new PropertyDescriptorCollection(new PropertyDescriptor[] { }); foreach(PropertyDescriptor pd in pdc) if(pd.Name != "HintPath") adjustedProps.Add(pd); else if(pd.GetValue(this) != null) adjustedProps.Add(pd); return adjustedProps; } #endregion } }
// // Log.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; using System.Threading; namespace Hyena { public delegate void LogNotifyHandler (LogNotifyArgs args); public class LogNotifyArgs : EventArgs { private LogEntry entry; public LogNotifyArgs (LogEntry entry) { this.entry = entry; } public LogEntry Entry { get { return entry; } } } public enum LogEntryType { Debug, Warning, Error, Information } public class LogEntry { private LogEntryType type; private string message; private string details; private DateTime timestamp; internal LogEntry (LogEntryType type, string message, string details) { this.type = type; this.message = message; this.details = details; this.timestamp = DateTime.Now; } public LogEntryType Type { get { return type; } } public string Message { get { return message; } } public string Details { get { return details; } } public DateTime TimeStamp { get { return timestamp; } } } public static class Log { static Log () { // On Windows, if running uninstalled, leave STDOUT alone so it's visible in the IDE, // otherwise write it to a file so it's not lost. if (PlatformDetection.IsWindows && !ApplicationContext.CommandLine.Contains ("uninstalled")) { var log_path = Paths.Combine (Paths.ApplicationData, "banshee.log"); Console.WriteLine ("Logging to {0}", log_path); try { var log_writer = new System.IO.StreamWriter (log_path, false); log_writer.AutoFlush = true; Console.SetOut (log_writer); } catch (Exception ex) { Console.Error.WriteLine ("Unable to log to {0}: {1}", log_path, ex); } } } public static event LogNotifyHandler Notify; private static Dictionary<uint, DateTime> timers = new Dictionary<uint, DateTime> (); private static uint next_timer_id = 1; private static bool debugging = false; public static bool Debugging { get { return debugging; } set { debugging = value; } } public static void Commit (LogEntryType type, string message, string details, bool showUser) { if (type == LogEntryType.Debug && !Debugging) { return; } if (type != LogEntryType.Information || (type == LogEntryType.Information && !showUser)) { switch (type) { case LogEntryType.Error: ConsoleCrayon.ForegroundColor = ConsoleColor.Red; break; case LogEntryType.Warning: ConsoleCrayon.ForegroundColor = ConsoleColor.DarkYellow; break; case LogEntryType.Information: ConsoleCrayon.ForegroundColor = ConsoleColor.Green; break; case LogEntryType.Debug: ConsoleCrayon.ForegroundColor = ConsoleColor.Blue; break; } var thread_name = String.Empty; if (Debugging) { var thread = Thread.CurrentThread; thread_name = String.Format ("{0} ", thread.ManagedThreadId); } Console.Write ("[{5}{0} {1:00}:{2:00}:{3:00}.{4:000}]", TypeString (type), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond, thread_name); ConsoleCrayon.ResetColor (); if (details != null) { Console.WriteLine (" {0} - {1}", message, details); } else { Console.WriteLine (" {0}", message); } } if (showUser) { OnNotify (new LogEntry (type, message, details)); } } private static string TypeString (LogEntryType type) { switch (type) { case LogEntryType.Debug: return "Debug"; case LogEntryType.Warning: return "Warn "; case LogEntryType.Error: return "Error"; case LogEntryType.Information: return "Info "; } return null; } private static void OnNotify (LogEntry entry) { LogNotifyHandler handler = Notify; if (handler != null) { handler (new LogNotifyArgs (entry)); } } #region Timer Methods public static uint DebugTimerStart (string message) { return TimerStart (message, false); } public static uint InformationTimerStart (string message) { return TimerStart (message, true); } private static uint TimerStart (string message, bool isInfo) { if (!Debugging && !isInfo) { return 0; } if (isInfo) { Information (message); } else { Debug (message); } return TimerStart (isInfo); } public static uint DebugTimerStart () { return TimerStart (false); } public static uint InformationTimerStart () { return TimerStart (true); } private static uint TimerStart (bool isInfo) { if (!Debugging && !isInfo) { return 0; } uint timer_id = next_timer_id++; timers.Add (timer_id, DateTime.Now); return timer_id; } public static void DebugTimerPrint (uint id) { if (!Debugging) { return; } TimerPrint (id, "Operation duration: {0}", false); } public static void DebugTimerPrint (uint id, string message) { if (!Debugging) { return; } TimerPrint (id, message, false); } public static void InformationTimerPrint (uint id) { TimerPrint (id, "Operation duration: {0}", true); } public static void InformationTimerPrint (uint id, string message) { TimerPrint (id, message, true); } private static void TimerPrint (uint id, string message, bool isInfo) { if (!Debugging && !isInfo) { return; } DateTime finish = DateTime.Now; if (!timers.ContainsKey (id)) { return; } TimeSpan duration = finish - timers[id]; string d_message; if (duration.TotalSeconds < 60) { d_message = duration.TotalSeconds.ToString (); } else { d_message = duration.ToString (); } if (isInfo) { InformationFormat (message, d_message); } else { DebugFormat (message, d_message); } } #endregion #region Public Debug Methods public static void Debug (string message, string details) { if (Debugging) { Commit (LogEntryType.Debug, message, details, false); } } public static void Debug (string message) { if (Debugging) { Debug (message, null); } } public static void DebugFormat (string format, params object [] args) { if (Debugging) { Debug (String.Format (format, args)); } } #endregion #region Public Information Methods public static void Information (string message) { Information (message, null); } public static void Information (string message, string details) { Information (message, details, false); } public static void Information (string message, string details, bool showUser) { Commit (LogEntryType.Information, message, details, showUser); } public static void Information (string message, bool showUser) { Information (message, null, showUser); } public static void InformationFormat (string format, params object [] args) { Information (String.Format (format, args)); } #endregion #region Public Warning Methods public static void Warning (string message) { Warning (message, (string)null); } public static void Warning (string message, string details) { Warning (message, details, false); } public static void Warning (string message, string details, bool showUser) { Commit (LogEntryType.Warning, message, details, showUser); } public static void Warning (Exception e) { Warning (null, e); } public static void Warning (string message, Exception e) { Exception (message, e, false); } public static void Warning (string message, bool showUser) { Warning (message, null, showUser); } public static void WarningFormat (string format, params object [] args) { Warning (String.Format (format, args)); } #endregion #region Public Error Methods public static void Error (string message) { Error (message, (string)null); } public static void Error (string message, string details) { Error (message, details, false); } public static void Error (string message, string details, bool showUser) { Commit (LogEntryType.Error, message, details, showUser); } public static void Error (string message, bool showUser) { Error (message, null, showUser); } public static void Error (Exception e) { Error (null, e); } public static void Error (string message, Exception e) { Exception (message, e, true); } public static void ErrorFormat (string format, params object [] args) { Error (String.Format (format, args)); } #endregion #region Public Exception Methods public static void DebugException (Exception e) { if (Debugging) { Exception (null, e, false); } } [Obsolete ("Use Error(ex) or Warning(ex)")] public static void Exception (Exception e) { Exception (null, e); } [Obsolete ("Use Error(msg,ex) or Warning(msg,ex)")] public static void Exception (string message, Exception e) { bool severe = String.IsNullOrEmpty (message); Exception (message, e, severe); } private static void Exception (string message, Exception e, bool severe) { Stack<Exception> exception_chain = new Stack<Exception> (); StringBuilder builder = new StringBuilder (); while (e != null) { exception_chain.Push (e); e = e.InnerException; } while (exception_chain.Count > 0) { e = exception_chain.Pop (); builder.AppendFormat ("{0}: {1} (in `{2}')", e.GetType (), e.Message, e.Source).AppendLine (); builder.Append (e.StackTrace); if (exception_chain.Count > 0) { builder.AppendLine (); } } var msg = message ?? "Caught an exception"; if (!severe) { Log.Warning (msg, builder.ToString (), false); } else { Log.Error (msg, builder.ToString (), false); } } #endregion } }
#region BSD License /* Copyright (c) 2012, Clarius Consulting All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion namespace Clide.Diagnostics { using System; using System.Diagnostics; using System.Globalization; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; /// <summary> /// Extensions to <see cref="ITracer"/> for activity tracing. /// </summary> static partial class StartActivityExtension { /// <summary> /// Starts a new activity scope. /// </summary> public static IDisposable StartActivity(this ITracer tracer, string format, params object[] args) { return new TraceActivity(tracer, format, args); } /// <summary> /// Starts a new activity scope. /// </summary> public static IDisposable StartActivity(this ITracer tracer, string displayName) { return new TraceActivity(tracer, displayName); } /// <devdoc> /// In order for activity tracing to happen, the trace source needs to /// have <see cref="SourceLevels.ActivityTracing"/> enabled. /// </devdoc> partial class TraceActivity : IDisposable { string displayName; bool disposed; ITracer tracer; Guid oldId; Guid newId; public TraceActivity(ITracer tracer, string displayName) : this(tracer, displayName, null) { } public TraceActivity(ITracer tracer, string displayName, params object[] args) { this.tracer = tracer; this.displayName = displayName; if (args != null && args.Length > 0) this.displayName = string.Format(displayName, args, CultureInfo.CurrentCulture); newId = Guid.NewGuid(); oldId = Trace.CorrelationManager.ActivityId; tracer.Trace(TraceEventType.Transfer, this.newId); Trace.CorrelationManager.ActivityId = newId; // The XmlWriterTraceListener expects Start/Stop events to receive an XPathNavigator // with XML in a specific format so that the Service Trace Viewer can properly render // the activity graph. tracer.Trace(TraceEventType.Start, new ActivityData(this.displayName, true)); } public void Dispose() { if (!this.disposed) { tracer.Trace(TraceEventType.Stop, new ActivityData(displayName, false)); tracer.Trace(TraceEventType.Transfer, oldId); Trace.CorrelationManager.ActivityId = oldId; } this.disposed = true; } class ActivityData : XPathNavigator { string displayName; XPathNavigator xml; public ActivityData(string displayName, bool isStart) { this.displayName = displayName; // The particular XML format expected by the Service Trace Viewer was // inferred from the actual tool behavior and usage. this.xml = XDocument.Parse(string.Format(@" <TraceRecord xmlns='http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord' Severity='{0}'> <TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ActivityBoundary.aspx</TraceIdentifier> <Description>Activity boundary.</Description> <AppDomain>client.vshost.exe</AppDomain> <ExtendedData xmlns='http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord'> <ActivityName>{1}</ActivityName> <ActivityType>ActivityTracing</ActivityType> </ExtendedData> </TraceRecord>", isStart ? "Start" : "Stop", displayName)).CreateNavigator(); } public override string BaseURI { get { return xml.BaseURI; } } public override XPathNavigator Clone() { return xml.Clone(); } public override bool IsEmptyElement { get { return xml.IsEmptyElement; } } public override bool IsSamePosition(XPathNavigator other) { return xml.IsSamePosition(other); } public override string LocalName { get { return xml.LocalName; } } public override bool MoveTo(XPathNavigator other) { return xml.MoveTo(other); } public override bool MoveToFirstAttribute() { return xml.MoveToFirstAttribute(); } public override bool MoveToFirstChild() { return xml.MoveToFirstChild(); } public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { return xml.MoveToFirstNamespace(namespaceScope); } public override bool MoveToId(string id) { return xml.MoveToId(id); } public override bool MoveToNext() { return xml.MoveToNext(); } public override bool MoveToNextAttribute() { return xml.MoveToNextAttribute(); } public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { return xml.MoveToNextNamespace(namespaceScope); } public override bool MoveToParent() { return xml.MoveToParent(); } public override bool MoveToPrevious() { return xml.MoveToPrevious(); } public override string Name { get { return xml.Name; } } public override XmlNameTable NameTable { get { return xml.NameTable; } } public override string NamespaceURI { get { return xml.NamespaceURI; } } public override XPathNodeType NodeType { get { return xml.NodeType; } } public override string Prefix { get { return xml.Prefix; } } public override string Value { get { return xml.Value; } } public override string ToString() { return displayName; } } } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Admin.DS { public class sys_RecordSecurityParamDS { public sys_RecordSecurityParamDS() { } private const string THIS = "PCSComUtils.Admin.DS.sys_RecordSecurityParamDS"; //************************************************************************** /// <Description> /// This method uses to add data to sys_RecordSecurityParam /// </Description> /// <Inputs> /// sys_RecordSecurityParamVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { sys_RecordSecurityParamVO objObject = (sys_RecordSecurityParamVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO sys_RecordSecurityParam(" + sys_RecordSecurityParamTable.SOURCETABLENAME_FLD + "," + sys_RecordSecurityParamTable.MENUNAME_FLD + "," + sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD + ")" + "VALUES(?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.SOURCETABLENAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.SOURCETABLENAME_FLD].Value = objObject.SourceTableName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.MENUNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.MENUNAME_FLD].Value = objObject.MenuName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD].Value = objObject.SecurityTableName; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_RecordSecurityParam /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + sys_RecordSecurityParamTable.TABLE_NAME + " WHERE " + "RecordSecurityParamID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_RecordSecurityParam /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// sys_RecordSecurityParamVO /// </Outputs> /// <Returns> /// sys_RecordSecurityParamVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD + "," + sys_RecordSecurityParamTable.SOURCETABLENAME_FLD + "," + sys_RecordSecurityParamTable.MENUNAME_FLD + "," + sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD + " FROM " + sys_RecordSecurityParamTable.TABLE_NAME +" WHERE " + sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); sys_RecordSecurityParamVO objObject = new sys_RecordSecurityParamVO(); while (odrPCS.Read()) { objObject.RecordSecurityParamID = int.Parse(odrPCS[sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD].ToString().Trim()); objObject.SourceTableName = odrPCS[sys_RecordSecurityParamTable.SOURCETABLENAME_FLD].ToString().Trim(); objObject.MenuName = odrPCS[sys_RecordSecurityParamTable.MENUNAME_FLD].ToString().Trim(); objObject.SecurityTableName = odrPCS[sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD].ToString().Trim(); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to sys_RecordSecurityParam /// </Description> /// <Inputs> /// sys_RecordSecurityParamVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; sys_RecordSecurityParamVO objObject = (sys_RecordSecurityParamVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE sys_RecordSecurityParam SET " + sys_RecordSecurityParamTable.SOURCETABLENAME_FLD + "= ?" + "," + sys_RecordSecurityParamTable.MENUNAME_FLD + "= ?" + "," + sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD + "= ?" +" WHERE " + sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.SOURCETABLENAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.SOURCETABLENAME_FLD].Value = objObject.SourceTableName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.MENUNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.MENUNAME_FLD].Value = objObject.MenuName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD].Value = objObject.SecurityTableName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD].Value = objObject.RecordSecurityParamID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_RecordSecurityParam /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD + "," + sys_RecordSecurityParamTable.SOURCETABLENAME_FLD + "," + sys_RecordSecurityParamTable.MENUNAME_FLD + "," + sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD + " FROM " + sys_RecordSecurityParamTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,sys_RecordSecurityParamTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + sys_RecordSecurityParamTable.RECORDSECURITYPARAMID_FLD + "," + sys_RecordSecurityParamTable.SOURCETABLENAME_FLD + "," + sys_RecordSecurityParamTable.MENUNAME_FLD + "," + sys_RecordSecurityParamTable.SECURITYTABLENAME_FLD + " FROM " + sys_RecordSecurityParamTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,sys_RecordSecurityParamTable.TABLE_NAME); } catch(OleDbException ex) { if(ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
/* * 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.Cache { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Cache.Query; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Portable; using Apache.Ignite.Core.Impl.Portable.IO; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Portable; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native cache wrapper. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV> { /** Duration: unchanged. */ private const long DurUnchanged = -2; /** Duration: eternal. */ private const long DurEternal = -1; /** Duration: zero. */ private const long DurZero = 0; /** Ignite instance. */ private readonly Ignite _ignite; /** Flag: skip store. */ private readonly bool _flagSkipStore; /** Flag: keep portable. */ private readonly bool _flagKeepPortable; /** Flag: async mode.*/ private readonly bool _flagAsync; /** Flag: no-retries.*/ private readonly bool _flagNoRetries; /** * Result converter for async InvokeAll operation. * In future result processing there is only one TResult generic argument, * and we can't get the type of ICacheEntryProcessorResult at compile time from it. * This field caches converter for the last InvokeAll operation to avoid using reflection. */ private readonly ThreadLocal<object> _invokeAllConverter = new ThreadLocal<object>(); /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="flagSkipStore">Skip store flag.</param> /// <param name="flagKeepPortable">Keep portable flag.</param> /// <param name="flagAsync">Async mode flag.</param> /// <param name="flagNoRetries">No-retries mode flag.</param> public CacheImpl(Ignite grid, IUnmanagedTarget target, PortableMarshaller marsh, bool flagSkipStore, bool flagKeepPortable, bool flagAsync, bool flagNoRetries) : base(target, marsh) { _ignite = grid; _flagSkipStore = flagSkipStore; _flagKeepPortable = flagKeepPortable; _flagAsync = flagAsync; _flagNoRetries = flagNoRetries; } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /** <inheritDoc /> */ public bool IsAsync { get { return _flagAsync; } } /** <inheritDoc /> */ public IFuture GetFuture() { throw new NotSupportedException("GetFuture() should be called through CacheProxyImpl"); } /** <inheritDoc /> */ public IFuture<TResult> GetFuture<TResult>() { throw new NotSupportedException("GetFuture() should be called through CacheProxyImpl"); } /// <summary> /// Gets and resets future for previous asynchronous operation. /// </summary> /// <param name="lastAsyncOpId">The last async op id.</param> /// <returns> /// Future for previous asynchronous operation. /// </returns> /// <exception cref="System.InvalidOperationException">Asynchronous mode is disabled</exception> internal IFuture<TResult> GetFuture<TResult>(int lastAsyncOpId) { if (!_flagAsync) throw IgniteUtils.GetAsyncModeDisabledException(); var converter = GetFutureResultConverter<TResult>(lastAsyncOpId); _invokeAllConverter.Value = null; return GetFuture((futId, futTypeId) => UU.TargetListenFutureForOperation(Target, futId, futTypeId, lastAsyncOpId), _flagKeepPortable, converter); } /** <inheritDoc /> */ public string Name { get { return DoInOp<string>((int)CacheOp.GetName); } } /** <inheritDoc /> */ public bool IsEmpty { get { return Size() == 0; } } /** <inheritDoc /> */ public ICache<TK, TV> WithSkipStore() { if (_flagSkipStore) return this; return new CacheImpl<TK, TV>(_ignite, UU.CacheWithSkipStore(Target), Marshaller, true, _flagKeepPortable, _flagAsync, true); } /// <summary> /// Skip store flag getter. /// </summary> internal bool IsSkipStore { get { return _flagSkipStore; } } /** <inheritDoc /> */ public ICache<TK1, TV1> WithKeepPortable<TK1, TV1>() { if (_flagKeepPortable) { var result = this as ICache<TK1, TV1>; if (result == null) throw new InvalidOperationException( "Can't change type of portable cache. WithKeepPortable has been called on an instance of " + "portable cache with incompatible generic arguments."); return result; } return new CacheImpl<TK1, TV1>(_ignite, UU.CacheWithKeepPortable(Target), Marshaller, _flagSkipStore, true, _flagAsync, _flagNoRetries); } /** <inheritDoc /> */ public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc) { IgniteArgumentCheck.NotNull(plc, "plc"); long create = ConvertDuration(plc.GetExpiryForCreate()); long update = ConvertDuration(plc.GetExpiryForUpdate()); long access = ConvertDuration(plc.GetExpiryForAccess()); IUnmanagedTarget cache0 = UU.CacheWithExpiryPolicy(Target, create, update, access); return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepPortable, _flagAsync, _flagNoRetries); } /// <summary> /// Convert TimeSpan to duration recognizable by Java. /// </summary> /// <param name="dur">.Net duration.</param> /// <returns>Java duration in milliseconds.</returns> private static long ConvertDuration(TimeSpan? dur) { if (dur.HasValue) { if (dur.Value == TimeSpan.MaxValue) return DurEternal; long dur0 = (long)dur.Value.TotalMilliseconds; return dur0 > 0 ? dur0 : DurZero; } return DurUnchanged; } /** <inheritDoc /> */ public ICache<TK, TV> WithAsync() { return _flagAsync ? this : new CacheImpl<TK, TV>(_ignite, UU.CacheWithAsync(Target), Marshaller, _flagSkipStore, _flagKeepPortable, true, _flagNoRetries); } /** <inheritDoc /> */ public bool KeepPortable { get { return _flagKeepPortable; } } /** <inheritDoc /> */ public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { LoadCache0(p, args, (int)CacheOp.LoadCache); } /** <inheritDoc /> */ public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { LoadCache0(p, args, (int)CacheOp.LocLoadCache); } /// <summary> /// Loads the cache. /// </summary> private void LoadCache0(ICacheEntryFilter<TK, TV> p, object[] args, int opId) { DoOutOp(opId, writer => { if (p != null) { var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK)k, (TV)v)), Marshaller, KeepPortable); writer.WriteObject(p0); writer.WriteLong(p0.Handle); } else writer.WriteObject<CacheEntryFilterHolder>(null); writer.WriteObjectArray(args); }); } /** <inheritDoc /> */ public bool ContainsKey(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.ContainsKey, key) == True; } /** <inheritDoc /> */ public bool ContainsKeys(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOp((int)CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys)) == True; } /** <inheritDoc /> */ public TV LocalPeek(TK key, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOp<TV>((int)CacheOp.Peek, writer => { writer.Write(key); writer.WriteInt(EncodePeekModes(modes)); }); } /** <inheritDoc /> */ public TV Get(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOp<TK, TV>((int)CacheOp.Get, key); } /** <inheritDoc /> */ public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOp((int)CacheOp.GetAll, writer => WriteEnumerable(writer, keys), input => { var reader = Marshaller.StartUnmarshal(input, _flagKeepPortable); return ReadGetAllDictionary(reader); }); } /** <inheritdoc /> */ public void Put(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); DoOutOp((int)CacheOp.Put, key, val); } /** <inheritDoc /> */ public TV GetAndPut(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOp<TK, TV, TV>((int)CacheOp.GetAndPut, key, val); } /** <inheritDoc /> */ public TV GetAndReplace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOp<TK, TV, TV>((int)CacheOp.GetAndReplace, key, val); } /** <inheritDoc /> */ public TV GetAndRemove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOp<TK, TV>((int)CacheOp.GetAndRemove, key); } /** <inheritdoc /> */ public bool PutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int) CacheOp.PutIfAbsent, key, val) == True; } /** <inheritdoc /> */ public TV GetAndPutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOp<TK, TV, TV>((int)CacheOp.GetAndPutIfAbsent, key, val); } /** <inheritdoc /> */ public bool Replace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int)CacheOp.Replace2, key, val) == True; } /** <inheritdoc /> */ public bool Replace(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); return DoOutOp((int)CacheOp.Replace3, key, oldVal, newVal) == True; } /** <inheritdoc /> */ public void PutAll(IDictionary<TK, TV> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); DoOutOp((int) CacheOp.PutAll, writer => WriteDictionary(writer, vals)); } /** <inheritdoc /> */ public void LocalEvict(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int) CacheOp.LocEvict, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public void Clear() { UU.CacheClear(Target); } /** <inheritdoc /> */ public void Clear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp((int)CacheOp.Clear, key); } /** <inheritdoc /> */ public void ClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.ClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public void LocalClear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp((int) CacheOp.LocalClear, key); } /** <inheritdoc /> */ public void LocalClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public bool Remove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.RemoveObj, key) == True; } /** <inheritDoc /> */ public bool Remove(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int)CacheOp.RemoveBool, key, val) == True; } /** <inheritDoc /> */ public void RemoveAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public void RemoveAll() { UU.CacheRemoveAll(Target); } /** <inheritDoc /> */ public int LocalSize(params CachePeekMode[] modes) { return Size0(true, modes); } /** <inheritDoc /> */ public int Size(params CachePeekMode[] modes) { return Size0(false, modes); } /// <summary> /// Internal size routine. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="modes">peek modes</param> /// <returns>Size.</returns> private int Size0(bool loc, params CachePeekMode[] modes) { int modes0 = EncodePeekModes(modes); return UU.CacheSize(Target, modes0, loc); } /** <inheritDoc /> */ public void LocalPromote(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.LocPromote, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public TR Invoke<TR, TA>(TK key, ICacheEntryProcessor<TK, TV, TA, TR> processor, TA arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TA)a), typeof(TK), typeof(TV)); return DoOutInOp((int)CacheOp.Invoke, writer => { writer.Write(key); writer.Write(holder); }, input => GetResultOrThrow<TR>(Unmarshal<object>(input))); } /** <inheritdoc /> */ public IDictionary<TK, ICacheEntryProcessorResult<TR>> InvokeAll<TR, TA>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TA, TR> processor, TA arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TA)a), typeof(TK), typeof(TV)); return DoOutInOp((int)CacheOp.InvokeAll, writer => { WriteEnumerable(writer, keys); writer.Write(holder); }, input => { if (IsAsync) _invokeAllConverter.Value = (Func<PortableReaderImpl, IDictionary<TK, ICacheEntryProcessorResult<TR>>>) (reader => ReadInvokeAllResults<TR>(reader.Stream)); return ReadInvokeAllResults<TR>(input); }); } /** <inheritdoc /> */ public ICacheLock Lock(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOp((int)CacheOp.Lock, writer => { writer.Write(key); }, input => new CacheLock(input.ReadInt(), Target)); } /** <inheritdoc /> */ public ICacheLock LockAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOp((int)CacheOp.LockAll, writer => { WriteEnumerable(writer, keys); }, input => new CacheLock(input.ReadInt(), Target)); } /** <inheritdoc /> */ public bool IsLocalLocked(TK key, bool byCurrentThread) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.IsLocalLocked, writer => { writer.Write(key); writer.WriteBoolean(byCurrentThread); }) == True; } /** <inheritDoc /> */ public ICacheMetrics GetMetrics() { return DoInOp((int)CacheOp.Metrics, stream => { IPortableRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public IFuture Rebalance() { return GetFuture<object>((futId, futTyp) => UU.CacheRebalance(Target, futId)); } /** <inheritDoc /> */ public ICache<TK, TV> WithNoRetries() { if (_flagNoRetries) return this; return new CacheImpl<TK, TV>(_ignite, UU.CacheWithNoRetries(Target), Marshaller, _flagSkipStore, _flagKeepPortable, _flagAsync, true); } /// <summary> /// Gets a value indicating whether this instance is in no-retries mode. /// </summary> internal bool IsNoRetries { get { return _flagNoRetries; } } #region Queries /** <inheritDoc /> */ public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry) { IgniteArgumentCheck.NotNull(qry, "qry"); if (string.IsNullOrEmpty(qry.Sql)) throw new ArgumentException("Sql cannot be null or empty"); IUnmanagedTarget cursor; using (var stream = IgniteManager.Memory.Allocate().Stream()) { var writer = Marshaller.StartMarshal(stream); writer.WriteBoolean(qry.Local); writer.WriteString(qry.Sql); writer.WriteInt(qry.PageSize); WriteQueryArgs(writer, qry.Arguments); FinishMarshal(writer); cursor = UU.CacheOutOpQueryCursor(Target, (int) CacheOp.QrySqlFields, stream.SynchronizeOutput()); } return new FieldsQueryCursor(cursor, Marshaller, _flagKeepPortable); } /** <inheritDoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry) { IgniteArgumentCheck.NotNull(qry, "qry"); IUnmanagedTarget cursor; using (var stream = IgniteManager.Memory.Allocate().Stream()) { var writer = Marshaller.StartMarshal(stream); qry.Write(writer, KeepPortable); FinishMarshal(writer); cursor = UU.CacheOutOpQueryCursor(Target, (int)qry.OpId, stream.SynchronizeOutput()); } return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepPortable); } /// <summary> /// Write query arguments. /// </summary> /// <param name="writer">Writer.</param> /// <param name="args">Arguments.</param> private static void WriteQueryArgs(PortableWriterImpl writer, object[] args) { if (args == null) writer.WriteInt(0); else { writer.WriteInt(args.Length); foreach (var arg in args) writer.WriteObject(arg); } } /** <inheritdoc /> */ public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry) { IgniteArgumentCheck.NotNull(qry, "qry"); return QueryContinuousImpl(qry, null); } /** <inheritdoc /> */ public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { IgniteArgumentCheck.NotNull(qry, "qry"); IgniteArgumentCheck.NotNull(initialQry, "initialQry"); return QueryContinuousImpl(qry, initialQry); } /// <summary> /// QueryContinuous implementation. /// </summary> private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { qry.Validate(); var hnd = new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepPortable); using (var stream = IgniteManager.Memory.Allocate().Stream()) { var writer = Marshaller.StartMarshal(stream); hnd.Start(_ignite, writer, () => { if (initialQry != null) { writer.WriteInt((int) initialQry.OpId); initialQry.Write(writer, KeepPortable); } else writer.WriteInt(-1); // no initial query FinishMarshal(writer); // ReSharper disable once AccessToDisposedClosure return UU.CacheOutOpContinuousQuery(Target, (int)CacheOp.QryContinuous, stream.SynchronizeOutput()); }, qry); } return hnd; } #endregion #region Enumerable support /** <inheritdoc /> */ public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes) { return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes)); } /** <inheritdoc /> */ public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator() { return new CacheEnumeratorProxy<TK, TV>(this, false, 0); } /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Create real cache enumerator. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="peekModes">Peek modes for local enumerator.</param> /// <returns>Cache enumerator.</returns> internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes) { if (loc) return new CacheEnumerator<TK, TV>(UU.CacheLocalIterator(Target, peekModes), Marshaller, _flagKeepPortable); return new CacheEnumerator<TK, TV>(UU.CacheIterator(Target), Marshaller, _flagKeepPortable); } #endregion /** <inheritDoc /> */ protected override T Unmarshal<T>(IPortableStream stream) { return Marshaller.Unmarshal<T>(stream, _flagKeepPortable); } /// <summary> /// Encodes the peek modes into a single int value. /// </summary> private static int EncodePeekModes(CachePeekMode[] modes) { int modesEncoded = 0; if (modes != null) { foreach (var mode in modes) modesEncoded |= (int) mode; } return modesEncoded; } /// <summary> /// Unwraps an exception from PortableResultHolder, if any. Otherwise does the cast. /// </summary> /// <typeparam name="T">Result type.</typeparam> /// <param name="obj">Object.</param> /// <returns>Result.</returns> private static T GetResultOrThrow<T>(object obj) { var holder = obj as PortableResultWrapper; if (holder != null) { var err = holder.Result as Exception; if (err != null) throw err as CacheEntryProcessorException ?? new CacheEntryProcessorException(err); } return obj == null ? default(T) : (T) obj; } /// <summary> /// Reads results of InvokeAll operation. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="inStream">Stream.</param> /// <returns>Results of InvokeAll operation.</returns> private IDictionary<TK, ICacheEntryProcessorResult<T>> ReadInvokeAllResults<T>(IPortableStream inStream) { var count = inStream.ReadInt(); if (count == -1) return null; var results = new Dictionary<TK, ICacheEntryProcessorResult<T>>(count); for (var i = 0; i < count; i++) { var key = Unmarshal<TK>(inStream); var hasError = inStream.ReadBool(); results[key] = hasError ? new CacheEntryProcessorResult<T>(ReadException(inStream)) : new CacheEntryProcessorResult<T>(Unmarshal<T>(inStream)); } return results; } /// <summary> /// Reads the exception, either in portable wrapper form, or as a pair of strings. /// </summary> /// <param name="inStream">The stream.</param> /// <returns>Exception.</returns> private CacheEntryProcessorException ReadException(IPortableStream inStream) { var item = Unmarshal<object>(inStream); var clsName = item as string; if (clsName == null) return new CacheEntryProcessorException((Exception) ((PortableResultWrapper) item).Result); var msg = Unmarshal<string>(inStream); return new CacheEntryProcessorException(ExceptionUtils.GetException(clsName, msg)); } /// <summary> /// Read dictionary returned by GET_ALL operation. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Dictionary.</returns> private static IDictionary<TK, TV> ReadGetAllDictionary(PortableReaderImpl reader) { IPortableStream stream = reader.Stream; if (stream.ReadBool()) { int size = stream.ReadInt(); IDictionary<TK, TV> res = new Dictionary<TK, TV>(size); for (int i = 0; i < size; i++) { TK key = reader.ReadObject<TK>(); TV val = reader.ReadObject<TV>(); res[key] = val; } return res; } return null; } /// <summary> /// Gets the future result converter based on the last operation id. /// </summary> /// <typeparam name="TResult">The type of the future result.</typeparam> /// <param name="lastAsyncOpId">The last op id.</param> /// <returns>Future result converter.</returns> private Func<PortableReaderImpl, TResult> GetFutureResultConverter<TResult>(int lastAsyncOpId) { if (lastAsyncOpId == (int) CacheOp.GetAll) return reader => (TResult)ReadGetAllDictionary(reader); if (lastAsyncOpId == (int)CacheOp.Invoke) return reader => { var hasError = reader.ReadBoolean(); if (hasError) throw ReadException(reader.Stream); return reader.ReadObject<TResult>(); }; if (lastAsyncOpId == (int) CacheOp.InvokeAll) return _invokeAllConverter.Value as Func<PortableReaderImpl, TResult>; return null; } } }
using Klarna.Checkout; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Globalization; using System.Web; using TeaCommerce.Api; using TeaCommerce.Api.Common; using TeaCommerce.Api.Infrastructure.Logging; using TeaCommerce.Api.Models; using TeaCommerce.Api.Services; using TeaCommerce.Api.Web.PaymentProviders; using KlarnaOrder = Klarna.Checkout.Order; using Order = TeaCommerce.Api.Models.Order; namespace TeaCommerce.PaymentProviders.Inline { [PaymentProvider( "Klarna" )] public class Klarna : APaymentProvider { protected const string KlarnaApiRequestContentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"; public override IDictionary<string, string> DefaultSettings { get { Dictionary<string, string> defaultSettings = new Dictionary<string, string>(); defaultSettings[ "merchant.id" ] = ""; defaultSettings[ "locale" ] = "sv-se"; defaultSettings[ "paymentFormUrl" ] = ""; defaultSettings[ "merchant.confirmation_uri" ] = ""; defaultSettings[ "merchant.terms_uri" ] = ""; defaultSettings[ "sharedSecret" ] = ""; defaultSettings[ "totalSku" ] = "0001"; defaultSettings[ "totalName" ] = "Totala"; defaultSettings[ "testMode" ] = "1"; return defaultSettings; } } public override PaymentHtmlForm GenerateHtmlForm( Order order, string teaCommerceContinueUrl, string teaCommerceCancelUrl, string teaCommerceCallBackUrl, string teaCommerceCommunicationUrl, IDictionary<string, string> settings ) { order.MustNotBeNull( "order" ); settings.MustNotBeNull( "settings" ); settings.MustContainKey( "paymentFormUrl", "settings" ); PaymentHtmlForm htmlForm = new PaymentHtmlForm { Action = settings[ "paymentFormUrl" ] }; order.Properties.AddOrUpdate( new CustomProperty( "teaCommerceCommunicationUrl", teaCommerceCommunicationUrl ) { ServerSideOnly = true } ); order.Properties.AddOrUpdate( new CustomProperty( "teaCommerceContinueUrl", teaCommerceContinueUrl ) { ServerSideOnly = true } ); order.Properties.AddOrUpdate( new CustomProperty( "teaCommerceCallbackUrl", teaCommerceCallBackUrl ) { ServerSideOnly = true } ); return htmlForm; } public override string GetContinueUrl( Order order, IDictionary<string, string> settings ) { settings.MustNotBeNull( "settings" ); settings.MustContainKey( "merchant.confirmation_uri", "settings" ); return settings[ "merchant.confirmation_uri" ]; } public override string GetCancelUrl( Order order, IDictionary<string, string> settings ) { return ""; //not used in Klarna } public override CallbackInfo ProcessCallback( Order order, HttpRequest request, IDictionary<string, string> settings ) { CallbackInfo callbackInfo = null; try { order.MustNotBeNull( "order" ); request.MustNotBeNull( "request" ); settings.MustNotBeNull( "settings" ); settings.MustContainKey( "sharedSecret", "settings" ); IConnector connector = Connector.Create( settings[ "sharedSecret" ] ); KlarnaOrder klarnaOrder = new KlarnaOrder( connector, new Uri( order.Properties[ "klarnaLocation" ] ) ) { ContentType = KlarnaApiRequestContentType }; klarnaOrder.Fetch(); if ( (string)klarnaOrder.GetValue( "status" ) == "checkout_complete" ) { //We need to populate the order with the information entered into Klarna. SaveOrderPropertiesFromKlarnaCallback( order, klarnaOrder ); decimal amount = ( (JObject)klarnaOrder.GetValue( "cart" ) )[ "total_price_including_tax" ].Value<decimal>() / 100M; string klarnaId = klarnaOrder.GetValue( "id" ).ToString(); callbackInfo = new CallbackInfo( amount, klarnaId, PaymentState.Authorized ); klarnaOrder.Update( new Dictionary<string, object>() { { "status", "created" } } ); } else { throw new Exception( "Trying to process a callback from Klarna with an order that isn't completed" ); } } catch ( Exception ex ) { LoggingService.Instance.Log( "Klarna(" + order.CartNumber + ") - Error recieving callback - Error: " + ex ); } return callbackInfo; } protected virtual void SaveOrderPropertiesFromKlarnaCallback( Order order, KlarnaOrder klarnaOrder ) { //Some order properties in Tea Commerce comes with a special alias, //defining a mapping of klarna propteries to these aliases. Store store = StoreService.Instance.Get( order.StoreId ); Dictionary<string, string> magicOrderPropertyAliases = new Dictionary<string, string>{ { "billing_address.given_name", Constants.OrderPropertyAliases.FirstNamePropertyAlias }, { "billing_address.family_name", Constants.OrderPropertyAliases.LastNamePropertyAlias }, { "billing_address.email", Constants.OrderPropertyAliases.EmailPropertyAlias }, }; //The klarna properties we wish to save on the order. List<string> klarnaPropertyAliases = new List<string>{ "billing_address.given_name", "billing_address.family_name", "billing_address.care_of", "billing_address.street_address", "billing_address.postal_code", "billing_address.city", "billing_address.email", "billing_address.phone", "shipping_address.given_name", "shipping_address.family_name", "shipping_address.care_of", "shipping_address.street_address", "shipping_address.postal_code", "shipping_address.city", "shipping_address.email", "shipping_address.phone" , }; Dictionary<string, object> klarnaProperties = klarnaOrder.Marshal(); foreach ( string klarnaPropertyAlias in klarnaPropertyAliases ) { //if a property mapping exists then use the magic alias, otherwise use the property name itself. string tcOrderPropertyAlias = magicOrderPropertyAliases.ContainsKey( klarnaPropertyAlias ) ? magicOrderPropertyAliases[ klarnaPropertyAlias ] : klarnaPropertyAlias; string klarnaPropertyValue = ""; /* Some klarna properties are of the form parent.child * in which case the lookup in klarnaProperties * needs to be (in pseudocode) * klarnaProperties[parent].getValue(child) . * In the case that there is no '.' we assume that * klarnaProperties[klarnaPropertyAlias].ToString() * contains what we need. */ string[] klarnaPropertyParts = klarnaPropertyAlias.Split( '.' ); if ( klarnaPropertyParts.Length == 1 && klarnaProperties.ContainsKey( klarnaPropertyAlias ) ) { klarnaPropertyValue = klarnaProperties[ klarnaPropertyAlias ].ToString(); } else if ( klarnaPropertyParts.Length == 2 && klarnaProperties.ContainsKey( klarnaPropertyParts[ 0 ] ) ) { JObject parent = klarnaProperties[ klarnaPropertyParts[ 0 ] ] as JObject; if ( parent != null ) { JToken value = parent.GetValue( klarnaPropertyParts[ 1 ] ); klarnaPropertyValue = value != null ? value.ToString() : ""; } } if ( !string.IsNullOrEmpty( klarnaPropertyValue ) ) { order.Properties.AddOrUpdate( tcOrderPropertyAlias, klarnaPropertyValue ); } } // order was passed as reference and updated. Saving it now. order.Save(); } public override string ProcessRequest( Order order, HttpRequest request, IDictionary<string, string> settings ) { string response = ""; try { order.MustNotBeNull( "order" ); settings.MustNotBeNull( "settings" ); settings.MustContainKey( "sharedSecret", "settings" ); string communicationType = request[ "communicationType" ]; KlarnaOrder klarnaOrder = null; IConnector connector = Connector.Create( settings[ "sharedSecret" ] ); if ( communicationType == "checkout" ) { settings.MustContainKey( "merchant.id", "settings" ); settings.MustContainKey( "merchant.terms_uri", "settings" ); settings.MustContainKey( "locale", "settings" ); //Cart information List<Dictionary<string, object>> cartItems = new List<Dictionary<string, object>> { new Dictionary<string, object> { {"reference", settings.ContainsKey( "totalSku" ) ? settings[ "totalSku" ] : "0001"}, {"name", settings.ContainsKey( "totalName" ) ? settings[ "totalName" ] : "Total"}, {"quantity", 1}, {"unit_price", (int) ( order.TotalPrice.Value.WithVat*100M )}, {"tax_rate", 0} } }; Dictionary<string, object> data = new Dictionary<string, object> { { "cart", new Dictionary<string, object> { { "items", cartItems } } } }; string klarnaLocation = order.Properties[ "klarnaLocation" ]; string merchantTermsUri = settings[ "merchant.terms_uri" ]; if ( !merchantTermsUri.StartsWith( "http" ) ) { Uri baseUrl = new UriBuilder( HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port ).Uri; merchantTermsUri = new Uri( baseUrl, merchantTermsUri ).AbsoluteUri; } //Merchant information data[ "merchant" ] = new Dictionary<string, object> { {"id", settings[ "merchant.id" ]}, {"terms_uri", merchantTermsUri}, {"checkout_uri", request.UrlReferrer.ToString()}, {"confirmation_uri", order.Properties[ "teaCommerceContinueUrl" ]}, {"push_uri", order.Properties[ "teaCommerceCallbackUrl" ]} }; data[ "merchant_reference" ] = new Dictionary<string, object>() { {"orderid1", order.CartNumber} }; //Combined data Currency currency = CurrencyService.Instance.Get( order.StoreId, order.CurrencyId ); //If the currency is not a valid iso4217 currency then throw an error if ( !Iso4217CurrencyCodes.ContainsKey( currency.IsoCode ) ) { throw new Exception( "You must specify an ISO 4217 currency code for the " + currency.Name + " currency" ); } data[ "purchase_country" ] = CountryService.Instance.Get( order.StoreId, order.PaymentInformation.CountryId ).RegionCode; data[ "purchase_currency" ] = currency.IsoCode; data[ "locale" ] = settings[ "locale" ]; //Check if the order has a Klarna location URI property - then we try and update the order if ( !string.IsNullOrEmpty( klarnaLocation ) ) { try { klarnaOrder = new KlarnaOrder( connector, new Uri( klarnaLocation ) ) { ContentType = KlarnaApiRequestContentType }; klarnaOrder.Fetch(); klarnaOrder.Update( data ); } catch ( Exception ) { //Klarna cart session has expired and we make sure to remove the Klarna location URI property klarnaOrder = null; } } //If no Klarna order was found to update or the session expired - then create new Klarna order if ( klarnaOrder == null ) { klarnaOrder = new KlarnaOrder( connector ) { BaseUri = settings.ContainsKey( "testMode" ) && settings[ "testMode" ] == "1" ? new Uri( "https://checkout.testdrive.klarna.com/checkout/orders" ) : new Uri( "https://checkout.klarna.com/checkout/orders" ), ContentType = KlarnaApiRequestContentType }; //Create new order klarnaOrder.Create( data ); klarnaOrder.Fetch(); order.Properties.AddOrUpdate( new CustomProperty( "klarnaLocation", klarnaOrder.Location.ToString() ) { ServerSideOnly = true } ); order.Save(); } } else if ( communicationType == "confirmation" ) { //get confirmation response string klarnaLocation = order.Properties[ "klarnaLocation" ]; if ( !string.IsNullOrEmpty( klarnaLocation ) ) { //Fetch and show confirmation page if status is not checkout_incomplete klarnaOrder = new KlarnaOrder( connector, new Uri( klarnaLocation ) ) { ContentType = KlarnaApiRequestContentType }; klarnaOrder.Fetch(); if ( (string)klarnaOrder.GetValue( "status" ) == "checkout_incomplete" ) { throw new Exception( "Confirmation page reached without a Klarna order that is finished" ); } } } //Get the JavaScript snippet from the Klarna order if ( klarnaOrder != null ) { JObject guiElement = klarnaOrder.GetValue( "gui" ) as JObject; if ( guiElement != null ) { response = guiElement[ "snippet" ].ToString(); } } } catch ( Exception exp ) { LoggingService.Instance.Log( exp, "Klarna(" + order.CartNumber + ") - ProcessRequest" ); } return response; } public override string GetLocalizedSettingsKey( string settingsKey, CultureInfo culture ) { switch ( settingsKey ) { case "paymentFormUrl": return settingsKey + "<br/><small>e.g. /payment/</small>"; case "merchant.confirmation_uri": return settingsKey + "<br/><small>e.g. /continue/</small>"; case "merchant.terms_uri": return settingsKey + "<br/><small>e.g. /terms/</small>"; case "testMode": return settingsKey + "<br/><small>1 = true; 0 = false</small>"; default: return base.GetLocalizedSettingsKey( settingsKey, culture ); } } } }
using System; using System.Collections.Generic; using LD28.Animation; using System.Collections; using System.Linq; using Microsoft.Xna.Framework; using LD28.Entity; namespace LD28.Animations { /// <summary> /// A chain animation of one or more other animations, executed in sequence. /// </summary> public sealed class Chain : IAnimation, IList<IAnimation> { private readonly List<IAnimation> _animationList = new List<IAnimation>(); private long _startTime; private long _endTime; private int _animationIndex; public IEasing Easing { get { return null; } set { } } public TimeSpan Duration { get { return TimeSpan.FromTicks(_animationList.Sum(x => x.Duration.Ticks)); } set { throw new InvalidOperationException(); } } public AnimationState State { get; private set; } public IEntity Entity { get; private set; } public float Position { get; private set; } #region Events public event AnimationStarted Started; private void OnStarted() { if (Started != null) { Started(this); } } public event AnimationProgressEventHandler Progress; private void OnProgress(float progress) { if (Progress != null) { Progress(this, progress); } } public event AnimationFinished Finished; private void OnFinished() { if (Finished != null) { Finished(this); } } #endregion public void Play(IEntity _entity) { if (State == AnimationState.Stopped || State == AnimationState.Finished) { Entity = _entity; _startTime = -1; State = AnimationState.Playing; } } public void Stop() { if (State != AnimationState.Finished) { Entity = null; _startTime = -1; State = AnimationState.Stopped; foreach (var animation in _animationList) { animation.Stop(); } } } public void Update(GameTime gameTime) { if (State == AnimationState.Playing) { var currentTime = gameTime.TotalGameTime.Ticks; // Initialize the star time if necessary. if (_startTime < 0) { _startTime = currentTime; _endTime = _startTime + Duration.Ticks; OnStarted(); // Start the first animation. _animationList[_animationIndex].Play(Entity); } // Calculate the current progress. Position = MathHelper.Clamp(1.0f - 1.0f / (_endTime - _startTime) * (_endTime - currentTime), 0.0f, 1.0f); OnProgress(Position); // Update the current animation. var animation = _animationList[_animationIndex]; animation.Update(gameTime); if (animation.Position >= 1.0f && _animationIndex + 1 < _animationList.Count) { _animationList[++_animationIndex].Play(Entity); } // Check if the animation has been finished. if (currentTime >= _endTime) { State = AnimationState.Finished; OnFinished(); } } } #region List Members public int IndexOf(IAnimation item) { return _animationList.IndexOf(item); } public void Insert(int index, IAnimation item) { _animationList.Insert(index, item); } public void RemoveAt(int index) { _animationList.RemoveAt(index); } public IAnimation this[int index] { get { return _animationList[index]; } set { _animationList[index] = value; } } public void Add(IAnimation item) { _animationList.Add(item); } public void Clear() { _animationList.Clear(); } public bool Contains(IAnimation item) { return _animationList.Contains(item); } public void CopyTo(IAnimation[] array, int arrayIndex) { _animationList.CopyTo(array, arrayIndex); } public int Count { get { return _animationList.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(IAnimation item) { return _animationList.Remove(item); } public IEnumerator<IAnimation> GetEnumerator() { return _animationList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
/* The MIT License (MIT) Copyright (c) 2015 Huw Bowles & Daniel Zimmermann 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. */ // this is an attempt to generalise the sample slice advection based on FPI to support full 3D transformations // (so a 2D ray scale texture). the core works but the slice extension proved to be difficult and was never // implemented using UnityEngine; using System.Collections; [ExecuteInEditMode] public class AdvectedScales2D_FPI : MonoBehaviour { [Tooltip("Used to differentiate/sort the two advection computations")] public int radiusIndex = 0; [Tooltip("The radius of this sample slice. Advection is performed at this radius")] public float radius = 10.0f; AdvectedScalesSettings settings; public float[,] scales_norm; Vector3 lastPos; Vector3 lastForward; Vector3 lastRight; Vector3 lastUp; float motionMeasure = 0.0f; void Start() { settings = GetComponent<AdvectedScalesSettings> (); scales_norm = new float[settings.scaleCount,settings.scaleCount]; // init scales to something interesting for( int j = 0; j < settings.scaleCount; j++ ) { float phi = getPhi( j ); for( int i = 0; i < settings.scaleCount; i++ ) { float theta = getTheta( i ); float fixedZ = Mathf.Lerp( Mathf.Cos(CloudsBase.halfFov_horiz_rad), 1.0f, settings.fixedZProp ) / (Mathf.Sin(theta)*Mathf.Cos(phi)); float fixedR = (Mathf.Sin(13f*j/(float)settings.scaleCount)*Mathf.Sin(8f*i/(float)settings.scaleCount)*settings.fixedRNoise + 1f); scales_norm[i,j] = Mathf.Lerp( fixedZ, fixedR, settings.reInitCurvature ); } } lastPos = transform.position; lastForward = transform.forward; lastRight = transform.right; lastUp = transform.up; } void Update() { if( scales_norm == null || settings.scaleCount*settings.scaleCount != scales_norm.Length || settings.reInitScales ) Start(); float dt = Mathf.Max( Time.deltaTime, 0.033f ); float vel = (transform.position - lastPos).magnitude / dt; if( settings.clearOnTeleport && vel > 100.0f ) { ClearAfterTeleport(); return; } // compute motion measures // compute rotation of camera (heading only) float rotRad = Vector3.Angle( transform.forward, lastForward ) * Mathf.Sign( Vector3.Cross( lastForward, transform.forward ).y ) * Mathf.Deg2Rad; // compute motion measure float motionMeasureRot = Mathf.Clamp01(Mathf.Abs(settings.motionMeasCoeffRot * rotRad/dt)); float motionMeasureTrans = Mathf.Clamp01(Mathf.Abs(settings.motionMeasCoeffStrafe * vel)); motionMeasure = Mathf.Max( motionMeasureRot, motionMeasureTrans ); if (!settings.useMotionMeas) motionMeasure = 1; // working data float[,] scales_new_norm = new float[settings.scaleCount, settings.scaleCount]; //////////////////////////////// // advection if( settings.doAdvection ) { bool oneIn = false; for( int j = 0; j < settings.scaleCount; j++ ) { float phi1 = getPhi(j); for( int i = 0; i < settings.scaleCount; i++ ) { float theta1 = getTheta(i); float theta0, phi0; InvertAdvection( theta1, phi1, out theta0, out phi0 ); float r1 = ComputeR1( theta0, phi0 ); scales_new_norm[i, j] = r1 / radius; // detect case where no samples were taken from the old slice oneIn = oneIn || (thetaWithinView(theta0) && phiWithinView(phi0)); } } /* // if no samples taken, call this a teleport, reinit scales if( !oneIn && !settings.debugFreezeAdvection ) { ClearAfterTeleport(); } */ /* // now clamp the scales if( settings.clampScaleValues ) { // clamp the values for( int j = 0; j < settings.scaleCount; j++ ) { for( int i = 0; i < settings.scaleCount; i++ ) { // min: an inverted circle, i.e. concave instead of convex. this allows obiting // max: the fixed z line at the highest point of the circle. this allows strafing after rotating without aliasing scales_new_norm[i,j] = Mathf.Clamp( scales_new_norm[i,j], 0.9f*(1.0f - (Mathf.Sin(getTheta(i))-Mathf.Cos(CloudsBase.halfFov_horiz_rad))), 1.0f/Mathf.Sin(getTheta(i)) ); } } } */ /* // limit/relax the gradients if( settings.limitGradient ) { RelaxGradients( scales_new_norm ); } */ // all done - store the new r values if( !settings.debugFreezeAdvection ) { // normal path - store the scales then debug draw for( int j = 0; j < settings.scaleCount; j++ ) { for( int i = 0; i < settings.scaleCount; i++ ) { scales_norm[i, j] = scales_new_norm[i, j]; } } Draw(); } /*else { // for freezing advection, apply the scales temporarily and draw them, but then revert them float[] bkp = new float[scales_norm.Length]; for( int i = 0; i < bkp.Length; i++ ) bkp[i] = scales_norm[i]; for( int i = 0; i < settings.scaleCount; i++ ) scales_norm[i] = scales_new_norm[i]; Draw(); for( int i = 0; i < settings.scaleCount; i++ ) scales_norm[i] = bkp[i]; }*/ } if( !settings.debugFreezeAdvection ) { lastPos = transform.position; lastForward = transform.forward; lastRight = transform.right; lastUp = transform.up; } } // gradient relaxation // the following is complex and I don't know how much of this could maybe be done // in a single pass or otherwise simplified. more experimentation is needed. // // the two scales at the sides of the frustum are not changed by this process. // there are two stages - the first is an inside-out scheme which starts from // the middle and moves outwards. the second is an outside-in scheme which moves // towards the middle from the side. void RelaxGradients( float[] r_new ) { // INSIDE OUT for( int i = settings.scaleCount/2; i < settings.scaleCount-1; i++ ) { RelaxGradient( i, i-1, r_new ); } for( int i = settings.scaleCount/2; i >= 1; i-- ) { RelaxGradient( i, i+1, r_new ); } // OUTSIDE IN for( int i = 1; i <= settings.scaleCount/2; i++ ) { RelaxGradient( i, i-1, r_new ); } for( int i = settings.scaleCount-2; i >= settings.scaleCount/2; i-- ) { RelaxGradient( i, i+1, r_new ); } } void RelaxGradient( int i, int i1, float[] scales_new_norm ) { float dx = radius*scales_new_norm[i]*Mathf.Cos(getTheta(i)) - radius*scales_new_norm[i1]*Mathf.Cos(getTheta(i1)); if( Mathf.Abs(dx) < 0.0001f ) { //Debug.LogError("dx too small! " + dx); dx = Mathf.Sign(dx) * 0.0001f; } float meas = ( radius*scales_new_norm[i]*Mathf.Sin(getTheta(i)) - radius*scales_new_norm[i1]*Mathf.Sin(getTheta(i1)) ) / dx; float measClamped = Mathf.Clamp( meas, -settings.maxGradient, settings.maxGradient ); float dt = Mathf.Max( Time.deltaTime, 1.0f/30.0f ); scales_new_norm[i] = Mathf.Lerp( radius*scales_new_norm[i], (measClamped*dx + radius*scales_new_norm[i1]*Mathf.Sin(getTheta(i1))) / Mathf.Sin(getTheta(i)), motionMeasure*settings.alphaGradient * 30.0f * dt ) / radius; } // reset scales to a fixed-z layout void ClearAfterTeleport() { Debug.Log( "Teleport event, resetting layout" ); for( int j = 0; j < settings.scaleCount; j++ ) { float cos_phi = Mathf.Cos( getPhi( j ) ); for( int i = 0; i < settings.scaleCount; i++ ) { scales_norm[i, j] = Mathf.Cos( CloudsBase.halfFov_horiz_rad ) / (Mathf.Sin(getTheta(i))*cos_phi); } } lastPos = transform.position; lastForward = transform.forward; lastRight = transform.right; lastUp = transform.up; } public float getTheta( int i ) { return CloudsBase.halfFov_horiz_rad * (2.0f * (float)i/(float)(settings.scaleCount-1) - 1.0f) + Mathf.PI/2.0f; } bool thetaWithinView( float theta ) { return Mathf.Abs( theta - Mathf.PI/2.0f ) <= CloudsBase.halfFov_horiz_rad; } public float getPhi( int j ) { return CloudsBase.halfFov_vert_rad * (2.0f * (float)j/(float)(settings.scaleCount-1) - 1.0f); } bool phiWithinView( float phi ) { return Mathf.Abs( phi ) <= CloudsBase.halfFov_vert_rad; } Vector3 GetRay( float theta ) { Quaternion q = Quaternion.AngleAxis( theta * Mathf.Rad2Deg, -Vector3.up ); return q * transform.right; } // note that theta for the center of the screen is PI/2. its really incovenient that angles are computed from the X axis, but // the view direction is down the Z axis. we adopted this scheme as it made a bunch of the math simpler (i think!) // // Z axis (theta = PI/2) // | // frust. \ | / // \ | / // \ | / \ theta // \|/ | // ----------------------- X axis (theta = 0) // // for theta within the view, we sample the scale from the sample slice directly // for theta outside the view, we compute a linear extension from the last point on // the sample slice, to the corresponding scale at the side of the new camera position // frustum. this is a linear approximation to how the sample slice needs to be extended // when the frustum moves. if you rotate the camera fast then you will see the linear // segments. public float sampleR( float theta, float phi ) { // move theta from [pi/2 - halfFov, pi/2 + halfFov] to [0,1] float s = (theta - (Mathf.PI/2.0f-CloudsBase.halfFov_horiz_rad))/(2.0f*CloudsBase.halfFov_horiz_rad); float t = (phi + CloudsBase.halfFov_vert_rad)/(2.0f*CloudsBase.halfFov_vert_rad); s = Mathf.Clamp01(s); t = Mathf.Clamp01(t); /*if( s < 0f || s > 1f ) { // determine which side we're on. s<0 is right side as angles increase anti-clockwise bool rightSide = s < 0f; int lastIndex = rightSide ? 0 : settings.scaleCount-1; // the start and end position of the extension Vector3 pos_slice_end, pos_extrapolated; pos_slice_end = lastPos + radius * scales_norm[lastIndex] * Mathf.Cos( getTheta(lastIndex) ) * lastRight + radius * scales_norm[lastIndex] * Mathf.Sin( getTheta(lastIndex) ) * lastForward; float theta_edge = getTheta(lastIndex); // we always nudge scale back to default val (scale return). to compute how much we're nudging // the scale, we find our how far we're extending it, and we do this in radians. Vector3 extrapolatedDir = transform.forward * Mathf.Sin(theta_edge) + transform.right * Mathf.Cos(theta_edge); float angleSubtended = Vector3.Angle( pos_slice_end - transform.position, extrapolatedDir ) * Mathf.Deg2Rad; float lerpAlpha = Mathf.Clamp01( motionMeasure*settings.alphaScaleReturn*angleSubtended ); float r_extrap = Mathf.Lerp( sampleR(theta_edge), radius, lerpAlpha ); // now compute actual pos pos_extrapolated = transform.position + transform.forward * r_extrap * Mathf.Sin(theta_edge) + transform.right * r_extrap * Mathf.Cos(theta_edge); // now intersect ray with extension to find scale. Vector3 rayExtent = lastPos + Mathf.Cos( theta ) * lastRight + Mathf.Sin( theta ) * lastForward; Vector2 inter; bool found; found = IntersectLineSegments( new Vector2( pos_slice_end.x, pos_slice_end.z ), new Vector2( pos_extrapolated.x, pos_extrapolated.z ), new Vector2( lastPos.x, lastPos.z ), new Vector2( rayExtent.x, rayExtent.z ), out inter ); // no unique intersection point - shouldnt happen if( !found ) return sampleR(theta_edge); // the intersection point between the ray for the query theta and the linear extension Vector3 pt = new Vector3( inter.x, 0f, inter.y ); // make flatland Vector3 offset = pt - lastPos; offset.y = 0f; return offset.magnitude; }*/ // get from 0 to rCount-1 s *= (float)(settings.scaleCount-1); t *= (float)(settings.scaleCount-1); int i0 = Mathf.FloorToInt(s); int i1 = Mathf.CeilToInt(s); int j0 = Mathf.FloorToInt(t); int j1 = Mathf.CeilToInt(t); float resultj0 = Mathf.Lerp( scales_norm[i0,j0], scales_norm[i1,j0], Mathf.Repeat(s, 1.0f) ); float resultj1 = Mathf.Lerp( scales_norm[i0,j1], scales_norm[i1,j1], Mathf.Repeat(s, 1.0f) ); float result = Mathf.Lerp( resultj0, resultj1, Mathf.Repeat(t, 1.0f) ); return radius * result; } // this assumes that sampleR, lastPos, etc all return values from the PREVIOUS frame! Vector3 ComputePos0_world( float theta, float phi ) { float r0 = sampleR( theta, phi ); // 3d polar coordinates return lastPos + r0 * Mathf.Cos(phi) * (Mathf.Cos(theta) * lastRight + Mathf.Sin(theta) * lastForward) + r0 * Mathf.Sin(phi) * lastUp; } // solver. after the camera has moved, for a particular ray scale at angle theta1, we can find the angle to the corresponding // sample before the camera move theta0 using an iterative computation - fixed point iteration. // we previously published a paper titled Iterative Image Warping about using FPI for very similar use cases: // http://www.disneyresearch.com/wp-content/uploads/Iterative-Image-Warping-Paper.pdf void InvertAdvection( float theta1, float phi1, out float theta0, out float phi0 ) { // just guess the source position is the current pos (basically, that the camera hasn't moved) theta0 = theta1; phi0 = phi1; // N iterations of FPI. compute where our guess would get us, and then update our guess with the error. // we could monitor the iteration to ensure convergence etc but the advection seems to be well behaved for 8 iterations for( int i = 0; i < settings.advectionIters; i++ ) { float newTheta0 = theta0 + theta1 - ComputeTheta1( theta0, phi0 ); float newPhi0 = phi0 + phi1 - ComputePhi1( theta0, phi0 ); theta0 = newTheta0; phi0 = newPhi0; } } // input: theta0 is angle before camera moved, which specifies a specific point on the sample slice P // output: theta1 gives angle after camera moved to the sample slice point P // this is the opposite to what we want - we will know the angle afterwards theta1 and want to compute // the angle before theta0. however we invert this using FPI. float ComputeTheta1( float theta0, float phi0 ) { Vector3 pos0 = ComputePos0_world( theta0, phi0 ); // end position, removing foward motion of cam, in local space Vector3 pos1_local = transform.InverseTransformPoint( pos0 ); float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward); if( !settings.advectionCompensatesForwardPin ) pos1_local += pullInCam * Vector3.forward; else pos1_local += pullInCam * pos1_local.normalized * sampleR(theta0, phi0) / sampleR(Mathf.PI/2.0f, 0.0f); return Mathf.Atan2( pos1_local.z, pos1_local.x ); } float ComputePhi1( float theta0, float phi0 ) { Vector3 pos0 = ComputePos0_world( theta0, phi0 ); // end position, removing foward motion of cam, in local space Vector3 pos1_local = transform.InverseTransformPoint( pos0 ); float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward); if( !settings.advectionCompensatesForwardPin ) pos1_local += pullInCam * Vector3.forward; else pos1_local += pullInCam * pos1_local.normalized * sampleR(theta0, phi0) / sampleR(Mathf.PI/2.0f, 0.0f); // 3d polar coordinates are fun return Mathf.Atan2( pos1_local.y, Mathf.Sqrt(pos1_local.x*pos1_local.x+pos1_local.z*pos1_local.z) ); } // for an angle theta0 specifying a point on the sample slice before the camera moves, // we can compute a radius to this point by computing the distance to the new camera // position. this completes the advection computation float ComputeR1( float theta0, float phi0 ) { Vector3 pos0 = ComputePos0_world( theta0, phi0 ); // end position, removing forward motion of cam Vector3 pos1 = transform.position; float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward); if( !settings.advectionCompensatesForwardPin ) pos1 -= pullInCam * transform.forward; Vector3 offset = pos0 - pos1; if( settings.advectionCompensatesForwardPin ) offset += pullInCam * offset.normalized * sampleR(theta0, phi0) / sampleR(Mathf.PI/2f, 0f); return offset.magnitude; } void Draw() { float angleExpand = 1.2f; for( int j = 1; j < settings.scaleCount; j++ ) { float prevPhi = getPhi(j-1) * angleExpand; float thisPhi = getPhi(j) * angleExpand; for( int i = 1; i < settings.scaleCount; i++ ) { // only draw every 4th for perf reasons if( ( i + j ) % 4 != 0 ) continue; float prevTheta = getTheta(i-1); float thisTheta = getTheta(i); prevTheta = Mathf.PI/2.0f + (prevTheta-Mathf.PI/2.0f) * angleExpand; thisTheta = Mathf.PI/2.0f + (thisTheta-Mathf.PI/2.0f) * angleExpand; Color col = Color.white; if( !thetaWithinView(thisTheta) || !thetaWithinView(prevTheta) || !phiWithinView(thisPhi) || !phiWithinView(prevPhi) ) col *= 0.5f; Debug.DrawLine( ComputePos0_world( prevTheta, prevPhi ), ComputePos0_world( thisTheta, thisPhi ), col ); /*if( settings.debugDrawAdvectionGuides ) { scale = settings.debugDrawScale * 1.0f; Color fadeRed = Color.red; fadeRed.a = 0.25f; Debug.DrawLine( transform.position + prevRd * radius * scale, transform.position + thisRd * radius * scale, fadeRed ); scale = Mathf.Cos(CloudsBase.halfFov_horiz_rad) / Mathf.Sin(thisTheta); Debug.DrawLine( transform.position + prevRd * radius * scale, transform.position + thisRd * radius * scale, fadeRed ); }*/ } } } // loosely based on http://ideone.com/PnPJgb // performance of this is very bad, lots of temp things being constructed. i should really just inline the code // above but leaving like this for now. static bool IntersectLineSegments(Vector2 A, Vector2 B, Vector2 C, Vector2 D, out Vector2 intersect ) { Vector2 r = B - A; Vector2 s = D - C; float rxs = r.x * s.y - r.y * s.x; if( Mathf.Abs(rxs) <= Mathf.Epsilon ) { // Lines are parallel or collinear - this is useless for us intersect = Vector2.zero; return false; } Vector2 CmA = C - A; float CmAxs = CmA.x * s.y - CmA.y * s.x; float t = CmAxs / rxs; intersect = Vector2.Lerp( A, B, t ); return true; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Apress.Recipes.WebApi.WebHost.Areas.HelpPage.ModelDescriptions; using Apress.Recipes.WebApi.WebHost.Areas.HelpPage.Models; namespace Apress.Recipes.WebApi.WebHost.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Storage.Models; namespace Microsoft.WindowsAzure.Management.Storage { /// <summary> /// The Service Management API includes operations for managing the storage /// accounts beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx for /// more information) /// </summary> public partial interface IStorageAccountOperations { /// <summary> /// Abort storage account migration api validates and aborts the given /// storage account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> AbortMigrationAsync(string storageAccountName, CancellationToken cancellationToken); /// <summary> /// Abort storage account migration api validates and aborts the given /// storage account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginAbortMigrationAsync(string storageAccountName, CancellationToken cancellationToken); /// <summary> /// Commit storage account migration api validates and commits the /// given storage account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginCommitMigrationAsync(string storageAccountName, CancellationToken cancellationToken); /// <summary> /// The Begin Creating Storage Account operation creates a new storage /// account in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Begin Creating Storage Account operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginCreatingAsync(StorageAccountCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Prepare storage account migration api validates and prepares the /// given storage account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginPrepareMigrationAsync(string storageAccountName, CancellationToken cancellationToken); /// <summary> /// The Check Name Availability operation checks if a storage account /// name is available for use in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx /// for more information) /// </summary> /// <param name='accountName'> /// The desired storage account name to check for availability. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response to a storage account check name availability request. /// </returns> Task<CheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string accountName, CancellationToken cancellationToken); /// <summary> /// Commit storage account migration api validates and commits the /// given storage account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> CommitMigrationAsync(string storageAccountName, CancellationToken cancellationToken); /// <summary> /// The Create Storage Account operation creates a new storage account /// in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Storage Account operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> CreateAsync(StorageAccountCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Delete Storage Account operation deletes the specified storage /// account from Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264517.aspx /// for more information) /// </summary> /// <param name='accountName'> /// The name of the storage account to be deleted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> DeleteAsync(string accountName, CancellationToken cancellationToken); /// <summary> /// The Get Storage Account Properties operation returns system /// properties for the specified storage account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx /// for more information) /// </summary> /// <param name='accountName'> /// Name of the storage account to get properties for. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Storage Account Properties operation response. /// </returns> Task<StorageAccountGetResponse> GetAsync(string accountName, CancellationToken cancellationToken); /// <summary> /// The Get Storage Keys operation returns the primary and secondary /// access keys for the specified storage account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460785.aspx /// for more information) /// </summary> /// <param name='accountName'> /// The name of the desired storage account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The primary and secondary access keys for a storage account. /// </returns> Task<StorageAccountGetKeysResponse> GetKeysAsync(string accountName, CancellationToken cancellationToken); /// <summary> /// The List Storage Accounts operation lists the storage accounts /// available under the current subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Storage Accounts operation response. /// </returns> Task<StorageAccountListResponse> ListAsync(CancellationToken cancellationToken); /// <summary> /// Prepare storage account migration api validates and prepares the /// given storage account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> PrepareMigrationAsync(string storageAccountName, CancellationToken cancellationToken); /// <summary> /// The Regenerate Keys operation regenerates the primary or secondary /// access key for the specified storage account. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Regenerate Keys operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The primary and secondary access keys for a storage account. /// </returns> Task<StorageAccountRegenerateKeysResponse> RegenerateKeysAsync(StorageAccountRegenerateKeysParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Update Storage Account operation updates the label and the /// description, and enables or disables the geo-replication status /// for a storage account in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx /// for more information) /// </summary> /// <param name='accountName'> /// Name of the storage account to update. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Storage Account operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> UpdateAsync(string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Validate storage account migration api validates the given storage /// account for IaaS Classic to ARM migration. /// </summary> /// <param name='storageAccountName'> /// Name of storage account to be migrated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Validate Storage Account Migration operation response. /// </returns> Task<XrpMigrationValidateStorageResponse> ValidateMigrationAsync(string storageAccountName, CancellationToken cancellationToken); } }
namespace Volante.Impl { using System; using System.Collections; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics; using System.Text; using Volante; public sealed class ClassDescriptor : Persistent { internal ClassDescriptor next; internal String name; internal FieldDescriptor[] allFields; internal bool hasReferences; internal static Module lastModule; public class FieldDescriptor : Persistent { internal String fieldName; internal String className; internal FieldType type; internal ClassDescriptor valueDesc; [NonSerialized()] internal FieldInfo field; [NonSerialized()] internal bool recursiveLoading; [NonSerialized()] internal MethodInfo constructor; public bool equals(FieldDescriptor fd) { return fieldName.Equals(fd.fieldName) && className.Equals(fd.className) && valueDesc == fd.valueDesc && type == fd.type; } } [NonSerialized()] internal Type cls; [NonSerialized()] internal bool hasSubclasses; [NonSerialized()] internal ConstructorInfo defaultConstructor; [NonSerialized()] internal bool resolved; [NonSerialized()] internal GeneratedSerializer serializer; public enum FieldType { tpBoolean, tpByte, tpSByte, tpShort, tpUShort, tpChar, tpEnum, tpInt, tpUInt, tpLong, tpULong, tpFloat, tpDouble, tpString, tpDate, tpObject, tpOid, tpValue, tpRaw, tpGuid, tpDecimal, tpLink, tpArrayOfBoolean, tpArrayOfByte, tpArrayOfSByte, tpArrayOfShort, tpArrayOfUShort, tpArrayOfChar, tpArrayOfEnum, tpArrayOfInt, tpArrayOfUInt, tpArrayOfLong, tpArrayOfULong, tpArrayOfFloat, tpArrayOfDouble, tpArrayOfString, tpArrayOfDate, tpArrayOfObject, tpArrayOfOid, tpArrayOfValue, tpArrayOfRaw, tpArrayOfGuid, tpArrayOfDecimal, tpLast } internal static int[] Sizeof = new int[] { 1, // tpBoolean, 1, // tpByte, 1, // tpSByte, 2, // tpShort, 2, // tpUShort, 2, // tpChar, 4, // tpEnum, 4, // tpInt, 4, // tpUInt, 8, // tpLong, 8, // tpULong, 4, // tpFloat, 8, // tpDouble, 0, // tpString, 8, // tpDate, 4, // tpObject, 4, // tpOid, 0, // tpValue, 0, // tpRaw, 16,// tpGuid, 16,// tpDecimal, 0, // tpLink, 0, // tpArrayOfBoolean, 0, // tpArrayOfByte, 0, // tpArrayOfSByte, 0, // tpArrayOfShort, 0, // tpArrayOfUShort, 0, // tpArrayOfChar, 0, // tpArrayOfEnum, 0, // tpArrayOfInt, 0, // tpArrayOfUInt, 0, // tpArrayOfLong, 0, // tpArrayOfULong, 0, // tpArrayOfFloat, 0, // tpArrayOfDouble, 0, // tpArrayOfString, 0, // tpArrayOfDate, 0, // tpArrayOfObject, 0, // tpArrayOfOid, 0, // tpArrayOfValue, 0, // tpArrayOfRaw, 0, // tpArrayOfGuid, 0 // tpArrayOfDecimal, }; internal static Type[] defaultConstructorProfile = new Type[0]; internal static object[] noArgs = new object[0]; #if CF static internal object parseEnum(Type type, String value) { foreach (FieldInfo fi in type.GetFields()) { if (fi.IsLiteral && fi.Name.Equals(value)) { return fi.GetValue(null); } } throw new ArgumentException(value); } #endif public bool equals(ClassDescriptor cd) { if (cd == null || allFields.Length != cd.allFields.Length) { return false; } for (int i = 0; i < allFields.Length; i++) { if (!allFields[i].equals(cd.allFields[i])) { return false; } } return true; } internal Object newInstance() { try { return defaultConstructor.Invoke(noArgs); } catch (System.Exception x) { throw new DatabaseException(DatabaseException.ErrorCode.CONSTRUCTOR_FAILURE, cls, x); } } #if CF internal void generateSerializer() {} #else private static CodeGenerator serializerGenerator = CodeGenerator.Instance; internal void generateSerializer() { if (!cls.IsPublic || defaultConstructor == null || !defaultConstructor.IsPublic) return; FieldDescriptor[] flds = allFields; for (int i = 0, n = flds.Length; i < n; i++) { FieldDescriptor fd = flds[i]; switch (fd.type) { case FieldType.tpValue: case FieldType.tpArrayOfValue: case FieldType.tpArrayOfObject: case FieldType.tpArrayOfEnum: case FieldType.tpArrayOfRaw: case FieldType.tpLink: case FieldType.tpArrayOfOid: return; default: break; } FieldInfo f = flds[i].field; if (f == null || !f.IsPublic) return; } serializer = serializerGenerator.Generate(this); } static private bool isObjectProperty(Type cls, FieldInfo f) { return typeof(PersistentWrapper).IsAssignableFrom(cls) && f.Name.StartsWith("r_"); } #endif MethodInfo GetConstructor(FieldInfo f, string name) { MethodInfo mi = typeof(DatabaseImpl).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); //return mi.BindGenericParameters(f.FieldType.GetGenericArguments()); //TODO: verify it's MakeGenericMethod return mi.MakeGenericMethod(f.FieldType.GetGenericArguments()); } internal static String getTypeName(Type t) { if (t.IsGenericType) { Type[] genericArgs = t.GetGenericArguments(); t = t.GetGenericTypeDefinition(); StringBuilder buf = new StringBuilder(t.FullName); buf.Append('='); char sep = '['; for (int j = 0; j < genericArgs.Length; j++) { buf.Append(sep); sep = ','; buf.Append(getTypeName(genericArgs[j])); } buf.Append(']'); return buf.ToString(); } return t.FullName; } static bool isVolanteInternalType(Type t) { return t.Namespace == typeof(IPersistent).Namespace && t != typeof(IPersistent) && t != typeof(PersistentContext) && t != typeof(Persistent); } internal void buildFieldList(DatabaseImpl db, System.Type cls, ArrayList list) { System.Type superclass = cls.BaseType; if (superclass != null && superclass != typeof(MarshalByRefObject)) { buildFieldList(db, superclass, list); } System.Reflection.FieldInfo[] flds = cls.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly); #if !CF bool isWrapper = typeof(PersistentWrapper).IsAssignableFrom(cls); #endif bool hasTransparentAttribute = cls.GetCustomAttributes(typeof(TransparentPersistenceAttribute), true).Length != 0; for (int i = 0; i < flds.Length; i++) { FieldInfo f = flds[i]; if (!f.IsNotSerialized && !f.IsStatic) { FieldDescriptor fd = new FieldDescriptor(); fd.field = f; fd.fieldName = f.Name; fd.className = getTypeName(cls); Type fieldType = f.FieldType; FieldType type = getTypeCode(fieldType); switch (type) { #if !CF case FieldType.tpInt: if (isWrapper && isObjectProperty(cls, f)) { hasReferences = true; type = FieldType.tpOid; } break; #endif case FieldType.tpArrayOfOid: fd.constructor = GetConstructor(f, "ConstructArray"); hasReferences = true; break; case FieldType.tpLink: fd.constructor = GetConstructor(f, "ConstructLink"); hasReferences = true; break; case FieldType.tpArrayOfObject: case FieldType.tpObject: hasReferences = true; if (hasTransparentAttribute && isVolanteInternalType(fieldType)) { fd.recursiveLoading = true; } break; case FieldType.tpValue: fd.valueDesc = db.getClassDescriptor(f.FieldType); hasReferences |= fd.valueDesc.hasReferences; break; case FieldType.tpArrayOfValue: fd.valueDesc = db.getClassDescriptor(f.FieldType.GetElementType()); hasReferences |= fd.valueDesc.hasReferences; break; } fd.type = type; list.Add(fd); } } } public static FieldType getTypeCode(System.Type c) { FieldType type; if (c.Equals(typeof(byte))) { type = FieldType.tpByte; } else if (c.Equals(typeof(sbyte))) { type = FieldType.tpSByte; } else if (c.Equals(typeof(short))) { type = FieldType.tpShort; } else if (c.Equals(typeof(ushort))) { type = FieldType.tpUShort; } else if (c.Equals(typeof(char))) { type = FieldType.tpChar; } else if (c.Equals(typeof(int))) { type = FieldType.tpInt; } else if (c.Equals(typeof(uint))) { type = FieldType.tpUInt; } else if (c.Equals(typeof(long))) { type = FieldType.tpLong; } else if (c.Equals(typeof(ulong))) { type = FieldType.tpULong; } else if (c.Equals(typeof(float))) { type = FieldType.tpFloat; } else if (c.Equals(typeof(double))) { type = FieldType.tpDouble; } else if (c.Equals(typeof(System.String))) { type = FieldType.tpString; } else if (c.Equals(typeof(bool))) { type = FieldType.tpBoolean; } else if (c.Equals(typeof(System.DateTime))) { type = FieldType.tpDate; } else if (c.IsEnum) { type = FieldType.tpEnum; } else if (c.Equals(typeof(decimal))) { type = FieldType.tpDecimal; } else if (c.Equals(typeof(Guid))) { type = FieldType.tpGuid; } else if (typeof(IPersistent).IsAssignableFrom(c)) { type = FieldType.tpObject; } else if (typeof(ValueType).IsAssignableFrom(c)) { type = FieldType.tpValue; } else if (typeof(IGenericPArray).IsAssignableFrom(c)) { type = FieldType.tpArrayOfOid; } else if (typeof(IGenericLink).IsAssignableFrom(c)) { type = FieldType.tpLink; } else if (c.IsArray) { type = getTypeCode(c.GetElementType()); if ((int)type >= (int)FieldType.tpLink) { throw new DatabaseException(DatabaseException.ErrorCode.UNSUPPORTED_TYPE, c); } type = (FieldType)((int)type + (int)FieldType.tpArrayOfBoolean); } else { type = FieldType.tpRaw; } return type; } internal ClassDescriptor() { } internal ClassDescriptor(DatabaseImpl db, Type cls) { this.cls = cls; name = getTypeName(cls); ArrayList list = new ArrayList(); buildFieldList(db, cls, list); allFields = (FieldDescriptor[])list.ToArray(typeof(FieldDescriptor)); defaultConstructor = cls.GetConstructor(BindingFlags.Instance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly, null, defaultConstructorProfile, null); if (defaultConstructor == null && !typeof(ValueType).IsAssignableFrom(cls)) throw new DatabaseException(DatabaseException.ErrorCode.DESCRIPTOR_FAILURE, cls); resolved = true; } internal static Type lookup(IDatabase db, String name) { var resolvedTypes = ((DatabaseImpl)db).resolvedTypes; lock (resolvedTypes) { Type cls; var ok = resolvedTypes.TryGetValue(name, out cls); if (ok) return cls; IClassLoader loader = db.Loader; if (loader != null) { cls = loader.LoadClass(name); if (cls != null) { resolvedTypes[name] = cls; return cls; } } Module last = lastModule; if (last != null) { cls = last.GetType(name); if (cls != null) { resolvedTypes[name] = cls; return cls; } } int p = name.IndexOf('='); if (p >= 0) { Type genericType = lookup(db, name.Substring(0, p)); Type[] genericParams = new Type[genericType.GetGenericArguments().Length]; int nest = 0; int i = p += 2; int n = 0; while (true) { switch (name[i++]) { case '[': nest += 1; break; case ']': if (--nest < 0) { genericParams[n++] = lookup(db, name.Substring(p, i - p - 1)); Debug.Assert(n == genericParams.Length); cls = genericType.MakeGenericType(genericParams); if (cls == null) { throw new DatabaseException(DatabaseException.ErrorCode.CLASS_NOT_FOUND, name); } resolvedTypes[name] = cls; return cls; } break; case ',': if (nest == 0) { genericParams[n++] = lookup(db, name.Substring(p, i - p - 1)); p = i; } break; } } } #if CF foreach (Assembly ass in DatabaseImpl.assemblies) #else foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies()) #endif { foreach (Module mod in ass.GetModules()) { Type t = mod.GetType(name); if (t != null) { if (cls != null) { throw new DatabaseException(DatabaseException.ErrorCode.AMBIGUITY_CLASS, name); } else { lastModule = mod; cls = t; } } } } #if !CF if (cls == null && name.EndsWith("Wrapper")) { Type originalType = lookup(db, name.Substring(0, name.Length - 7)); lock (db) { cls = ((DatabaseImpl)db).getWrapper(originalType); } } #endif if (cls == null) { throw new DatabaseException(DatabaseException.ErrorCode.CLASS_NOT_FOUND, name); } resolvedTypes[name] = cls; return cls; } } public override void OnLoad() { cls = lookup(Database, name); int n = allFields.Length; bool hasTransparentAttribute = cls.GetCustomAttributes(typeof(TransparentPersistenceAttribute), true).Length != 0; for (int i = n; --i >= 0; ) { FieldDescriptor fd = allFields[i]; fd.Load(); fd.field = cls.GetField(fd.fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (hasTransparentAttribute && fd.type == FieldType.tpObject && isVolanteInternalType(fd.field.FieldType)) { fd.recursiveLoading = true; } switch (fd.type) { case FieldType.tpArrayOfOid: fd.constructor = GetConstructor(fd.field, "ConstructArray"); break; case FieldType.tpLink: fd.constructor = GetConstructor(fd.field, "ConstructLink"); break; default: break; } } defaultConstructor = cls.GetConstructor(BindingFlags.Instance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly, null, defaultConstructorProfile, null); if (defaultConstructor == null && !typeof(ValueType).IsAssignableFrom(cls)) { throw new DatabaseException(DatabaseException.ErrorCode.DESCRIPTOR_FAILURE, cls); } DatabaseImpl s = (DatabaseImpl)Database; if (!s.classDescMap.ContainsKey(cls)) { ((DatabaseImpl)Database).classDescMap.Add(cls, this); } } internal void resolve() { if (resolved) return; DatabaseImpl classStorage = (DatabaseImpl)Database; ClassDescriptor desc = new ClassDescriptor(classStorage, cls); resolved = true; if (!desc.equals(this)) { classStorage.registerClassDescriptor(desc); } } public override bool RecursiveLoading() { return false; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Runtime; namespace Orleans { /// <summary> /// Factory for accessing grains. /// </summary> internal class GrainFactory : IInternalGrainFactory { /// <summary> /// The mapping between concrete grain interface types and delegate /// </summary> private readonly ConcurrentDictionary<Type, GrainReferenceCaster> casters = new ConcurrentDictionary<Type, GrainReferenceCaster>(); /// <summary> /// The collection of <see cref="IGrainMethodInvoker"/>s for their corresponding grain interface type. /// </summary> private readonly ConcurrentDictionary<Type, IGrainMethodInvoker> invokers = new ConcurrentDictionary<Type, IGrainMethodInvoker>(); /// <summary> /// The cache of typed system target references. /// </summary> private readonly Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>> typedSystemTargetReferenceCache = new Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>>(); /// <summary> /// The cache of type metadata. /// </summary> private readonly TypeMetadataCache typeCache; /// <summary> /// The runtime client. /// </summary> private readonly IRuntimeClient runtimeClient; // Make this internal so that client code is forced to access the IGrainFactory using the // GrainClient (to make sure they don't forget to initialize the client). public GrainFactory(IRuntimeClient runtimeClient, TypeMetadataCache typeCache) { this.runtimeClient = runtimeClient; this.typeCache = typeCache; } /// <summary> /// Casts an <see cref="IAddressable"/> to a concrete <see cref="GrainReference"/> implementaion. /// </summary> /// <param name="existingReference">The existing <see cref="IAddressable"/> reference.</param> /// <returns>The concrete <see cref="GrainReference"/> implementation.</returns> internal delegate object GrainReferenceCaster(IAddressable existingReference); /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidKey { Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = TypeCodeMapper.ComposeGrainId(implementation, primaryKey, interfaceType); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerKey { Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = TypeCodeMapper.ComposeGrainId(implementation, primaryKey, interfaceType); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithStringKey { Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = TypeCodeMapper.ComposeGrainId(implementation, primaryKey, interfaceType); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="keyExtension">The key extention of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidCompoundKey { GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension); Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = TypeCodeMapper.ComposeGrainId(implementation, primaryKey, interfaceType, keyExtension); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="keyExtension">The key extention of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerCompoundKey { GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension); Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = TypeCodeMapper.ComposeGrainId(implementation, primaryKey, interfaceType, keyExtension); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Creates a reference to the provided <paramref name="obj"/>. /// </summary> /// <typeparam name="TGrainObserverInterface"> /// The specific <see cref="IGrainObserver"/> type of <paramref name="obj"/>. /// </typeparam> /// <param name="obj">The object to create a reference to.</param> /// <returns>The reference to <paramref name="obj"/>.</returns> public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj) where TGrainObserverInterface : IGrainObserver { return Task.FromResult(this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj)); } /// <summary> /// Deletes the provided object reference. /// </summary> /// <typeparam name="TGrainObserverInterface"> /// The specific <see cref="IGrainObserver"/> type of <paramref name="obj"/>. /// </typeparam> /// <param name="obj">The reference being deleted.</param> /// <returns>A <see cref="Task"/> representing the work performed.</returns> public Task DeleteObjectReference<TGrainObserverInterface>( IGrainObserver obj) where TGrainObserverInterface : IGrainObserver { this.runtimeClient.DeleteObjectReference(obj); return TaskDone.Done; } public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable { return this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj); } private TGrainObserverInterface CreateObjectReferenceImpl<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable { var interfaceType = typeof(TGrainObserverInterface); var interfaceTypeInfo = interfaceType.GetTypeInfo(); if (!interfaceTypeInfo.IsInterface) { throw new ArgumentException( $"The provided type parameter must be an interface. '{interfaceTypeInfo.FullName}' is not an interface."); } if (!interfaceTypeInfo.IsInstanceOfType(obj)) { throw new ArgumentException($"The provided object must implement '{interfaceTypeInfo.FullName}'.", nameof(obj)); } IGrainMethodInvoker invoker; if (!this.invokers.TryGetValue(interfaceType, out invoker)) { invoker = this.MakeInvoker(interfaceType); this.invokers.TryAdd(interfaceType, invoker); } return this.Cast<TGrainObserverInterface>(this.runtimeClient.CreateObjectReference(obj, invoker)); } private IAddressable MakeGrainReferenceFromType(Type interfaceType, GrainId grainId) { var typeInfo = interfaceType.GetTypeInfo(); return GrainReference.FromGrainId( grainId, typeInfo.IsGenericType ? TypeUtils.GenericTypeArgsString(typeInfo.UnderlyingSystemType.FullName) : null); } private GrainClassData GetGrainClassData(Type interfaceType, string grainClassNamePrefix) { if (!GrainInterfaceUtils.IsGrainType(interfaceType)) { throw new ArgumentException("Cannot fabricate grain-reference for non-grain type: " + interfaceType.FullName); } var implementation = TypeCodeMapper.GetImplementation(this.runtimeClient.GrainTypeResolver, interfaceType, grainClassNamePrefix); return implementation; } private IGrainMethodInvoker MakeInvoker(Type interfaceType) { var invokerType = this.typeCache.GetGrainMethodInvokerType(interfaceType); return (IGrainMethodInvoker)Activator.CreateInstance(invokerType); } #region Interface Casting /// <summary> /// Casts the provided <paramref name="grain"/> to the specified interface /// </summary> /// <typeparam name="TGrainInterface">The target grain interface type.</typeparam> /// <param name="grain">The grain reference being cast.</param> /// <returns> /// A reference to <paramref name="grain"/> which implements <typeparamref name="TGrainInterface"/>. /// </returns> public TGrainInterface Cast<TGrainInterface>(IAddressable grain) { var interfaceType = typeof(TGrainInterface); return (TGrainInterface)this.Cast(grain, interfaceType); } /// <summary> /// Casts the provided <paramref name="grain"/> to the provided <paramref name="interfaceType"/>. /// </summary> /// <param name="grain">The grain.</param> /// <param name="interfaceType">The resulting interface type.</param> /// <returns>A reference to <paramref name="grain"/> which implements <paramref name="interfaceType"/>.</returns> public object Cast(IAddressable grain, Type interfaceType) { GrainReferenceCaster caster; if (!this.casters.TryGetValue(interfaceType, out caster)) { // Create and cache a caster for the interface type. caster = this.casters.GetOrAdd(interfaceType, this.MakeCaster); } return caster(grain); } /// <summary> /// Creates and returns a new grain reference caster. /// </summary> /// <param name="interfaceType">The interface which the result will cast to.</param> /// <returns>A new grain reference caster.</returns> private GrainReferenceCaster MakeCaster(Type interfaceType) { var grainReferenceType = this.typeCache.GetGrainReferenceType(interfaceType); return GrainCasterFactory.CreateGrainReferenceCaster(interfaceType, grainReferenceType); } #endregion #region SystemTargets /// <summary> /// Gets a reference to the specified system target. /// </summary> /// <typeparam name="TGrainInterface">The system target interface.</typeparam> /// <param name="grainId">The id of the target.</param> /// <param name="destination">The destination silo.</param> /// <returns>A reference to the specified system target.</returns> public TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId, SiloAddress destination) where TGrainInterface : ISystemTarget { Dictionary<SiloAddress, ISystemTarget> cache; Tuple<GrainId, Type> key = Tuple.Create(grainId, typeof(TGrainInterface)); lock (this.typedSystemTargetReferenceCache) { if (this.typedSystemTargetReferenceCache.ContainsKey(key)) cache = this.typedSystemTargetReferenceCache[key]; else { cache = new Dictionary<SiloAddress, ISystemTarget>(); this.typedSystemTargetReferenceCache[key] = cache; } } ISystemTarget reference; lock (cache) { if (cache.ContainsKey(destination)) { reference = cache[destination]; } else { reference = this.Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, null, destination)); cache[destination] = reference; // Store for next time } } return (TGrainInterface)reference; } #endregion } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.Tasks; using Cassandra.Compression; using Cassandra.Requests; using Cassandra.Responses; using Cassandra.Serialization; using Microsoft.IO; namespace Cassandra { /// <summary> /// Represents a TCP connection to a Cassandra Node /// </summary> internal class Connection : IDisposable { private static readonly Logger Logger = new Logger(typeof(Connection)); private readonly Serializer _serializer; private readonly TcpSocket _tcpSocket; private int _disposed; /// <summary> /// Determines that the connection canceled pending operations. /// It could be because its being closed or there was a socket error. /// </summary> private volatile bool _isCanceled; private readonly object _cancelLock = new object(); private readonly Timer _idleTimer; private AutoResetEvent _pendingWaitHandle; private int _timedOutOperations; /// <summary> /// Stores the available stream ids. /// </summary> private ConcurrentStack<short> _freeOperations; /// <summary> Contains the requests that were sent through the wire and that hasn't been received yet.</summary> private ConcurrentDictionary<short, OperationState> _pendingOperations; /// <summary> It contains the requests that could not be written due to streamIds not available</summary> private ConcurrentQueue<OperationState> _writeQueue; /// <summary> /// Small buffer (less than 8 bytes) that is used when the next received message is smaller than 8 bytes, /// and it is not possible to read the header. /// </summary> private volatile byte[] _minimalBuffer; private volatile string _keyspace; private readonly SemaphoreSlim _keyspaceSwitchSemaphore = new SemaphoreSlim(1); private volatile Task<bool> _keyspaceSwitchTask; private volatile byte _frameHeaderSize; private MemoryStream _readStream; private int _isWriteQueueRuning; private int _inFlight; /// <summary> /// The event that represents a event RESPONSE from a Cassandra node /// </summary> public event CassandraEventHandler CassandraEventResponse; /// <summary> /// Event raised when there is an error when executing the request to prevent idle disconnects /// </summary> public event Action<Exception> OnIdleRequestException; /// <summary> /// Event that gets raised when a write has been completed. Testing purposes only. /// </summary> public event Action WriteCompleted; private const string IdleQuery = "SELECT key from system.local"; private const long CoalescingThreshold = 8000; public IFrameCompressor Compressor { get; set; } public IPEndPoint Address { get { return _tcpSocket.IPEndPoint; } } /// <summary> /// Determines the amount of operations that are not finished. /// </summary> public virtual int InFlight { get { return Thread.VolatileRead(ref _inFlight); } } /// <summary> /// Gets the amount of operations that timed out and didn't get a response /// </summary> public virtual int TimedOutOperations { get { return Thread.VolatileRead(ref _timedOutOperations); } } /// <summary> /// Determine if the Connection is closed /// </summary> public bool IsClosed { //if the connection attempted to cancel pending operations get { return _isCanceled; } } /// <summary> /// Determine if the Connection has been explicitly disposed /// </summary> public bool IsDisposed { get { return Thread.VolatileRead(ref _disposed) > 0; } } /// <summary> /// Gets the current keyspace. /// </summary> public string Keyspace { get { return _keyspace; } } /// <summary> /// Gets the amount of concurrent requests depending on the protocol version /// </summary> public int MaxConcurrentRequests { get { if (_serializer.ProtocolVersion < 3) { return 128; } //Protocol 3 supports up to 32K concurrent request without waiting a response //Allowing larger amounts of concurrent requests will cause large memory consumption //Limit to 2K per connection sounds reasonable. return 2048; } } public ProtocolOptions Options { get { return Configuration.ProtocolOptions; } } public Configuration Configuration { get; set; } public Connection(Serializer serializer, IPEndPoint endpoint, Configuration configuration) { if (serializer == null) { throw new ArgumentNullException("serializer"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (configuration.BufferPool == null) { throw new ArgumentNullException(null, "BufferPool can not be null"); } _serializer = serializer; Configuration = configuration; _tcpSocket = new TcpSocket(endpoint, configuration.SocketOptions, configuration.ProtocolOptions.SslOptions); _idleTimer = new Timer(IdleTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Starts the authentication flow /// </summary> /// <param name="name">Authenticator name from server.</param> /// <exception cref="AuthenticationException" /> private Task<Response> StartAuthenticationFlow(string name) { //Determine which authentication flow to use. //Check if its using a C* 1.2 with authentication patched version (like DSE 3.1) var protocolVersion = _serializer.ProtocolVersion; var isPatchedVersion = protocolVersion == 1 && !(Configuration.AuthProvider is NoneAuthProvider) && Configuration.AuthInfoProvider == null; if (protocolVersion < 2 && !isPatchedVersion) { //Use protocol v1 authentication flow if (Configuration.AuthInfoProvider == null) { throw new AuthenticationException( String.Format("Host {0} requires authentication, but no credentials provided in Cluster configuration", Address), Address); } var credentialsProvider = Configuration.AuthInfoProvider; var credentials = credentialsProvider.GetAuthInfos(Address); var request = new CredentialsRequest(credentials); return Send(request) .ContinueSync(response => { if (!(response is ReadyResponse)) { //If Cassandra replied with a auth response error //The task already is faulted and the exception was already thrown. throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name); } return response; }); } //Use protocol v2+ authentication flow if (Configuration.AuthProvider is IAuthProviderNamed) { //Provide name when required ((IAuthProviderNamed) Configuration.AuthProvider).SetName(name); } //NewAuthenticator will throw AuthenticationException when NoneAuthProvider var authenticator = Configuration.AuthProvider.NewAuthenticator(Address); var initialResponse = authenticator.InitialResponse() ?? new byte[0]; return Authenticate(initialResponse, authenticator); } /// <exception cref="AuthenticationException" /> private Task<Response> Authenticate(byte[] token, IAuthenticator authenticator) { var request = new AuthResponseRequest(token); return Send(request) .Then(response => { if (response is AuthSuccessResponse) { //It is now authenticated // ReSharper disable once SuspiciousTypeConversion.Global var disposableAuthenticator = authenticator as IDisposable; if (disposableAuthenticator != null) { disposableAuthenticator.Dispose(); } return TaskHelper.ToTask(response); } if (response is AuthChallengeResponse) { token = authenticator.EvaluateChallenge(((AuthChallengeResponse)response).Token); if (token == null) { // If we get a null response, then authentication has completed //return without sending a further response back to the server. return TaskHelper.ToTask(response); } return Authenticate(token, authenticator); } throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name); }); } /// <summary> /// It callbacks all operations already sent / or to be written, that do not have a response. /// </summary> internal void CancelPending(Exception ex, SocketError? socketError = null) { //Multiple IO worker threads may been notifying that the socket is closing/in error lock (_cancelLock) { _isCanceled = true; Logger.Info("Canceling pending operations {0} and write queue {1}", Thread.VolatileRead(ref _inFlight), _writeQueue.Count); if (socketError != null) { Logger.Verbose("The socket status received was {0}", socketError.Value); } if (_pendingOperations.IsEmpty && _writeQueue.IsEmpty) { if (_pendingWaitHandle != null) { _pendingWaitHandle.Set(); } return; } if (ex == null || ex is ObjectDisposedException) { if (socketError != null) { ex = new SocketException((int)socketError.Value); } else { //It is closing ex = new SocketException((int)SocketError.NotConnected); } } //Callback all the items in the write queue OperationState state; while (_writeQueue.TryDequeue(out state)) { state.InvokeCallback(ex); } //Callback for every pending operation foreach (var item in _pendingOperations) { item.Value.InvokeCallback(ex); } _pendingOperations.Clear(); Interlocked.Exchange(ref _inFlight, 0); if (_pendingWaitHandle != null) { _pendingWaitHandle.Set(); } } } public virtual void Dispose() { if (Interlocked.Increment(ref _disposed) != 1) { //Only dispose once return; } _idleTimer.Dispose(); _tcpSocket.Dispose(); _keyspaceSwitchSemaphore.Dispose(); var readStream = Interlocked.Exchange(ref _readStream, null); if (readStream != null) { readStream.Close(); } } private void EventHandler(Exception ex, Response response) { if (!(response is EventResponse)) { Logger.Error("Unexpected response type for event: " + response.GetType().Name); return; } if (CassandraEventResponse != null) { CassandraEventResponse(this, ((EventResponse) response).CassandraEventArgs); } } /// <summary> /// Gets executed once the idle timeout has passed /// </summary> private void IdleTimeoutHandler(object state) { //Ensure there are no more idle timeouts until the query finished sending if (_isCanceled) { if (!IsDisposed) { //If it was not manually disposed Logger.Warning("Can not issue an heartbeat request as connection is closed"); if (OnIdleRequestException != null) { OnIdleRequestException(new SocketException((int)SocketError.NotConnected)); } } return; } Logger.Verbose("Connection idling, issuing a Request to prevent idle disconnects"); var request = new QueryRequest(_serializer.ProtocolVersion, IdleQuery, false, QueryProtocolOptions.Default); Send(request, (ex, response) => { if (ex == null) { //The send succeeded //There is a valid response but we don't care about the response return; } Logger.Warning("Received heartbeat request exception " + ex.ToString()); if (ex is SocketException && OnIdleRequestException != null) { OnIdleRequestException(ex); } }); } /// <summary> /// Initializes the connection. /// </summary> /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception> /// <exception cref="AuthenticationException" /> /// <exception cref="UnsupportedProtocolVersionException"></exception> public Task<Response> Open() { _freeOperations = new ConcurrentStack<short>(Enumerable.Range(0, MaxConcurrentRequests).Select(s => (short)s).Reverse()); _pendingOperations = new ConcurrentDictionary<short, OperationState>(); _writeQueue = new ConcurrentQueue<OperationState>(); if (Options.CustomCompressor != null) { Compressor = Options.CustomCompressor; } else if (Options.Compression == CompressionType.LZ4) { Compressor = new LZ4Compressor(); } else if (Options.Compression == CompressionType.Snappy) { Compressor = new SnappyCompressor(); } //Init TcpSocket _tcpSocket.Init(); _tcpSocket.Error += CancelPending; _tcpSocket.Closing += () => CancelPending(null, null); //Read and write event handlers are going to be invoked using IO Threads _tcpSocket.Read += ReadHandler; _tcpSocket.WriteCompleted += WriteCompletedHandler; var protocolVersion = _serializer.ProtocolVersion; return _tcpSocket .Connect() .Then(_ => Startup()) .ContinueWith(t => { if (t.IsFaulted && t.Exception != null) { //Adapt the inner exception and rethrow var ex = t.Exception.InnerException; if (ex is ProtocolErrorException) { //As we are starting up, check for protocol version errors //There is no other way than checking the error message from Cassandra if (ex.Message.Contains("Invalid or unsupported protocol version")) { throw new UnsupportedProtocolVersionException(protocolVersion, ex); } } if (ex is ServerErrorException && protocolVersion >= 3 && ex.Message.Contains("ProtocolException: Invalid or unsupported protocol version")) { //For some versions of Cassandra, the error is wrapped into a server error //See CASSANDRA-9451 throw new UnsupportedProtocolVersionException(protocolVersion, ex); } throw ex; } return t.Result; }, TaskContinuationOptions.ExecuteSynchronously) .Then(response => { if (response is AuthenticateResponse) { return StartAuthenticationFlow(((AuthenticateResponse)response).Authenticator); } if (response is ReadyResponse) { return TaskHelper.ToTask(response); } throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name); }); } /// <summary> /// Silently kill the connection, for testing purposes only /// </summary> internal void Kill() { _tcpSocket.Kill(); } private void ReadHandler(byte[] buffer, int bytesReceived) { if (_isCanceled) { //All pending operations have been canceled, there is no point in reading from the wire. return; } //We are currently using an IO Thread //Parse the data received var streamIdAvailable = ReadParse(buffer, bytesReceived); if (!streamIdAvailable) { return; } if (_pendingWaitHandle != null && _pendingOperations.IsEmpty && _writeQueue.IsEmpty) { _pendingWaitHandle.Set(); } //Process a next item in the queue if possible. //Maybe there are there items in the write queue that were waiting on a fresh streamId RunWriteQueue(); } private volatile FrameHeader _receivingHeader; /// <summary> /// Parses the bytes received into a frame. Uses the internal operation state to do the callbacks. /// Returns true if a full operation (streamId) has been processed and there is one available. /// </summary> /// <returns>True if a full operation (streamId) has been processed.</returns> internal bool ReadParse(byte[] buffer, int length) { if (length <= 0) { return false; } byte protocolVersion; if (_frameHeaderSize == 0) { //The server replies the first message with the max protocol version supported protocolVersion = FrameHeader.GetProtocolVersion(buffer); _serializer.ProtocolVersion = protocolVersion; _frameHeaderSize = FrameHeader.GetSize(protocolVersion); } else { protocolVersion = _serializer.ProtocolVersion; } //Use _readStream to buffer between messages, under low pressure, it should be null most of the times var stream = Interlocked.Exchange(ref _readStream, null); var operationCallbacks = new LinkedList<Action<MemoryStream>>(); var offset = 0; if (_minimalBuffer != null) { //use a negative offset to identify that there is a previous header buffer offset = -1 * _minimalBuffer.Length; } while (offset < length) { FrameHeader header; //The remaining body length to read from this buffer int remainingBodyLength; if (_receivingHeader == null) { if (length - offset < _frameHeaderSize) { _minimalBuffer = offset >= 0 ? Utils.SliceBuffer(buffer, offset, length - offset) : //it should almost never be the case there isn't enough bytes to read the header more than once // ReSharper disable once PossibleNullReferenceException Utils.JoinBuffers(_minimalBuffer, 0, _minimalBuffer.Length, buffer, 0, length); break; } if (offset >= 0) { header = FrameHeader.ParseResponseHeader(protocolVersion, buffer, offset); } else { header = FrameHeader.ParseResponseHeader(protocolVersion, _minimalBuffer, buffer); _minimalBuffer = null; } Logger.Verbose("Received #{0} from {1}", header.StreamId, Address); offset += _frameHeaderSize; remainingBodyLength = header.BodyLength; } else { header = _receivingHeader; remainingBodyLength = header.BodyLength - (int) stream.Length; _receivingHeader = null; } if (remainingBodyLength > length - offset) { //the buffer does not contains the body for this frame, buffer for later MemoryStream nextMessageStream; if (operationCallbacks.Count == 0 && stream != null) { //There hasn't been any operations completed with this buffer //And there is a previous stream: reuse it nextMessageStream = stream; } else { nextMessageStream = Configuration.BufferPool.GetStream(typeof(Connection) + "/Read"); } nextMessageStream.Write(buffer, offset, length - offset); Interlocked.Exchange(ref _readStream, nextMessageStream); _receivingHeader = header; break; } stream = stream ?? Configuration.BufferPool.GetStream(typeof (Connection) + "/Read"); OperationState state; if (header.Opcode != EventResponse.OpCode) { state = RemoveFromPending(header.StreamId); } else { //Its an event state = new OperationState(EventHandler); } stream.Write(buffer, offset, remainingBodyLength); var callback = state.SetCompleted(); operationCallbacks.AddLast(CreateResponseAction(header, callback)); offset += remainingBodyLength; } return InvokeReadCallbacks(stream, operationCallbacks); } /// <summary> /// Returns an action that capture the parameters closure /// </summary> private Action<MemoryStream> CreateResponseAction(FrameHeader header, Action<Exception, Response> callback) { var compressor = Compressor; return delegate(MemoryStream stream) { Response response = null; Exception ex = null; var nextPosition = stream.Position + header.BodyLength; try { Stream plainTextStream = stream; if (header.Flags.HasFlag(FrameHeader.HeaderFlag.Compression)) { plainTextStream = compressor.Decompress(new WrappedStream(stream, header.BodyLength)); plainTextStream.Position = 0; } response = FrameParser.Parse(new Frame(header, plainTextStream, _serializer)); } catch (Exception catchedException) { ex = catchedException; } if (response is ErrorResponse) { //Create an exception from the response error ex = ((ErrorResponse) response).Output.CreateException(); response = null; } //We must advance the position of the stream manually in case it was not correctly parsed stream.Position = nextPosition; callback(ex, response); }; } /// <summary> /// Invokes the callbacks using the default TaskScheduler. /// </summary> /// <returns>Returns true if one or more callback has been invoked.</returns> private static bool InvokeReadCallbacks(MemoryStream stream, ICollection<Action<MemoryStream>> operationCallbacks) { if (operationCallbacks.Count == 0) { //Not enough data to read a frame return false; } //Invoke all callbacks using the default TaskScheduler Task.Factory.StartNew(() => { stream.Position = 0; foreach (var cb in operationCallbacks) { cb(stream); } stream.Dispose(); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return true; } /// <summary> /// Sends a protocol STARTUP message /// </summary> private Task<Response> Startup() { var startupOptions = new Dictionary<string, string>(); startupOptions.Add("CQL_VERSION", "3.0.0"); if (Options.Compression == CompressionType.LZ4) { startupOptions.Add("COMPRESSION", "lz4"); } else if (Options.Compression == CompressionType.Snappy) { startupOptions.Add("COMPRESSION", "snappy"); } return Send(new StartupRequest(startupOptions)); } /// <summary> /// Sends a new request if possible. If it is not possible it queues it up. /// </summary> public Task<Response> Send(IRequest request) { var tcs = new TaskCompletionSource<Response>(); Send(request, tcs.TrySet); return tcs.Task; } /// <summary> /// Sends a new request if possible and executes the callback when the response is parsed. If it is not possible it queues it up. /// </summary> public OperationState Send(IRequest request, Action<Exception, Response> callback, int timeoutMillis = Timeout.Infinite) { if (_isCanceled) { callback(new SocketException((int)SocketError.NotConnected), null); return null; } var state = new OperationState(callback) { Request = request, TimeoutMillis = timeoutMillis > 0 ? timeoutMillis : Configuration.SocketOptions.ReadTimeoutMillis }; _writeQueue.Enqueue(state); RunWriteQueue(); return state; } private void RunWriteQueue() { var isAlreadyRunning = Interlocked.CompareExchange(ref _isWriteQueueRuning, 1, 0) == 1; if (isAlreadyRunning) { //there is another thread writing to the wire return; } //Start a new task using the TaskScheduler for writing Task.Factory.StartNew(RunWriteQueueAction, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void RunWriteQueueAction() { //Dequeue all items until threshold is passed long totalLength = 0; RecyclableMemoryStream stream = null; var streamIdsAvailable = true; while (totalLength < CoalescingThreshold) { OperationState state; if (!_writeQueue.TryDequeue(out state)) { //No more items in the write queue break; } short streamId; if (!_freeOperations.TryPop(out streamId)) { streamIdsAvailable = false; //Queue it up for later. _writeQueue.Enqueue(state); //When receiving the next complete message, we can process it. Logger.Info("Enqueued, no streamIds available. If this message is recurrent consider configuring more connections per host or lower the pressure"); break; } Logger.Verbose("Sending #{0} for {1} to {2}", streamId, state.Request.GetType().Name, Address); _pendingOperations.AddOrUpdate(streamId, state, (k, oldValue) => state); Interlocked.Increment(ref _inFlight); int frameLength; try { //lazy initialize the stream stream = stream ?? (RecyclableMemoryStream) Configuration.BufferPool.GetStream(GetType().Name + "/SendStream"); frameLength = state.Request.WriteFrame(streamId, stream, _serializer); if (state.TimeoutMillis > 0 && Configuration.Timer != null) { state.Timeout = Configuration.Timer.NewTimeout(OnTimeout, streamId, state.TimeoutMillis); } } catch (Exception ex) { //There was an error while serializing or begin sending Logger.Error(ex); //The request was not written, clear it from pending operations RemoveFromPending(streamId); //Callback with the Exception state.InvokeCallback(ex); break; } //We will not use the request any more, stop reference it. state.Request = null; totalLength += frameLength; } if (totalLength == 0L) { //nothing to write Interlocked.Exchange(ref _isWriteQueueRuning, 0); if (streamIdsAvailable && !_writeQueue.IsEmpty) { //The write queue is not empty //An item was added to the queue but we were running: try to launch a new queue RunWriteQueue(); } if (stream != null) { //The stream instance could be created if there was an exception while generating the frame stream.Dispose(); } return; } //Write and close the stream when flushed // ReSharper disable once PossibleNullReferenceException : if totalLength > 0 the stream is initialized _tcpSocket.Write(stream, () => stream.Dispose()); } /// <summary> /// Removes an operation from pending and frees the stream id /// </summary> /// <param name="streamId"></param> internal protected virtual OperationState RemoveFromPending(short streamId) { OperationState state; if (_pendingOperations.TryRemove(streamId, out state)) { Interlocked.Decrement(ref _inFlight); } //Set the streamId as available _freeOperations.Push(streamId); return state; } /// <summary> /// Sets the keyspace of the connection. /// If the keyspace is different from the current value, it sends a Query request to change it /// </summary> public Task<bool> SetKeyspace(string value) { if (String.IsNullOrEmpty(value) || _keyspace == value) { //No need to switch return TaskHelper.Completed; } Task<bool> keyspaceSwitch; try { if (!_keyspaceSwitchSemaphore.Wait(0)) { //Could not enter semaphore //It is very likely that the connection is already switching keyspace keyspaceSwitch = _keyspaceSwitchTask; if (keyspaceSwitch != null) { return keyspaceSwitch.Then(_ => { //validate if the new keyspace is the expected if (_keyspace != value) { //multiple concurrent switches to different keyspace return SetKeyspace(value); } return TaskHelper.Completed; }); } _keyspaceSwitchSemaphore.Wait(); } } catch (ObjectDisposedException) { //The semaphore was disposed, this connection is closed return TaskHelper.FromException<bool>(new SocketException((int) SocketError.NotConnected)); } //Semaphore entered if (_keyspace == value) { //While waiting to enter the semaphore, the connection switched keyspace try { _keyspaceSwitchSemaphore.Release(); } catch (ObjectDisposedException) { //this connection is now closed but the switch completed successfully } return TaskHelper.Completed; } var request = new QueryRequest(_serializer.ProtocolVersion, string.Format("USE \"{0}\"", value), false, QueryProtocolOptions.Default); Logger.Info("Connection to host {0} switching to keyspace {1}", Address, value); keyspaceSwitch = _keyspaceSwitchTask = Send(request).ContinueSync(r => { _keyspace = value; try { _keyspaceSwitchSemaphore.Release(); } catch (ObjectDisposedException) { //this connection is now closed but the switch completed successfully } _keyspaceSwitchTask = null; return true; }); return keyspaceSwitch; } private void OnTimeout(object stateObj) { var streamId = (short)stateObj; OperationState state; if (!_pendingOperations.TryGetValue(streamId, out state)) { return; } var ex = new OperationTimedOutException(Address, state.TimeoutMillis); //Invoke if it hasn't been invoked yet //Once the response is obtained, we decrement the timed out counter var timedout = state.SetTimedOut(ex, () => Interlocked.Decrement(ref _timedOutOperations) ); if (!timedout) { //The response was obtained since the timer elapsed, move on return; } //Increase timed-out counter Interlocked.Increment(ref _timedOutOperations); } /// <summary> /// Method that gets executed when a write request has been completed. /// </summary> protected virtual void WriteCompletedHandler() { //This handler is invoked by IO threads //Make it quick if (WriteCompleted != null) { WriteCompleted(); } //There is no need for synchronization here //Only 1 thread can be here at the same time. //Set the idle timeout to avoid idle disconnects var heartBeatInterval = Configuration.PoolingOptions != null ? Configuration.PoolingOptions.GetHeartBeatInterval() : null; if (heartBeatInterval > 0 && !_isCanceled) { try { _idleTimer.Change(heartBeatInterval.Value, Timeout.Infinite); } catch (ObjectDisposedException) { //This connection is being disposed //Don't mind } } Interlocked.Exchange(ref _isWriteQueueRuning, 0); //Send the next request, if exists //It will use a new thread RunWriteQueue(); } internal WaitHandle WaitPending() { if (_pendingWaitHandle == null) { _pendingWaitHandle = new AutoResetEvent(false); } if (_pendingOperations.IsEmpty && _writeQueue.IsEmpty) { _pendingWaitHandle.Set(); } return _pendingWaitHandle; } } }
// 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class IfKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInPreprocessor1() { VerifyAbsence(AddInsideMethod( "#if $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void EmptyStatement() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterHash() { VerifyKeyword( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterHashFollowedBySkippedTokens() { VerifyKeyword( @"#$$ aeu"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterHashAndSpace() { VerifyKeyword( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideMethod() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void BeforeStatement() { VerifyKeyword(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStatement() { VerifyKeyword(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterBlock() { VerifyKeyword(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterIf() { VerifyAbsence(AddInsideMethod( @"if $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCase() { VerifyKeyword(AddInsideMethod( @"switch (true) { case 0: $$ }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCaseBlock() { VerifyKeyword(AddInsideMethod( @"switch (true) { case 0: { $$ } }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefaultCase() { VerifyKeyword(AddInsideMethod( @"switch (true) { default: $$ }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefaultCaseBlock() { VerifyKeyword(AddInsideMethod( @"switch (true) { default: { $$ } }")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLabel() { VerifyKeyword(AddInsideMethod( @"label: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterDoBlock() { VerifyAbsence(AddInsideMethod( @"do { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InActiveRegion1() { VerifyKeyword(AddInsideMethod( @"#if true $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InActiveRegion2() { VerifyKeyword(AddInsideMethod( @"#if true $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterElse() { VerifyKeyword(AddInsideMethod( @"if (foo) { } else $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatch() { VerifyAbsence(AddInsideMethod( @"try {} catch $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatchDeclaration1() { VerifyAbsence(AddInsideMethod( @"try {} catch (Exception) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatchDeclaration2() { VerifyAbsence(AddInsideMethod( @"try {} catch (Exception e) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterCatchDeclarationEmpty() { VerifyAbsence(AddInsideMethod( @"try {} catch () $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterTryBlock() { VerifyAbsence(AddInsideMethod( @"try {} $$")); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> embeddedFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool embedAllSourceFiles = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; string instrument = ""; CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; string sourceLink = null; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { instrument = value; } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "sourcelink": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory); } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; case "embed": if (string.IsNullOrEmpty(value)) { embedAllSourceFiles = true; continue; } embeddedFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } if (sourceLink != null) { if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SourceLinkRequiresPortablePdb); } } if (embedAllSourceFiles) { embeddedFiles.AddRange(sourceFiles); } if (embeddedFiles.Count > 0) { // Restricted to portable PDBs for now, but the IsPortable condition should be removed // and the error message adjusted accordingly when native PDB support is added. if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_CannotEmbedWithoutPdb); } } var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: parsedFeatures ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrument: instrument ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, SourceLink = sourceLink, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer, EmbeddedFiles = embeddedFiles.AsImmutable() }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!PortableShim.Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, out LanguageVersion version) { var defaultVersion = LanguageVersion.Latest.MapLatestToVersion(); if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "7": version = LanguageVersion.CSharp7; return true; case "default": version = defaultVersion; return true; default: // We are likely to introduce minor version numbers after C# 7, thus breaking the // one-to-one correspondence between the integers and the corresponding // LanguageVersion enum values. But for compatibility we continue to accept any // integral value parsed by int.TryParse for its corresponding LanguageVersion enum // value for language version C# 6 and earlier (e.g. leading zeros are allowed) int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && versionNumber <= 6 && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
// 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.Runtime.InteropServices; #pragma warning disable 618 // Must test deprecated features [ComVisible(true)] [Guid(Server.Contract.Guids.ArrayTesting)] public class ArrayTesting : Server.Contract.IArrayTesting { private static double Mean(byte[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(short[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(ushort[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(int[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(uint[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(long[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(ulong[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(float[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } private static double Mean(double[] d) { double t = 0.0; foreach (var b in d) { t += b; } return (t / d.Length); } public double Mean_Byte_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] byte[] d) { return Mean(d); } public double Mean_Short_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] short[] d) { return Mean(d); } public double Mean_UShort_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ushort[] d) { return Mean(d); } public double Mean_Int_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] d) { return Mean(d); } public double Mean_UInt_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] uint[] d) { return Mean(d); } public double Mean_Long_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] long[] d) { return Mean(d); } public double Mean_ULong_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ulong[] d) { return Mean(d); } public double Mean_Float_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] float[] d) { return Mean(d); } public double Mean_Double_LP_PreLen(int len, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] double[] d) { return Mean(d); } public double Mean_Byte_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] byte[] d, int len) { return Mean(d); } public double Mean_Short_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] short[] d, int len) { return Mean(d); } public double Mean_UShort_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] ushort[] d, int len) { return Mean(d); } public double Mean_Int_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] int[] d, int len) { return Mean(d); } public double Mean_UInt_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] uint[] d, int len) { return Mean(d); } public double Mean_Long_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] long[] d, int len) { return Mean(d); } public double Mean_ULong_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] ulong[] d, int len) { return Mean(d); } public double Mean_Float_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] float[] d, int len) { return Mean(d); } public double Mean_Double_LP_PostLen([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] double[] d, int len) { return Mean(d); } public double Mean_Byte_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] byte[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_Short_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] short[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_UShort_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] ushort[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_Int_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] int[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_UInt_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] uint[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_Long_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] long[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_ULong_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] ulong[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_Float_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] float[] d, out int len) { len = d.Length; return Mean(d); } public double Mean_Double_SafeArray_OutLen([MarshalAs(UnmanagedType.SafeArray)] double[] d, out int len) { len = d.Length; return Mean(d); } } #pragma warning restore 618 // Must test deprecated features
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using SharpDX; using System.Diagnostics; #if !NETFX_CORE using System.Windows.Media.Imaging; using MediaColor = System.Windows.Media.Color; namespace HelixToolkit.Wpf.SharpDX #else #if CORE namespace HelixToolkit.SharpDX.Core #else namespace HelixToolkit.UWP #endif #endif { using Core; using Object3DGroup = System.Collections.Generic.List<Object3D>; #if CORE using Material = Model.MaterialCore; using PhongMaterial = Model.PhongMaterialCore; #endif #if NETFX_CORE using FileFormatException = Exception; #endif using Model; /// <summary> ///Ported from HelixToolkit.Wpf /// </summary> [Obsolete("Suggest to use HelixToolkit.SharpDX.Assimp")] public class StudioReader : IModelReader { private readonly Dictionary<string, MaterialCore> materials = new Dictionary<string, MaterialCore>(); private enum ChunkID { //// Primary chunk MAIN3DS = 0x4D4D, // Main Chunks EDIT3DS = 0x3D3D, // this is the start of the editor config KEYF3DS = 0xB000, // this is the start of the keyframer config VERSION = 0x0002, MESHVERSION = 0x3D3E, // sub defines of EDIT3DS EDIT_MATERIAL = 0xAFFF, EDIT_CONFIG1 = 0x0100, EDIT_CONFIG2 = 0x3E3D, EDIT_VIEW_P1 = 0x7012, EDIT_VIEW_P2 = 0x7011, EDIT_VIEW_P3 = 0x7020, EDIT_VIEW1 = 0x7001, EDIT_BACKGR = 0x1200, EDIT_AMBIENT = 0x2100, EDIT_OBJECT = 0x4000, EDIT_UNKNW01 = 0x1100, EDIT_UNKNW02 = 0x1201, EDIT_UNKNW03 = 0x1300, EDIT_UNKNW04 = 0x1400, EDIT_UNKNW05 = 0x1420, EDIT_UNKNW06 = 0x1450, EDIT_UNKNW07 = 0x1500, EDIT_UNKNW08 = 0x2200, EDIT_UNKNW09 = 0x2201, EDIT_UNKNW10 = 0x2210, EDIT_UNKNW11 = 0x2300, EDIT_UNKNW12 = 0x2302, EDIT_UNKNW13 = 0x3000, EDIT_UNKNW14 = 0xAFFF, // sub defines of EDIT_MATERIAL MAT_NAME01 = 0xA000, MAT_LUMINANCE = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030, MAT_SHININESS = 0xA040, MAT_MAP = 0xA200, MAT_MAPFILE = 0xA300, // MAT_AMBIENT= MAT_TRANSPARENCY = 0xA050, // sub defines of EDIT_OBJECT OBJ_TRIMESH = 0x4100, OBJ_LIGHT = 0x4600, OBJ_CAMERA = 0x4700, OBJ_UNKNWN01 = 0x4010, OBJ_UNKNWN02 = 0x4012, // Could be shadow // sub defines of OBJ_CAMERA CAM_UNKNWN01 = 0x4710, CAM_UNKNWN02 = 0x4720, // sub defines of OBJ_LIGHT LIT_OFF = 0x4620, LIT_SPOT = 0x4610, LIT_UNKNWN01 = 0x465A, // sub defines of OBJ_TRIMESH TRI_VERTEXL = 0x4110, TRI_FACEL2 = 0x4111, TRI_FACEL1 = 0x4120, TRI_FACEMAT = 0x4130, TRI_TEXCOORD = 0x4140, TRI_SMOOTH = 0x4150, TRI_LOCAL = 0x4160, TRI_VISIBLE = 0x4165, // sub defs of KEYF3DS KEYF_UNKNWN01 = 0xB009, KEYF_UNKNWN02 = 0xB00A, KEYF_FRAMES = 0xB008, KEYF_OBJDES = 0xB002, KEYF_HIERARCHY = 0xB030, KFNAME = 0xB010, // these define the different color chunk types COL_RGB = 0x0010, COL_TRU = 0x0011, // RGB24 COL_UNK = 0x0013, // defines for viewport chunks TOP = 0x0001, BOTTOM = 0x0002, LEFT = 0x0003, RIGHT = 0x0004, FRONT = 0x0005, BACK = 0x0006, USER = 0x0007, CAMERA = 0x0008, // = 0xFFFF is the actual code read from file LIGHT = 0x0009, DISABLED = 0x0010, BOGUS = 0x0011, // ReSharper restore UnusedMember.Local // ReSharper restore InconsistentNaming PERCENTW = 0x0030, PERCENTF = 0x0031, PERCENTD = 0x0032 } /// <summary> /// Helper class to create objects /// </summary> public Object3DGroup obGroup = new Object3DGroup(); /// <summary> /// Gets or sets the directory /// </summary> public string Directory { get; set; } /// <summary> /// Gets or sets the texture path. /// </summary> /// <value>The texture path.</value> public string TexturePath { get { return this.Directory; } set { this.Directory = value; } } public Object3DGroup Read(string path, ModelInfo info = default(ModelInfo)) { this.Directory = Path.GetDirectoryName(path); using (var s = File.OpenRead(path)) { return this.Read(s); }; } public Object3DGroup Read(Stream s, ModelInfo info = default(ModelInfo)) { using (var reader = new BinaryReader(s)) { var length = reader.BaseStream.Length; var headerId = this.ReadChunkId(reader); if (headerId != ChunkID.MAIN3DS) { throw new FileFormatException("Unknown file"); } var headerSize = this.ReadChunkSize(reader); //if (headerSize != length) //{ // throw new FileFormatException("Incomplete file (file length does not match header)"); //} while (reader.BaseStream.Position < reader.BaseStream.Length) { var id = this.ReadChunkId(reader); var size = this.ReadChunkSize(reader); switch (id) { case ChunkID.EDIT_MATERIAL: this.ReadMaterial(reader, size); break; case ChunkID.EDIT_OBJECT: this.ReadObject(reader, size); break; case ChunkID.EDIT3DS: case ChunkID.OBJ_CAMERA: case ChunkID.OBJ_LIGHT: case ChunkID.OBJ_TRIMESH: // don't read the whole chunk, read the sub-defines... break; default: // download the whole chunk this.ReadData(reader, size - 6); break; } } } return obGroup; } /// <summary> /// Read a chunk id. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// The chunk ID. /// </returns> private ChunkID ReadChunkId(BinaryReader reader) { return (ChunkID)reader.ReadUInt16(); } /// <summary> /// Read a chunk size. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// The read chunk size. /// </returns> private int ReadChunkSize(BinaryReader reader) { return (int)reader.ReadUInt32(); } /// <summary> /// reads the Material of a chunck /// </summary> /// <param name="reader"></param> /// <param name="chunkSize"></param> private void ReadMaterial(BinaryReader reader, int chunkSize) { var total = 6; string name = null; var luminance = Color.Transparent; //SharpDX.Color not System.Windows.Media.Color var diffuse = Color.Transparent; var specular = Color.Transparent; var shininess = Color.Transparent; double opacity = 0; string texture = null; float specularPower = 100;//check if we can find this somewhere instead of just setting it to 100 while (total < chunkSize) { var id = this.ReadChunkId(reader); var size = this.ReadChunkSize(reader); total += size; switch (id) { case ChunkID.MAT_NAME01: name = this.ReadString(reader); break; case ChunkID.MAT_TRANSPARENCY: // skip the first 6 bytes this.ReadData(reader, 6); // read the percent value as 16Bit Uint var data = this.ReadData(reader, 2); opacity = (100 - BitConverter.ToUInt16(data, 0)) / 100.0; break; case ChunkID.MAT_LUMINANCE: luminance = this.ReadColor(reader); break; case ChunkID.MAT_DIFFUSE: diffuse = this.ReadColor(reader); break; case ChunkID.MAT_SPECULAR: specular = this.ReadColor(reader); break; case ChunkID.MAT_SHININESS: //byte[] bytes = this.ReadData(reader, size - 6); specularPower = this.ReadPercent(reader, size - 6); break; case ChunkID.MAT_MAP: texture = this.ReadMatMap(reader, size - 6); break; case ChunkID.MAT_MAPFILE: this.ReadData(reader, size - 6); break; default: this.ReadData(reader, size - 6); break; } } var image = ReadBitmapSoure(texture, diffuse); if (Math.Abs(opacity) > 0.001) { diffuse.A = (byte)(opacity * 255); luminance.A = (byte)(opacity * 255); } var material = new PhongMaterialCore() { DiffuseColor = diffuse, AmbientColor = luminance, //not really sure about this, lib3ds uses 0xA010 as AmbientColor SpecularColor = specular, SpecularShininess = specularPower, }; if (image != null) { material.NormalMap = image; } if (name != null) { materials[name] = material; } } /// <summary> /// Reads an object /// </summary> /// <param name="reader"></param> /// <param name="chunkSize"></param> private void ReadObject(BinaryReader reader, int chunkSize) { var total = 6; var objectName = this.ReadString(reader); total += objectName.Length + 1; while (total < chunkSize) { var id = this.ReadChunkId(reader); var size = this.ReadChunkSize(reader); total += size; switch (id) { case ChunkID.OBJ_TRIMESH: this.ReadTriangularMesh(reader, size); break; default: { this.ReadData(reader, size - 6); break; } } } } /// <summary> /// Reads a triangular mesh. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <param name="chunkSize"> /// The chunk size. /// </param> private void ReadTriangularMesh(BinaryReader reader, int chunkSize) { var builder = new MeshBuilder(); var bytesRead = 6; Vector3Collection positions = null; IntCollection faces = null; Vector2Collection textureCoordinates = null; List<FaceSet> facesets = null; IntCollection triangleIndices = null; Vector3Collection normals = null; //Matrix matrix = Matrix.Identity; Vector3Collection tangents = null; Vector3Collection bitangents = null; var transforms = new List<Matrix>(); while (bytesRead < chunkSize) { var id = this.ReadChunkId(reader); var size = this.ReadChunkSize(reader); bytesRead += size; switch (id) { case ChunkID.TRI_VERTEXL: positions = this.ReadVertexList(reader); break; case ChunkID.TRI_FACEL1: faces = ReadFaceList(reader); size -= (faces.Count / 3 * 8) + 2; facesets = this.ReadFaceSets(reader, size - 6); break; case ChunkID.TRI_TEXCOORD: textureCoordinates = ReadTexCoords(reader); break; case ChunkID.TRI_LOCAL: transforms.Add(this.ReadTransformation(reader)); break; default: this.ReadData(reader, size - 6); break; } } if (faces == null) { //no faces defined?? return... return; } if (facesets == null || facesets.Count == 0) { triangleIndices = faces; CreateMesh(positions, textureCoordinates, triangleIndices, transforms, out normals, out tangents, out bitangents, new PhongMaterial() { Name = "Gray", AmbientColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f), DiffuseColor = new Color4(0.254902f, 0.254902f, 0.254902f, 1.0f), SpecularColor = new Color4(0.0225f, 0.0225f, 0.0225f, 1.0f), EmissiveColor = new Color4(0.0f, 0.0f, 0.0f, 1.0f), SpecularShininess = 12.8f, }); //Add default get and setter } else { foreach (var fm in facesets) { triangleIndices = ConvertFaceIndices(fm.Faces, faces); MaterialCore mat = null; if (this.materials.ContainsKey(fm.Name)) { mat = this.materials[fm.Name]; } CreateMesh(positions, textureCoordinates, triangleIndices, transforms, out normals, out tangents, out bitangents, mat); } } } /// <summary> /// Create a Mesh, with found props /// </summary> /// <param name="positions"></param> /// <param name="textureCoordinates"></param> /// <param name="triangleIndices"></param> /// <param name="normals"></param> /// <param name="tangents"></param> /// <param name="bitangents"></param> /// <param name="material"></param> /// <param name="transforms"></param> private void CreateMesh(Vector3Collection positions, Vector2Collection textureCoordinates, IntCollection triangleIndices, List<Matrix> transforms, out Vector3Collection normals, out Vector3Collection tangents, out Vector3Collection bitangents, MaterialCore material) { ComputeNormals(positions, triangleIndices, out normals); if (textureCoordinates == null) { textureCoordinates = new Vector2Collection(); foreach (var pos in positions) { textureCoordinates.Add(Vector2.One); } } MeshBuilder.ComputeTangents(positions, normals, textureCoordinates, triangleIndices, out tangents, out bitangents); var mesh = new MeshGeometry3D() { Positions = positions, Normals = normals, TextureCoordinates = textureCoordinates, Indices = triangleIndices, Tangents = tangents, BiTangents = bitangents }; var ob3d = new Object3D(); ob3d.Geometry = mesh; ob3d.Material = material; ob3d.Transform = transforms; ob3d.Name = "Default"; this.obGroup.Add(ob3d); } /// <summary> /// Stolen from MeshBuilder class, maybe make this static method there public... /// </summary> /// <param name="positions"></param> /// <param name="triangleIndices"></param> /// <param name="normals"></param> private static void ComputeNormals(Vector3Collection positions, IntCollection triangleIndices, out Vector3Collection normals) { normals = new Vector3Collection(positions.Count); normals.AddRange(Enumerable.Repeat(Vector3.Zero, positions.Count)); for (var t = 0; t < triangleIndices.Count; t += 3) { var i1 = triangleIndices[t]; var i2 = triangleIndices[t + 1]; var i3 = triangleIndices[t + 2]; var v1 = positions[i1]; var v2 = positions[i2]; var v3 = positions[i3]; var p1 = v2 - v1; var p2 = v3 - v1; var n = Vector3.Cross(p1, p2); // angle p1.Normalize(); p2.Normalize(); var a = (float)Math.Acos(Vector3.Dot(p1, p2)); n.Normalize(); normals[i1] += (a * n); normals[i2] += (a * n); normals[i3] += (a * n); } for (var i = 0; i < normals.Count; i++) { var n = normals[i]; n.Normalize(); normals[i] = n; } } private static IntCollection ConvertFaceIndices(List<int> subFaces, IList<int> faces) { var triangleIndices = new IntCollection(subFaces.Count * 3);// new List<int>(subFaces.Count * 3); foreach (var f in subFaces) { triangleIndices.Add(faces[f * 3]); triangleIndices.Add(faces[(f * 3) + 1]); triangleIndices.Add(faces[(f * 3) + 2]); } return triangleIndices; } private Vector2Collection ReadTexCoords(BinaryReader reader) { int size = reader.ReadUInt16(); var pts = new Vector2Collection(); for (var i = 0; i < size; i++) { var x = reader.ReadSingle(); var y = reader.ReadSingle(); pts.Add(new Vector2(x, 1 - y)); } return pts; } /// <summary> /// Reads face sets. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <param name="chunkSize"> /// The chunk size. /// </param> /// <returns> /// A list of face sets. /// </returns> private List<FaceSet> ReadFaceSets(BinaryReader reader, int chunkSize) { var total = 6; var list = new List<FaceSet>(); while (total < chunkSize) { var id = this.ReadChunkId(reader); var size = this.ReadChunkSize(reader); total += size; switch (id) { case ChunkID.TRI_FACEMAT: { var name = this.ReadString(reader); int n = reader.ReadUInt16(); var c = new List<int>(); for (var i = 0; i < n; i++) { c.Add(reader.ReadUInt16()); } var fm = new FaceSet { Name = name, Faces = c }; list.Add(fm); break; } case ChunkID.TRI_SMOOTH: { this.ReadData(reader, size - 6); break; } default: { this.ReadData(reader, size - 6); break; } } } return list; } private IntCollection ReadFaceList(BinaryReader reader) { int size = reader.ReadUInt16(); var faces = new IntCollection(); for (var i = 0; i < size; i++) { faces.Add(reader.ReadUInt16()); faces.Add(reader.ReadUInt16()); faces.Add(reader.ReadUInt16()); reader.ReadUInt16(); } return faces; } /// <summary> /// Reads a vector. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// A vector. /// </returns> private Vector3 ReadVector(BinaryReader reader) { return new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); } /// <summary> /// Reads a transformation. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// A transformation. /// </returns> private Matrix ReadTransformation(BinaryReader reader) { var localx = this.ReadVector(reader); var localy = this.ReadVector(reader); var localz = this.ReadVector(reader); var origin = this.ReadVector(reader); var matrix = new Matrix { M11 = localx.X, M21 = localx.Y, M31 = localx.Z, M12 = localy.X, M22 = localy.Y, M32 = localy.Z, M13 = localz.X, M23 = localz.Y, M33 = localz.Z, M41 = origin.X, M42 = origin.Y, M43 = origin.Z, M14 = 0, M24 = 0, M34 = 0, M44 = 1 }; return matrix; } private Vector3Collection ReadVertexList(BinaryReader reader) { int size = reader.ReadUInt16(); var pts = new Vector3Collection(); for (var i = 0; i < size; i++) { var x = reader.ReadSingle(); var y = reader.ReadSingle(); var z = reader.ReadSingle(); pts.Add(new Vector3(x, y, z)); } return pts; } /// <summary> /// A bit hacky we use the give texture as normalMap, if not existant we create a BitMapSource in the fallbackColor /// </summary> /// <param name="texture"></param> /// <param name="fallBackColor"></param> /// <returns></returns> /// private Stream ReadBitmapSoure(string texture, Color fallBackColor) { if (texture == null) { return null; } try { var ext = Path.GetExtension(texture); if (ext != null) { ext = ext.ToLower(); } // TGA not supported - convert textures to .png if (ext == ".tga") { texture = Path.ChangeExtension(texture, ".png"); } var actualTexturePath = this.TexturePath ?? string.Empty; var path = Path.GetFullPath(Path.Combine(actualTexturePath, texture)); if (File.Exists(path)) { var stream = new MemoryStream(); using (var fileStream = File.OpenRead(path)) { fileStream.CopyTo(stream); return stream; } } else { #if NETFX_CORE return null; #else return BitMapSoureFromFallBack(fallBackColor); #endif } } catch (Exception ex) //Not really nice { throw new FileFormatException(ex.Message); } } #if !NETFX_CORE /// <summary> /// Creates FallBack Bitmapsource http://stackoverflow.com/questions/10637064/create-bitmapimage-and-apply-to-it-a-specific-color /// </summary> /// <param name="fallBackColor"></param> /// <returns></returns> private static Stream BitMapSoureFromFallBack(Color fallBackColor) { //List<MediaColor> colors = new List<System.Windows.Media.Color>() { MediaColor.FromArgb(fallBackColor.A, fallBackColor.R, fallBackColor.G, fallBackColor.B) }; var color = MediaColor.FromArgb(fallBackColor.A, fallBackColor.R, fallBackColor.G, fallBackColor.G); var colors = new List<System.Windows.Media.Color>(); colors.Add(color); var palette = new BitmapPalette(colors); var width = 128; var height = 128; var stride = width / 8; var pixels = new byte[height * stride]; var bitmap = BitmapSource.Create(10, 10, 96, 96, System.Windows.Media.PixelFormats.Indexed1, palette, pixels, stride); return bitmap.ToMemoryStream(); } #endif /// <summary> /// Reads a material map. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <param name="size"> /// The size. /// </param> /// <returns> /// The mat map. /// </returns> private string ReadMatMap(BinaryReader reader, int size) { var id = this.ReadChunkId(reader); var siz = this.ReadChunkSize(reader); var f1 = reader.ReadUInt16(); var f2 = reader.ReadUInt16(); var f3 = reader.ReadUInt16(); var f4 = reader.ReadUInt16(); size -= 14; var cname = this.ReadString(reader); size -= cname.Length + 1; var morebytes = this.ReadData(reader, size); return cname; } /// <summary> /// Read a color. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// A color. /// </returns> private Color ReadColor(BinaryReader reader) { var type = this.ReadChunkId(reader); var csize = this.ReadChunkSize(reader); switch (type) { case ChunkID.COL_RGB: { var r = reader.ReadSingle(); var g = reader.ReadSingle(); var b = reader.ReadSingle(); return new Color(r, g, b, 1); // .FromScRgb(1, r, g, b); } case ChunkID.COL_TRU: { var r = reader.ReadByte(); var g = reader.ReadByte(); var b = reader.ReadByte(); return new Color(r, g, b); } default: this.ReadData(reader, csize); break; } return Color.White; } private float ReadPercent(BinaryReader reader, int size) { var type = ReadChunkId(reader); var cSize = ReadChunkSize(reader); size -= 6; float percent = 1; switch (type) { case ChunkID.PERCENTW: percent = reader.ReadUInt16(); break; case ChunkID.PERCENTF: percent = reader.ReadSingle(); break; case ChunkID.PERCENTD: reader.ReadBytes(size); break; } return percent; } /// <summary> /// Read data. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <param name="size"> /// Excluding header size /// </param> /// <returns> /// The data. /// </returns> private byte[] ReadData(BinaryReader reader, int size) { return reader.ReadBytes(size); } /// <summary> /// Reads a string. /// </summary> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// The string. /// </returns> private string ReadString(BinaryReader reader) { var sb = new StringBuilder(); while (true) { var ch = (char)reader.ReadByte(); if (ch == 0) { break; } sb.Append(ch); } return sb.ToString(); } /// <summary> /// Represents a set of faces that belongs to the same material. /// </summary> private class FaceSet { /// <summary> /// Gets or sets Faces. /// </summary> public List<int> Faces { get; set; } /// <summary> /// Gets or sets the name of the material. /// </summary> public string Name { get; set; } } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; namespace UMA.AssetBundles { public class AssetBundleLoadingIndicator : MonoBehaviour { public bool dontDestroyOnLoad = false; public enum statusOpts { Idle, Downloading, Unpacking, Complete }; //[System.NonSerialized] [ReadOnly] public statusOpts status = statusOpts.Idle; //[System.NonSerialized] [ReadOnly] public float percentDone = 0f; //[System.NonSerialized] [ReadOnly] public float currentDownloadMeg = 0f; public GameObject indicatorObject; public Text indicatorText; public Slider indicatorBar; public Text indicatorBarText; public string loadingText = "Loading AssetBundles..."; public string unpackingText = "Unpacking AssetBundles..."; public string loadedText = "AssetBundles Loaded!"; string _loadingMessage; string _unpackingMessage; string _loadedMessage; public List<string> _bundlesToCheck = new List<string>(); public float delayHideWhenDone = 0f; static AssetBundleLoadingIndicator _instance = null; public static AssetBundleLoadingIndicator Instance { get { if (_instance == null) { FindInstance(); } return _instance; } } // Use this for initialization void Start() { if (_instance != null && _instance != this) { if (_instance.dontDestroyOnLoad) Destroy(this.gameObject); else _instance = this; } else { _instance = this; if (this.dontDestroyOnLoad) DontDestroyOnLoad(this.gameObject); } } public static AssetBundleLoadingIndicator FindInstance() { if (_instance == null) { AssetBundleLoadingIndicator[] assetBundleLoadingIndicator = FindObjectsOfType(typeof(AssetBundleLoadingIndicator)) as AssetBundleLoadingIndicator[]; if (assetBundleLoadingIndicator.Length > 0) { _instance = assetBundleLoadingIndicator[0]; if (_instance.dontDestroyOnLoad) DontDestroyOnLoad(assetBundleLoadingIndicator[0].gameObject); } } return _instance; } // Update is called once per frame void Update() { #if UNITY_EDITOR //If the download fails and we are in the editor we will automatically be switched back into simulation mode- so in this case reset and hide if (AssetBundleManager.SimulateOverride) { _bundlesToCheck.Clear(); ResetAndHide(); } #endif if (status == statusOpts.Complete) { _bundlesToCheck.Clear(); Hide(); } if (status == statusOpts.Downloading || status == statusOpts.Unpacking) { if (_bundlesToCheck.Count > 0) { float overallProgress = 0; var newBundlesToCheck = new List<string>(); for (int i = 0; i < _bundlesToCheck.Count; i++) { var thisProgress = AssetBundleManager.GetBundleDownloadProgress(_bundlesToCheck[i], true); if(thisProgress != 1f) { newBundlesToCheck.Add(_bundlesToCheck[i]); overallProgress += thisProgress; } } _bundlesToCheck = newBundlesToCheck; if (_bundlesToCheck.Count > 0) { percentDone = overallProgress / _bundlesToCheck.Count; } else percentDone = 1f; } UpdateProgress(); } } public void UpdateProgress() { string donePercent = Mathf.Round(percentDone * 100).ToString(); string msg = _loadingMessage; if (donePercent == "99") { msg = _unpackingMessage; status = statusOpts.Unpacking; } if (donePercent == "100") { msg = _loadedMessage; status = statusOpts.Complete; } if (indicatorText != null) { indicatorText.text = msg + " (" + donePercent + "%)"; } if (indicatorBar != null) { indicatorBar.value = percentDone; } if (indicatorBarText != null) { indicatorBarText.text = donePercent + "%"; } } public void Show(string bundleToCheck, string loadingMessage = "", string unpackingMessage = "", string loadedMessage = "") { var bundlesToCheckList = new List<string>(); bundlesToCheckList.Add(bundleToCheck); Show(bundlesToCheckList, loadingMessage, unpackingMessage, loadedMessage); } public void Show(List<string> bundlesToCheck, string loadingMessage = "", string unpackingMessage = "", string loadedMessage = "") { StopCoroutine("DelayedHide"); ResetAndHide(); _bundlesToCheck.AddRange(bundlesToCheck); _loadingMessage = loadingMessage != "" ? loadingMessage : loadingText; _unpackingMessage = unpackingMessage != "" ? unpackingMessage : unpackingText; _loadedMessage = loadedMessage != "" ? loadedMessage : loadedText; if (indicatorText != null) { indicatorText.text = _loadingMessage + "(0%)"; } if (indicatorObject != null) { indicatorObject.SetActive(true); } status = statusOpts.Downloading; } public void ShowManual(float thisPercentDone, string loadingMessage = "", string unpackingMessage = "", string loadedMessage = "") { //if we are not showing a status if (_bundlesToCheck.Count == 0) { StopCoroutine("DelayedHide"); ResetAndHide(); _loadingMessage = loadingMessage != "" ? loadingMessage : loadingText; _unpackingMessage = unpackingMessage != "" ? unpackingMessage : unpackingText; _loadedMessage = loadedMessage != "" ? loadedMessage : loadedText; percentDone = thisPercentDone; string donePercent = Mathf.Round(percentDone * 100).ToString(); if (indicatorText != null) { indicatorText.text = _loadingMessage + "(" + donePercent + "%)"; } if (indicatorObject != null) { indicatorObject.SetActive(true); } if (indicatorBar != null) { indicatorBar.value = percentDone; } if (indicatorBarText != null) { indicatorBarText.text = donePercent + "%"; } status = statusOpts.Downloading; } } public void Hide() { if (delayHideWhenDone > 0) { StartCoroutine("DelayedHide"); } else { ResetAndHide(); } } IEnumerator DelayedHide() { yield return null; if (indicatorText != null) { indicatorText.text = _loadedMessage + " (100%)"; } if (indicatorBar != null) { indicatorBar.value = 1f; } if (indicatorBarText != null) { indicatorBarText.text = "100%"; } yield return new WaitForSeconds(delayHideWhenDone); ResetAndHide(); } void ResetAndHide() { if (indicatorBar != null) { indicatorBar.value = 0; } if (indicatorText != null) { indicatorText.text = ""; } if (indicatorBarText != null) { indicatorBarText.text = "0%"; } if (indicatorObject != null) { indicatorObject.SetActive(false); } status = statusOpts.Idle; } } }
using NSubstitute; using NuKeeper.Abstractions.CollaborationModels; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Git; using NuKeeper.Abstractions.Logging; using NuKeeper.Abstractions.Output; using NuKeeper.BitBucketLocal; using NuKeeper.Collaboration; using NuKeeper.Commands; using NuKeeper.Engine; using NuKeeper.GitHub; using NuKeeper.Inspection.Files; using NuKeeper.Inspection.Logging; using NUnit.Framework; using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; namespace NuKeeper.Tests.Commands { [TestFixture] public class RepositoryCommandTests { private IEnvironmentVariablesProvider _environmentVariablesProvider; public static async Task<(SettingsContainer settingsContainer, CollaborationPlatformSettings platformSettings)> CaptureSettings( FileSettings settingsIn, bool addLabels = false, int? maxPackageUpdates = null, int? maxOpenPullRequests = null ) { var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); var environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>(); fileSettings.GetSettings().Returns(settingsIn); var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { settingReader }; var collaborationFactory = GetCollaborationFactory(environmentVariablesProvider, settingsReaders); SettingsContainer settingsOut = null; var engine = Substitute.For<ICollaborationEngine>(); await engine.Run(Arg.Do<SettingsContainer>(x => settingsOut = x)); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders); command.PersonalAccessToken = "testToken"; command.RepositoryUri = "http://github.com/test/test"; if (addLabels) { command.Label = new List<string> { "runLabel1", "runLabel2" }; } command.MaxPackageUpdates = maxPackageUpdates; command.MaxOpenPullRequests = maxOpenPullRequests; await command.OnExecute(); return (settingsOut, collaborationFactory.Settings); } [Test] public async Task EmptyFileResultsInDefaultSettings() { var fileSettings = FileSettings.Empty(); var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(7))); Assert.That(settings.PackageFilters.Excludes, Is.Null); Assert.That(settings.PackageFilters.Includes, Is.Null); Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(3)); Assert.That(settings.UserSettings, Is.Not.Null); Assert.That(settings.UserSettings.AllowedChange, Is.EqualTo(VersionChange.Major)); Assert.That(settings.UserSettings.NuGetSources, Is.Null); Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Console)); Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Text)); Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(1)); Assert.That(settings.UserSettings.ConsolidateUpdatesInSinglePullRequest, Is.False); Assert.That(settings.BranchSettings, Is.Not.Null); Assert.That(settings.BranchSettings.BranchNameTemplate, Is.Null); Assert.That(settings.BranchSettings.DeleteBranchAfterMerge, Is.EqualTo(true)); Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Null); Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Null); } [Test] public async Task LabelsOnCommandLineWillReplaceFileLabels() { var fileSettings = new FileSettings { Label = new List<string> { "testLabel" } }; var (settings, _) = await CaptureSettings(fileSettings, true); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(2)); Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("runLabel1")); Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("runLabel2")); Assert.That(settings.SourceControlServerSettings.Labels, Does.Not.Contain("testLabel")); } [Test] public async Task MaxPackageUpdatesFromCommandLineOverridesFiles() { var fileSettings = new FileSettings { MaxPackageUpdates = 42 }; var (settings, _) = await CaptureSettings(fileSettings, false, 101); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(101)); } [Test] public async Task MaxOpenPullRequestsFromCommandLineOverridesFiles() { var fileSettings = new FileSettings { MaxOpenPullRequests = 10 }; var (settings, _) = await CaptureSettings(fileSettings, false, null, 15); Assert.That(settings.UserSettings.MaxOpenPullRequests, Is.EqualTo(15)); } [SetUp] public void Setup() { _environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>(); } [Test] public async Task ShouldCallEngineAndNotSucceedWithoutParams() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { settingReader }; var collaborationFactory = GetCollaborationFactory(_environmentVariablesProvider, settingsReaders); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders); var status = await command.OnExecute(); Assert.That(status, Is.EqualTo(-1)); await engine .DidNotReceive() .Run(Arg.Any<SettingsContainer>()); } [Test] public async Task ShouldCallEngineAndSucceedWithRequiredGithubParams() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { settingReader }; var collaborationFactory = GetCollaborationFactory(_environmentVariablesProvider, settingsReaders); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders) { PersonalAccessToken = "abc", RepositoryUri = "http://github.com/abc/abc" }; var status = await command.OnExecute(); Assert.That(status, Is.EqualTo(0)); await engine .Received(1) .Run(Arg.Any<SettingsContainer>()); } [Test] public async Task ShouldInitialiseCollaborationFactory() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(FileSettings.Empty()); var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { settingReader }; var collaborationFactory = Substitute.For<ICollaborationFactory>(); collaborationFactory.Settings.Returns(new CollaborationPlatformSettings()); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders) { PersonalAccessToken = "abc", RepositoryUri = "http://github.com/abc/abc", ForkMode = ForkMode.PreferSingleRepository }; await command.OnExecute(); await collaborationFactory .Received(1) .Initialise( Arg.Is(new Uri("https://api.github.com")), Arg.Is("abc"), Arg.Is<ForkMode?>(ForkMode.PreferSingleRepository), Arg.Is((Platform?)null)); } [Test] public async Task ShouldInitialiseForkModeFromFile() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns( new FileSettings { ForkMode = ForkMode.PreferFork }); var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { settingReader }; var collaborationFactory = Substitute.For<ICollaborationFactory>(); collaborationFactory.Settings.Returns(new CollaborationPlatformSettings()); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders) { PersonalAccessToken = "abc", RepositoryUri = "http://github.com/abc/abc", ForkMode = null }; await command.OnExecute(); await collaborationFactory .Received(1) .Initialise( Arg.Is(new Uri("https://api.github.com")), Arg.Is("abc"), Arg.Is<ForkMode?>(ForkMode.PreferFork), Arg.Is((Platform?)null)); } [Test] public async Task ShouldInitialisePlatformFromFile() { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns( new FileSettings { Platform = Platform.BitbucketLocal }); var settingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { settingReader }; var collaborationFactory = Substitute.For<ICollaborationFactory>(); collaborationFactory.Settings.Returns(new CollaborationPlatformSettings()); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders) { PersonalAccessToken = "abc", RepositoryUri = "http://github.com/abc/abc", ForkMode = null }; await command.OnExecute(); await collaborationFactory .Received(1) .Initialise( Arg.Is(new Uri("https://api.github.com")), Arg.Is("abc"), Arg.Is((ForkMode?)null), Arg.Is((Platform?)Platform.BitbucketLocal)); } [TestCase(Platform.BitbucketLocal, "https://myRepo.ch/")] [TestCase(Platform.GitHub, "https://api.github.com")] public async Task ShouldInitialisePlatformFromParameter(Platform platform, string expectedApi) { var engine = Substitute.For<ICollaborationEngine>(); var logger = Substitute.For<IConfigureLogger>(); var fileSettings = Substitute.For<IFileSettingsCache>(); fileSettings.GetSettings().Returns(new FileSettings()); var gitHubSettingReader = new GitHubSettingsReader(new MockedGitDiscoveryDriver(), _environmentVariablesProvider); var bitbucketLocalSettingReader = new BitBucketLocalSettingsReader(_environmentVariablesProvider); var settingsReaders = new List<ISettingsReader> { gitHubSettingReader, bitbucketLocalSettingReader }; var collaborationFactory = Substitute.For<ICollaborationFactory>(); collaborationFactory.Settings.Returns(new CollaborationPlatformSettings()); collaborationFactory.Initialise(default, default, default, default).ReturnsForAnyArgs(ValidationResult.Success); var command = new RepositoryCommand(engine, logger, fileSettings, collaborationFactory, settingsReaders) { Platform = platform, RepositoryUri = "https://myRepo.ch/abc/abc" // Repo Uri does not contain any information about the platform. }; await command.OnExecute(); await collaborationFactory .Received(1) .Initialise( Arg.Is(new Uri(expectedApi)), // Is populated by the settings reader. Thus, can be used to check if the correct one was selected. Arg.Is((string)null), Arg.Is((ForkMode?)null), Arg.Is((Platform?)platform)); } [Test] public async Task ShouldPopulateSourceControlServerSettings() { var fileSettings = FileSettings.Empty(); var (settings, platformSettings) = await CaptureSettings(fileSettings); Assert.That(platformSettings, Is.Not.Null); Assert.That(platformSettings.Token, Is.Not.Null); Assert.That(platformSettings.Token, Is.EqualTo("testToken")); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Scope, Is.EqualTo(ServerScope.Repository)); Assert.That(settings.SourceControlServerSettings.OrganisationName, Is.Null); } [Test] public async Task UseCustomCheckoutDirectoryIfParameterIsProvidedForRemote() { var testUri = new Uri("https://github.com"); var collaborationFactorySubstitute = Substitute.For<ICollaborationFactory>(); collaborationFactorySubstitute.ForkFinder.FindPushFork(Arg.Any<string>(), Arg.Any<ForkData>()).Returns(Task.FromResult(new ForkData(testUri, "nukeeper", "nukeeper"))); var folderFactorySubstitute = Substitute.For<IFolderFactory>(); folderFactorySubstitute.FolderFromPath(Arg.Any<string>()) .Returns(ci => new Folder(Substitute.For<INuKeeperLogger>(), new System.IO.DirectoryInfo(ci.Arg<string>()))); var updater = Substitute.For<IRepositoryUpdater>(); var gitEngine = new GitRepositoryEngine(updater, collaborationFactorySubstitute, folderFactorySubstitute, Substitute.For<INuKeeperLogger>(), Substitute.For<IRepositoryFilter>(), Substitute.For<NuGet.Common.ILogger>()); await gitEngine.Run(new RepositorySettings { RepositoryUri = testUri, RepositoryOwner = "nukeeper", RepositoryName = "nukeeper" }, new GitUsernamePasswordCredentials() { Password = "..", Username = "nukeeper" }, new SettingsContainer() { SourceControlServerSettings = new SourceControlServerSettings() { Scope = ServerScope.Repository }, UserSettings = new UserSettings() { Directory = "testdirectory" } }, null); await updater.Received().Run(Arg.Any<IGitDriver>(), Arg.Any<RepositoryData>(), Arg.Is<SettingsContainer>(c => c.WorkingFolder.FullPath.EndsWith("testdirectory", StringComparison.Ordinal))); } [Test] public async Task UseCustomTargetBranchIfParameterIsProvided() { var testUri = new Uri("https://github.com"); var collaborationFactorySubstitute = Substitute.For<ICollaborationFactory>(); collaborationFactorySubstitute.ForkFinder.FindPushFork(Arg.Any<string>(), Arg.Any<ForkData>()).Returns(Task.FromResult(new ForkData(testUri, "nukeeper", "nukeeper"))); var updater = Substitute.For<IRepositoryUpdater>(); var gitEngine = new GitRepositoryEngine(updater, collaborationFactorySubstitute, Substitute.For<IFolderFactory>(), Substitute.For<INuKeeperLogger>(), Substitute.For<IRepositoryFilter>(), Substitute.For<NuGet.Common.ILogger>()); await gitEngine.Run(new RepositorySettings { RepositoryUri = testUri, RemoteInfo = new RemoteInfo() { BranchName = "custombranch", }, RepositoryOwner = "nukeeper", RepositoryName = "nukeeper" }, new GitUsernamePasswordCredentials() { Password = "..", Username = "nukeeper" }, new SettingsContainer() { SourceControlServerSettings = new SourceControlServerSettings() { Scope = ServerScope.Repository } }, null); await updater.Received().Run(Arg.Any<IGitDriver>(), Arg.Is<RepositoryData>(r => r.DefaultBranch == "custombranch"), Arg.Any<SettingsContainer>()); } [Test] public async Task UseCustomTargetBranchIfParameterIsProvidedForLocal() { var testUri = new Uri("https://github.com"); var collaborationFactorySubstitute = Substitute.For<ICollaborationFactory>(); collaborationFactorySubstitute.ForkFinder.FindPushFork(Arg.Any<string>(), Arg.Any<ForkData>()).Returns(Task.FromResult(new ForkData(testUri, "nukeeper", "nukeeper"))); var updater = Substitute.For<IRepositoryUpdater>(); var gitEngine = new GitRepositoryEngine(updater, collaborationFactorySubstitute, Substitute.For<IFolderFactory>(), Substitute.For<INuKeeperLogger>(), Substitute.For<IRepositoryFilter>(), Substitute.For<NuGet.Common.ILogger>()); await gitEngine.Run(new RepositorySettings { RepositoryUri = testUri, RemoteInfo = new RemoteInfo() { LocalRepositoryUri = testUri, BranchName = "custombranch", WorkingFolder = new Uri(Assembly.GetExecutingAssembly().Location), RemoteName = "github" }, RepositoryOwner = "nukeeper", RepositoryName = "nukeeper" }, new GitUsernamePasswordCredentials() { Password = "..", Username = "nukeeper" }, new SettingsContainer() { SourceControlServerSettings = new SourceControlServerSettings() { Scope = ServerScope.Repository } }, null); await updater.Received().Run(Arg.Any<IGitDriver>(), Arg.Is<RepositoryData>(r => r.DefaultBranch == "custombranch"), Arg.Any<SettingsContainer>()); } [Test] public async Task WillNotReadMaxRepoFromFile() { var fileSettings = new FileSettings { MaxRepo = 42 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(1)); } [Test] public async Task WillReadApiFromFile() { var fileSettings = new FileSettings { Api = "http://github.contoso.com/" }; var (_, platformSettings) = await CaptureSettings(fileSettings); Assert.That(platformSettings, Is.Not.Null); Assert.That(platformSettings.BaseApiUrl, Is.Not.Null); Assert.That(platformSettings.BaseApiUrl, Is.EqualTo(new Uri("http://github.contoso.com/"))); } [Test] public async Task WillReadBranchNamePrefixFromFile() { var testTemplate = "nukeeper/MyBranch"; var fileSettings = new FileSettings { BranchNameTemplate = testTemplate }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.BranchSettings, Is.Not.Null); Assert.That(settings.BranchSettings.BranchNameTemplate, Is.EqualTo(testTemplate)); } [Test] public async Task WillReadConsolidateFromFile() { var fileSettings = new FileSettings { Consolidate = true }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.UserSettings.ConsolidateUpdatesInSinglePullRequest, Is.True); } [Test] public async Task WillReadLabelFromFile() { var fileSettings = new FileSettings { Label = new List<string> { "testLabel" } }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null); Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(1)); Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("testLabel")); } [Test] public async Task WillReadMaxPackageUpdatesFromFile() { var fileSettings = new FileSettings { MaxPackageUpdates = 42 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings, Is.Not.Null); Assert.That(settings.PackageFilters, Is.Not.Null); Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(42)); } [Test] public async Task WillReadMaxOpenPullRequestsFromFile() { var fileSettings = new FileSettings { MaxOpenPullRequests = 202 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings.UserSettings.MaxOpenPullRequests, Is.EqualTo(202)); } [Test] public async Task MaxOpenPullRequestsIsOneIfConsolidatedIsTrue() { var fileSettings = new FileSettings { Consolidate = true, MaxPackageUpdates = 20 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings.UserSettings.MaxOpenPullRequests, Is.EqualTo(1)); } [Test] public async Task MaxOpenPullRequestsIsMaxPackageUpdatesIfConsolidatedIsFalse() { var fileSettings = new FileSettings { Consolidate = false, MaxPackageUpdates = 20 }; var (settings, _) = await CaptureSettings(fileSettings); Assert.That(settings.UserSettings.MaxOpenPullRequests, Is.EqualTo(20)); } private static ICollaborationFactory GetCollaborationFactory(IEnvironmentVariablesProvider environmentVariablesProvider, IEnumerable<ISettingsReader> settingReaders = null) { return new CollaborationFactory( settingReaders ?? new ISettingsReader[] { new GitHubSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider) }, Substitute.For<INuKeeperLogger>(), 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 NPOI.HSSF.UserModel { using System; using System.IO; using System.Collections; using NPOI.HSSF.Record; using NPOI.SS.UserModel; /// <summary> /// Represents a Font used in a workbook. /// @version 1.0-pre /// @author Andrew C. Oliver /// </summary> internal class HSSFFont:NPOI.SS.UserModel.IFont { public const String FONT_ARIAL = "Arial"; private FontRecord font; private short index; /// <summary> /// Initializes a new instance of the <see cref="HSSFFont"/> class. /// </summary> /// <param name="index">The index.</param> /// <param name="rec">The record.</param> public HSSFFont(short index, FontRecord rec) { font = rec; this.index = index; } /// <summary> /// Get the name for the font (i.e. Arial) /// </summary> /// <value>the name of the font to use</value> public String FontName { get { return font.FontName; } set { font.FontName = value; } } /// <summary> /// Get the index within the HSSFWorkbook (sequence within the collection of Font objects) /// </summary> /// <value>Unique index number of the Underlying record this Font represents (probably you don't care /// Unless you're comparing which one is which)</value> public short Index { get { return index; } } /// <summary> /// Get or sets the font height in Unit's of 1/20th of a point. Maybe you might want to /// use the GetFontHeightInPoints which matches to the familiar 10, 12, 14 etc.. /// </summary> /// <value>height in 1/20ths of a point.</value> public short FontHeight { get { return font.FontHeight; } set { font.FontHeight = value; } } /// <summary> /// Gets or sets the font height in points. /// </summary> /// <value>height in the familiar Unit of measure - points.</value> public short FontHeightInPoints { get { return (short)(font.FontHeight / 20); } set { font.FontHeight=(short)(value * 20); } } /// <summary> /// Gets or sets whether to use italics or not /// </summary> /// <value><c>true</c> if this instance is italic; otherwise, <c>false</c>.</value> public bool IsItalic { get { return font.IsItalic; } set { font.IsItalic=value; } } /// <summary> /// Get whether to use a strikeout horizontal line through the text or not /// </summary> /// <value> /// strikeout or not /// </value> public bool IsStrikeout { get { return font.IsStrikeout; } set { font.IsStrikeout=value; } } /// <summary> /// Gets or sets the color for the font. /// </summary> /// <value>The color to use.</value> public short Color { get { return font.ColorPaletteIndex; } set { font.ColorPaletteIndex=value; } } /// <summary> /// Gets or sets the boldness to use /// </summary> /// <value>The boldweight.</value> public short Boldweight { get { return font.BoldWeight; } set { font.BoldWeight=value; } } /// <summary> /// Gets or sets normal,base or subscript. /// </summary> /// <value>offset type to use (none,base,sub)</value> public short TypeOffset { get { return font.SuperSubScript; } set { font.SuperSubScript=(short)value; } } /// <summary> /// Gets or sets the type of text Underlining to use /// </summary> /// <value>The Underlining type.</value> public byte Underline { get { return font.Underline; } set { font.Underline=(byte)value; } } /// <summary> /// Gets or sets the char set to use. /// </summary> /// <value>The char set.</value> public short Charset { get { return font.Charset; } set { font.Charset = (byte)value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { return "NPOI.HSSF.UserModel.HSSFFont{" + font + "}"; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + ((font == null) ? 0 : font.GetHashCode()); result = prime * result + index; return result; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj is HSSFFont) { HSSFFont other = (HSSFFont)obj; if (font == null) { if (other.font != null) return false; } else if (!font.Equals(other.font)) return false; if (index != other.index) return false; return true; } return false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace System.Numerics.Matrices { /// <summary> /// Represents a matrix of double precision floating-point values defined by its number of columns and rows /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Matrix4x4: IEquatable<Matrix4x4>, IMatrix { public const int ColumnCount = 4; public const int RowCount = 4; static Matrix4x4() { Zero = new Matrix4x4(0); Identity = new Matrix4x4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } /// <summary> /// Constant Matrix4x4 with value intialized to the identity of a 4 x 4 matrix /// </summary> public static readonly Matrix4x4 Identity; /// <summary> /// Gets the smallest value used to determine equality /// </summary> public double Epsilon { get { return MatrixHelper.Epsilon; } } /// <summary> /// Constant Matrix4x4 with all values initialized to zero /// </summary> public static readonly Matrix4x4 Zero; /// <summary> /// Initializes a Matrix4x4 with all of it values specifically set /// </summary> /// <param name="m11">The column 1, row 1 value</param> /// <param name="m21">The column 2, row 1 value</param> /// <param name="m31">The column 3, row 1 value</param> /// <param name="m41">The column 4, row 1 value</param> /// <param name="m12">The column 1, row 2 value</param> /// <param name="m22">The column 2, row 2 value</param> /// <param name="m32">The column 3, row 2 value</param> /// <param name="m42">The column 4, row 2 value</param> /// <param name="m13">The column 1, row 3 value</param> /// <param name="m23">The column 2, row 3 value</param> /// <param name="m33">The column 3, row 3 value</param> /// <param name="m43">The column 4, row 3 value</param> /// <param name="m14">The column 1, row 4 value</param> /// <param name="m24">The column 2, row 4 value</param> /// <param name="m34">The column 3, row 4 value</param> /// <param name="m44">The column 4, row 4 value</param> public Matrix4x4(double m11, double m21, double m31, double m41, double m12, double m22, double m32, double m42, double m13, double m23, double m33, double m43, double m14, double m24, double m34, double m44) { M11 = m11; M21 = m21; M31 = m31; M41 = m41; M12 = m12; M22 = m22; M32 = m32; M42 = m42; M13 = m13; M23 = m23; M33 = m33; M43 = m43; M14 = m14; M24 = m24; M34 = m34; M44 = m44; } /// <summary> /// Initialized a Matrix4x4 with all values set to the same value /// </summary> /// <param name="value">The value to set all values to</param> public Matrix4x4(double value) { M11 = M21 = M31 = M41 = M12 = M22 = M32 = M42 = M13 = M23 = M33 = M43 = M14 = M24 = M34 = M44 = value; } public double M11; public double M21; public double M31; public double M41; public double M12; public double M22; public double M32; public double M42; public double M13; public double M23; public double M33; public double M43; public double M14; public double M24; public double M34; public double M44; public unsafe double this[int col, int row] { get { if (col < 0 || col >= ColumnCount) throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col)); if (row < 0 || row >= RowCount) throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row)); fixed (Matrix4x4* p = &this) { double* d = (double*)p; return d[row * ColumnCount + col]; } } set { if (col < 0 || col >= ColumnCount) throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col)); if (row < 0 || row >= RowCount) throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row)); fixed (Matrix4x4* p = &this) { double* d = (double*)p; d[row * ColumnCount + col] = value; } } } /// <summary> /// Gets the number of columns in the matrix /// </summary> public int Columns { get { return ColumnCount; } } /// <summary> /// Get the number of rows in the matrix /// </summary> public int Rows { get { return RowCount; } } /// <summary> /// Gets a new Matrix1x4 containing the values of column 1 /// </summary> public Matrix1x4 Column1 { get { return new Matrix1x4(M11, M12, M13, M14); } } /// <summary> /// Gets a new Matrix1x4 containing the values of column 2 /// </summary> public Matrix1x4 Column2 { get { return new Matrix1x4(M21, M22, M23, M24); } } /// <summary> /// Gets a new Matrix1x4 containing the values of column 3 /// </summary> public Matrix1x4 Column3 { get { return new Matrix1x4(M31, M32, M33, M34); } } /// <summary> /// Gets a new Matrix1x4 containing the values of column 4 /// </summary> public Matrix1x4 Column4 { get { return new Matrix1x4(M41, M42, M43, M44); } } /// <summary> /// Gets a new Matrix4x1 containing the values of column 1 /// </summary> public Matrix4x1 Row1 { get { return new Matrix4x1(M11, M21, M31, M41); } } /// <summary> /// Gets a new Matrix4x1 containing the values of column 2 /// </summary> public Matrix4x1 Row2 { get { return new Matrix4x1(M12, M22, M32, M42); } } /// <summary> /// Gets a new Matrix4x1 containing the values of column 3 /// </summary> public Matrix4x1 Row3 { get { return new Matrix4x1(M13, M23, M33, M43); } } /// <summary> /// Gets a new Matrix4x1 containing the values of column 4 /// </summary> public Matrix4x1 Row4 { get { return new Matrix4x1(M14, M24, M34, M44); } } public override bool Equals(object obj) { if (obj is Matrix4x4) return this == (Matrix4x4)obj; return false; } public bool Equals(Matrix4x4 other) { return this == other; } public unsafe override int GetHashCode() { fixed (Matrix4x4* p = &this) { int* x = (int*)p; unchecked { return 0xFFE1 + 7 * ((((x[00] ^ x[01]) << 0) + ((x[02] ^ x[03]) << 1) + ((x[04] ^ x[05]) << 2) + ((x[06] ^ x[07]) << 3)) << 0) + 7 * ((((x[04] ^ x[05]) << 0) + ((x[06] ^ x[07]) << 1) + ((x[08] ^ x[09]) << 2) + ((x[10] ^ x[11]) << 3)) << 1) + 7 * ((((x[08] ^ x[09]) << 0) + ((x[10] ^ x[11]) << 1) + ((x[12] ^ x[13]) << 2) + ((x[14] ^ x[15]) << 3)) << 2) + 7 * ((((x[12] ^ x[13]) << 0) + ((x[14] ^ x[15]) << 1) + ((x[16] ^ x[17]) << 2) + ((x[18] ^ x[19]) << 3)) << 3); } } } public override string ToString() { return "Matrix4x4: " + String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M11, M21, M31, M41) + String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M12, M22, M32, M42) + String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M13, M23, M33, M43) + String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M14, M24, M34, M44); } /// <summary> /// Creates and returns a transposed matrix /// </summary> /// <returns>Matrix with transposed values</returns> public Matrix4x4 Transpose() { return new Matrix4x4(M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44); } public static bool operator ==(Matrix4x4 matrix1, Matrix4x4 matrix2) { return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11) && MatrixHelper.AreEqual(matrix1.M21, matrix2.M21) && MatrixHelper.AreEqual(matrix1.M31, matrix2.M31) && MatrixHelper.AreEqual(matrix1.M41, matrix2.M41) && MatrixHelper.AreEqual(matrix1.M12, matrix2.M12) && MatrixHelper.AreEqual(matrix1.M22, matrix2.M22) && MatrixHelper.AreEqual(matrix1.M32, matrix2.M32) && MatrixHelper.AreEqual(matrix1.M42, matrix2.M42) && MatrixHelper.AreEqual(matrix1.M13, matrix2.M13) && MatrixHelper.AreEqual(matrix1.M23, matrix2.M23) && MatrixHelper.AreEqual(matrix1.M33, matrix2.M33) && MatrixHelper.AreEqual(matrix1.M43, matrix2.M43) && MatrixHelper.AreEqual(matrix1.M14, matrix2.M14) && MatrixHelper.AreEqual(matrix1.M24, matrix2.M24) && MatrixHelper.AreEqual(matrix1.M34, matrix2.M34) && MatrixHelper.AreEqual(matrix1.M44, matrix2.M44); } public static bool operator !=(Matrix4x4 matrix1, Matrix4x4 matrix2) { return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11) || MatrixHelper.NotEqual(matrix1.M21, matrix2.M21) || MatrixHelper.NotEqual(matrix1.M31, matrix2.M31) || MatrixHelper.NotEqual(matrix1.M41, matrix2.M41) || MatrixHelper.NotEqual(matrix1.M12, matrix2.M12) || MatrixHelper.NotEqual(matrix1.M22, matrix2.M22) || MatrixHelper.NotEqual(matrix1.M32, matrix2.M32) || MatrixHelper.NotEqual(matrix1.M42, matrix2.M42) || MatrixHelper.NotEqual(matrix1.M13, matrix2.M13) || MatrixHelper.NotEqual(matrix1.M23, matrix2.M23) || MatrixHelper.NotEqual(matrix1.M33, matrix2.M33) || MatrixHelper.NotEqual(matrix1.M43, matrix2.M43) || MatrixHelper.NotEqual(matrix1.M14, matrix2.M14) || MatrixHelper.NotEqual(matrix1.M24, matrix2.M24) || MatrixHelper.NotEqual(matrix1.M34, matrix2.M34) || MatrixHelper.NotEqual(matrix1.M44, matrix2.M44); } public static Matrix4x4 operator +(Matrix4x4 matrix1, Matrix4x4 matrix2) { double m11 = matrix1.M11 + matrix2.M11; double m21 = matrix1.M21 + matrix2.M21; double m31 = matrix1.M31 + matrix2.M31; double m41 = matrix1.M41 + matrix2.M41; double m12 = matrix1.M12 + matrix2.M12; double m22 = matrix1.M22 + matrix2.M22; double m32 = matrix1.M32 + matrix2.M32; double m42 = matrix1.M42 + matrix2.M42; double m13 = matrix1.M13 + matrix2.M13; double m23 = matrix1.M23 + matrix2.M23; double m33 = matrix1.M33 + matrix2.M33; double m43 = matrix1.M43 + matrix2.M43; double m14 = matrix1.M14 + matrix2.M14; double m24 = matrix1.M24 + matrix2.M24; double m34 = matrix1.M34 + matrix2.M34; double m44 = matrix1.M44 + matrix2.M44; return new Matrix4x4(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43, m14, m24, m34, m44); } public static Matrix4x4 operator -(Matrix4x4 matrix1, Matrix4x4 matrix2) { double m11 = matrix1.M11 - matrix2.M11; double m21 = matrix1.M21 - matrix2.M21; double m31 = matrix1.M31 - matrix2.M31; double m41 = matrix1.M41 - matrix2.M41; double m12 = matrix1.M12 - matrix2.M12; double m22 = matrix1.M22 - matrix2.M22; double m32 = matrix1.M32 - matrix2.M32; double m42 = matrix1.M42 - matrix2.M42; double m13 = matrix1.M13 - matrix2.M13; double m23 = matrix1.M23 - matrix2.M23; double m33 = matrix1.M33 - matrix2.M33; double m43 = matrix1.M43 - matrix2.M43; double m14 = matrix1.M14 - matrix2.M14; double m24 = matrix1.M24 - matrix2.M24; double m34 = matrix1.M34 - matrix2.M34; double m44 = matrix1.M44 - matrix2.M44; return new Matrix4x4(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43, m14, m24, m34, m44); } public static Matrix4x4 operator *(Matrix4x4 matrix, double scalar) { double m11 = matrix.M11 * scalar; double m21 = matrix.M21 * scalar; double m31 = matrix.M31 * scalar; double m41 = matrix.M41 * scalar; double m12 = matrix.M12 * scalar; double m22 = matrix.M22 * scalar; double m32 = matrix.M32 * scalar; double m42 = matrix.M42 * scalar; double m13 = matrix.M13 * scalar; double m23 = matrix.M23 * scalar; double m33 = matrix.M33 * scalar; double m43 = matrix.M43 * scalar; double m14 = matrix.M14 * scalar; double m24 = matrix.M24 * scalar; double m34 = matrix.M34 * scalar; double m44 = matrix.M44 * scalar; return new Matrix4x4(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43, m14, m24, m34, m44); } public static Matrix4x4 operator *(double scalar, Matrix4x4 matrix) { double m11 = scalar * matrix.M11; double m21 = scalar * matrix.M21; double m31 = scalar * matrix.M31; double m41 = scalar * matrix.M41; double m12 = scalar * matrix.M12; double m22 = scalar * matrix.M22; double m32 = scalar * matrix.M32; double m42 = scalar * matrix.M42; double m13 = scalar * matrix.M13; double m23 = scalar * matrix.M23; double m33 = scalar * matrix.M33; double m43 = scalar * matrix.M43; double m14 = scalar * matrix.M14; double m24 = scalar * matrix.M24; double m34 = scalar * matrix.M34; double m44 = scalar * matrix.M44; return new Matrix4x4(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43, m14, m24, m34, m44); } public static Matrix1x4 operator *(Matrix4x4 matrix1, Matrix1x4 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12 + matrix1.M33 * matrix2.M13 + matrix1.M43 * matrix2.M14; double m14 = matrix1.M14 * matrix2.M11 + matrix1.M24 * matrix2.M12 + matrix1.M34 * matrix2.M13 + matrix1.M44 * matrix2.M14; return new Matrix1x4(m11, m12, m13, m14); } public static Matrix2x4 operator *(Matrix4x4 matrix1, Matrix2x4 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14; double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14; double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22 + matrix1.M32 * matrix2.M23 + matrix1.M42 * matrix2.M24; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12 + matrix1.M33 * matrix2.M13 + matrix1.M43 * matrix2.M14; double m23 = matrix1.M13 * matrix2.M21 + matrix1.M23 * matrix2.M22 + matrix1.M33 * matrix2.M23 + matrix1.M43 * matrix2.M24; double m14 = matrix1.M14 * matrix2.M11 + matrix1.M24 * matrix2.M12 + matrix1.M34 * matrix2.M13 + matrix1.M44 * matrix2.M14; double m24 = matrix1.M14 * matrix2.M21 + matrix1.M24 * matrix2.M22 + matrix1.M34 * matrix2.M23 + matrix1.M44 * matrix2.M24; return new Matrix2x4(m11, m21, m12, m22, m13, m23, m14, m24); } public static Matrix3x4 operator *(Matrix4x4 matrix1, Matrix3x4 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14; double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24; double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32 + matrix1.M31 * matrix2.M33 + matrix1.M41 * matrix2.M34; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14; double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22 + matrix1.M32 * matrix2.M23 + matrix1.M42 * matrix2.M24; double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32 + matrix1.M32 * matrix2.M33 + matrix1.M42 * matrix2.M34; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12 + matrix1.M33 * matrix2.M13 + matrix1.M43 * matrix2.M14; double m23 = matrix1.M13 * matrix2.M21 + matrix1.M23 * matrix2.M22 + matrix1.M33 * matrix2.M23 + matrix1.M43 * matrix2.M24; double m33 = matrix1.M13 * matrix2.M31 + matrix1.M23 * matrix2.M32 + matrix1.M33 * matrix2.M33 + matrix1.M43 * matrix2.M34; double m14 = matrix1.M14 * matrix2.M11 + matrix1.M24 * matrix2.M12 + matrix1.M34 * matrix2.M13 + matrix1.M44 * matrix2.M14; double m24 = matrix1.M14 * matrix2.M21 + matrix1.M24 * matrix2.M22 + matrix1.M34 * matrix2.M23 + matrix1.M44 * matrix2.M24; double m34 = matrix1.M14 * matrix2.M31 + matrix1.M24 * matrix2.M32 + matrix1.M34 * matrix2.M33 + matrix1.M44 * matrix2.M34; return new Matrix3x4(m11, m21, m31, m12, m22, m32, m13, m23, m33, m14, m24, m34); } public static Matrix4x4 operator *(Matrix4x4 matrix1, Matrix4x4 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14; double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24; double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32 + matrix1.M31 * matrix2.M33 + matrix1.M41 * matrix2.M34; double m41 = matrix1.M11 * matrix2.M41 + matrix1.M21 * matrix2.M42 + matrix1.M31 * matrix2.M43 + matrix1.M41 * matrix2.M44; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14; double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22 + matrix1.M32 * matrix2.M23 + matrix1.M42 * matrix2.M24; double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32 + matrix1.M32 * matrix2.M33 + matrix1.M42 * matrix2.M34; double m42 = matrix1.M12 * matrix2.M41 + matrix1.M22 * matrix2.M42 + matrix1.M32 * matrix2.M43 + matrix1.M42 * matrix2.M44; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12 + matrix1.M33 * matrix2.M13 + matrix1.M43 * matrix2.M14; double m23 = matrix1.M13 * matrix2.M21 + matrix1.M23 * matrix2.M22 + matrix1.M33 * matrix2.M23 + matrix1.M43 * matrix2.M24; double m33 = matrix1.M13 * matrix2.M31 + matrix1.M23 * matrix2.M32 + matrix1.M33 * matrix2.M33 + matrix1.M43 * matrix2.M34; double m43 = matrix1.M13 * matrix2.M41 + matrix1.M23 * matrix2.M42 + matrix1.M33 * matrix2.M43 + matrix1.M43 * matrix2.M44; double m14 = matrix1.M14 * matrix2.M11 + matrix1.M24 * matrix2.M12 + matrix1.M34 * matrix2.M13 + matrix1.M44 * matrix2.M14; double m24 = matrix1.M14 * matrix2.M21 + matrix1.M24 * matrix2.M22 + matrix1.M34 * matrix2.M23 + matrix1.M44 * matrix2.M24; double m34 = matrix1.M14 * matrix2.M31 + matrix1.M24 * matrix2.M32 + matrix1.M34 * matrix2.M33 + matrix1.M44 * matrix2.M34; double m44 = matrix1.M14 * matrix2.M41 + matrix1.M24 * matrix2.M42 + matrix1.M34 * matrix2.M43 + matrix1.M44 * matrix2.M44; return new Matrix4x4(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43, m14, m24, m34, m44); } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using NUnit.Util; namespace NUnit.UiKit { public class TreeBasedSettingsDialog : NUnit.UiKit.SettingsDialogBase { private System.Windows.Forms.TreeView treeView1; private System.Windows.Forms.Panel panel1; private System.ComponentModel.IContainer components = null; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.GroupBox groupBox1; private SettingsPage current; public static void Display( Form owner, params SettingsPage[] pages ) { using( TreeBasedSettingsDialog dialog = new TreeBasedSettingsDialog() ) { owner.Site.Container.Add( dialog ); dialog.Font = owner.Font; dialog.SettingsPages.AddRange( pages ); dialog.ShowDialog(); } } public TreeBasedSettingsDialog() { // This call is required by the Windows Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TreeBasedSettingsDialog)); this.treeView1 = new System.Windows.Forms.TreeView(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.panel1 = new System.Windows.Forms.Panel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.SuspendLayout(); // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(592, 392); this.cancelButton.Name = "cancelButton"; // // okButton // this.okButton.Location = new System.Drawing.Point(504, 392); this.okButton.Name = "okButton"; // // treeView1 // this.treeView1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.treeView1.HideSelection = false; this.treeView1.ImageList = this.imageList1; this.treeView1.Location = new System.Drawing.Point(16, 16); this.treeView1.Name = "treeView1"; this.treeView1.PathSeparator = "."; this.treeView1.Size = new System.Drawing.Size(176, 350); this.treeView1.TabIndex = 19; this.treeView1.AfterExpand += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterExpand); this.treeView1.AfterCollapse += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterCollapse); this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect); // // imageList1 // this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // panel1 // this.panel1.Location = new System.Drawing.Point(208, 16); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(456, 336); this.panel1.TabIndex = 20; // // groupBox1 // this.groupBox1.Location = new System.Drawing.Point(208, 360); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(456, 8); this.groupBox1.TabIndex = 21; this.groupBox1.TabStop = false; // // TreeBasedSettingsDialog // this.ClientSize = new System.Drawing.Size(682, 426); this.Controls.Add(this.groupBox1); this.Controls.Add(this.panel1); this.Controls.Add(this.treeView1); this.Name = "TreeBasedSettingsDialog"; this.Load += new System.EventHandler(this.TreeBasedSettingsDialog_Load); this.Controls.SetChildIndex(this.treeView1, 0); this.Controls.SetChildIndex(this.okButton, 0); this.Controls.SetChildIndex(this.cancelButton, 0); this.Controls.SetChildIndex(this.panel1, 0); this.Controls.SetChildIndex(this.groupBox1, 0); this.ResumeLayout(false); } #endregion private void TreeBasedSettingsDialog_Load(object sender, System.EventArgs e) { foreach( SettingsPage page in SettingsPages ) AddBranchToTree( treeView1.Nodes, page.Key ); if ( treeView1.VisibleCount >= treeView1.GetNodeCount( true ) ) treeView1.ExpandAll(); SelectInitialPage(); treeView1.Select(); } private void SelectInitialPage() { string initialPage = Services.UserSettings.GetSetting("Gui.Settings.InitialPage") as string; if (initialPage != null) SelectPage(initialPage); else if (treeView1.Nodes.Count > 0) SelectFirstPage(treeView1.Nodes); } private void SelectPage(string initialPage) { TreeNode node = FindNode(treeView1.Nodes, initialPage); if (node != null) treeView1.SelectedNode = node; else SelectFirstPage(treeView1.Nodes); } private TreeNode FindNode(TreeNodeCollection nodes, string key) { int dot = key.IndexOf('.'); string tail = null; if (dot >= 0) { tail = key.Substring(dot + 1); key = key.Substring(0, dot); } foreach (TreeNode node in nodes) if (node.Text == key) return tail == null ? node : FindNode(node.Nodes, tail); return null; } private void SelectFirstPage(TreeNodeCollection nodes) { if ( nodes[0].Nodes.Count == 0 ) treeView1.SelectedNode = nodes[0]; else { nodes[0].Expand(); SelectFirstPage(nodes[0].Nodes); } } private void AddBranchToTree( TreeNodeCollection nodes, string key ) { int dot = key.IndexOf( '.' ); if ( dot < 0 ) { nodes.Add( new TreeNode( key, 2, 2 ) ); return; } string name = key.Substring( 0, dot ); key = key.Substring(dot+1); TreeNode node = FindOrAddNode( nodes, name ); if ( key != null ) AddBranchToTree( node.Nodes, key ); } private TreeNode FindOrAddNode( TreeNodeCollection nodes, string name ) { foreach( TreeNode node in nodes ) if ( node.Text == name ) return node; TreeNode newNode = new TreeNode(name, 0, 0); nodes.Add( newNode ); return newNode; } private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { string key = e.Node.FullPath; SettingsPage page = SettingsPages[key]; Services.UserSettings.SaveSetting("Gui.Settings.InitialPage", key); if ( page != null && page != current ) { panel1.Controls.Clear(); panel1.Controls.Add( page ); page.Dock = DockStyle.Fill; current = page; return; } } private void treeView1_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e) { e.Node.ImageIndex = e.Node.SelectedImageIndex = 1; } private void treeView1_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e) { e.Node.ImageIndex = e.Node.SelectedImageIndex = 0; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using DocuSign.eSign.Client; using DocuSign.eSign.Model; namespace DocuSign.eSign.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface INotaryApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns></returns> NotaryJournalList ListNotaryJournals (NotaryApi.ListNotaryJournalsOptions options = null); /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>ApiResponse of </returns> ApiResponse<NotaryJournalList> ListNotaryJournalsWithHttpInfo (NotaryApi.ListNotaryJournalsOptions options = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>Task of NotaryJournalList</returns> System.Threading.Tasks.Task<NotaryJournalList> ListNotaryJournalsAsync (NotaryApi.ListNotaryJournalsOptions options = null); /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>Task of ApiResponse (NotaryJournalList)</returns> System.Threading.Tasks.Task<ApiResponse<NotaryJournalList>> ListNotaryJournalsAsyncWithHttpInfo (NotaryApi.ListNotaryJournalsOptions options = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class NotaryApi : INotaryApi { private DocuSign.eSign.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="NotaryApi"/> class. /// </summary> /// <returns></returns> public NotaryApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = DocuSign.eSign.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="NotaryApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public NotaryApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = DocuSign.eSign.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public DocuSign.eSign.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Get notary jurisdictions for a user /// </summary> public class ListNotaryJournalsOptions { /// public string count {get; set;} /// public string searchText {get; set;} /// public string startPosition {get; set;} } /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>NotaryJournalList</returns> public NotaryJournalList ListNotaryJournals (NotaryApi.ListNotaryJournalsOptions options = null) { ApiResponse<NotaryJournalList> localVarResponse = ListNotaryJournalsWithHttpInfo(options); return localVarResponse.Data; } /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>ApiResponse of NotaryJournalList</returns> public ApiResponse< NotaryJournalList > ListNotaryJournalsWithHttpInfo (NotaryApi.ListNotaryJournalsOptions options = null) { var localVarPath = "/v2/current_user/notary/journals"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (options != null) { if (options.count != null) localVarQueryParams.Add("count", Configuration.ApiClient.ParameterToString(options.count)); // query parameter if (options.searchText != null) localVarQueryParams.Add("search_text", Configuration.ApiClient.ParameterToString(options.searchText)); // query parameter if (options.startPosition != null) localVarQueryParams.Add("start_position", Configuration.ApiClient.ParameterToString(options.startPosition)); // query parameter } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ListNotaryJournals", localVarResponse); if (exception != null) throw exception; } // DocuSign: Handle for PDF return types if (localVarResponse.ContentType != null && !localVarResponse.ContentType.ToLower().Contains("json")) { return new ApiResponse<NotaryJournalList>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NotaryJournalList) Configuration.ApiClient.Deserialize(localVarResponse.RawBytes, typeof(NotaryJournalList))); } else { return new ApiResponse<NotaryJournalList>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NotaryJournalList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NotaryJournalList))); } } /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>Task of NotaryJournalList</returns> public async System.Threading.Tasks.Task<NotaryJournalList> ListNotaryJournalsAsync (NotaryApi.ListNotaryJournalsOptions options = null) { ApiResponse<NotaryJournalList> localVarResponse = await ListNotaryJournalsAsyncWithHttpInfo(options); return localVarResponse.Data; } /// <summary> /// Get notary jurisdictions for a user /// </summary> /// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>Task of ApiResponse (NotaryJournalList)</returns> public async System.Threading.Tasks.Task<ApiResponse<NotaryJournalList>> ListNotaryJournalsAsyncWithHttpInfo (NotaryApi.ListNotaryJournalsOptions options = null) { var localVarPath = "/v2/current_user/notary/journals"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (options != null) { if (options.count != null) localVarQueryParams.Add("count", Configuration.ApiClient.ParameterToString(options.count)); // query parameter if (options.searchText != null) localVarQueryParams.Add("search_text", Configuration.ApiClient.ParameterToString(options.searchText)); // query parameter if (options.startPosition != null) localVarQueryParams.Add("start_position", Configuration.ApiClient.ParameterToString(options.startPosition)); // query parameter } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ListNotaryJournals", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NotaryJournalList>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NotaryJournalList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NotaryJournalList))); } } }
// 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. namespace MassTransit.NLogIntegration.Logging { using System; using MassTransit.Logging; using NLog; using Util; /// <summary> /// A logger that wraps to NLog. See http://stackoverflow.com/questions/7412156/how-to-retain-callsite-information-when-wrapping-nlog /// </summary> public class NLogLog : ILog { readonly NLog.Logger _log; /// <summary> /// Create a new NLog logger instance. /// </summary> /// <param name="name">Name of type to log as.</param> public NLogLog([NotNull] NLog.Logger log, [NotNull] string name) { if (name == null) throw new ArgumentNullException("name"); _log = log; } public bool IsDebugEnabled { get { return _log.IsDebugEnabled; } } public bool IsInfoEnabled { get { return _log.IsInfoEnabled; } } public bool IsWarnEnabled { get { return _log.IsWarnEnabled; } } public bool IsErrorEnabled { get { return _log.IsErrorEnabled; } } public bool IsFatalEnabled { get { return _log.IsFatalEnabled; } } public void Log(MassTransit.Logging.LogLevel level, object obj) { _log.Log(GetNLogLevel(level), obj); } public void Log(MassTransit.Logging.LogLevel level, object obj, Exception exception) { _log.LogException(GetNLogLevel(level), obj == null ? "" : obj.ToString(), exception); } public void Log(MassTransit.Logging.LogLevel level, LogOutputProvider messageProvider) { _log.Log(GetNLogLevel(level), ToGenerator(messageProvider)); } public void LogFormat(MassTransit.Logging.LogLevel level, IFormatProvider formatProvider, string format, params object[] args) { _log.Log(GetNLogLevel(level), formatProvider, format, args); } public void LogFormat(MassTransit.Logging.LogLevel level, string format, params object[] args) { _log.Log(GetNLogLevel(level), format, args); } public void Debug(object obj) { _log.Log(NLog.LogLevel.Debug, obj); } public void Debug(object obj, Exception exception) { _log.LogException(NLog.LogLevel.Debug, obj == null ? "" : obj.ToString(), exception); } public void Debug(LogOutputProvider messageProvider) { _log.Debug(ToGenerator(messageProvider)); } public void Info(object obj) { _log.Log(NLog.LogLevel.Info, obj); } public void Info(object obj, Exception exception) { _log.LogException(NLog.LogLevel.Info, obj == null ? "" : obj.ToString(), exception); } public void Info(LogOutputProvider messageProvider) { _log.Info(ToGenerator(messageProvider)); } public void Warn(object obj) { _log.Log(NLog.LogLevel.Warn, obj); } public void Warn(object obj, Exception exception) { _log.LogException(NLog.LogLevel.Warn, obj == null ? "" : obj.ToString(), exception); } public void Warn(LogOutputProvider messageProvider) { _log.Warn(ToGenerator(messageProvider)); } public void Error(object obj) { _log.Log(NLog.LogLevel.Error, obj); } public void Error(object obj, Exception exception) { _log.LogException(NLog.LogLevel.Error, obj == null ? "" : obj.ToString(), exception); } public void Error(LogOutputProvider messageProvider) { _log.Error(ToGenerator(messageProvider)); } public void Fatal(object obj) { _log.Log(NLog.LogLevel.Fatal, obj); } public void Fatal(object obj, Exception exception) { _log.LogException(NLog.LogLevel.Fatal, obj == null ? "" : obj.ToString(), exception); } public void Fatal(LogOutputProvider messageProvider) { _log.Fatal(ToGenerator(messageProvider)); } public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Debug, formatProvider, format, args); } public void DebugFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Debug, format, args); } public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Info, formatProvider, format, args); } public void InfoFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Info, format, args); } public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Warn, formatProvider, format, args); } public void WarnFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Warn, format, args); } public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Error, formatProvider, format, args); } public void ErrorFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Error, format, args); } public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Fatal, formatProvider, format, args); } public void FatalFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Fatal, format, args); } NLog.LogLevel GetNLogLevel(MassTransit.Logging.LogLevel level) { if (level == MassTransit.Logging.LogLevel.Fatal) return NLog.LogLevel.Fatal; if (level == MassTransit.Logging.LogLevel.Error) return NLog.LogLevel.Error; if (level == MassTransit.Logging.LogLevel.Warn) return NLog.LogLevel.Warn; if (level == MassTransit.Logging.LogLevel.Info) return NLog.LogLevel.Info; if (level == MassTransit.Logging.LogLevel.Debug) return NLog.LogLevel.Debug; if (level == MassTransit.Logging.LogLevel.All) return NLog.LogLevel.Trace; return NLog.LogLevel.Off; } LogMessageGenerator ToGenerator(LogOutputProvider provider) { return () => { object obj = provider(); return obj == null ? "" : obj.ToString(); }; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.Diagnostics.Contracts; namespace System.Windows { // Summary: // Implements a structure that is used to describe the System.Windows.Size of // an object. // [Serializable] // [ValueSerializer(typeof(SizeValueSerializer))] // [TypeConverter(typeof(SizeConverter))] public struct Size // : IFormattable { // // Summary: // Initializes a new instance of the System.Windows.Size structure and assigns // it an initial width and height. // // Parameters: // width: // The initial width of the instance of System.Windows.Size. // // height: // The initial height of the instance of System.Windows.Size. public Size(double width, double height) { Contract.Requires((width >= 0.0) || double.IsNaN(width) || double.IsPositiveInfinity(width)); Contract.Requires((height >= 0.0) || double.IsNaN(height) || double.IsPositiveInfinity(height)); Contract.Ensures(Contract.ValueAtReturn(out this).Width == width); Contract.Ensures(Contract.ValueAtReturn(out this).Height == height); } // Summary: // Compares two instances of System.Windows.Size for inequality. // // Parameters: // size1: // The first instance of System.Windows.Size to compare. // // size2: // The second instance of System.Windows.Size to compare. // // Returns: // true if the instances of System.Windows.Size are not equal; otherwise false. public static bool operator !=(Size size1, Size size2) { Contract.Ensures(Contract.Result<bool>() == ((size1.Width != size2.Width) || (size1.Height != size2.Height))); return default(bool); } // // Summary: // Compares two instances of System.Windows.Size for equality. // // Parameters: // size1: // The first instance of System.Windows.Size to compare. // // size2: // The second instance of System.Windows.Size to compare. // // Returns: // true if the two instances of System.Windows.Size are equal; otherwise false. public static bool operator ==(Size size1, Size size2) { Contract.Ensures(Contract.Result<bool>() == ((size1.Width == size2.Width) && (size1.Height == size2.Height))); return default(bool); } // // Summary: // Explicitly converts an instance of System.Windows.Size to an instance of // System.Windows.Point. // // Parameters: // size: // The System.Windows.Size value to be converted. // // Returns: // A System.Windows.Point equal in value to this instance of System.Windows.Size. //public static explicit operator Point(Size size); // // Summary: // Explicitly converts an instance of System.Windows.Size to an instance of // System.Windows.Vector. // // Parameters: // size: // The System.Windows.Size value to be converted. // // Returns: // A System.Windows.Vector equal in value to this instance of System.Windows.Size. //public static explicit operator Vector(Size size); // Summary: // Gets a value that represents a static empty System.Windows.Size. // // Returns: // An empty instance of System.Windows.Size. public static Size Empty { get { Contract.Ensures(Contract.Result<Size>().Width == Double.NegativeInfinity); Contract.Ensures(Contract.Result<Size>().Height == Double.NegativeInfinity); return default(Size); } } // // Summary: // Gets or sets the System.Windows.Size.Height of this instance of System.Windows.Size. // // Returns: // The System.Windows.Size.Height of this instance of System.Windows.Size. The // default is 0. The value cannot be negative. public double Height { get { Contract.Ensures(this.IsEmpty || Contract.Result<double>() >= 0.0 || Double.IsNaN(Contract.Result<double>())); return default(double); } set { // Contract.Requires(!this.IsEmpty); => see comment in Rect Contract.Requires(value >= 0.0 || Double.IsNaN(value)); Contract.Ensures(this.Height == value || Double.IsNaN(value)); } } // // Summary: // Gets a value that indicates whether this instance of System.Windows.Size // is System.Windows.Size.Empty. // // Returns: // true if this instance of size is System.Windows.Size.Empty; otherwise false. public bool IsEmpty { get { Contract.Ensures(Contract.Result<bool>() == this.Width < 0.0); return default(bool); } } // // Summary: // Gets or sets the System.Windows.Size.Width of this instance of System.Windows.Size. // // Returns: // The System.Windows.Size.Width of this instance of System.Windows.Size. The // default value is 0. The value cannot be negative. public double Width { get { Contract.Ensures(this.IsEmpty || Contract.Result<double>() >= 0.0 || Double.IsNaN(Contract.Result<double>())); return default(double); } set { // Contract.Requires(!this.IsEmpty); => see comment in Rect Contract.Requires(value >= 0.0 || Double.IsNaN(value)); Contract.Ensures(this.Width == value || Double.IsNaN(value)); } } // Summary: // Compares an object to an instance of System.Windows.Size for equality. // // Parameters: // o: // The System.Object to compare. // // Returns: // true if the sizes are equal; otherwise, false. //public override bool Equals(object o); // // Summary: // Compares a value to an instance of System.Windows.Size for equality. // // Parameters: // value: // The size to compare to this current instance of System.Windows.Size. // // Returns: // true if the instances of System.Windows.Size are equal; otherwise, false. //public bool Equals(Size value); // // Summary: // Compares two instances of System.Windows.Size for equality. // // Parameters: // size1: // The first instance of System.Windows.Size to compare. // // size2: // The second instance of System.Windows.Size to compare. // // Returns: // true if the instances of System.Windows.Size are equal; otherwise, false. //public static bool Equals(Size size1, Size size2); // // Summary: // Gets the hash code for this instance of System.Windows.Size. // // Returns: // The hash code for this instance of System.Windows.Size. //public override int GetHashCode(); // // Summary: // Returns an instance of System.Windows.Size from a converted System.String. // // Parameters: // source: // A System.String value to parse to a System.Windows.Size value. // // Returns: // An instance of System.Windows.Size. //public static Size Parse(string source); // // Summary: // Returns a System.String that represents this System.Windows.Size object. // // Returns: // A System.String that represents this instance of System.Windows.Size. //public override string ToString(); // // Summary: // Returns a System.String that represents this instance of System.Windows.Size. // // Parameters: // provider: // An object that provides a way to control formatting. // // Returns: // A System.String that represents this System.Windows.Size object. //public string ToString(IFormatProvider provider); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Search; using Microsoft.Azure.Search.Models; namespace Microsoft.Azure.Search { /// <summary> /// Client that can be used to manage and query indexes and documents on an /// Azure Search service. (see /// https://msdn.microsoft.com/library/azure/dn798935.aspx for more /// information) /// </summary> public static partial class DataSourceOperationsExtensions { /// <summary> /// Creates a new Azure Search datasource. (see /// https://msdn.microsoft.com/library/azure/dn946876.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSource'> /// Required. The definition of the datasource to create. /// </param> /// <returns> /// Response from a Create, Update, or Get DataSource request. If /// successful, it includes the full definition of the datasource that /// was created, updated, or retrieved. /// </returns> public static DataSourceDefinitionResponse Create(this IDataSourceOperations operations, DataSource dataSource) { return Task.Factory.StartNew((object s) => { return ((IDataSourceOperations)s).CreateAsync(dataSource); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search datasource. (see /// https://msdn.microsoft.com/library/azure/dn946876.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSource'> /// Required. The definition of the datasource to create. /// </param> /// <returns> /// Response from a Create, Update, or Get DataSource request. If /// successful, it includes the full definition of the datasource that /// was created, updated, or retrieved. /// </returns> public static Task<DataSourceDefinitionResponse> CreateAsync(this IDataSourceOperations operations, DataSource dataSource) { return operations.CreateAsync(dataSource, CancellationToken.None); } /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it /// already exists. (see /// https://msdn.microsoft.com/library/azure/dn946900.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSource'> /// Required. The definition of the datasource to create or update. /// </param> /// <returns> /// Response from a Create, Update, or Get DataSource request. If /// successful, it includes the full definition of the datasource that /// was created, updated, or retrieved. /// </returns> public static DataSourceDefinitionResponse CreateOrUpdate(this IDataSourceOperations operations, DataSource dataSource) { return Task.Factory.StartNew((object s) => { return ((IDataSourceOperations)s).CreateOrUpdateAsync(dataSource); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it /// already exists. (see /// https://msdn.microsoft.com/library/azure/dn946900.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSource'> /// Required. The definition of the datasource to create or update. /// </param> /// <returns> /// Response from a Create, Update, or Get DataSource request. If /// successful, it includes the full definition of the datasource that /// was created, updated, or retrieved. /// </returns> public static Task<DataSourceDefinitionResponse> CreateOrUpdateAsync(this IDataSourceOperations operations, DataSource dataSource) { return operations.CreateOrUpdateAsync(dataSource, CancellationToken.None); } /// <summary> /// Deletes an Azure Search datasource. (see /// https://msdn.microsoft.com/library/azure/dn946881.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSourceName'> /// Required. The name of the datasource to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IDataSourceOperations operations, string dataSourceName) { return Task.Factory.StartNew((object s) => { return ((IDataSourceOperations)s).DeleteAsync(dataSourceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search datasource. (see /// https://msdn.microsoft.com/library/azure/dn946881.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSourceName'> /// Required. The name of the datasource to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IDataSourceOperations operations, string dataSourceName) { return operations.DeleteAsync(dataSourceName, CancellationToken.None); } /// <summary> /// Retrieves a datasource definition from Azure Search. (see /// https://msdn.microsoft.com/library/azure/dn946893.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSourceName'> /// Required. The name of the datasource to retrieve. /// </param> /// <returns> /// Response from a Create, Update, or Get DataSource request. If /// successful, it includes the full definition of the datasource that /// was created, updated, or retrieved. /// </returns> public static DataSourceDefinitionResponse Get(this IDataSourceOperations operations, string dataSourceName) { return Task.Factory.StartNew((object s) => { return ((IDataSourceOperations)s).GetAsync(dataSourceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves a datasource definition from Azure Search. (see /// https://msdn.microsoft.com/library/azure/dn946893.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <param name='dataSourceName'> /// Required. The name of the datasource to retrieve. /// </param> /// <returns> /// Response from a Create, Update, or Get DataSource request. If /// successful, it includes the full definition of the datasource that /// was created, updated, or retrieved. /// </returns> public static Task<DataSourceDefinitionResponse> GetAsync(this IDataSourceOperations operations, string dataSourceName) { return operations.GetAsync(dataSourceName, CancellationToken.None); } /// <summary> /// Lists all datasources available for an Azure Search service. (see /// https://msdn.microsoft.com/library/azure/dn946878.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <returns> /// Response from a List Datasources request. If successful, it /// includes the full definitions of all datasources. /// </returns> public static DataSourceListResponse List(this IDataSourceOperations operations) { return Task.Factory.StartNew((object s) => { return ((IDataSourceOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all datasources available for an Azure Search service. (see /// https://msdn.microsoft.com/library/azure/dn946878.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDataSourceOperations. /// </param> /// <returns> /// Response from a List Datasources request. If successful, it /// includes the full definitions of all datasources. /// </returns> public static Task<DataSourceListResponse> ListAsync(this IDataSourceOperations operations) { return operations.ListAsync(CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Net; using System.Reflection; using NSubstitute; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using SineSignal.Ottoman.Specs.Framework; using SineSignal.Ottoman.Commands; using SineSignal.Ottoman.Exceptions; using SineSignal.Ottoman.Http; namespace SineSignal.Ottoman.Specs { public class CouchDocumentSessionSpecs { public class When_storing_a_new_entity_into_the_session : ConcernFor<CouchDocumentSession> { private Employee entity1; private Type entity1Type; private PropertyInfo identityProperty; private Type identityType; private Guid id; private ICouchDocumentConvention documentConvention; private ICouchDatabase couchDatabase; protected override void Given() { entity1 = new Employee { Name = "Bob", Login = "boblogin" }; entity1Type = entity1.GetType(); identityProperty = entity1Type.GetProperty("Id"); identityType = identityProperty.PropertyType; id = Guid.NewGuid(); documentConvention = Fake<ICouchDocumentConvention>(); documentConvention.GetIdentityPropertyFor(entity1Type).Returns(identityProperty); documentConvention.GenerateIdentityFor(identityType).Returns(id); couchDatabase = Fake<ICouchDatabase>(); couchDatabase.CouchDocumentConvention.Returns(documentConvention); } public override CouchDocumentSession CreateSystemUnderTest() { return new CouchDocumentSession(couchDatabase); } protected override void When() { Sut.Store(entity1); } [Test] public void Should_call_get_identity_property() { documentConvention.Received().GetIdentityPropertyFor(entity1Type); } [Test] public void Should_call_generate_document_id() { documentConvention.Received().GenerateIdentityFor(identityType); } [Test] public void Should_generate_id_for_entity() { Assert.That(entity1.Id, Is.EqualTo(id)); } [Test] public void Should_add_entity_to_identity_map() { Employee entity = Sut.Load<Employee>(id.ToString()); Assert.That(entity, Is.EqualTo(entity1)); } } public class When_storing_an_entity_with_an_id_already_assigned : ConcernFor<CouchDocumentSession> { private Guid id; private Employee entity1; private Type entity1Type; private PropertyInfo identityProperty; private ICouchDocumentConvention documentConvention; private ICouchDatabase couchDatabase; protected override void Given() { id = Guid.NewGuid(); entity1 = new Employee { Id = id, Name = "Bob", Login = "boblogin" }; entity1Type = entity1.GetType(); identityProperty = entity1Type.GetProperty("Id"); documentConvention = Fake<ICouchDocumentConvention>(); documentConvention.GetIdentityPropertyFor(entity1Type).Returns(identityProperty); couchDatabase = Fake<ICouchDatabase>(); couchDatabase.CouchDocumentConvention.Returns(documentConvention); } public override CouchDocumentSession CreateSystemUnderTest() { return new CouchDocumentSession(couchDatabase); } protected override void When() { Sut.Store(entity1); } [Test] public void Should_call_get_identity_property() { documentConvention.Received().GetIdentityPropertyFor(entity1Type); } [Test] public void Should_not_call_generate_document_id() { documentConvention.DidNotReceive().GenerateIdentityFor(identityProperty.PropertyType); } [Test] public void Should_not_modify_the_id() { Assert.That(id, Is.EqualTo(entity1.Id)); } [Test] public void Should_add_entity_to_identity_map() { Employee entity = Sut.Load<Employee>(id.ToString()); Assert.That(entity, Is.EqualTo(entity1)); } } public class When_attempting_to_store_a_different_entity_with_the_same_id_as_another : ConcernFor<CouchDocumentSession> { private Guid id; private Employee entity1; private Employee entity2; private Type entity2Type; private PropertyInfo identityProperty; private NonUniqueEntityException thrownException; private ICouchDocumentConvention documentConvention; private ICouchDatabase couchDatabase; protected override void Given() { id = Guid.NewGuid(); entity1 = new Employee { Id = id, Name = "Bob", Login = "boblogin" }; entity2 = new Employee { Id = id, Name = "Carl", Login = "carllogin" }; entity2Type = entity2.GetType(); identityProperty = entity2Type.GetProperty("Id"); documentConvention = Fake<ICouchDocumentConvention>(); documentConvention.GetIdentityPropertyFor(entity2Type).Returns(identityProperty); couchDatabase = Fake<ICouchDatabase>(); couchDatabase.CouchDocumentConvention.Returns(documentConvention); } public override CouchDocumentSession CreateSystemUnderTest() { var couchDocumentSession = new CouchDocumentSession(couchDatabase); couchDocumentSession.Store(entity1); return couchDocumentSession; } protected override void When() { try { Sut.Store(entity2); } catch (NonUniqueEntityException ex) { thrownException = ex; } } [Test] public void Should_throw_non_unique_entity_exception() { Assert.That(thrownException, Is.Not.Null); Assert.That(thrownException.Message, Is.EqualTo("Attempted to associate a different entity with id '" + id + "'.")); } } public class When_saving_changes_after_storing_a_new_entity : ConcernFor<CouchDocumentSession> { private Employee entity1; private Type entity1Type; private PropertyInfo identityProperty; private Type identityType; private Guid id; private ICouchDocumentConvention documentConvention; private BulkDocsResult[] bulkDocsResults; private ICouchProxy couchProxy; private ICouchDatabase couchDatabase; protected override void Given() { entity1 = new Employee { Name = "Bob", Login = "boblogin" }; entity1Type = entity1.GetType(); identityProperty = entity1Type.GetProperty("Id"); identityType = identityProperty.PropertyType; id = Guid.NewGuid(); documentConvention = Fake<ICouchDocumentConvention>(); documentConvention.GetIdentityPropertyFor(entity1Type).Returns(identityProperty); documentConvention.GenerateIdentityFor(identityType).Returns(id); bulkDocsResults = new BulkDocsResult[1]; bulkDocsResults[0] = new BulkDocsResult { Id = id.ToString(), Rev = "123456" }; couchProxy = Fake<ICouchProxy>(); couchProxy.Execute<BulkDocsResult[]>(Arg.Any<BulkDocsCommand>()).Returns(bulkDocsResults); couchDatabase = Fake<ICouchDatabase>(); couchDatabase.CouchDocumentConvention.Returns(documentConvention); couchDatabase.Name.Returns("ottoman-test-database"); couchDatabase.CouchProxy.Returns(couchProxy); } public override CouchDocumentSession CreateSystemUnderTest() { return new CouchDocumentSession(couchDatabase); } protected override void When() { Sut.Store(entity1); Sut.SaveChanges(); } [Test] public void Should_call_get_identity_property() { documentConvention.Received().GetIdentityPropertyFor(entity1Type); } [Test] public void Should_execute_bulk_docs_command_with_couch_proxy() { couchProxy.Received().Execute<BulkDocsResult[]>(Arg.Is<BulkDocsCommand>(c => { var message = (BulkDocsMessage)c.Message; return c.Route == couchDatabase.Name + "/_bulk_docs" && c.Operation == HttpMethod.Post && (message.NonAtomic == false && message.AllOrNothing == false && message.Docs.Length == 1); })); } } public class When_loading_a_simple_entity : ConcernFor<CouchDocumentSession> { private Guid documentId; private Employee entity1; private Type entity1Type; private PropertyInfo identityProperty; private ICouchDocumentConvention documentConvention; private ICouchProxy couchProxy; private ICouchDatabase couchDatabase; protected override void Given() { documentId = Guid.NewGuid(); entity1Type = typeof(Employee); identityProperty = entity1Type.GetProperty("Id"); documentConvention = Fake<ICouchDocumentConvention>(); documentConvention.GetIdentityPropertyFor(entity1Type).Returns(identityProperty); var couchDocument = new CouchDocument(); couchDocument.Add("_id", documentId.ToString()); couchDocument.Add("_rev", "123456"); couchDocument.Add("Type", entity1Type.Name); couchDocument.Add("Name", "Bob"); couchDocument.Add("Login", "boblogin"); couchProxy = Fake<ICouchProxy>(); couchProxy.Execute<CouchDocument>(Arg.Any<GetDocumentCommand>()).Returns(couchDocument); couchDatabase = Fake<ICouchDatabase>(); couchDatabase.Name.Returns("ottoman-test-database"); couchDatabase.CouchProxy.Returns(couchProxy); couchDatabase.CouchDocumentConvention.Returns(documentConvention); } public override CouchDocumentSession CreateSystemUnderTest() { return new CouchDocumentSession(couchDatabase); } protected override void When() { entity1 = Sut.Load<Employee>(documentId.ToString()); } [Test] public void Should_execute_get_document_command_with_couch_proxy() { couchProxy.Received().Execute<CouchDocument>(Arg.Is<GetDocumentCommand>(c => { return c.Route == couchDatabase.Name + "/" + documentId.ToString() && c.Operation == HttpMethod.Get && c.Message == null && c.SuccessStatusCode == HttpStatusCode.OK; })); } [Test] public void Should_call_get_identity_property() { documentConvention.Received().GetIdentityPropertyFor(entity1Type); } [Test] public void Should_return_populated_entity() { Assert.That(entity1.Id, Is.EqualTo(documentId)); Assert.That(entity1.Name, Is.EqualTo("Bob")); Assert.That(entity1.Login, Is.EqualTo("boblogin")); } } public class When_deleting_an_entity : ConcernFor<CouchDocumentSession> { private Guid documentId; private Employee entity1; private Type entity1Type; private PropertyInfo identityProperty; private BulkDocsResult[] bulkDocsResults; private ICouchDocumentConvention documentConvention; private ICouchProxy couchProxy; private ICouchDatabase couchDatabase; protected override void Given() { documentId = Guid.NewGuid(); entity1Type = typeof(Employee); identityProperty = entity1Type.GetProperty("Id"); documentConvention = Fake<ICouchDocumentConvention>(); documentConvention.GetIdentityPropertyFor(entity1Type).Returns(identityProperty); var couchDocument = new CouchDocument(); couchDocument.Add("_id", documentId.ToString()); couchDocument.Add("_rev", "123456"); couchDocument.Add("Type", entity1Type.Name); couchDocument.Add("Name", "Bob"); couchDocument.Add("Login", "boblogin"); bulkDocsResults = new BulkDocsResult[1]; bulkDocsResults[0] = new BulkDocsResult { Id = documentId.ToString(), Rev = "123456" }; couchProxy = Fake<ICouchProxy>(); couchProxy.Execute<CouchDocument>(Arg.Any<GetDocumentCommand>()).Returns(couchDocument); couchProxy.Execute<BulkDocsResult[]>(Arg.Any<BulkDocsCommand>()).Returns(bulkDocsResults); couchDatabase = Fake<ICouchDatabase>(); couchDatabase.Name.Returns("ottoman-test-database"); couchDatabase.CouchProxy.Returns(couchProxy); couchDatabase.CouchDocumentConvention.Returns(documentConvention); } public override CouchDocumentSession CreateSystemUnderTest() { return new CouchDocumentSession(couchDatabase); } protected override void When() { entity1 = Sut.Load<Employee>(documentId.ToString()); Sut.Delete<Employee>(entity1); Sut.SaveChanges(); } [Test] public void Should_call_get_identity_property() { documentConvention.Received().GetIdentityPropertyFor(entity1Type); } [Test] public void Should_execute_bulk_docs_command_with_couch_proxy() { couchProxy.Received().Execute<BulkDocsResult[]>(Arg.Is<BulkDocsCommand>(c => { var message = (BulkDocsMessage)c.Message; return c.Route == couchDatabase.Name + "/_bulk_docs" && c.Operation == HttpMethod.Post && (message.NonAtomic == false && message.AllOrNothing == false && message.Docs.Length == 1); })); } } } public class Employee { public Guid Id { get; set; } public string Name { get; set; } public string Login { get; set; } public override bool Equals (object obj) { if (obj == null) return false; Employee employee = obj as Employee; if (employee == null) return false; return (this.Id == employee.Id) && (this.Name == employee.Name) && (this.Login == employee.Login); } public override int GetHashCode () { return Id.GetHashCode() ^ Name.GetHashCode() ^ Login.GetHashCode(); } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using Box2D.Collision; using Box2D.Collision.Shapes; using Box2D.Common; using Box2D.Dynamics; using Box2D.Dynamics.Contacts; using Box2D.Dynamics.Joints; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using CocosSharp; using Random = System.Random; namespace Box2D.TestBed { public static class Rand { public static Random Random = new Random(0x2eed2eed); public static void Randomize(int seed) { Random = new Random(seed); } /// <summary> /// Random number in range [-1,1] /// </summary> /// <returns></returns> public static float RandomFloat() { return (float)(Random.NextDouble() * 2.0 - 1.0); } /// <summary> /// Random floating point number in range [lo, hi] /// </summary> /// <param name="lo">The lo.</param> /// <param name="hi">The hi.</param> /// <returns></returns> public static float RandomFloat(float lo, float hi) { float r = (float)Random.NextDouble(); r = (hi - lo) * r + lo; return r; } } public struct TestEntry { public Func<Test> CreateFcn; public string Name; } public class DestructionListener : b2DestructionListener { public override void SayGoodbye(b2Fixture fixture) { } public override void SayGoodbye(b2Joint joint) { if (test.m_mouseJoint == joint) { test.m_mouseJoint = null; } else { test.JointDestroyed(joint); } } public Test test; }; public class Settings { public b2Vec2 viewCenter = new b2Vec2(0.0f, 20.0f); public float hz = 60.0f; public int velocityIterations = 8; public int positionIterations = 3; public bool drawShapes = true; public bool drawJoints = true; public bool drawAABBs = false; public bool drawPairs = false; public bool drawContactPoints = false; public int drawContactNormals = 0; public int drawContactForces = 0; public int drawFrictionForces = 0; public bool drawCOMs = false; public bool drawStats = true; public bool drawProfile = true; public int enableWarmStarting = 1; public int enableContinuous = 1; public int enableSubStepping = 0; public bool pause = false; public bool singleStep = false; } public class ContactPoint { public b2Fixture fixtureA; public b2Fixture fixtureB; public b2Vec2 normal; public b2Vec2 position; public b2PointState state; }; public class QueryCallback : b2QueryCallback { public QueryCallback(b2Vec2 point) { m_point = point; m_fixture = null; } public override bool ReportFixture(b2Fixture fixture) { b2Body body = fixture.Body; if (body.BodyType == b2BodyType.b2_dynamicBody) { bool inside = fixture.TestPoint(m_point); if (inside) { m_fixture = fixture; // We are done, terminate the query. return false; } } // Continue the query. return true; } public b2Vec2 m_point; public b2Fixture m_fixture; } public class Test : b2ContactListener { public const int k_maxContactPoints = 2048; public b2Body m_groundBody; public b2AABB m_worldAABB; public ContactPoint[] m_points = new ContactPoint[k_maxContactPoints]; public int m_pointCount; public DestructionListener m_destructionListener; public CCBox2dDraw m_debugDraw; public int m_textLine; public b2World m_world; public b2Body m_bomb; public b2MouseJoint m_mouseJoint; public b2Vec2 m_bombSpawnPoint; public bool m_bombSpawning; public b2Vec2 m_mouseWorld; public int m_stepCount; #if PROFILING public b2Profile m_maxProfile; public b2Profile m_totalProfile; #endif public Test() { m_destructionListener = new DestructionListener(); m_debugDraw = new CCBox2dDraw("fonts/arial-12"); b2Vec2 gravity = new b2Vec2(); gravity.Set(0.0f, -10.0f); m_world = new b2World(gravity); m_bomb = null; m_textLine = 30; m_mouseJoint = null; m_pointCount = 0; m_destructionListener.test = this; m_world.SetDestructionListener(m_destructionListener); m_world.SetContactListener(this); m_world.SetDebugDraw(m_debugDraw); m_world.SetContinuousPhysics(true); m_world.SetWarmStarting(true); m_bombSpawning = false; m_stepCount = 0; b2BodyDef bodyDef = new b2BodyDef(); m_groundBody = m_world.CreateBody(bodyDef); } public virtual void JointDestroyed(b2Joint joint) { } public void DrawTitle(int x, int y, string title) { m_debugDraw.DrawString(x, y, title); } public virtual bool MouseDown(b2Vec2 p) { m_mouseWorld = p; if (m_mouseJoint != null) { return false; } // Make a small box. b2AABB aabb = new b2AABB(); b2Vec2 d = new b2Vec2(); d.Set(0.001f, 0.001f); aabb.LowerBound = p - d; aabb.UpperBound = p + d; // Query the world for overlapping shapes. QueryCallback callback = new QueryCallback(p); m_world.QueryAABB(callback, aabb); if (callback.m_fixture != null) { b2Body body = callback.m_fixture.Body; b2MouseJointDef md = new b2MouseJointDef(); md.BodyA = m_groundBody; md.BodyB = body; md.target = p; md.maxForce = 1000.0f * body.Mass; m_mouseJoint = (b2MouseJoint) m_world.CreateJoint(md); body.SetAwake(true); return true; } return false; } public void SpawnBomb(b2Vec2 worldPt) { m_bombSpawnPoint = worldPt; m_bombSpawning = true; } public void CompleteBombSpawn(b2Vec2 p) { if (m_bombSpawning == false) { return; } const float multiplier = 30.0f; b2Vec2 vel = m_bombSpawnPoint - p; vel *= multiplier; LaunchBomb(m_bombSpawnPoint, vel); m_bombSpawning = false; } public void ShiftMouseDown(b2Vec2 p) { m_mouseWorld = p; if (m_mouseJoint != null) { return; } SpawnBomb(p); } public virtual void MouseUp(b2Vec2 p) { if (m_mouseJoint != null) { m_world.DestroyJoint(m_mouseJoint); m_mouseJoint = null; } if (m_bombSpawning) { CompleteBombSpawn(p); } } public void MouseMove(b2Vec2 p) { m_mouseWorld = p; if (m_mouseJoint != null) { m_mouseJoint.SetTarget(p); } } public void LaunchBomb() { b2Vec2 p = new b2Vec2(Rand.RandomFloat(-15.0f, 15.0f), 30.0f); b2Vec2 v = -5.0f * p; LaunchBomb(p, v); } public void LaunchBomb(b2Vec2 position, b2Vec2 velocity) { if (m_bomb != null) { m_world.DestroyBody(m_bomb); m_bomb = null; } b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position = position; bd.bullet = true; m_bomb = m_world.CreateBody(bd); m_bomb.LinearVelocity = velocity; b2CircleShape circle = new b2CircleShape(); circle.Radius = 0.3f; b2FixtureDef fd = new b2FixtureDef(); fd.shape = circle; fd.density = 20.0f; fd.restitution = 0.0f; b2Vec2 minV = position - new b2Vec2(0.3f, 0.3f); b2Vec2 maxV = position + new b2Vec2(0.3f, 0.3f); b2AABB aabb = new b2AABB(); aabb.LowerBound = minV; aabb.UpperBound = maxV; m_bomb.CreateFixture(fd); } public void InternalDraw(Settings settings) { m_textLine = 30; m_debugDraw.Begin(); Draw(settings); m_debugDraw.End(); } protected virtual void Draw(Settings settings) { m_world.DrawDebugData(); if (settings.drawStats) { int bodyCount = m_world.BodyCount; int contactCount = m_world.ContactCount; int jointCount = m_world.JointCount; m_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = {0}/{1}/{2}", bodyCount, contactCount, jointCount); m_textLine += 15; int proxyCount = m_world.GetProxyCount(); int height = m_world.GetTreeHeight(); int balance = m_world.GetTreeBalance(); float quality = m_world.GetTreeQuality(); m_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = {0}/{1}/{2}/{3}", proxyCount, height, balance, quality); m_textLine += 15; } #if PROFILING // Track maximum profile times { b2Profile p = m_world.Profile; m_maxProfile.step = Math.Max(m_maxProfile.step, p.step); m_maxProfile.collide = Math.Max(m_maxProfile.collide, p.collide); m_maxProfile.solve = Math.Max(m_maxProfile.solve, p.solve); m_maxProfile.solveInit = Math.Max(m_maxProfile.solveInit, p.solveInit); m_maxProfile.solveVelocity = Math.Max(m_maxProfile.solveVelocity, p.solveVelocity); m_maxProfile.solvePosition = Math.Max(m_maxProfile.solvePosition, p.solvePosition); m_maxProfile.solveTOI = Math.Max(m_maxProfile.solveTOI, p.solveTOI); m_maxProfile.broadphase = Math.Max(m_maxProfile.broadphase, p.broadphase); m_totalProfile.step += p.step; m_totalProfile.collide += p.collide; m_totalProfile.solve += p.solve; m_totalProfile.solveInit += p.solveInit; m_totalProfile.solveVelocity += p.solveVelocity; m_totalProfile.solvePosition += p.solvePosition; m_totalProfile.solveTOI += p.solveTOI; m_totalProfile.broadphase += p.broadphase; } if (settings.drawProfile) { b2Profile p = m_world.Profile; b2Profile aveProfile = new b2Profile(); if (m_stepCount > 0) { float scale = 1.0f / m_stepCount; aveProfile.step = scale * m_totalProfile.step; aveProfile.collide = scale * m_totalProfile.collide; aveProfile.solve = scale * m_totalProfile.solve; aveProfile.solveInit = scale * m_totalProfile.solveInit; aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; aveProfile.solvePosition = scale * m_totalProfile.solvePosition; aveProfile.solveTOI = scale * m_totalProfile.solveTOI; aveProfile.broadphase = scale * m_totalProfile.broadphase; } m_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.step, aveProfile.step, m_maxProfile.step); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.collide, aveProfile.collide, m_maxProfile.collide); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solve, aveProfile.solve, m_maxProfile.solve); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = {0:00000.00} [{1:000000.00}] ({2:000000.00})", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase); m_textLine += 15; } #endif if (m_mouseJoint != null) { b2Vec2 p1 = m_mouseJoint.GetAnchorB(); b2Vec2 p2 = m_mouseJoint.GetTarget(); b2Color c = new b2Color(); c.Set(0.0f, 1.0f, 0.0f); m_debugDraw.DrawPoint(p1, 4.0f, c); m_debugDraw.DrawPoint(p2, 4.0f, c); c.Set(0.8f, 0.8f, 0.8f); m_debugDraw.DrawSegment(p1, p2, c); } if (m_bombSpawning) { b2Color c = new b2Color(); c.Set(0.0f, 0.0f, 1.0f); m_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); c.Set(0.8f, 0.8f, 0.8f); m_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); } if (settings.drawContactPoints) { //const float32 k_impulseScale = 0.1f; float k_axisScale = 0.3f; for (int i = 0; i < m_pointCount; ++i) { ContactPoint point = m_points[i]; if (point.state == b2PointState.b2_addState) { // Add m_debugDraw.DrawPoint(point.position, 10.0f, new b2Color(0.3f, 0.95f, 0.3f)); } else if (point.state == b2PointState.b2_persistState) { // Persist m_debugDraw.DrawPoint(point.position, 5.0f, new b2Color(0.3f, 0.3f, 0.95f)); } if (settings.drawContactNormals == 1) { b2Vec2 p1 = point.position; b2Vec2 p2 = p1 + k_axisScale * point.normal; m_debugDraw.DrawSegment(p1, p2, new b2Color(0.9f, 0.9f, 0.9f)); } else if (settings.drawContactForces == 1) { //b2Vec2 p1 = point->position; //b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal; //DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); } if (settings.drawFrictionForces == 1) { //b2Vec2 tangent = b2Cross(point->normal, 1.0f); //b2Vec2 p1 = point->position; //b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent; //DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); } } } } public virtual void Step(Settings settings) { float timeStep = settings.hz > 0.0f ? 1.0f / settings.hz : 0.0f; if (settings.pause) { if (settings.singleStep) { settings.singleStep = false; } else { timeStep = 0.0f; } m_debugDraw.DrawString(5, m_textLine, "****PAUSED****"); m_textLine += 15; } b2DrawFlags flags = 0; if (settings.drawShapes) flags |= b2DrawFlags.e_shapeBit; if (settings.drawJoints) flags |= b2DrawFlags.e_jointBit; if (settings.drawAABBs) flags |= b2DrawFlags.e_aabbBit; if (settings.drawPairs) flags |= b2DrawFlags.e_pairBit; if (settings.drawCOMs) flags |= b2DrawFlags.e_centerOfMassBit; m_debugDraw.SetFlags(flags); m_world.SetWarmStarting(settings.enableWarmStarting > 0); m_world.SetContinuousPhysics(settings.enableContinuous > 0); m_world.SetSubStepping(settings.enableSubStepping > 0); m_pointCount = 0; m_world.Step(timeStep, settings.velocityIterations, settings.positionIterations); if (timeStep > 0.0f) { ++m_stepCount; } } public virtual void Keyboard(char key) { } public virtual void KeyboardUp(char key) { } b2PointState[] state1 = new b2PointState[b2Settings.b2_maxManifoldPoints]; b2PointState[] state2 = new b2PointState[b2Settings.b2_maxManifoldPoints]; b2WorldManifold worldManifold = new b2WorldManifold(); public override void PreSolve(b2Contact contact, b2Manifold oldManifold) { b2Manifold manifold = contact.GetManifold(); if (manifold.pointCount == 0) { return; } b2Fixture fixtureA = contact.GetFixtureA(); b2Fixture fixtureB = contact.GetFixtureB(); b2Collision.b2GetPointStates(state1, state2, oldManifold, manifold); contact.GetWorldManifold(ref worldManifold); for (int i = 0; i < manifold.pointCount && m_pointCount < k_maxContactPoints; ++i) { ContactPoint cp = m_points[m_pointCount]; if (cp == null) { cp = new ContactPoint(); m_points[m_pointCount] = cp; } cp.fixtureA = fixtureA; cp.fixtureB = fixtureB; cp.position = worldManifold.points[i]; cp.normal = worldManifold.normal; cp.state = state2[i]; ++m_pointCount; } } public override void PostSolve(b2Contact contact, ref b2ContactImpulse impulse) { } public override void BeginContact(b2Contact contact) {} public override void EndContact(b2Contact contact) {} } }
using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using NDesk.Options; using GitTfs.Core; using StructureMap; using GitTfs.Util; using GitTfs.Core.TfsInterop; namespace GitTfs.Commands { [Pluggable("clone")] [Description("clone [options] tfs-url-or-instance-name repository-path <git-repository-path>\n ex : git tfs clone http://myTfsServer:8080/tfs/TfsRepository $/ProjectName/ProjectBranch\n")] public class Clone : GitTfsCommand { private readonly Fetch _fetch; private readonly Init _init; private readonly Globals _globals; private readonly InitBranch _initBranch; private bool _resumable; public Clone(Globals globals, Fetch fetch, Init init, InitBranch initBranch) { _fetch = fetch; _init = init; _globals = globals; _initBranch = initBranch; globals.GcCountdown = globals.GcPeriod; } public OptionSet OptionSet { get { return _init.OptionSet.Merge(_fetch.OptionSet) .Add("resumable", "if an error occurred, try to continue when you restart clone with same parameters", v => _resumable = v != null); } } public int Run(string tfsUrl, string tfsRepositoryPath) { return Run(tfsUrl, tfsRepositoryPath, Path.GetFileName(tfsRepositoryPath)); } public int Run(string tfsUrl, string tfsRepositoryPath, string gitRepositoryPath) { var currentDir = Environment.CurrentDirectory; var repositoryDirCreated = InitGitDir(gitRepositoryPath); // TFS string representations of repository paths do not end in trailing slashes if (tfsRepositoryPath != GitTfsConstants.TfsRoot) tfsRepositoryPath = (tfsRepositoryPath ?? string.Empty).TrimEnd('/'); int retVal = 0; try { if (repositoryDirCreated) { retVal = _init.Run(tfsUrl, tfsRepositoryPath, gitRepositoryPath); } else { try { Environment.CurrentDirectory = gitRepositoryPath; _globals.Repository = _init.GitHelper.MakeRepository(_globals.GitDir); } catch (Exception) { retVal = _init.Run(tfsUrl, tfsRepositoryPath, gitRepositoryPath); } } VerifyTfsPathToClone(tfsRepositoryPath); } catch { if (!_resumable) { try { // if we appeared to be inside repository dir when exception was thrown - we won't be able to delete it Environment.CurrentDirectory = currentDir; if (repositoryDirCreated) Directory.Delete(gitRepositoryPath, recursive: true); else CleanDirectory(gitRepositoryPath); } catch (IOException e) { // swallow IOException. Smth went wrong before this and we're much more interested in that error string msg = string.Format("warning: Something went wrong while cleaning file after internal error (See below).\n Can't clean up files because of IOException:\n{0}\n", e.IndentExceptionMessage()); Trace.WriteLine(msg); } catch (UnauthorizedAccessException e) { // swallow it also string msg = string.Format("warning: Something went wrong while cleaning file after internal error (See below).\n Can't clean up files because of UnauthorizedAccessException:\n{0}\n", e.IndentExceptionMessage()); Trace.WriteLine(msg); } } throw; } bool errorOccurs = false; try { if (tfsRepositoryPath == GitTfsConstants.TfsRoot) _fetch.BranchStrategy = BranchStrategy.None; _globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, (_fetch.BranchStrategy == BranchStrategy.None).ToString()); if (retVal == 0) { _fetch.Run(_fetch.BranchStrategy == BranchStrategy.All); _globals.Repository.GarbageCollect(); } if (_fetch.BranchStrategy == BranchStrategy.All && _initBranch != null) { _initBranch.CloneAllBranches = true; retVal = _initBranch.Run(); } } catch (GitTfsException) { errorOccurs = true; throw; } catch (Exception ex) { errorOccurs = true; throw new GitTfsException("error: a problem occurred when trying to clone the repository. Try to solve the problem described below.\nIn any case, after, try to continue using command `git tfs " + (_fetch.BranchStrategy == BranchStrategy.All ? "branch init --all" : "fetch") + "`\n", ex); } finally { try { if (!_init.IsBare) _globals.Repository.Merge(_globals.Repository.ReadTfsRemote(_globals.RemoteId).RemoteRef); } catch (Exception) { //Swallow exception because the previously thrown exception is more important... if (!errorOccurs) throw; } } return retVal; } private void VerifyTfsPathToClone(string tfsRepositoryPath) { if (_initBranch == null) return; try { var remote = _globals.Repository.ReadTfsRemote(GitTfsConstants.DefaultRepositoryId); if (!remote.Tfs.IsExistingInTfs(tfsRepositoryPath)) throw new GitTfsException("error: the path " + tfsRepositoryPath + " you want to clone doesn't exist!") .WithRecommendation("To discover which branch to clone, you could use the command :\ngit tfs list-remote-branches " + remote.TfsUrl); if (!remote.Tfs.CanGetBranchInformation) return; var tfsTrunkRepository = remote.Tfs.GetRootTfsBranchForRemotePath(tfsRepositoryPath, false); if (tfsTrunkRepository == null) { var tfsRootBranches = remote.Tfs.GetAllTfsRootBranchesOrderedByCreation(); if (!tfsRootBranches.Any()) { Trace.TraceInformation("info: no TFS root found !\n\nPS:perhaps you should convert your trunk folder into a branch in TFS."); return; } var cloneMsg = " => If you want to manage branches with git-tfs, clone one of this branch instead :\n" + " - " + tfsRootBranches.Aggregate((s1, s2) => s1 + "\n - " + s2) + "\n\nPS:if your branch is not listed here, perhaps you should convert the containing folder to a branch in TFS."; if (_fetch.BranchStrategy == BranchStrategy.All) throw new GitTfsException("error: cloning the whole repository or too high in the repository path doesn't permit to manage branches!\n" + cloneMsg); Trace.TraceWarning("warning: you are going to clone the whole repository or too high in the repository path !\n" + cloneMsg); return; } var tfsBranchesPath = tfsTrunkRepository.GetAllChildren(); var tfsPathToClone = tfsRepositoryPath.TrimEnd('/').ToLower(); var tfsTrunkRepositoryPath = tfsTrunkRepository.Path; if (tfsPathToClone != tfsTrunkRepositoryPath.ToLower()) { if (tfsBranchesPath.Select(e => e.Path.ToLower()).Contains(tfsPathToClone)) Trace.TraceInformation("info: you are going to clone a branch instead of the trunk ( {0} )\n" + " => If you want to manage branches with git-tfs, clone {0} with '--branches=all' option instead...)", tfsTrunkRepositoryPath); else Trace.TraceWarning("warning: you are going to clone a subdirectory of a branch and won't be able to manage branches :(\n" + " => If you want to manage branches with git-tfs, clone " + tfsTrunkRepositoryPath + " with '--branches=all' option instead...)"); } } catch (GitTfsException) { throw; } catch (Exception ex) { Trace.TraceWarning("warning: a server error occurs when trying to verify the tfs path cloned:\n " + ex.Message + "\n try to continue anyway..."); } } private bool InitGitDir(string gitRepositoryPath) { bool repositoryDirCreated = false; var di = new DirectoryInfo(gitRepositoryPath); if (di.Exists) { bool isDebuggerAttached = false; #if DEBUG isDebuggerAttached = Debugger.IsAttached; #endif if (!isDebuggerAttached && !_resumable) { if (di.EnumerateFileSystemInfos().Any()) throw new GitTfsException("error: Specified git repository directory is not empty"); } } else { repositoryDirCreated = true; di.Create(); } return repositoryDirCreated; } private static void CleanDirectory(string gitRepositoryPath) { var di = new DirectoryInfo(gitRepositoryPath); foreach (var fileSystemInfo in di.EnumerateDirectories()) fileSystemInfo.Delete(true); foreach (var fileSystemInfo in di.EnumerateFiles()) fileSystemInfo.Delete(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// BasicOperations operations. /// </summary> public partial class BasicOperations : IServiceOperations<AutoRestComplexTestService>, IBasicOperations { /// <summary> /// Initializes a new instance of the BasicOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public BasicOperations(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex type {id: 2, name: 'abc', color: 'YELLOW'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is invalid for the local strong type /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type whose properties are null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type while the server doesn't provide a response /// payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* The MIT License (MIT) Copyright (c) 2015 Huw Bowles & Daniel Zimmermann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEngine; using System.Collections; [ExecuteInEditMode] public class AdvectedScales2D : MonoBehaviour { [Tooltip("Used to differentiate/sort the two advection computations")] public int radiusIndex = 0; [Tooltip("The radius of this sample slice. Advection is performed at this radius")] public float radius = 10.0f; AdvectedScalesSettings settings; public float[,] scales_norm; Vector3 lastPos; Vector3 lastForward; Vector3 lastRight; Vector3 lastUp; float motionMeasure = 0.0f; void Start() { settings = GetComponent<AdvectedScalesSettings> (); scales_norm = new float[settings.scaleCount,settings.scaleCount]; // init scales to something interesting for( int j = 0; j < settings.scaleCount; j++ ) { float phi = getPhi( j ); for( int i = 0; i < settings.scaleCount; i++ ) { float theta = getTheta( i ); float fixedZ = Mathf.Lerp( Mathf.Cos(CloudsBase.halfFov_horiz_rad), 1.0f, settings.fixedZProp ) / (Mathf.Sin(theta)*Mathf.Cos(phi)); float fixedR = (Mathf.Sin(13f*j/(float)settings.scaleCount)*Mathf.Sin(8f*i/(float)settings.scaleCount)*settings.fixedRNoise + 1f); scales_norm[i,j] = Mathf.Lerp( fixedZ, fixedR, settings.reInitCurvature ); } } lastPos = transform.position; lastForward = transform.forward; lastRight = transform.right; lastUp = transform.up; } void Update() { if( scales_norm == null || settings.scaleCount*settings.scaleCount != scales_norm.Length || settings.reInitScales ) Start(); float dt = Mathf.Max( Time.deltaTime, 0.033f ); float vel = (transform.position - lastPos).magnitude / dt; if( settings.clearOnTeleport && vel > 100.0f ) { ClearAfterTeleport(); return; } // compute motion measures // compute rotation of camera (heading only) float rotRad = Vector3.Angle( transform.forward, lastForward ) * Mathf.Sign( Vector3.Cross( lastForward, transform.forward ).y ) * Mathf.Deg2Rad; // compute motion measure float motionMeasureRot = Mathf.Clamp01(Mathf.Abs(settings.motionMeasCoeffRot * rotRad/dt)); float motionMeasureTrans = Mathf.Clamp01(Mathf.Abs(settings.motionMeasCoeffStrafe * vel)); motionMeasure = Mathf.Max( motionMeasureRot, motionMeasureTrans ); if (!settings.useMotionMeas) motionMeasure = 1; // working data float[,] scales_new_norm = new float[settings.scaleCount, settings.scaleCount]; //////////////////////////////// // advection if( settings.doAdvection ) { bool oneIn = false; for( int j = 0; j < settings.scaleCount; j++ ) { float phi1 = getPhi(j); for( int i = 0; i < settings.scaleCount; i++ ) { float theta1 = getTheta(i); float theta0, phi0; InvertAdvection( theta1, phi1, out theta0, out phi0 ); float r1 = ComputeR1( theta0, phi0 ); scales_new_norm[i, j] = r1 / radius; // detect case where no samples were taken from the old slice oneIn = oneIn || (thetaWithinView(theta0) && phiWithinView(phi0)); } } /* // if no samples taken, call this a teleport, reinit scales if( !oneIn && !settings.debugFreezeAdvection ) { ClearAfterTeleport(); } */ /* // now clamp the scales if( settings.clampScaleValues ) { // clamp the values for( int j = 0; j < settings.scaleCount; j++ ) { for( int i = 0; i < settings.scaleCount; i++ ) { // min: an inverted circle, i.e. concave instead of convex. this allows obiting // max: the fixed z line at the highest point of the circle. this allows strafing after rotating without aliasing scales_new_norm[i,j] = Mathf.Clamp( scales_new_norm[i,j], 0.9f*(1.0f - (Mathf.Sin(getTheta(i))-Mathf.Cos(CloudsBase.halfFov_horiz_rad))), 1.0f/Mathf.Sin(getTheta(i)) ); } } } */ /* // limit/relax the gradients if( settings.limitGradient ) { RelaxGradients( scales_new_norm ); } */ // all done - store the new r values if( !settings.debugFreezeAdvection ) { // normal path - store the scales then debug draw for( int j = 0; j < settings.scaleCount; j++ ) { for( int i = 0; i < settings.scaleCount; i++ ) { scales_norm[i, j] = scales_new_norm[i, j]; } } Draw(); } /*else { // for freezing advection, apply the scales temporarily and draw them, but then revert them float[] bkp = new float[scales_norm.Length]; for( int i = 0; i < bkp.Length; i++ ) bkp[i] = scales_norm[i]; for( int i = 0; i < settings.scaleCount; i++ ) scales_norm[i] = scales_new_norm[i]; Draw(); for( int i = 0; i < settings.scaleCount; i++ ) scales_norm[i] = bkp[i]; }*/ } if( !settings.debugFreezeAdvection ) { lastPos = transform.position; lastForward = transform.forward; lastRight = transform.right; lastUp = transform.up; } } // gradient relaxation // the following is complex and I don't know how much of this could maybe be done // in a single pass or otherwise simplified. more experimentation is needed. // // the two scales at the sides of the frustum are not changed by this process. // there are two stages - the first is an inside-out scheme which starts from // the middle and moves outwards. the second is an outside-in scheme which moves // towards the middle from the side. void RelaxGradients( float[] r_new ) { // INSIDE OUT for( int i = settings.scaleCount/2; i < settings.scaleCount-1; i++ ) { RelaxGradient( i, i-1, r_new ); } for( int i = settings.scaleCount/2; i >= 1; i-- ) { RelaxGradient( i, i+1, r_new ); } // OUTSIDE IN for( int i = 1; i <= settings.scaleCount/2; i++ ) { RelaxGradient( i, i-1, r_new ); } for( int i = settings.scaleCount-2; i >= settings.scaleCount/2; i-- ) { RelaxGradient( i, i+1, r_new ); } } void RelaxGradient( int i, int i1, float[] scales_new_norm ) { float dx = radius*scales_new_norm[i]*Mathf.Cos(getTheta(i)) - radius*scales_new_norm[i1]*Mathf.Cos(getTheta(i1)); if( Mathf.Abs(dx) < 0.0001f ) { //Debug.LogError("dx too small! " + dx); dx = Mathf.Sign(dx) * 0.0001f; } float meas = ( radius*scales_new_norm[i]*Mathf.Sin(getTheta(i)) - radius*scales_new_norm[i1]*Mathf.Sin(getTheta(i1)) ) / dx; float measClamped = Mathf.Clamp( meas, -settings.maxGradient, settings.maxGradient ); float dt = Mathf.Max( Time.deltaTime, 1.0f/30.0f ); scales_new_norm[i] = Mathf.Lerp( radius*scales_new_norm[i], (measClamped*dx + radius*scales_new_norm[i1]*Mathf.Sin(getTheta(i1))) / Mathf.Sin(getTheta(i)), motionMeasure*settings.alphaGradient * 30.0f * dt ) / radius; } // reset scales to a fixed-z layout void ClearAfterTeleport() { Debug.Log( "Teleport event, resetting layout" ); for( int j = 0; j < settings.scaleCount; j++ ) { float cos_phi = Mathf.Cos( getPhi( j ) ); for( int i = 0; i < settings.scaleCount; i++ ) { scales_norm[i, j] = Mathf.Cos( CloudsBase.halfFov_horiz_rad ) / (Mathf.Sin(getTheta(i))*cos_phi); } } lastPos = transform.position; lastForward = transform.forward; lastRight = transform.right; lastUp = transform.up; } public float getTheta( int i ) { return CloudsBase.halfFov_horiz_rad * (2.0f * (float)i/(float)(settings.scaleCount-1) - 1.0f) + Mathf.PI/2.0f; } bool thetaWithinView( float theta ) { return Mathf.Abs( theta - Mathf.PI/2.0f ) <= CloudsBase.halfFov_horiz_rad; } public float getPhi( int j ) { return CloudsBase.halfFov_vert_rad * (2.0f * (float)j/(float)(settings.scaleCount-1) - 1.0f); } bool phiWithinView( float phi ) { return Mathf.Abs( phi ) <= CloudsBase.halfFov_vert_rad; } Vector3 GetRay( float theta ) { Quaternion q = Quaternion.AngleAxis( theta * Mathf.Rad2Deg, -Vector3.up ); return q * transform.right; } // note that theta for the center of the screen is PI/2. its really incovenient that angles are computed from the X axis, but // the view direction is down the Z axis. we adopted this scheme as it made a bunch of the math simpler (i think!) // // Z axis (theta = PI/2) // | // frust. \ | / // \ | / // \ | / \ theta // \|/ | // ----------------------- X axis (theta = 0) // // for theta within the view, we sample the scale from the sample slice directly // for theta outside the view, we compute a linear extension from the last point on // the sample slice, to the corresponding scale at the side of the new camera position // frustum. this is a linear approximation to how the sample slice needs to be extended // when the frustum moves. if you rotate the camera fast then you will see the linear // segments. public float sampleR( float theta, float phi ) { // move theta from [pi/2 - halfFov, pi/2 + halfFov] to [0,1] float s = (theta - (Mathf.PI/2.0f-CloudsBase.halfFov_horiz_rad))/(2.0f*CloudsBase.halfFov_horiz_rad); float t = (phi + CloudsBase.halfFov_vert_rad)/(2.0f*CloudsBase.halfFov_vert_rad); s = Mathf.Clamp01(s); t = Mathf.Clamp01(t); /*if( s < 0f || s > 1f ) { // determine which side we're on. s<0 is right side as angles increase anti-clockwise bool rightSide = s < 0f; int lastIndex = rightSide ? 0 : settings.scaleCount-1; // the start and end position of the extension Vector3 pos_slice_end, pos_extrapolated; pos_slice_end = lastPos + radius * scales_norm[lastIndex] * Mathf.Cos( getTheta(lastIndex) ) * lastRight + radius * scales_norm[lastIndex] * Mathf.Sin( getTheta(lastIndex) ) * lastForward; float theta_edge = getTheta(lastIndex); // we always nudge scale back to default val (scale return). to compute how much we're nudging // the scale, we find our how far we're extending it, and we do this in radians. Vector3 extrapolatedDir = transform.forward * Mathf.Sin(theta_edge) + transform.right * Mathf.Cos(theta_edge); float angleSubtended = Vector3.Angle( pos_slice_end - transform.position, extrapolatedDir ) * Mathf.Deg2Rad; float lerpAlpha = Mathf.Clamp01( motionMeasure*settings.alphaScaleReturn*angleSubtended ); float r_extrap = Mathf.Lerp( sampleR(theta_edge), radius, lerpAlpha ); // now compute actual pos pos_extrapolated = transform.position + transform.forward * r_extrap * Mathf.Sin(theta_edge) + transform.right * r_extrap * Mathf.Cos(theta_edge); // now intersect ray with extension to find scale. Vector3 rayExtent = lastPos + Mathf.Cos( theta ) * lastRight + Mathf.Sin( theta ) * lastForward; Vector2 inter; bool found; found = IntersectLineSegments( new Vector2( pos_slice_end.x, pos_slice_end.z ), new Vector2( pos_extrapolated.x, pos_extrapolated.z ), new Vector2( lastPos.x, lastPos.z ), new Vector2( rayExtent.x, rayExtent.z ), out inter ); // no unique intersection point - shouldnt happen if( !found ) return sampleR(theta_edge); // the intersection point between the ray for the query theta and the linear extension Vector3 pt = new Vector3( inter.x, 0f, inter.y ); // make flatland Vector3 offset = pt - lastPos; offset.y = 0f; return offset.magnitude; }*/ // get from 0 to rCount-1 s *= (float)(settings.scaleCount-1); t *= (float)(settings.scaleCount-1); int i0 = Mathf.FloorToInt(s); int i1 = Mathf.CeilToInt(s); int j0 = Mathf.FloorToInt(t); int j1 = Mathf.CeilToInt(t); float resultj0 = Mathf.Lerp( scales_norm[i0,j0], scales_norm[i1,j0], Mathf.Repeat(s, 1.0f) ); float resultj1 = Mathf.Lerp( scales_norm[i0,j1], scales_norm[i1,j1], Mathf.Repeat(s, 1.0f) ); float result = Mathf.Lerp( resultj0, resultj1, Mathf.Repeat(t, 1.0f) ); return radius * result; } // this assumes that sampleR, lastPos, etc all return values from the PREVIOUS frame! Vector3 ComputePos0_world( float theta, float phi ) { float r0 = sampleR( theta, phi ); // 3d polar coordinates return lastPos + r0 * Mathf.Cos(phi) * (Mathf.Cos(theta) * lastRight + Mathf.Sin(theta) * lastForward) + r0 * Mathf.Sin(phi) * lastUp; } // solver. after the camera has moved, for a particular ray scale at angle theta1, we can find the angle to the corresponding // sample before the camera move theta0 using an iterative computation - fixed point iteration. // we previously published a paper titled Iterative Image Warping about using FPI for very similar use cases: // http://www.disneyresearch.com/wp-content/uploads/Iterative-Image-Warping-Paper.pdf void InvertAdvection( float theta1, float phi1, out float theta0, out float phi0 ) { // just guess the source position is the current pos (basically, that the camera hasn't moved) theta0 = theta1; phi0 = phi1; // N iterations of FPI. compute where our guess would get us, and then update our guess with the error. // we could monitor the iteration to ensure convergence etc but the advection seems to be well behaved for 8 iterations for( int i = 0; i < settings.advectionIters; i++ ) { float newTheta0 = theta0 + theta1 - ComputeTheta1( theta0, phi0 ); float newPhi0 = phi0 + phi1 - ComputePhi1( theta0, phi0 ); theta0 = newTheta0; phi0 = newPhi0; } } // input: theta0 is angle before camera moved, which specifies a specific point on the sample slice P // output: theta1 gives angle after camera moved to the sample slice point P // this is the opposite to what we want - we will know the angle afterwards theta1 and want to compute // the angle before theta0. however we invert this using FPI. float ComputeTheta1( float theta0, float phi0 ) { Vector3 pos0 = ComputePos0_world( theta0, phi0 ); // end position, removing foward motion of cam, in local space Vector3 pos1_local = transform.InverseTransformPoint( pos0 ); float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward); if( !settings.advectionCompensatesForwardPin ) pos1_local += pullInCam * Vector3.forward; else pos1_local += pullInCam * pos1_local.normalized * sampleR(theta0, phi0) / sampleR(Mathf.PI/2.0f, 0.0f); return Mathf.Atan2( pos1_local.z, pos1_local.x ); } float ComputePhi1( float theta0, float phi0 ) { Vector3 pos0 = ComputePos0_world( theta0, phi0 ); // end position, removing foward motion of cam, in local space Vector3 pos1_local = transform.InverseTransformPoint( pos0 ); float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward); if( !settings.advectionCompensatesForwardPin ) pos1_local += pullInCam * Vector3.forward; else pos1_local += pullInCam * pos1_local.normalized * sampleR(theta0, phi0) / sampleR(Mathf.PI/2.0f, 0.0f); // 3d polar coordinates are fun return Mathf.Atan2( pos1_local.y, Mathf.Sqrt(pos1_local.x*pos1_local.x+pos1_local.z*pos1_local.z) ); } // for an angle theta0 specifying a point on the sample slice before the camera moves, // we can compute a radius to this point by computing the distance to the new camera // position. this completes the advection computation float ComputeR1( float theta0, float phi0 ) { Vector3 pos0 = ComputePos0_world( theta0, phi0 ); // end position, removing forward motion of cam Vector3 pos1 = transform.position; float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward); if( !settings.advectionCompensatesForwardPin ) pos1 -= pullInCam * transform.forward; Vector3 offset = pos0 - pos1; if( settings.advectionCompensatesForwardPin ) offset += pullInCam * offset.normalized * sampleR(theta0, phi0) / sampleR(Mathf.PI/2f, 0f); return offset.magnitude; } void Draw() { float angleExpand = 1.2f; for( int j = 1; j < settings.scaleCount; j++ ) { float prevPhi = getPhi(j-1) * angleExpand; float thisPhi = getPhi(j) * angleExpand; for( int i = 1; i < settings.scaleCount; i++ ) { // only draw every 4th for perf reasons if( ( i + j ) % 4 != 0 ) continue; float prevTheta = getTheta(i-1); float thisTheta = getTheta(i); prevTheta = Mathf.PI/2.0f + (prevTheta-Mathf.PI/2.0f) * angleExpand; thisTheta = Mathf.PI/2.0f + (thisTheta-Mathf.PI/2.0f) * angleExpand; Color col = Color.white; if( !thetaWithinView(thisTheta) || !thetaWithinView(prevTheta) || !phiWithinView(thisPhi) || !phiWithinView(prevPhi) ) col *= 0.5f; Debug.DrawLine( ComputePos0_world( prevTheta, prevPhi ), ComputePos0_world( thisTheta, thisPhi ), col ); /*if( settings.debugDrawAdvectionGuides ) { scale = settings.debugDrawScale * 1.0f; Color fadeRed = Color.red; fadeRed.a = 0.25f; Debug.DrawLine( transform.position + prevRd * radius * scale, transform.position + thisRd * radius * scale, fadeRed ); scale = Mathf.Cos(CloudsBase.halfFov_horiz_rad) / Mathf.Sin(thisTheta); Debug.DrawLine( transform.position + prevRd * radius * scale, transform.position + thisRd * radius * scale, fadeRed ); }*/ } } } // loosely based on http://ideone.com/PnPJgb // performance of this is very bad, lots of temp things being constructed. i should really just inline the code // above but leaving like this for now. static bool IntersectLineSegments(Vector2 A, Vector2 B, Vector2 C, Vector2 D, out Vector2 intersect ) { Vector2 r = B - A; Vector2 s = D - C; float rxs = r.x * s.y - r.y * s.x; if( Mathf.Abs(rxs) <= Mathf.Epsilon ) { // Lines are parallel or collinear - this is useless for us intersect = Vector2.zero; return false; } Vector2 CmA = C - A; float CmAxs = CmA.x * s.y - CmA.y * s.x; float t = CmAxs / rxs; intersect = Vector2.Lerp( A, B, t ); return true; } }
namespace Sharpen { using System; public class ByteBuffer { private byte[] buffer; private DataConverter c; private int capacity; private int index; private int limit; private int mark; private int offset; private ByteOrder order; public ByteBuffer () { this.c = DataConverter.BigEndian; } private ByteBuffer (byte[] buf, int start, int len) { this.buffer = buf; this.offset = 0; this.limit = start + len; this.index = start; this.mark = start; this.capacity = buf.Length; this.c = DataConverter.BigEndian; } public static ByteBuffer Allocate (int size) { return new ByteBuffer (new byte[size], 0, size); } public static ByteBuffer AllocateDirect (int size) { return Allocate (size); } public byte[] Array () { return buffer; } public int ArrayOffset () { return offset; } public int Capacity () { return capacity; } private void CheckGetLimit (int inc) { if ((index + inc) > limit) { throw new BufferUnderflowException (); } } private void CheckPutLimit (int inc) { if ((index + inc) > limit) { throw new BufferUnderflowException (); } } public void Clear () { index = offset; limit = offset + capacity; } public void Flip () { limit = index; index = offset; } public byte Get () { CheckGetLimit (1); return buffer[index++]; } public void Get (byte[] data) { Get (data, 0, data.Length); } public void Get (byte[] data, int start, int len) { CheckGetLimit (len); for (int i = 0; i < len; i++) { data[i + start] = buffer[index++]; } } public int GetInt () { CheckGetLimit (4); int num = c.GetInt32 (buffer, index); index += 4; return num; } public short GetShort () { CheckGetLimit (2); short num = c.GetInt16 (buffer, index); index += 2; return num; } public bool HasArray () { return true; } public int Limit () { return (limit - offset); } public void Limit (int newLimit) { limit = newLimit; } public void Mark () { mark = index; } public void Order (ByteOrder order) { this.order = order; if (order == ByteOrder.BIG_ENDIAN) { c = DataConverter.BigEndian; } else { c = DataConverter.LittleEndian; } } public int Position () { return (index - offset); } public void Position (int pos) { if ((pos < offset) || (pos > limit)) { throw new BufferUnderflowException (); } index = pos + offset; } public void Put (byte[] data) { Put (data, 0, data.Length); } public void Put (byte data) { CheckPutLimit (1); buffer[index++] = data; } public void Put (byte[] data, int start, int len) { CheckPutLimit (len); for (int i = 0; i < len; i++) { buffer[index++] = data[i + start]; } } public void PutInt (int i) { Put (c.GetBytes (i)); } public void PutShort (short i) { Put (c.GetBytes (i)); } public int Remaining () { return (limit - index); } public void Reset () { index = mark; } public ByteBuffer Slice () { ByteBuffer b = Wrap (buffer, index, buffer.Length - index); b.offset = index; b.limit = limit; b.order = order; b.c = c; b.capacity = limit - index; return b; } public static ByteBuffer Wrap(byte[] buf) { return new ByteBuffer (buf, 0, buf.Length); } public static ByteBuffer Wrap(sbyte[] buf) { return Wrap(Extensions.ConvertToByteArray(buf)); } public static ByteBuffer Wrap (byte[] buf, int start, int len) { return new ByteBuffer (buf, start, len); } } }
// // System.IO.StreamWriter.cs // // Authors: // Dietmar Maurer (dietmar@ximian.com) // Paolo Molaro (lupus@ximian.com) // Marek Safar (marek.safar@gmail.com) // // (C) Ximian, Inc. http://www.ximian.com // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // Copyright 2011, 2013 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Text; using System.Runtime.InteropServices; #if NET_4_5 using System.Threading.Tasks; #endif namespace System.IO { [Serializable] [ComVisible (true)] public class StreamWriter : TextWriter { private Encoding internalEncoding; private Stream internalStream; private const int DefaultBufferSize = 1024; private const int DefaultFileBufferSize = 4096; private const int MinimumBufferSize = 256; private byte[] byte_buf; private char[] decode_buf; private int byte_pos; private int decode_pos; private bool iflush; private bool preamble_done; #if NET_4_5 readonly bool leave_open; IDecoupledTask async_task; #endif public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8, 1); public StreamWriter (Stream stream) : this (stream, Encoding.UTF8, DefaultBufferSize) {} public StreamWriter (Stream stream, Encoding encoding) : this (stream, encoding, DefaultBufferSize) {} internal void Initialize(Encoding encoding, int bufferSize) { internalEncoding = encoding; decode_pos = byte_pos = 0; int BufferSize = Math.Max(bufferSize, MinimumBufferSize); decode_buf = new char [BufferSize]; byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)]; // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513 if (internalStream.CanSeek && internalStream.Position > 0) preamble_done = true; } #if NET_4_5 public StreamWriter (Stream stream, Encoding encoding, int bufferSize) : this (stream, encoding, bufferSize, false) { } public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) #else const bool leave_open = false; public StreamWriter (Stream stream, Encoding encoding, int bufferSize) #endif { if (null == stream) throw new ArgumentNullException("stream"); if (null == encoding) throw new ArgumentNullException("encoding"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); if (!stream.CanWrite) throw new ArgumentException ("Can not write to stream"); #if NET_4_5 leave_open = leaveOpen; #endif internalStream = stream; Initialize(encoding, bufferSize); } public StreamWriter (string path) : this (path, false, Encoding.UTF8, DefaultFileBufferSize) {} public StreamWriter (string path, bool append) : this (path, append, Encoding.UTF8, DefaultFileBufferSize) {} public StreamWriter (string path, bool append, Encoding encoding) : this (path, append, encoding, DefaultFileBufferSize) {} public StreamWriter (string path, bool append, Encoding encoding, int bufferSize) { if (null == encoding) throw new ArgumentNullException("encoding"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); FileMode mode; if (append) mode = FileMode.Append; else mode = FileMode.Create; internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read); if (append) internalStream.Position = internalStream.Length; else internalStream.SetLength (0); Initialize(encoding, bufferSize); } public virtual bool AutoFlush { get { return iflush; } set { iflush = value; if (iflush) Flush (); } } public virtual Stream BaseStream { get { return internalStream; } } public override Encoding Encoding { get { return internalEncoding; } } protected override void Dispose (bool disposing) { if (byte_buf == null || !disposing) return; try { Flush (); } finally { byte_buf = null; internalEncoding = null; decode_buf = null; if (!leave_open) { internalStream.Close (); } internalStream = null; } } public override void Flush () { CheckState (); FlushCore (); } // Keep in sync with FlushCoreAsync void FlushCore () { Decode (); if (byte_pos > 0) { FlushBytes (); internalStream.Flush (); } } // how the speedup works: // the Write () methods simply copy the characters in a buffer of chars (decode_buf) // Decode () is called when the buffer is full or we need to flash. // Decode () will use the encoding to get the bytes and but them inside // byte_buf. From byte_buf the data is finally outputted to the stream. void FlushBytes () { // write the encoding preamble only at the start of the stream if (!preamble_done && byte_pos > 0) { byte[] preamble = internalEncoding.GetPreamble (); if (preamble.Length > 0) internalStream.Write (preamble, 0, preamble.Length); preamble_done = true; } internalStream.Write (byte_buf, 0, byte_pos); byte_pos = 0; } void Decode () { if (byte_pos > 0) FlushBytes (); if (decode_pos > 0) { int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos); byte_pos += len; decode_pos = 0; } } void LowLevelWrite (char[] buffer, int index, int count) { while (count > 0) { int todo = decode_buf.Length - decode_pos; if (todo == 0) { Decode (); todo = decode_buf.Length; } if (todo > count) todo = count; Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2); count -= todo; index += todo; decode_pos += todo; } } void LowLevelWrite (string s) { int count = s.Length; int index = 0; while (count > 0) { int todo = decode_buf.Length - decode_pos; if (todo == 0) { Decode (); todo = decode_buf.Length; } if (todo > count) todo = count; for (int i = 0; i < todo; i ++) decode_buf [i + decode_pos] = s [i + index]; count -= todo; index += todo; decode_pos += todo; } } #if NET_4_5 async Task FlushCoreAsync () { await DecodeAsync ().ConfigureAwait (false); if (byte_pos > 0) { await FlushBytesAsync ().ConfigureAwait (false); await internalStream.FlushAsync ().ConfigureAwait (false); } } async Task FlushBytesAsync () { // write the encoding preamble only at the start of the stream if (!preamble_done && byte_pos > 0) { byte[] preamble = internalEncoding.GetPreamble (); if (preamble.Length > 0) await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false); preamble_done = true; } await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false); byte_pos = 0; } async Task DecodeAsync () { if (byte_pos > 0) await FlushBytesAsync ().ConfigureAwait (false); if (decode_pos > 0) { int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos); byte_pos += len; decode_pos = 0; } } async Task LowLevelWriteAsync (char[] buffer, int index, int count) { while (count > 0) { int todo = decode_buf.Length - decode_pos; if (todo == 0) { await DecodeAsync ().ConfigureAwait (false); todo = decode_buf.Length; } if (todo > count) todo = count; Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2); count -= todo; index += todo; decode_pos += todo; } } async Task LowLevelWriteAsync (string s) { int count = s.Length; int index = 0; while (count > 0) { int todo = decode_buf.Length - decode_pos; if (todo == 0) { await DecodeAsync ().ConfigureAwait (false); todo = decode_buf.Length; } if (todo > count) todo = count; for (int i = 0; i < todo; i ++) decode_buf [i + decode_pos] = s [i + index]; count -= todo; index += todo; decode_pos += todo; } } #endif public override void Write (char[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (index < 0) throw new ArgumentOutOfRangeException ("index", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); // re-ordered to avoid possible integer overflow if (index > buffer.Length - count) throw new ArgumentException ("index + count > buffer.Length"); CheckState (); LowLevelWrite (buffer, index, count); if (iflush) FlushCore (); } public override void Write (char value) { CheckState (); // the size of decode_buf is always > 0 and // we check for overflow right away if (decode_pos >= decode_buf.Length) Decode (); decode_buf [decode_pos++] = value; if (iflush) FlushCore (); } public override void Write (char[] buffer) { CheckState (); if (buffer != null) LowLevelWrite (buffer, 0, buffer.Length); if (iflush) FlushCore (); } public override void Write (string value) { CheckState (); if (value == null) return; LowLevelWrite (value); if (iflush) FlushCore (); } public override void Close() { Dispose (true); } void CheckState () { if (byte_buf == null) throw new ObjectDisposedException ("StreamWriter"); #if NET_4_5 if (async_task != null && !async_task.IsCompleted) throw new InvalidOperationException (); #endif } #if NET_4_5 public override Task FlushAsync () { CheckState (); DecoupledTask res; async_task = res = new DecoupledTask (FlushCoreAsync ()); return res.Task; } public override Task WriteAsync (char value) { CheckState (); DecoupledTask res; async_task = res = new DecoupledTask (WriteAsyncCore (value)); return res.Task; } async Task WriteAsyncCore (char value) { // the size of decode_buf is always > 0 and // we check for overflow right away if (decode_pos >= decode_buf.Length) await DecodeAsync ().ConfigureAwait (false); decode_buf [decode_pos++] = value; if (iflush) await FlushCoreAsync ().ConfigureAwait (false); } public override Task WriteAsync (char[] buffer, int index, int count) { CheckState (); if (buffer == null) return TaskConstants.Finished; DecoupledTask res; async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count)); return res.Task; } async Task WriteAsyncCore (char[] buffer, int index, int count) { // Debug.Assert (buffer == null); await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false); if (iflush) await FlushCoreAsync ().ConfigureAwait (false); } public override Task WriteAsync (string value) { CheckState (); if (value == null) return TaskConstants.Finished; DecoupledTask res; async_task = res = new DecoupledTask (WriteAsyncCore (value, false)); return res.Task; } async Task WriteAsyncCore (string value, bool appendNewLine) { // Debug.Assert (value == null); await LowLevelWriteAsync (value).ConfigureAwait (false); if (appendNewLine) await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false); if (iflush) await FlushCoreAsync ().ConfigureAwait (false); } public override Task WriteLineAsync () { CheckState (); DecoupledTask res; async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length)); return res.Task; } public override Task WriteLineAsync (char value) { CheckState (); DecoupledTask res; async_task = res = new DecoupledTask (WriteLineAsyncCore (value)); return res.Task; } async Task WriteLineAsyncCore (char value) { await WriteAsyncCore (value).ConfigureAwait (false); await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false); if (iflush) await FlushCoreAsync ().ConfigureAwait (false); } public override Task WriteLineAsync (char[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (index < 0) throw new ArgumentOutOfRangeException ("index", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); // re-ordered to avoid possible integer overflow if (index > buffer.Length - count) throw new ArgumentException ("index + count > buffer.Length"); CheckState (); DecoupledTask res; async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count)); return res.Task; } async Task WriteLineAsyncCore (char[] buffer, int index, int count) { // Debug.Assert (buffer == null); await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false); await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false); if (iflush) await FlushCoreAsync ().ConfigureAwait (false); } public override Task WriteLineAsync (string value) { if (value == null) return WriteLineAsync (); CheckState (); DecoupledTask res; async_task = res = new DecoupledTask (WriteAsyncCore (value, true)); return res.Task; } #endif } }
using System; using OpenTK; namespace Bearded.Utilities.Math { /// <summary> /// A typesafe representation of a direction in two dimensional space. /// </summary> public struct Direction2 : IEquatable<Direction2> { private const float fromRadians = uint.MaxValue / Mathf.TwoPi; private const float toRadians = Mathf.TwoPi / uint.MaxValue; private const float fromDegrees = uint.MaxValue / 360f; private const float toDegrees = 360f / uint.MaxValue; private readonly uint data; #region Constructing private Direction2(uint data) { this.data = data; } /// <summary> /// Initialises a direction from an absolute angle value in radians. /// </summary> public static Direction2 FromRadians(float radians) { return new Direction2((uint)(radians * Direction2.fromRadians)); } /// <summary> /// Initialises a direction from an absolute angle value in degrees. /// </summary> public static Direction2 FromDegrees(float degrees) { return new Direction2((uint)(degrees * Direction2.fromDegrees)); } /// <summary> /// Initialises a direction along a vector. /// </summary> public static Direction2 Of(Vector2 vector) { return Direction2.FromRadians(Mathf.Atan2(vector.Y, vector.X)); } /// <summary> /// Initialises the direction between two points. /// </summary> /// <param name="from">The base point.</param> /// <param name="to">The point the directions "points" towards.</param> public static Direction2 Between(Vector2 from, Vector2 to) { return Direction2.Of(to - from); } #endregion #region Static Fields /// <summary> /// Default base direction (along positive X axis). /// </summary> public static readonly Direction2 Zero = new Direction2(0); #endregion #region Properties /// <summary> /// Gets the absolute angle of the direction in radians between 0 and 2pi. /// </summary> public float Radians { get { return this.data * Direction2.toRadians; } } /// <summary> /// Gets the absolute angle of the direction in degrees between 0 and 360. /// </summary> public float Degrees { get { return this.data * Direction2.toDegrees; } } /// <summary> /// Gets the absolute angle of the direction in radians between -pi and pi. /// </summary> public float RadiansSigned { get { return (int)this.data * Direction2.toRadians; } } /// <summary> /// Gets the absolute angle of the direction in degrees between -180 and 180. /// </summary> public float DegreesSigned { get { return (int)this.data * Direction2.toDegrees; } } /// <summary> /// Gets the unit vector pointing in this direction. /// </summary> public Vector2 Vector { get { var radians = this.Radians; return new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)); } } #endregion #region Methods /// <summary> /// Returns this direction turnen towards a goal direction with a given maximum step length in radians. /// This will never overshoot the goal. /// </summary> /// <param name="goal">The goal direction.</param> /// <param name="maxStepInRadians">The maximum step length in radians. Negative values will return the original direction.</param> public Direction2 TurnedTowards(Direction2 goal, float maxStepInRadians) { if (maxStepInRadians <= 0) return this; var step = maxStepInRadians.Radians(); var thisToGoal = goal - this; if (step > thisToGoal.Abs()) return goal; step *= thisToGoal.Sign(); return this + step; } #region Statics /// <summary> /// Linearly interpolates between two directions. /// This always interpolates along the shorter arc. /// </summary> /// <param name="d0">The first direction (at p == 0).</param> /// <param name="d1">The second direction (at p == 1).</param> /// <param name="p">The parameter.</param> public static Direction2 Lerp(Direction2 d0, Direction2 d1, float p) { return d0 + p * (d1 - d0); } #endregion #endregion #region Operators #region Arithmetic /// <summary> /// Adds an angle to a direction. /// </summary> public static Direction2 operator +(Direction2 direction, Angle angle) { return new Direction2((uint)(direction.data + angle.Radians * Direction2.fromRadians)); } /// <summary> /// Substracts an angle from a direction. /// </summary> public static Direction2 operator -(Direction2 direction, Angle angle) { return new Direction2((uint)(direction.data - angle.Radians * Direction2.fromRadians)); } /// <summary> /// Gets the signed difference between two directions. /// Always returns the angle of the shorter arc. /// </summary> public static Angle operator -(Direction2 direction1, Direction2 direction2) { return Angle.FromRadians(((int)direction1.data - (int)direction2.data) * Direction2.toRadians); } /// <summary> /// Gets the inverse direction to a direction. /// </summary> public static Direction2 operator -(Direction2 direction) { return new Direction2(direction.data + (uint.MaxValue / 2 + 1)); } #endregion #region Boolean /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. /// </returns> public bool Equals(Direction2 other) { return this.data == other.data; } /// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return obj is Direction2 && this.Equals((Direction2)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return this.data.GetHashCode(); } /// <summary> /// Checks two directions for equality. /// </summary> public static bool operator ==(Direction2 x, Direction2 y) { return x.Equals(y); } /// <summary> /// Checks two directions for inequality. /// </summary> public static bool operator !=(Direction2 x, Direction2 y) { return !(x == y); } #endregion #region Casts #endregion #endregion } }
//! \file ImageDPO.cs //! \date 2019 Mar 20 //! \brief Jam Creation tiled image format. // // Copyright (C) 2019 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace GameRes.Formats.JamCreation { internal class DpoMetaData : ImageMetaData { public int Version; public IList<string> Files; public int LayoutOffset; } [Export(typeof(ImageFormat))] public class DpoFormat : ImageFormat { public override string Tag { get { return "DPO"; } } public override string Description { get { return "Jam Creation tiled image format"; } } public override uint Signature { get { return 0x69766944; } } // 'Divided Picture' public override ImageMetaData ReadMetaData (IBinaryStream file) { var header = file.ReadHeader (0x30); if (!header.AsciiEqual ("Divided Picture") || header.ToInt32 (0x10) != 1) return null; int version = header.ToInt32 (0x14); if (version != 1 && version != 2) return null; int info_pos = header.ToInt32 (0x18); if (header.ToInt32 (0x1C) < 4) return null; int name_table_pos = header.ToInt32 (0x20); int name_table_size = header.ToInt32 (0x24); int layout_pos = header.ToInt32 (0x28); file.Position = info_pos; ushort width = file.ReadUInt16(); ushort height = file.ReadUInt16(); file.Position = name_table_pos; int name_count = file.ReadUInt16(); if (name_count * 32 + 2 != name_table_size) return null; var dir_name = VFS.GetDirectoryName (file.Name); var files = new List<string> (name_count); for (int i = 0; i < name_count; ++i) { var name = file.ReadCString (0x20); if (name.StartsWith (@".\")) name = name.Substring (2); name = VFS.CombinePath (dir_name, name); files.Add (name); } return new DpoMetaData { Width = width, Height = height, BPP = 32, Version = version, LayoutOffset = layout_pos, Files = files, }; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { var reader = new DpoReader (file, (DpoMetaData)info); return reader.Unpack(); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("DpoFormat.Write not implemented"); } } internal class DpoReader { IBinaryStream m_input; DpoMetaData m_info; public DpoReader (IBinaryStream input, DpoMetaData info) { m_input = input; m_info = info; m_file_map = new Lazy<BitmapSource>[m_info.Files.Count]; for (int i = 0; i < m_info.Files.Count; ++i) { string filename = m_info.Files[i]; m_file_map[i] = new Lazy<BitmapSource> (() => LoadBitmap (filename)); } } Lazy<BitmapSource>[] m_file_map; public ImageData Unpack () { m_input.Position = m_info.LayoutOffset; int count = m_input.ReadInt32(); int tile_size = m_input.ReadInt32(); m_tile_stride = tile_size * 4; m_tile_buffer = new byte[tile_size * m_tile_stride]; var canvas = new WriteableBitmap (m_info.iWidth, m_info.iHeight, ImageData.DefaultDpiX, ImageData.DefaultDpiY, PixelFormats.Bgra32, null); var tile_def = new float[8]; for (int i = 0; i < count; ++i) { for (int j = 0; j < 8; ++j) { tile_def[j] = ReadFloat(); } int file_num = m_input.ReadUInt16(); int x = m_input.ReadUInt16(); int y = m_input.ReadUInt16(); var source = m_file_map[file_num].Value; int src_x = (int)(source.PixelWidth * tile_def[0]); int src_y = (int)(source.PixelHeight * tile_def[4]); int src_w = tile_size; int src_h = tile_size; if (m_info.Version > 1) { src_w = m_input.ReadUInt16(); src_h = m_input.ReadUInt16(); } var rect = new Int32Rect (src_x, src_y, src_w, src_h); CopyTile (canvas, x, y, source, rect); } canvas.Freeze(); return new ImageData (canvas, m_info); } int m_tile_stride; byte[] m_tile_buffer; void CopyTile (WriteableBitmap canvas, int x, int y, BitmapSource source, Int32Rect rect) { source.CopyPixels (rect, m_tile_buffer, m_tile_stride, 0); var width = Math.Min (rect.Width, canvas.PixelWidth - x); var height = Math.Min (rect.Height, canvas.PixelHeight - y); var src_rect = new Int32Rect (0, 0, width, height); canvas.WritePixels (src_rect, m_tile_buffer, m_tile_stride, x, y); } BitmapSource LoadBitmap (string filename) { using (var input = VFS.OpenBinaryStream (filename)) { var image = ImageFormat.Read (input); if (null == image) throw new InvalidFormatException(); var bitmap = image.Bitmap; if (bitmap.Format.BitsPerPixel != 32) bitmap = new FormatConvertedBitmap (bitmap, PixelFormats.Bgra32, null, 0); return bitmap; } } [StructLayout(LayoutKind.Explicit)] struct Union { [FieldOffset(0)] public uint u; [FieldOffset(0)] public float f; } Union m_flt_buffer = new Union(); float ReadFloat () { m_flt_buffer.u = m_input.ReadUInt32(); return m_flt_buffer.f; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Rest; using Rest.Azure; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for FirewallRulesOperations. /// </summary> public static partial class FirewallRulesOperationsExtensions { /// <summary> /// Creates or updates the specified firewall rule. During update, the firewall /// rule with the specified name will be replaced with this new firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to add the firewall rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the firewall rule. /// </param> public static FirewallRule CreateOrUpdate(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified firewall rule. During update, the firewall /// rule with the specified name will be replaced with this new firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to add the firewall rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the firewall rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> CreateOrUpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake Store /// account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to delete. /// </param> public static void Delete(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { operations.DeleteAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake Store /// account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Data Lake Store firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to retrieve. /// </param> public static FirewallRule Get(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return operations.GetAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake Store firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to retrieve. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> GetAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rules. /// </param> public static IPage<FirewallRule> ListByAccount(this IFirewallRulesOperations operations, string resourceGroupName, string accountName) { return operations.ListByAccountAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rules. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FirewallRule>> ListByAccountAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FirewallRule> ListByAccountNext(this IFirewallRulesOperations operations, string nextPageLink) { return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FirewallRule>> ListByAccountNextAsync(this IFirewallRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Perimetr.Web.Areas.HelpPage.ModelDescriptions; using Perimetr.Web.Areas.HelpPage.Models; namespace Perimetr.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System.Linq; using System.Reflection; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ResultsViewTests : CSharpResultProviderTestBase { // IEnumerable pattern not supported. [Fact] public void IEnumerablePattern() { var source = @"using System.Collections; class C { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } // IEnumerable<T> pattern not supported. [Fact] public void IEnumerableOfTPattern() { var source = @"using System.Collections.Generic; class C<T> { private readonly IEnumerable<T> e; internal C(IEnumerable<T> e) { this.e = e; } public IEnumerator<T> GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } [Fact] public void IEnumerableImplicitImplementation() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]")); } } [Fact] public void IEnumerableOfTImplicitImplementation() { var source = @"using System.Collections; using System.Collections.Generic; struct S<T> : IEnumerable<T> { private readonly IEnumerable<T> e; internal S(IEnumerable<T> e) { this.e = e; } public IEnumerator<T> GetEnumerator() { return this.e.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("S`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S<int>}", "S<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"), EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]")); } } [Fact] public void IEnumerableExplicitImplementation() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]")); } } [Fact] public void IEnumerableOfTExplicitImplementation() { var source = @"using System.Collections; using System.Collections.Generic; class C<T> : IEnumerable<T> { private readonly IEnumerable<T> e; internal C(IEnumerable<T> e) { this.e = e; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.e.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"), EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]")); } } // Results View not supported for // IEnumerator implementation. [Fact] public void IEnumerator() { var source = @"using System; using System.Collections; using System.Collections.Generic; class C : IEnumerator<int> { private int[] c = new[] { 1, 2, 3 }; private int i = 0; object IEnumerator.Current { get { return this.c[this.i]; } } int IEnumerator<int>.Current { get { return this.c[this.i]; } } bool IEnumerator.MoveNext() { this.i++; return this.i < this.c.Length; } void IEnumerator.Reset() { this.i = 0; } void IDisposable.Dispose() { } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "System.Collections.Generic.IEnumerator<int>.Current", "1", "int", "((System.Collections.Generic.IEnumerator<int>)o).Current", DkmEvaluationResultFlags.ReadOnly), EvalResult( "System.Collections.IEnumerator.Current", "1", "object {int}", "((System.Collections.IEnumerator)o).Current", DkmEvaluationResultFlags.ReadOnly), EvalResult("c", "{int[3]}", "int[]", "o.c", DkmEvaluationResultFlags.Expandable), EvalResult("i", "0", "int", "o.i")); } } [Fact] public void Overrides() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A : IEnumerable<object> { public virtual IEnumerator<object> GetEnumerator() { yield return 0; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B1 : A { public override IEnumerator<object> GetEnumerator() { yield return 1; } } class B2 : A, IEnumerable<int> { public new IEnumerator<int> GetEnumerator() { yield return 2; } } class B3 : A { public new IEnumerable<int> GetEnumerator() { yield return 3; } } class B4 : A { } class C { A _1 = new B1(); A _2 = new B2(); A _3 = new B3(); A _4 = new B4(); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{B1}", "A {B1}", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{B2}", "A {B2}", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{B3}", "A {B3}", "o._3", DkmEvaluationResultFlags.Expandable), EvalResult("_4", "{B4}", "A {B4}", "o._4", DkmEvaluationResultFlags.Expandable)); // A _1 = new B1(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._1).Items[0]")); // A _2 = new B2(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o._2).Items[0]")); // A _3 = new B3(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._3).Items[0]")); // A _4 = new B4(); moreChildren = GetChildren(children[3]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._4, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._4).Items[0]")); } } /// <summary> /// Include Results View on base types /// (matches legacy EE behavior). /// </summary> [Fact] public void BaseTypes() { var source = @"using System.Collections; using System.Collections.Generic; class A1 { } class B1 : A1, IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } } class A2 { public IEnumerator GetEnumerator() { yield return 1; } } class B2 : A2, IEnumerable<object> { IEnumerator<object> IEnumerable<object>.GetEnumerator() { yield return 2; } } struct S : IEnumerable { public IEnumerator GetEnumerator() { yield return 3; } } class C { A1 _1 = new B1(); B2 _2 = new B2(); System.ValueType _3 = new S(); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{B1}", "A1 {B1}", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{B2}", "B2", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{S}", "System.ValueType {S}", "o._3", DkmEvaluationResultFlags.Expandable)); // A1 _1 = new B1(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._1).Items[0]")); // B2 _2 = new B2(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._2).Items[0]")); // System.ValueType _3 = new S(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._3).Items[0]")); } } [Fact] public void Nullable() { var source = @"using System; using System.Collections; using System.Collections.Generic; struct S : IEnumerable<object> { internal readonly object[] c; internal S(object[] c) { this.c = c; } public IEnumerator<object> GetEnumerator() { foreach (var o in this.c) { yield return o; } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class C { S? F = new S(new object[] { null }); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{S}", "S?", "o.F", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[0]); Verify(children, EvalResult("c", "{object[1]}", "object[]", "o.F.c", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o.F, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o.F).Items[0]")); } } [Fact] public void ConstructedType() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { private readonly T[] items; internal A(T[] items) { this.items = items; } public IEnumerator<T> GetEnumerator() { foreach (var item in items) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B { internal object F; } class C : A<B> { internal C() : base(new[] { new B() }) { } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "items", "{B[1]}", "B[]", "o.items", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "[0]", "{B}", "B", "new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0]", DkmEvaluationResultFlags.Expandable /*TODO | DkmEvaluationResultFlags.ReadOnly*/)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("F", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0].F")); } } /// <summary> /// System.Array should not have Results View. /// </summary> [Fact] public void Array() { var source = @"using System; using System.Collections; class C { char[] _1 = new char[] { '1' }; Array _2 = new char[] { '2' }; IEnumerable _3 = new char[] { '3' }; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{char[1]}", "char[]", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{char[1]}", "System.Array {char[]}", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o._3", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "49 '1'", "char", "o._1[0]", editableValue: "'1'")); Verify(GetChildren(children[1]), EvalResult("[0]", "50 '2'", "char", "((char[])o._2)[0]", editableValue: "'2'")); children = GetChildren(children[2]); Verify(children, EvalResult("[0]", "51 '3'", "char", "((char[])o._3)[0]", editableValue: "'3'")); } } /// <summary> /// String should not have Results View. /// </summary> [Fact] public void String() { var source = @"using System.Collections; using System.Collections.Generic; class C { string _1 = ""1""; object _2 = ""2""; IEnumerable _3 = ""3""; IEnumerable<char> _4 = ""4""; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "\"1\"", "string", "o._1", DkmEvaluationResultFlags.RawString, editableValue: "\"1\""), EvalResult("_2", "\"2\"", "object {string}", "o._2", DkmEvaluationResultFlags.RawString, editableValue: "\"2\""), EvalResult("_3", "\"3\"", "System.Collections.IEnumerable {string}", "o._3", DkmEvaluationResultFlags.RawString, editableValue: "\"3\""), EvalResult("_4", "\"4\"", "System.Collections.Generic.IEnumerable<char> {string}", "o._4", DkmEvaluationResultFlags.RawString, editableValue: "\"4\"")); } } [WorkItem(1006160)] [Fact] public void MultipleImplementations_DifferentImplementors() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return default(T); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B1 : A<object>, IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } } class B2 : A<int>, IEnumerable<object> { IEnumerator<object> IEnumerable<object>.GetEnumerator() { yield return null; } } class B3 : A<object>, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 3; } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); // class B1 : A<object>, IEnumerable<int> var type = assembly.GetType("B1"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B1}", "B1", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]")); // class B2 : A<int>, IEnumerable<object> type = assembly.GetType("B2"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B2}", "B2", "o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]")); // class B3 : A<object>, IEnumerable type = assembly.GetType("B3"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B3}", "B3", "o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]")); } } [Fact] public void MultipleImplementations_SameImplementor() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A : IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return null; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B : IEnumerable<string>, IEnumerable<int> { IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); // class A : IEnumerable<int>, IEnumerable<string> var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("a", value); Verify(evalResult, EvalResult("a", "{A}", "A", "a", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "a, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(a).Items[0]")); // class B : IEnumerable<string>, IEnumerable<int> type = assembly.GetType("B"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("b", value); Verify(evalResult, EvalResult("b", "{B}", "B", "b", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "b, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "string", "new System.Linq.SystemCore_EnumerableDebugView<string>(b).Items[0]")); } } /// <summary> /// Types with [DebuggerTypeProxy] should not have Results View. /// </summary> [Fact] public void DebuggerTypeProxy() { var source = @"using System.Collections; using System.Diagnostics; public class P : IEnumerable { private readonly C c; public P(C c) { this.c = c; } public IEnumerator GetEnumerator() { return this.c.GetEnumerator(); } public int Length { get { return this.c.o.Length; } } } [DebuggerTypeProxy(typeof(P))] public class C : IEnumerable { internal readonly object[] o; public C(object[] o) { this.o = o; } public IEnumerator GetEnumerator() { return this.o.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new object[] { new object[] { string.Empty } }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Length", "1", "int", "new P(o).Length", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("o", "{object[1]}", "object[]", "o.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } /// <summary> /// Do not expose Results View if the proxy type is missing. /// </summary> [Fact] public void MissingProxyType() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = new[] { assembly }; using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } /// <summary> /// Proxy type not in System.Core.dll. /// </summary> [Fact] public void MissingProxyType_SystemCore() { // "System.Core.dll" var source0 = ""; var compilation0 = CSharpTestBase.CreateCompilationWithMscorlib(source0, assemblyName: "system.core"); var assembly0 = ReflectionUtilities.Load(compilation0.EmitToArray()); var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = new[] { assembly0, assembly }; using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); // Verify the module was found but ResolveTypeName failed. var module = runtime.Modules.Single(m => m.Assembly == assembly0); Assert.Equal(module.ResolveTypeNameFailures, 1); } } /// <summary> /// Report "Enumeration yielded no results" when /// GetEnumerator returns an empty collection or null. /// </summary> [Fact] public void GetEnumeratorEmptyOrNull() { var source = @"using System; using System.Collections; using System.Collections.Generic; // IEnumerable returns empty collection. class C0 : IEnumerable { public IEnumerator GetEnumerator() { yield break; } } // IEnumerable<T> returns empty collection. class C1<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } // IEnumerable returns null. class C2 : IEnumerable { public IEnumerator GetEnumerator() { return null; } } // IEnumerable<T> returns null. class C3<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class C { C0 _0 = new C0(); C1<object> _1 = new C1<object>(); C2 _2 = new C2(); C3<object> _3 = new C3<object>(); }"; using (new EnsureEnglishUICulture()) { var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_0", "{C0}", "C0", "o._0", DkmEvaluationResultFlags.Expandable), EvalResult("_1", "{C1<object>}", "C1<object>", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{C2}", "C2", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{C3<object>}", "C3<object>", "o._3", DkmEvaluationResultFlags.Expandable)); // C0 _0 = new C0(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._0, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C1<object> _1 = new C1<object>(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C2 _2 = new C2(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C3<object> _3 = new C3<object>(); moreChildren = GetChildren(children[3]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); } } } /// <summary> /// Do not instantiate proxy type for null IEnumerable. /// </summary> [WorkItem(1009646)] [Fact] public void IEnumerableNull() { var source = @"using System.Collections; using System.Collections.Generic; interface I : IEnumerable { } class C { IEnumerable<char> E = null; I F = null; string S = null; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("E", "null", "System.Collections.Generic.IEnumerable<char>", "o.E"), EvalResult("F", "null", "I", "o.F"), EvalResult("S", "null", "string", "o.S")); } } [Fact] public void GetEnumeratorException() { var source = @"using System; using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { throw new NotImplementedException(); } }"; using (new EnsureEnglishUICulture()) { var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children[6], EvalResult("Message", "\"The method or operation is not implemented.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } [Fact] public void GetEnumerableException() { var source = @"using System; using System.Collections; class E : Exception, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 1; } } class C { internal IEnumerable P { get { throw new NotImplementedException(); } } internal IEnumerable Q { get { throw new E(); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "P", "'o.P' threw an exception of type 'System.NotImplementedException'", "System.Collections.IEnumerable {System.NotImplementedException}", "o.P", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown), EvalResult( "Q", "'o.Q' threw an exception of type 'E'", "System.Collections.IEnumerable {E}", "o.Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown)); children = GetChildren(children[1]); Verify(children.Last(), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); } } [Fact] public void GetEnumerableError() { var source = @"using System.Collections; class C { bool f; internal ArrayList P { get { while (!this.f) { } return new ArrayList(); } } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "P") ? CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C"); var evalResult = FormatResult("o.P", memberValue); Verify(evalResult, EvalFailedResult("o.P", "Function evaluation timed out", "System.Collections.ArrayList", "o.P")); } } /// <summary> /// If evaluation of the proxy Items property returns an error /// (say, evaluation of the enumerable requires func-eval and /// either func-eval is disabled or we're debugging a .dmp), /// we should include a row that reports the error rather than /// having an empty expansion (since the container Items property /// is [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]). /// Note, the native EE has an empty expansion when .dmp debugging. /// </summary> [WorkItem(1043746)] [Fact] public void GetProxyPropertyValueError() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "Items") ? CreateErrorValue(runtime.GetType(typeof(object)).MakeArrayType(), string.Format("Unable to evaluate '{0}'", m)) : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalFailedResult("Error", "Unable to evaluate 'Items'", flags: DkmEvaluationResultFlags.None)); } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.IO; namespace FluorineFx.IO.Mp3 { /// <summary> /// Header of an Mp3 frame. /// http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm /// </summary> class Mp3Header { /// <summary> /// Sampling rates in hertz: 1. index = MPEG Version ID, 2. index = sampling rate index /// </summary> static int[,] SamplingRates = new int[,] { {11025, 12000, 8000, }, // MPEG 2.5 {0, 0, 0, }, // reserved {22050, 24000, 16000, }, // MPEG 2 {44100, 48000, 32000 } // MPEG 1 }; /// <summary> /// Bitrates: 1. index = LSF, 2. index = Layer, 3. index = bitrate index /// </summary> static int[,,] Bitrates = new int[,,] { { // MPEG 1 {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,}, // Layer1 {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,}, // Layer2 {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,} // Layer3 }, { // MPEG 2, 2.5 {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,}, // Layer1 {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,}, // Layer2 {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,} // Layer3 } }; /// <summary> /// Allowed combination of bitrate (1.index) and mono (2.index) /// </summary> static bool[,] AllowedModes = new bool[,] { // {stereo, intensity stereo, dual channel allowed, single channel allowed} {true,true}, // free mode {false,true}, // 32 {false,true}, // 48 {false,true}, // 56 {true,true}, // 64 {false,true}, // 80 {true,true}, // 96 {true,true}, // 112 {true,true}, // 128 {true,true}, // 160 {true,true}, // 192 {true,false}, // 224 {true,false}, // 256 {true,false}, // 320 {true,false} // 384 }; /// <summary> /// Samples per Frame: 1. index = LSF, 2. index = Layer /// </summary> static int[,] SamplesPerFrames = new int[,] { { // MPEG 1 384, // Layer1 1152, // Layer2 1152 // Layer3 }, { // MPEG 2, 2.5 384, // Layer1 1152, // Layer2 576 // Layer3 } }; /// <summary> /// Samples per Frame / 8 /// </summary> static int[,] Coefficients = new int[,] { { // MPEG 1 12, // Layer1 (must be multiplied with 4, because of slot size) 144, // Layer2 144 // Layer3 }, { // MPEG 2, 2.5 12, // Layer1 (must be multiplied with 4, because of slot size) 144, // Layer2 72 // Layer3 } }; /// <summary> /// Slot size per layer /// </summary> static int[] SlotSizes = new int[] { 4, // Layer1 1, // Layer2 1 // Layer3 }; /// <summary> /// Size of side information (only for Layer III) /// 1. index = LSF, 2. index = mono /// </summary> static int[,] SideInfoSizes = new int[,] { // MPEG 1 {32,17}, // MPEG 2/2.5 {17,9} }; /// <summary> /// Frame sync data /// </summary> private byte[] _data; /// <summary> /// Audio version id /// </summary> private byte _audioVersionId; /// <summary> /// Layer description /// </summary> private byte _layerDescription; /// <summary> /// Protection bit /// </summary> private bool _protectionBit; /// <summary> /// Bitrate used (index in array of bitrates) /// </summary> private byte _bitRateIndex; /// <summary> /// In bit per second (1 kb = 1000 bit, not 1024) /// </summary> private int _bitrate; /// <summary> /// Sampling rate used (index in array of sample rates) /// </summary> private byte _samplingRateIndex; private int _samplesPerSec; /// <summary> /// Padding bit /// </summary> private byte _paddingSize; /// <summary> /// Channel mode /// </summary> private byte _channelMode; /// <summary> /// 1 means lower sampling frequencies (=MPEG2/MPEG2.5) /// </summary> byte _lsf; public Mp3Header(byte[] data) { if ((data[0] == 0xFF) && ((data[1] & 0xE0) == 0xE0) && ((data[2] & 0xF0) != 0xF0)) // first 11 bits should be 1 { _data = data; // Mask only the rightmost 2 bits _audioVersionId = (byte)((_data[1] >> 3) & 0x03); if (_audioVersionId == 1)//MPEGReserved throw new Exception("Corrupt mp3 header"); _lsf = _audioVersionId == 3 ? (byte)0 : (byte)1;//MPEG1 // Get layer (0 = layer1, 2 = layer2, ...) [bit 13,14] _layerDescription = (byte)(3 - ((_data[1] >> 1) & 0x03)); if (_layerDescription == 3)//LayerReserved throw new Exception("Corrupt mp3 header"); // Protection bit (inverted) [bit 15] _protectionBit = ((data[1]) & 0x01) != 0; // Bitrate [bit 16..19] _bitRateIndex = (byte)((_data[2] >> 4) & 0x0F); _bitrate = Bitrates[_lsf, _layerDescription, _bitRateIndex] * 1000; // convert from kbit to bit // Sampling rate [bit 20,21] _samplingRateIndex = (byte)((_data[2] >> 2) & 0x03); if (_samplingRateIndex == 0x03) // all bits set is reserved throw new Exception("Corrupt mp3 header"); _samplesPerSec = SamplingRates[_audioVersionId, _samplingRateIndex]; // Padding bit [bit 22] _paddingSize = (byte)(1 * ((_data[2] >> 1) & 0x01)); // in Slots (always 1) // Channel mode [bit 24,25] _channelMode = (byte)((_data[3] >> 6) & 0x03); } else throw new Exception("Invalid frame sync word"); } public byte[] Data { get { return _data; } } public bool IsStereo { get { return _channelMode != 3; } } public bool IsProtected { get { return _protectionBit; } } public int BitRate { get { return _bitrate; } } public int SampleRate { get { return _samplesPerSec; } } public int FrameSize { get { return (int)(((Coefficients[_lsf, _layerDescription] * _bitrate / _samplesPerSec) + _paddingSize)) * SlotSizes[_layerDescription]; } } public double FrameDuration { get { switch (_layerDescription) { case 3: // Layer 1 return 384 / (SampleRate * 0.001); case 2: case 1: if (_audioVersionId == 3) { // MPEG 1, Layer 2 and 3 return 1152 / (SampleRate * 0.001); } else { // MPEG 2 or 2.5, Layer 2 and 3 return 576 / (SampleRate * 0.001); } default: // Unknown return -1; } } } } }
/******************************************************************** 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.IO; using System.Xml; using System.Collections; using System.Collections.Generic; using Axiom.Core; using Axiom.Graphics; using Axiom.MathLib; using Axiom.Utility; using Axiom.Input; using Multiverse; using Multiverse.Generator; using System.Diagnostics; using Axiom.SceneManagers.Multiverse; namespace Multiverse.Tools.MVSMTest { /// <summary> /// Summary description for Terrain. /// </summary> public class MVSMTest : TechDemo { private int lastHeightPointsGenerated = 0; private Multiverse.Generator.Generator gen; private LODSpec lodSpec; private LODSpecPrev lodSpecPrev; private bool followTerrain = false; private bool humanSpeed = false; private int lastTick; private float time = 0.0f; private readonly float oneMeter = 1000f; private bool preview = false; private bool captureFailed = false; private Mesh waterMesh; private SceneNode treeSceneNode; private Forest forest; private Boundary boundary1; private Boundary boundary2; private Boundary boundary3; private ColorEx fogColor = new ColorEx(0.5f, 0.58f, 0.77f); private float fogNear = 500 * 1000; private int frameCount = 0; Axiom.SceneManagers.Multiverse.SceneManager mvScene; private Road road1 = null; private Road road2 = null; protected override void ChooseSceneManager() { scene = Root.Instance.SceneManagers.GetSceneManager(SceneType.ExteriorClose); mvScene = scene as Axiom.SceneManagers.Multiverse.SceneManager; } protected override void CreateCamera() { camera = scene.CreateCamera("PlayerCam"); // camera.Position = new Vector3(128, 25, 128); // camera.LookAt(new Vector3(0, 0, -300)); // camera.Near = 1; // camera.Far = 384; //camera.Position = new Vector3(128 * oneMeter, 800 * oneMeter, 128 * oneMeter); //camera.Position = new Vector3(0 * oneMeter, 100 * oneMeter, 3900 * oneMeter); //camera.Position = new Vector3(90 * oneMeter, 65 * oneMeter, 4150 * oneMeter); //camera.Position = new Vector3(240 * oneMeter, 100 * oneMeter, 4593 * oneMeter); //camera.Position = new Vector3(326 * oneMeter, 78 * oneMeter, 4270 * oneMeter); camera.Position = new Vector3(339022, 63142, 4282656); //camera.LookAt(new Vector3(1, 100 * oneMeter, -300 * oneMeter)); //camera.LookAt(new Vector3(300, 1 * oneMeter, 3500 * oneMeter)); camera.LookAt(new Vector3(341022, 63142, 4282656)); camera.Near = 1 * oneMeter; camera.Far = 2000 * oneMeter; Console.WriteLine("Right: {0}, Up: {1}", camera.DerivedRight, camera.DerivedUp); } protected void SetupScene() { if (preview) { mvScene.SetWorldParams(gen, lodSpecPrev, 2000 * oneMeter, 2000 * oneMeter, 1024, 4); scene.LoadWorldGeometry(""); WorldManager.Instance.SeaLevel = oneMeter * 10; WorldManager.Instance.OceanWaveHeight = oneMeter * 1; camera.Far = 10000 * oneMeter; } else { mvScene.SetWorldParams(gen, lodSpec, 2000 * oneMeter, 2000 * oneMeter, 256, 4); scene.LoadWorldGeometry(""); camera.Far = 2000 * oneMeter; WorldManager.Instance.SeaLevel = oneMeter * 10; WorldManager.Instance.OceanWaveHeight = oneMeter * 1; } camera.Position = camera.Position + new Vector3(0, 1, 0); scene.AmbientLight = new ColorEx(1.0f, 0.5f, 0.5f, 0.5f); Light light = scene.CreateLight("MainLight"); light.Type = LightType.Directional; Vector3 lightDir = new Vector3(-80 * oneMeter, -70 * oneMeter, -80 * oneMeter); //lightDir = Vector3.UnitX; lightDir.Normalize(); light.Direction = lightDir; light.Position = -lightDir; light.Diffuse = ColorEx.White; light.SetAttenuation(1000 * oneMeter, 1, 0, 0); scene.SetFog(FogMode.Linear, fogColor, 0.5f, fogNear, fogNear * 2); //scene.SetFog(FogMode.None, fogColor, 0.5f, 500 * oneMeter, 1000 * oneMeter); //WorldManager.Instance.ShowOcean = false; //WorldManager.Instance.DrawStitches = false; //WorldManager.Instance.DrawTiles = false; // pampas WorldManager.Instance.AddDetailVegPlantType(1000, 0.375244f, 0.375244f + 0.124512f, 800, 1200, 800, 1200); // sunflower WorldManager.Instance.AddDetailVegPlantType(10, 0.625244f, 0.625244f + 0.124512f, 1600, 2400, 1600, 2400); // rose WorldManager.Instance.AddDetailVegPlantType(10, 0.500244f, 0.500244f + 0.124512f, 1300, 1700, 1300, 1700); // cattail WorldManager.Instance.AddDetailVegPlantType(10, 0.125244f, 0.125244f + 0.124512f, 1300, 1700, 1300, 1700); // marigold WorldManager.Instance.AddDetailVegPlantType(10, 0.250244f, 0.250244f + 0.124512f, 1300, 1700, 1300, 1700); // bird of paradise WorldManager.Instance.AddDetailVegPlantType(10, 0.000244f, 0.000244f + 0.124512f, 1500, 1500, 1500, 1500); // grass WorldManager.Instance.AddDetailVegPlantType(1000, 0.750244f, 0.750244f + 0.124512f, 1600, 2400, 800, 1200); WorldManager.Instance.DetailVegMinHeight = 40000; WorldManager.Instance.DetailVegMaxHeight = 150000; WorldManager.Instance.ShowDetailVeg = true; bool doForest1 = true; bool doForest2 = false; bool doLakes = false; bool doOcean = false; bool doBuildings = false; bool doRoads = false; AddContent(doForest1, doForest2, doLakes, doOcean, doBuildings, doRoads); if (!preview) { scene.SetSkyBox(true, "Multiverse/SceneSkyBox", 1000 * oneMeter); } } private void AddContent(bool drawForest1, bool drawForest2, bool lakes, bool ocean, bool buildings, bool roads) { if (drawForest1 || drawForest2) { treeSceneNode = scene.RootSceneNode.CreateChildSceneNode("Trees"); } bool betaWorldForest = false; if (betaWorldForest) { boundary1 = new Boundary("boundary1"); boundary1.AddPoint(new Vector3(441 * oneMeter, 0, 4269 * oneMeter)); boundary1.AddPoint(new Vector3(105 * oneMeter, 0, 4278 * oneMeter)); boundary1.AddPoint(new Vector3(66 * oneMeter, 0, 4162 * oneMeter)); boundary1.AddPoint(new Vector3(-132 * oneMeter, 0, 4102 * oneMeter)); boundary1.AddPoint(new Vector3(-540 * oneMeter, 0, 3658 * oneMeter)); boundary1.AddPoint(new Vector3(-639 * oneMeter, 0, 3570 * oneMeter)); boundary1.AddPoint(new Vector3(182 * oneMeter, 0, 3510 * oneMeter)); boundary1.AddPoint(new Vector3(236 * oneMeter, 0, 3845 * oneMeter)); boundary1.AddPoint(new Vector3(382 * oneMeter, 0, 3966 * oneMeter)); boundary1.Close(); //boundary1.Hilight = true; mvScene.AddBoundary(boundary1); forest = new Forest(1234, "Forest1", treeSceneNode); boundary1.AddSemantic(forest); forest.WindFilename = "demoWind.ini"; forest.WindDirection = Vector3.UnitX; forest.WindStrength = 0.0f; forest.AddTreeType("CedarOfLebanon_RT.spt", 55 * 300, 0, 4); forest.AddTreeType("WeepingWillow_RT.spt", 50 * 300, 0, 5); forest.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, 16); Boundary boundary4 = new Boundary("boundary4"); boundary4.AddPoint(new Vector3(441 * oneMeter, 0, 4269 * oneMeter)); boundary4.AddPoint(new Vector3(105 * oneMeter, 0, 4278 * oneMeter)); boundary4.AddPoint(new Vector3(66 * oneMeter, 0, 4162 * oneMeter)); boundary4.AddPoint(new Vector3(-132 * oneMeter, 0, 4102 * oneMeter)); boundary4.AddPoint(new Vector3(-540 * oneMeter, 0, 3658 * oneMeter)); boundary4.AddPoint(new Vector3(-639 * oneMeter, 0, 3570 * oneMeter)); boundary4.AddPoint(new Vector3(182 * oneMeter, 0, 3510 * oneMeter)); boundary4.AddPoint(new Vector3(236 * oneMeter, 0, 3845 * oneMeter)); boundary4.AddPoint(new Vector3(382 * oneMeter, 0, 3966 * oneMeter)); boundary4.Close(); //boundary1.Hilight = true; mvScene.AddBoundary(boundary4); Forest forest4 = new Forest(1234, "Forest4", treeSceneNode); boundary4.AddSemantic(forest); forest4.WindFilename = "demoWind.ini"; forest4.WindDirection = Vector3.UnitX; forest4.WindStrength = 1.0f; forest4.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, 14); forest4.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 23); forest4.AddTreeType("CinnamonFern_RT.spt", 70 * 300, 0, 14); boundary2 = new Boundary("boundary2"); boundary2.AddPoint(new Vector3(285 * oneMeter, 0, 3462 * oneMeter)); boundary2.AddPoint(new Vector3(-679 * oneMeter, 0, 3560 * oneMeter)); boundary2.AddPoint(new Vector3(-647 * oneMeter, 0, 3381 * oneMeter)); boundary2.AddPoint(new Vector3(-512 * oneMeter, 0, 3230 * oneMeter)); boundary2.AddPoint(new Vector3(402 * oneMeter, 0, 3116 * oneMeter)); boundary2.AddPoint(new Vector3(402 * oneMeter, 0, 3339 * oneMeter)); boundary2.AddPoint(new Vector3(305 * oneMeter, 0, 3363 * oneMeter)); boundary2.Close(); mvScene.AddBoundary(boundary2); Forest forest2 = new Forest(1234, "Forest2", treeSceneNode); boundary2.AddSemantic(forest2); forest2.WindFilename = "demoWind.ini"; forest2.WindDirection = Vector3.UnitX; forest2.WindStrength = 1.0f; forest2.AddTreeType("SpiderTree_RT_Dead.spt", 80 * 300, 0, 23); forest2.AddTreeType("CinnamonFern_RT.spt", 70 * 300, 0, 12); forest2.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 12); Boundary boundary3 = new Boundary("boundary3"); boundary3.AddPoint(new Vector3(285 * oneMeter, 0, 3462 * oneMeter)); boundary3.AddPoint(new Vector3(-679 * oneMeter, 0, 3560 * oneMeter)); boundary3.AddPoint(new Vector3(-647 * oneMeter, 0, 3381 * oneMeter)); boundary3.AddPoint(new Vector3(-512 * oneMeter, 0, 3230 * oneMeter)); boundary3.AddPoint(new Vector3(402 * oneMeter, 0, 3116 * oneMeter)); boundary3.AddPoint(new Vector3(402 * oneMeter, 0, 3339 * oneMeter)); boundary3.AddPoint(new Vector3(305 * oneMeter, 0, 3363 * oneMeter)); boundary3.Close(); mvScene.AddBoundary(boundary3); Forest forest3 = new Forest(1234, "Forest3", treeSceneNode); boundary3.AddSemantic(forest3); forest3.WindFilename = "demoWind.ini"; forest3.WindDirection = Vector3.UnitX; forest3.WindStrength = 1.0f; forest3.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, 14); forest3.AddTreeType("AmericanHolly_RT.spt", 40 * 300, 0, 24); forest3.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 23); forest3.AddTreeType("SpiderTree_RT_Dead.spt", 80 * 300, 0, 9); } if (drawForest1) { boundary1 = new Boundary("boundary1"); boundary1.AddPoint(new Vector3(441 * oneMeter, 0, 4269 * oneMeter)); boundary1.AddPoint(new Vector3(105 * oneMeter, 0, 4278 * oneMeter)); boundary1.AddPoint(new Vector3(66 * oneMeter, 0, 4162 * oneMeter)); boundary1.AddPoint(new Vector3(-132 * oneMeter, 0, 4102 * oneMeter)); boundary1.AddPoint(new Vector3(-540 * oneMeter, 0, 3658 * oneMeter)); boundary1.AddPoint(new Vector3(-639 * oneMeter, 0, 3570 * oneMeter)); boundary1.AddPoint(new Vector3(182 * oneMeter, 0, 3510 * oneMeter)); boundary1.AddPoint(new Vector3(236 * oneMeter, 0, 3845 * oneMeter)); boundary1.AddPoint(new Vector3(382 * oneMeter, 0, 3966 * oneMeter)); boundary1.Close(); //boundary1.Hilight = true; mvScene.AddBoundary(boundary1); forest = new Forest(1234, "Forest1", treeSceneNode); boundary1.AddSemantic(forest); forest.WindFilename = "demoWind.ini"; forest.WindDirection = Vector3.UnitX; forest.WindStrength = 1.0f; //forest.AddTreeType("EnglishOak_RT.spt", 55 * 300, 0, 100); //forest.AddTreeType("AmericanHolly_RT.spt", 40 * 300, 0, 100); //forest.AddTreeType("ChristmasScotchPine_RT.spt", 70 * 300, 0, 100); //forest.AddTreeType("CedarOfLebanon_RT.spt", 55 * 300, 0, 4); //forest.AddTreeType("WeepingWillow_RT.spt", 50 * 300, 0, 5); //forest.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, 16); //forest.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, 14); //forest.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 23); //forest.AddTreeType("CinnamonFern_RT.spt", 70 * 300, 0, 14); //forest.AddTreeType("SpiderTree_RT_Dead.spt", 80 * 300, 0, 23); //forest.AddTreeType("CinnamonFern_RT.spt", 70 * 300, 0, 12); //forest.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 12); //forest.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, 14); //forest.AddTreeType("AmericanHolly_RT.spt", 40 * 300, 0, 24); //forest.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 23); //forest.AddTreeType("SpiderTree_RT_Dead.spt", 80 * 300, 0, 9); uint numinstances = 50; //forest.AddTreeType("Azalea_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("Azalea_RT_Pink.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("AzaleaPatch_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("AzaleaPatch_RT_Pink.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("CurlyPalm_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("CurlyPalmCluster_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("FraserFir_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("FraserFir_RT_Snow.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("FraserFirCluster_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("FraserFirCluster_RT_Snow.spt", 55 * 300, 0, numinstances); forest.AddTreeType("RDApple_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("RDApple_RT_Apples.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("RDApple_RT_Spring.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("RDApple_RT_Winter.spt", 55 * 300, 0, numinstances); forest.AddTreeType("UmbrellaThorn_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("UmbrellaThorn_RT_Dead.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("UmbrellaThorn_RT_Flowers.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("WeepingWillow_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("WeepingWillow_RT_Fall.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("WeepingWillow_RT_Winter.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("AmericanBoxwood_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("AmericanBoxwoodCluster_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("Beech_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("Beech_RT_Fall.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("Beech_RT_Winter.spt", 55 * 300, 0, numinstances); forest.AddTreeType("SugarPine_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("SugarPine_RT_Winter.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("VenusTree_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("CherryTree_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("CherryTree_RT_Spring.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("CherryTree_RT_Fall.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("CherryTree_RT_Winter.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("SpiderTree_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("SpiderTree_RT_Dead.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("JungleBrush_RT.spt", 55 * 300, 0, numinstances); forest.AddTreeType("QueenPalm_RT.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("QueenPalm_RT_Flowers.spt", 55 * 300, 0, numinstances); //forest.AddTreeType("QueenPalmCluster_RT.spt", 55 * 300, 0, numinstances); if (false) { //uint numinstances = 30; forest.AddTreeType("CurlyPalm_RT.spt", 55 * 300, 0, numinstances); forest.AddTreeType("DatePalm_RT.spt", 40 * 300, 0, numinstances); forest.AddTreeType("JungleBrush_RT.spt", 70 * 300, 0, numinstances); forest.AddTreeType("Cercropia_RT.spt", 55 * 300, 0, numinstances); forest.AddTreeType("CommonOlive_RT_Summer.spt", 40 * 300, 0, numinstances); forest.AddTreeType("ColvilleaRacemosa_RT_Flower.spt", 70 * 300, 0, numinstances); forest.AddTreeType("JapaneseAngelica_RT_Summer.spt", 55 * 300, 0, numinstances); forest.AddTreeType("NorthIslandRata_RT_Spring.spt", 40 * 300, 0, numinstances); forest.AddTreeType("SpiderTree_RT.spt", 70 * 300, 0, numinstances); forest.AddTreeType("Stump_RT.spt", 150 * 300, 0, numinstances); forest.AddTreeType("UmbrellaThorn_RT_Flowers.spt", 70 * 300, 0, numinstances); forest.AddTreeType("AmurCork_RT_LateSummer.spt", 55 * 300, 0, numinstances); forest.AddTreeType("ArizonaBush_RT_Flowers.spt", 40 * 300, 0, numinstances); forest.AddTreeType("BananaTree_RT.spt", 70 * 300, 0, numinstances); forest.AddTreeType("Baobab_RT.spt", 55 * 300, 0, numinstances); forest.AddTreeType("CaliforniaBuckeye_RT_Nuts.spt", 120 * 300, 0, numinstances); forest.AddTreeType("CedarOfLebanon_RT.spt", 55 * 300, 0, numinstances); forest.AddTreeType("CherryTree_RT_Spring.spt", 40 * 300, 0, numinstances); forest.AddTreeType("CinnamonFern_RT.spt", 70 * 300, 0, numinstances); forest.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, numinstances); forest.AddTreeType("Crepe Myrtle_RT_Flowers.spt", 120 * 300, 0, numinstances); } //forest.AddTreeType("CedarOfLebanon_RT.spt", 100 * 300, 0, 30); //forest.AddTreeType("CherryTree_RT_Spring.spt", 40 * 300, 0, 30); //forest.AddTreeType("CinnamonFern_RT.spt", 70 * 300, 0, 30); //forest.AddTreeType("CoconutPalm_RT.spt", 55 * 300, 0, 30); //forest.AddTreeType("Crepe Myrtle_RT_Flowers.spt", 120 * 300, 0, 30); if (false) { forest.AddTreeType("Crepe Myrtle_RT_Winter.spt", 100 * 300, 0, 30); forest.AddTreeType("FanPalm_RT.spt", 40 * 300, 0, 30); forest.AddTreeType("ItalianCypress_RT.spt", 70 * 300, 0, 30); forest.AddTreeType("JapaneseMaple_RT_Summer.spt", 55 * 300, 0, 30); forest.AddTreeType("JoshuaTree_RT.spt", 120 * 300, 0, 30); forest.AddTreeType("KoreanStewartia_RT.spt", 100 * 300, 0, 30); forest.AddTreeType("ManchurianAngelicaTree_RT_Small.spt", 100 * 300, 0, 30); forest.AddTreeType("MimosaTree_RT.spt", 100 * 300, 0, 30); forest.AddTreeType("MimosaTree_RT_Flower.spt", 100 * 300, 0, 30); forest.AddTreeType("Mulga_RT_Flowers.spt", 50 * 300, 0, 30); forest.AddTreeType("OmenTree_RT.spt", 80 * 300, 0, 30); forest.AddTreeType("OrientalSpruce_RT.spt", 50 * 300, 0, 30); forest.AddTreeType("PonytailPalm_RT.spt", 140 * 300, 0, 30); forest.AddTreeType("QueenPalm_RT.spt", 55 * 300, 0, 30); forest.AddTreeType("ColvilleaRacemosa_RT.spt", 50 * 300, 0, 30); forest.AddTreeType("SpiderTree_RT_Dead.spt", 80 * 300, 0, 30); forest.AddTreeType("Tamarind_RT_Spring.spt", 50 * 300, 0, 30); forest.AddTreeType("WeepingWillow_RT.spt", 50 * 300, 0, 30); } } if ( drawForest2 ) { boundary2 = new Boundary("boundary2"); boundary2.AddPoint(new Vector3(285 * oneMeter, 0, 3462 * oneMeter)); boundary2.AddPoint(new Vector3(-679 * oneMeter, 0, 3560 * oneMeter)); boundary2.AddPoint(new Vector3(-647 * oneMeter, 0, 3381 * oneMeter)); boundary2.AddPoint(new Vector3(-512 * oneMeter, 0, 3230 * oneMeter)); boundary2.AddPoint(new Vector3(402 * oneMeter, 0, 3116 * oneMeter)); boundary2.AddPoint(new Vector3(402 * oneMeter, 0, 3339 * oneMeter)); boundary2.AddPoint(new Vector3(305 * oneMeter, 0, 3363 * oneMeter)); boundary2.Close(); mvScene.AddBoundary(boundary2); Forest forest2 = new Forest(1234, "Forest2", treeSceneNode); boundary2.AddSemantic(forest2); forest2.WindFilename = "demoWind.ini"; forest2.AddTreeType("EnglishOak_RT.spt", 55 * 300, 0, 150); forest2.AddTreeType("AmericanHolly_RT.spt", 40 * 300, 0, 150); forest2.AddTreeType("ChristmasScotchPine_RT.spt", 70 * 300, 0, 150); forest2.WindDirection = Vector3.UnitX; forest2.WindStrength = 0f; } if (lakes) { boundary3 = new Boundary("boundary3"); boundary3.AddPoint(new Vector3(-540 * oneMeter, 0, 3151 * oneMeter)); boundary3.AddPoint(new Vector3(-656 * oneMeter, 0, 3058 * oneMeter)); boundary3.AddPoint(new Vector3(-631 * oneMeter, 0, 2878 * oneMeter)); boundary3.AddPoint(new Vector3(-335 * oneMeter, 0, 2882 * oneMeter)); boundary3.AddPoint(new Vector3(-336 * oneMeter, 0, 3098 * oneMeter)); boundary3.AddPoint(new Vector3(-478 * oneMeter, 0, 3166 * oneMeter)); boundary3.Close(); //boundary3.Hilight = true; mvScene.AddBoundary(boundary3); WaterPlane waterSemantic = new WaterPlane(42 * WorldManager.oneMeter, "lake1", treeSceneNode); boundary3.AddSemantic(waterSemantic); } if (buildings) { Entity entity = scene.CreateEntity("tree", "demotree4.mesh"); SceneNode node = scene.RootSceneNode.CreateChildSceneNode(); node.AttachObject(entity); node.Position = new Vector3(332383, 71536, 4247994); entity = scene.CreateEntity("house", "human_house_stilt.mesh"); node = scene.RootSceneNode.CreateChildSceneNode(); node.AttachObject(entity); node.Position = new Vector3(0, 130.0f * oneMeter, 3900 * oneMeter); } if (ocean) { Entity waterEntity = scene.CreateEntity("Water", "WaterPlane"); Debug.Assert(waterEntity != null); waterEntity.MaterialName = "MVSMOcean"; SceneNode waterNode = scene.RootSceneNode.CreateChildSceneNode("WaterNode"); Debug.Assert(waterNode != null); waterNode.AttachObject(waterEntity); waterNode.Translate(new Vector3(0, 0, 0)); } if (roads) { road1 = mvScene.CreateRoad("Via Appia"); road1.HalfWidth = 2; List<Vector3> roadPoints = new List<Vector3>(); roadPoints.Add(new Vector3(97000, 0, 4156000)); roadPoints.Add(new Vector3(205000, 0, 4031000)); roadPoints.Add(new Vector3(254000, 0, 3954000)); roadPoints.Add(new Vector3(234000, 0, 3500000)); roadPoints.Add(new Vector3(256000, 0, 3337000)); roadPoints.Add(new Vector3(98000, 0, 3242000)); road1.AddPoints(roadPoints); } } private void NewRoad() { road2 = mvScene.CreateRoad("Via Sacra"); List<Vector3> road2Points = new List<Vector3>(); road2Points.Add(new Vector3(71000, 0, 4014000)); road2Points.Add(new Vector3(265000, 0, 4177000)); road2.AddPoints(road2Points); } protected override void CreateScene() { viewport.BackgroundColor = ColorEx.White; viewport.OverlaysEnabled = false; gen = new Multiverse.Generator.Generator(); gen.Algorithm = GeneratorAlgorithm.HybridMultifractalWithSeedMap; gen.LoadSeedMap("map.csv"); gen.OutsideMapSeedHeight = 0; gen.SeedMapOrigin = new Vector3(-3200, 0, -5120); gen.SeedMapMetersPerSample = 128; gen.XOff = -0.4f; gen.YOff = -0.3f; gen.HeightFloor = 0; gen.FractalOffset = 0.1f; gen.HeightOffset = -0.15f; gen.HeightScale = 300; gen.MetersPerPerlinUnit = 800; lodSpec = new LODSpec(); lodSpecPrev = new LODSpecPrev(); // water plane setup Plane waterPlane = new Plane(Vector3.UnitY, 10f * oneMeter); waterMesh = MeshManager.Instance.CreatePlane( "WaterPlane", waterPlane, 60 * 128 * oneMeter, 90 * 128 * oneMeter, 20, 20, true, 1, 10, 10, Vector3.UnitZ); Debug.Assert(waterMesh != null); SetupScene(); } protected override void OnFrameStarted(object source, FrameEventArgs e) { frameCount++; int tick = Environment.TickCount; time += e.TimeSinceLastFrame; float moveTime = e.TimeSinceLastFrame; if (moveTime > 1) { moveTime = 1; } Axiom.SceneManagers.Multiverse.WorldManager.Instance.Time = time; if ( ( tick - lastTick ) > 100 ) { Console.WriteLine("long frame: {0}", tick-lastTick); LogManager.Instance.Write("long frame: {0}", tick - lastTick); } lastTick = tick; // int hpg = gen.HeightPointsGenerated; // if ( lastHeightPointsGenerated != hpg ) // { // Console.WriteLine("HeightPointsGenerated: {0}", hpg - lastHeightPointsGenerated); // lastHeightPointsGenerated = hpg; // } float scaleMove = 20 * oneMeter * moveTime; // reset acceleration zero camAccel = Vector3.Zero; // set the scaling of camera motion cameraScale = 100 * moveTime; bool retry = true; //System.Threading.Thread.Sleep(3000); //while (retry) //{ // // TODO: Move this into an event queueing mechanism that is processed every frame // try // { // input.Capture(); // retry = false; // } // catch (Exception ex) // { // System.Threading.Thread.Sleep(1000); // } //} // TODO: Move this into an event queueing mechanism that is processed every frame bool realIsActive = window.IsActive; try { // force a reset of axiom's internal input state so that it will call Acquire() on the // input device again. if (captureFailed) { window.IsActive = false; input.Capture(); window.IsActive = realIsActive; } input.Capture(); captureFailed = false; } catch (Exception ex) { Console.WriteLine(ex.Message); captureFailed = true; System.Threading.Thread.Sleep(1000); } finally { window.IsActive = realIsActive; } if(input.IsKeyPressed(KeyCodes.Escape)) { Root.Instance.QueueEndRendering(); return; } if(input.IsKeyPressed(KeyCodes.A)) { camAccel.x = -0.5f; } if(input.IsKeyPressed(KeyCodes.D)) { camAccel.x = 0.5f; } if(input.IsKeyPressed(KeyCodes.W)) { camAccel.z = -1.0f; } if(input.IsKeyPressed(KeyCodes.S)) { camAccel.z = 1.0f; } if (!captureFailed) { camAccel.y += (float)(input.RelativeMouseZ * 0.1f); } if(input.IsKeyPressed(KeyCodes.Left)) { camera.Yaw(cameraScale); } if(input.IsKeyPressed(KeyCodes.Right)) { camera.Yaw(-cameraScale); } if(input.IsKeyPressed(KeyCodes.Up)) { camera.Pitch(cameraScale); } if(input.IsKeyPressed(KeyCodes.Down)) { camera.Pitch(-cameraScale); } // subtract the time since last frame to delay specific key presses toggleDelay -= e.TimeSinceLastFrame; // toggle rendering mode if(input.IsKeyPressed(KeyCodes.R) && toggleDelay < 0) { if(camera.SceneDetail == SceneDetailLevel.Points) { camera.SceneDetail = SceneDetailLevel.Solid; } else if(camera.SceneDetail == SceneDetailLevel.Solid) { camera.SceneDetail = SceneDetailLevel.Wireframe; } else { camera.SceneDetail = SceneDetailLevel.Points; } Console.WriteLine("Rendering mode changed to '{0}'.", camera.SceneDetail); toggleDelay = 1; } if ( input.IsKeyPressed(KeyCodes.F) && toggleDelay < 0 ) { followTerrain = !followTerrain; toggleDelay = 1; } if ( input.IsKeyPressed(KeyCodes.H) && toggleDelay < 0 ) { humanSpeed = !humanSpeed; toggleDelay = 1; } if(input.IsKeyPressed(KeyCodes.T) && toggleDelay < 0) { // toggle the texture settings switch(filtering) { case TextureFiltering.Bilinear: filtering = TextureFiltering.Trilinear; aniso = 1; break; case TextureFiltering.Trilinear: filtering = TextureFiltering.Anisotropic; aniso = 8; break; case TextureFiltering.Anisotropic: filtering = TextureFiltering.Bilinear; aniso = 1; break; } Console.WriteLine("Texture Filtering changed to '{0}'.", filtering); // set the new default MaterialManager.Instance.SetDefaultTextureFiltering(filtering); MaterialManager.Instance.DefaultAnisotropy = aniso; toggleDelay = 1; } if(input.IsKeyPressed(KeyCodes.P)) { string[] temp = Directory.GetFiles(Environment.CurrentDirectory, "screenshot*.jpg"); string fileName = string.Format("screenshot{0}.jpg", temp.Length + 1); // show briefly on the screen window.DebugText = string.Format("Wrote screenshot '{0}'.", fileName); TakeScreenshot(fileName); // show for 2 seconds debugTextDelay = 2.0f; } if(input.IsKeyPressed(KeyCodes.B)) { scene.ShowBoundingBoxes = !scene.ShowBoundingBoxes; } if(input.IsKeyPressed(KeyCodes.O)) { // hide all overlays, includes ones besides the debug overlay viewport.OverlaysEnabled = !viewport.OverlaysEnabled; } if ( input.IsKeyPressed(KeyCodes.F1) && toggleDelay < 0 ) { Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawStitches = ! Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawStitches; toggleDelay = 1; } if ( input.IsKeyPressed(KeyCodes.F2) && toggleDelay < 0 ) { Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawTiles = ! Axiom.SceneManagers.Multiverse.WorldManager.Instance.DrawTiles; toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F3) && toggleDelay < 0) { Console.WriteLine("Camera Location: {0}, {1}, {2}", camera.Position.x.ToString("F3"), camera.Position.y.ToString("F3"), camera.Position.z.ToString("F3")); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F4) && toggleDelay < 0) { preview = !preview; if (preview) { // when in preview mode, move the camera up high and look at the ground camera.MoveRelative(new Vector3(0, 1000 * oneMeter, 0)); camera.LookAt(new Vector3(0, 0, 0)); followTerrain = false; } else { // when not in preview mode, hug the ground followTerrain = true; } SetupScene(); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F5) && toggleDelay < 0) { if (WorldManager.Instance.OceanWaveHeight >= 500) { WorldManager.Instance.OceanWaveHeight -= 500; } toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F6) && toggleDelay < 0) { WorldManager.Instance.OceanWaveHeight += 500; toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F7) && toggleDelay < 0) { NewRoad(); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F8) && toggleDelay < 0) { WorldManager.Instance.SeaLevel += 500; toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F9) && toggleDelay < 0) { StreamWriter s = new StreamWriter("boundaries.xml"); XmlTextWriter w = new XmlTextWriter(s); //w.Formatting = Formatting.Indented; //w.Indentation = 2; //w.IndentChar = ' '; mvScene.ExportBoundaries(w); w.Close(); s.Close(); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F10) && toggleDelay < 0) { StreamReader s = new StreamReader("boundaries.xml"); XmlTextReader r = new XmlTextReader(s); mvScene.ImportBoundaries(r); r.Close(); s.Close(); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F11) && toggleDelay < 0) { StreamWriter s = new StreamWriter("terrain.xml"); gen.ToXML(s); s.Close(); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.F12) && toggleDelay < 0) { StreamReader s = new StreamReader("terrain.xml"); gen.FromXML(s); s.Close(); SetupScene(); toggleDelay = 1; } if (input.IsKeyPressed(KeyCodes.I)) { //point camera north camera.Direction = Vector3.NegativeUnitZ; } if (input.IsKeyPressed(KeyCodes.K)) { //point camera south camera.Direction = Vector3.UnitZ; } if (input.IsKeyPressed(KeyCodes.J)) { //point camera west camera.Direction = Vector3.NegativeUnitX; } if (input.IsKeyPressed(KeyCodes.L)) { //point camera east camera.Direction = Vector3.UnitX; } if (!captureFailed) { if (!input.IsMousePressed(MouseButtons.Left)) { float cameraYaw = -input.RelativeMouseX * .13f; float cameraPitch = -input.RelativeMouseY * .13f; camera.Yaw(cameraYaw); camera.Pitch(cameraPitch); } else { cameraVector.x += input.RelativeMouseX * 0.13f; } } if ( humanSpeed ) { // in game running speed is 7m/sec //camVelocity = camAccel * 7 * oneMeter; camVelocity = camAccel * 32 * oneMeter; } else { camVelocity += (camAccel * scaleMove * camSpeed); } // Console.WriteLine("ScameMove: {0}", scaleMove.ToString("F3")); // Console.WriteLine("Camera Accel: {0}, {1}, {2}", camAccel.x.ToString("F3"), //camAccel.y.ToString("F3"), camAccel.z.ToString("F3")); // Console.WriteLine("Camera Velocity: {0}, {1}, {2}", camVelocity.x.ToString("F3"), //camVelocity.y.ToString("F3"), camVelocity.z.ToString("F3")); // move the camera based on the accumulated movement vector camera.MoveRelative(camVelocity * moveTime); // Now dampen the Velocity - only if user is not accelerating if (camAccel == Vector3.Zero) { float slowDown = 6 * moveTime; if (slowDown > 1) { slowDown = 1; } camVelocity *= (1 - slowDown); } if ( followTerrain ) { // adjust new camera position to be a fixed distance above the ground Axiom.Core.RaySceneQuery raySceneQuery = scene.CreateRayQuery( new Ray(camera.Position, Vector3.NegativeUnitY)); raySceneQuery.QueryMask = (ulong)Axiom.SceneManagers.Multiverse.RaySceneQueryType.Height; ArrayList results = raySceneQuery.Execute(); RaySceneQueryResultEntry result = (RaySceneQueryResultEntry)results[0]; camera.Position = new Vector3(camera.Position.x, result.worldFragment.SingleIntersection.y + ( 2f * oneMeter ), camera.Position.z); } // update performance stats once per second if(statDelay < 0.0f && showDebugOverlay) { UpdateStats(); statDelay = 1.0f; } else { statDelay -= e.TimeSinceLastFrame; } // turn off debug text when delay ends if(debugTextDelay < 0.0f) { debugTextDelay = 0.0f; window.DebugText = ""; } else if(debugTextDelay > 0.0f) { debugTextDelay -= e.TimeSinceLastFrame; } } static void Main() { MVSMTest app = new MVSMTest(); app.Start(); } } }
using UnityEngine; using System.Xml; using System.Collections.Generic; public enum State { GameStarting, PlayerSelectAction, PlayerMove, PlayerTarget, PlayerSelectItem, AIActions, MissionComplete, GameComplete, GameOver, } public class Game : MonoBehaviour { // visible information public TextAsset MissionFile; private TextAsset nextMissionFile; public int TileSize = 16; public float Scale = 2f; // mission details private int missionNum; private bool finalMission; // class necessities private BackgroundMaker bg; private XmlDocument doc; private GUILayer gui; private Map map; private Font font; private Overlay overlay; // entities private List<Entity> entities; private Stack<Entity> entsToProcess; private Entity player; private List<Item> items; private List<Exit> exits; private int totalObjectives; private int objectivesInHand; // gui needs private int playerMenuItem; private int playerTargeting; private List<Entity> entitiesInSight; private bool itemInRange; private bool enemyInSight; private bool exitEnabled; // turn information private Entity turnEnt; private State state; // buttons private KeyCode AButton = KeyCode.Space; private KeyCode BButton = KeyCode.LeftControl; // ai options private float nextAIMove; private const float timeBetweenAIMoves = 0.8f; // menu keys private const int MENU_MOVE = 0; private const int MENU_FIRE = 1; private const int MENU_WAIT = 2; private const int MENU_TAKE = 3; private const int MENU_END = 3; // audio bits AudioClip moveSound; AudioClip selectSound; AudioClip pickupSound; AudioClip gameCompleteSound; AudioClip missionStartSound; AudioClip missionSuccessSound; AudioClip missionFailSound; void Awake() { bg = this.GetComponentInChildren<BackgroundMaker>(); bg.scale = Scale; missionNum = 0; finalMission = false; } // Use this for initialization void Start() { InitSounds(); InitFont(); InitGUI(); InitGame(); } void InitSounds() { this.gameObject.AddComponent<AudioSource>(); GetComponent<AudioSource>().maxDistance = 100; GetComponent<AudioSource>().minDistance = 0; GetComponent<AudioSource>().loop = false; GetComponent<AudioSource>().volume = 1; GetComponent<AudioSource>().playOnAwake = false; moveSound = Resources.Load("Sounds/move") as AudioClip; selectSound = Resources.Load("Sounds/select") as AudioClip; pickupSound = Resources.Load("Sounds/pickup") as AudioClip; gameCompleteSound = Resources.Load("Sounds/game-complete") as AudioClip; missionStartSound = Resources.Load("Sounds/mission-start") as AudioClip; missionSuccessSound = Resources.Load("Sounds/mission-success") as AudioClip; missionFailSound = Resources.Load("Sounds/mission-fail") as AudioClip; } void NextTurn(bool firstTurn = false) { map.UpdateEntities(entities); if (entsToProcess.Count == 0) { entsToProcess = new Stack<Entity>(); // add non-players first foreach (var ent in entities) if (ent != player) entsToProcess.Push(ent); // player gets first move entsToProcess.Push(player); } turnEnt = entsToProcess.Pop(); turnEnt.AP = turnEnt.MaxAP; if (turnEnt == player) { state = State.PlayerSelectAction; playerMenuItem = 0; CheckPlayerHasVisionOnEnemy(); CheckForItemsInRange(); CentreCameraOnEntity(player); DisplayPlayerTurnGUI(); } else // ai { if (map.HasVision(turnEnt.Position, player.Position)) CentreCameraOnEntity(turnEnt); nextAIMove = Time.time + timeBetweenAIMoves; state = State.AIActions; DisplayAITurnGUI(); } } void DisplayPlayerTurnGUI() { gui.RefreshGUI(); gui.AddWindow(96, 190, 70, 34, Color.gray); gui.AddWindow(98, 192, 66, 30, Color.blue); gui.AddText("YOUR TURN", 100, 208, Color.white); gui.AddText("AP:", 100, 194, Color.white); gui.AddText(player.AP.ToString(), 121, 194, Color.green); gui.AddText("HP:", 135, 194, Color.white); gui.AddText(player.Health.ToString(), 156, 194, Color.green); if (state == State.PlayerSelectAction) { gui.AddWindow(6, 126, 36, 80, Color.gray); gui.AddWindow(8, 128, 32, 76, Color.blue); var textColors = new Color[4] { Color.white, Color.gray, Color.white, Color.gray }; if (enemyInSight) { textColors[MENU_FIRE] = Color.white; if (!player.CanFire()) { textColors[MENU_FIRE] = Color.red; if (playerMenuItem == MENU_FIRE) // if you were on fire but cant fire playerMenuItem = MENU_MOVE; // go back to move action } } if (itemInRange) textColors[MENU_TAKE] = Color.white; else if (playerMenuItem == MENU_TAKE) playerMenuItem = MENU_MOVE; textColors[playerMenuItem] = Color.yellow; gui.AddText("MOVE", 10, 190, textColors[MENU_MOVE]); gui.AddText("FIRE", 10, 170, textColors[MENU_FIRE]); gui.AddText("WAIT", 10, 150, textColors[MENU_WAIT]); gui.AddText("TAKE", 10, 130, textColors[MENU_TAKE]); var y = 188 - (playerMenuItem * 20); gui.AddTexture(Resources.Load("Textures/menu-select-arrow") as Texture2D, 42, y); } else if (state == State.PlayerMove) { gui.AddWindow(1, 190, 40, 34, Color.gray); gui.AddWindow(3, 192, 36, 30, Color.blue); gui.AddText("MOVE:", 5, 208, Color.white); gui.AddText(" 1AP ", 5, 194, Color.white); } else if (state == State.PlayerTarget) { gui.AddWindow(1, 176, 40, 48, Color.gray); gui.AddWindow(3, 178, 36, 44, Color.blue); gui.AddText("FIRE:", 5, 208, Color.white); gui.AddText(" " + player.Weapon.APCost + "AP ", 5, 194, Color.white); gui.AddText(" " + player.ChanceToHit(entitiesInSight[playerTargeting]).ToString() + "%", 5, 180, Color.white); gui.AddText("PLAYER", 5, 44, Color.blue); gui.AddText(player.Weapon.Name, 5, 31, Color.white); gui.AddText("RNG: " + player.Weapon.MaxRange, 5, 18, Color.white); gui.AddText("DMG: " + player.Weapon.Damage, 5, 5, Color.white); var targeted = entitiesInSight[playerTargeting]; gui.AddText(targeted.Name, 150, 31, Color.red); gui.AddText(targeted.Weapon.Name, 150, 18, Color.white); gui.AddText("HEALTH: " + targeted.Health, 150, 5, Color.white); } else if (state == State.PlayerSelectItem) { gui.AddWindow(1, 190, 40, 34, Color.gray); gui.AddWindow(3, 192, 36, 30, Color.blue); gui.AddText("TAKE:", 5, 208, Color.white); gui.AddText(" 1AP ", 5, 194, Color.white); var item = ItemUnderCursor(); if (item != null) gui.AddText(item.Name, 5, 5, Color.white); } if (exitEnabled) { gui.AddWindow(179, 204, 76, 20, Color.gray); gui.AddWindow(181, 206, 72, 16, Color.blue); gui.AddText("FIND EXIT!", 183, 208, Color.yellow); } if (state != State.PlayerTarget && state != State.PlayerSelectItem) { gui.AddText("PLAYER", 5, 18, Color.white); gui.AddText(player.Weapon.Name, 5, 5, Color.white); } } Item ItemUnderCursor() { Item pickup = null; foreach (var item in items) if (item.Position == overlay.Position) pickup = item; return pickup; } void DisplayMissionGUI() { gui.RefreshGUI(); gui.AddWindow(12, 143, 234, 67, Color.gray); gui.AddWindow(14, 145, 230, 63, Color.blue); gui.AddText(map.Name, 18, 193, Color.green); gui.AddText(map.Brief1, 18, 177, Color.white); gui.AddText(map.Brief2, 18, 164, Color.white); gui.AddText("PRESS SPACE TO BEGIN", 57, 147, Color.white); gui.AddWindow(12, 11, 234, 59, Color.gray); gui.AddWindow(14, 13, 230, 55, Color.blue); gui.AddText("CONTROLS:", 18, 54, Color.white); gui.AddText("ARROW KEYS: MOVE/TARGET/SELECT", 18, 41, Color.white); gui.AddText("SPACE: ACCEPT", 18, 28, Color.white); gui.AddText("LEFT CONTROL: CANCEL", 18, 15, Color.white); } void DisplayAITurnGUI() { gui.RefreshGUI(); gui.AddWindow(99, 205, 63, 20, Color.gray); gui.AddWindow(101, 207, 59, 16, Color.blue); gui.AddText("CPU TURN", 103, 209, Color.white); if (map.HasVision(turnEnt.Position, player.Position)) { gui.AddText(turnEnt.Name, 5, 31, Color.white); gui.AddText(turnEnt.Weapon.Name, 5, 18, Color.white); gui.AddText("HEALTH: " + turnEnt.Health, 5, 5, Color.white); } } void DisplayGameCompleteGUI() { gui.RefreshGUI(); gui.AddWindow(44, 131, 165, 37, Color.black); gui.AddWindow(46, 133, 161, 33, Color.white); gui.AddWindow(48, 135, 157, 29, Color.blue); gui.AddText("YOU WIN!!", 100, 150, Color.green); gui.AddText("THANK YOU FOR PLAYING!", 50, 137, Color.white); } void DisplayGameOverGUI() { gui.RefreshGUI(); gui.AddWindow(46, 133, 161, 33, Color.red); gui.AddWindow(48, 135, 157, 29, Color.black); gui.AddText("GAME OVER", 100, 150, Color.red); gui.AddText(" PRESS SPACE TO RETRY", 50, 137, Color.white); } void InitFont() { font = new Font(); } void InitGUI() { var guiObj = new GameObject("GUI Layer"); guiObj.transform.parent = Camera.main.transform; gui = guiObj.AddComponent<GUILayer>(); gui.Scale = Scale; gui.Font = font; gui.transform.position = new Vector3(0f, 0f, -8f); overlay = new Overlay(TileSize, Scale); } void InitGame() { state = State.GameStarting; missionNum++; doc = new XmlDocument(); doc.LoadXml(MissionFile.text); itemInRange = false; enemyInSight = false; exitEnabled = false; InitMissionDetails(); InitMissionMap(); InitEntities(); CentreCameraOnEntity(player); if (missionNum == 1) GetComponent<AudioSource>().PlayOneShot(missionStartSound); } void InitMissionDetails() { var next = doc["mission"]["next-mission"]; if (next != null) { nextMissionFile = Resources.Load("Missions/" + next.InnerText) as TextAsset; } else finalMission = true; } void InitMissionMap() { var mapTex = doc["mission"]["map"]["texture"].InnerText; var tex = Resources.Load("Textures/" + mapTex) as Texture2D; bg.InitMap(tex); map = new Map(doc); } void InitEntities() { XmlNode entityNodes = doc["mission"]["entities"]; entities = new List<Entity>(); items = new List<Item>(); exits = new List<Exit>(); entsToProcess = new Stack<Entity>(); totalObjectives = 0; objectivesInHand = 0; foreach (XmlNode node in entityNodes) { var start = node.InnerText.Split(','); var loc = new Vector3(float.Parse(start[0]), float.Parse(start[1]), -1); if (node.Name == "player") { player = EntityFactory.MakePlayer(this.gameObject, loc, TileSize, Scale); entities.Add(player); // copied here for easier searching later } else if (node.Name == "secguard") entities.Add(EntityFactory.MakeSecurity(this.gameObject, loc, TileSize, Scale)); else if (node.Name == "soldier") entities.Add(EntityFactory.MakeSoldier(this.gameObject, loc, TileSize, Scale)); else if (node.Name == "agent") entities.Add(EntityFactory.MakeAgent(this.gameObject, loc, TileSize, Scale)); else if (node.Name == "documents") { SpawnItem(ItemType.Document, loc); totalObjectives++; } else if (node.Name == "exit") { var exitObj = new GameObject("Exit"); var exit = exitObj.AddComponent<Exit>(); exit.TileSize = TileSize; exit.Scale = Scale; exit.SetPosition(loc); exits.Add(exit); } } } // convenience function for weapons mostly void SpawnItem(string type, Vector2 loc) { ItemType item = ItemType.Document; if (type == "Pistol") item = ItemType.Pistol; else if (type == "Silenced Pistol") item = ItemType.SilencedPistol; else if (type == "Rifle") item = ItemType.Rifle; SpawnItem(item, loc); } void SpawnItem(ItemType type, Vector2 loc) { var go = new GameObject("Item"); var item = go.AddComponent<Item>(); item.Type = type; var tileScale = TileSize * Scale; item.transform.position = new Vector3(loc.x * tileScale, loc.y * tileScale, -4); item.Position = loc; items.Add(item); } void EnableExits() { exitEnabled = true; foreach (var exit in exits) exit.EnableExit(); } void EndMission() { state = State.GameStarting; MissionFile = nextMissionFile; WipeScene(); if (finalMission) { state = State.GameComplete; GetComponent<AudioSource>().PlayOneShot(gameCompleteSound); } else { GetComponent<AudioSource>().PlayOneShot(missionSuccessSound); InitGame(); } } void WipeScene() { foreach (var e in entities) DestroyImmediate(e.gameObject); foreach (var e in exits) DestroyImmediate(e.gameObject); foreach (var i in items) DestroyImmediate(i.gameObject); entities.Clear(); exits.Clear(); items.Clear(); turnEnt = null; player = null; } // Update is called once per frame void Update() { if (state == State.MissionComplete) { EndMission(); return; } while (GameObject.Find("Bullet") != null) return; CheckForDeadEntities(); bool redraw = false; if (state == State.PlayerSelectAction && player.AP == 0) NextTurn(); #region Player Input if (state == State.GameStarting) { redraw = true; if (Input.GetKeyDown(AButton)) { NextTurn(true); } } else if (state == State.PlayerMove) { if (Input.GetKeyDown(KeyCode.RightArrow)) { AttemptMove(player, Vector2.right); redraw = true; } if (Input.GetKeyDown(KeyCode.LeftArrow)) { AttemptMove(player, -Vector2.right); redraw = true; } if (Input.GetKeyDown(KeyCode.UpArrow)) { AttemptMove(player, Vector2.up); redraw = true; } if (Input.GetKeyDown(KeyCode.DownArrow)) { AttemptMove(player, -Vector2.up); redraw = true; } if (redraw) // moved GetComponent<AudioSource>().PlayOneShot(moveSound); // cancel state if (Input.GetKeyDown(BButton)) { state = State.PlayerSelectAction; redraw = true; } } else if (state == State.PlayerSelectAction) { if (Input.GetKeyDown(AButton)) { if (playerMenuItem == MENU_MOVE) state = State.PlayerMove; if (playerMenuItem == MENU_FIRE) { InitTargeting(); } if (playerMenuItem == MENU_WAIT) { NextTurn(); return; } if (playerMenuItem == MENU_TAKE) { state = State.PlayerSelectItem; overlay.SetOverlayMode(OverlayMode.Selection); overlay.SetPosition(player.Position); overlay.SetHidden(false); } redraw = true; } if (Input.GetKeyDown(KeyCode.UpArrow)) { if (playerMenuItem > 0) { playerMenuItem--; if (playerMenuItem == MENU_FIRE && (!enemyInSight || !player.CanFire())) playerMenuItem--; } redraw = true; } if (Input.GetKeyDown(KeyCode.DownArrow)) { if (playerMenuItem < MENU_END) { playerMenuItem++; if (playerMenuItem == MENU_FIRE && (!enemyInSight || !player.CanFire())) playerMenuItem++; if (playerMenuItem == MENU_TAKE && !itemInRange) playerMenuItem--; } redraw = true; } } else if (state == State.PlayerTarget) { if (Input.GetKeyDown(BButton)) { overlay.SetHidden(true); state = State.PlayerSelectAction; redraw = true; } else if (Input.GetKeyDown(KeyCode.RightArrow)) { MoveOverlayToNextTarget(1); redraw = true; } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { MoveOverlayToNextTarget(-1); redraw = true; } else if (Input.GetKeyDown(AButton)) { var ent = entitiesInSight[playerTargeting]; player.Attack(ent); if (player.AP < 1) { overlay.SetHidden(true); NextTurn(); } if (!player.CanFire()) { overlay.SetHidden(true); state = State.PlayerSelectAction; } if (ent.State == EntState.Dead) KillEntity(ent); // no enemies in sight, leave targeting mode (relevant with rifles) if (entitiesInSight == null || entitiesInSight.Count < 1) state = State.PlayerSelectAction; redraw = true; } } else if (state == State.PlayerSelectItem) { if (Input.GetKeyDown(BButton)) { state = State.PlayerSelectAction; overlay.SetHidden(true); redraw = true; } if (Input.GetKeyDown(KeyCode.RightArrow)) { if (overlay.Position.y == player.Position.y && overlay.Position.x < player.Position.x + 1) overlay.Move(Vector2.right); redraw = true; } if (Input.GetKeyDown(KeyCode.LeftArrow)) { if (overlay.Position.y == player.Position.y && overlay.Position.x > player.Position.x - 1) overlay.Move(-Vector2.right); redraw = true; } if (Input.GetKeyDown(KeyCode.DownArrow)) { if (overlay.Position.x == player.Position.x && overlay.Position.y > player.Position.y - 1) overlay.Move(-Vector2.up); redraw = true; } if (Input.GetKeyDown(KeyCode.UpArrow)) { if (overlay.Position.x == player.Position.x && overlay.Position.y < player.Position.y + 1) overlay.Move(Vector2.up); redraw = true; } if (redraw) // moved GetComponent<AudioSource>().PlayOneShot(selectSound); if (Input.GetKeyDown(AButton)) { var pickup = ItemUnderCursor(); if (pickup != null) { GetComponent<AudioSource>().PlayOneShot(pickupSound); if (pickup.Type == ItemType.Document) { objectivesInHand++; if (objectivesInHand >= totalObjectives) EnableExits(); } else if (pickup.Type == ItemType.Pistol) { SpawnItem(player.Weapon.Name, player.Position); player.Weapon = new Pistol(); } else if (pickup.Type == ItemType.Rifle) { SpawnItem(player.Weapon.Name, player.Position); player.Weapon = new Rifle(); } player.TakeItem(pickup); items.Remove(pickup); Destroy(pickup.gameObject); state = State.PlayerSelectAction; redraw = true; overlay.SetHidden(true); } } } else if (state == State.GameOver) { redraw = true; if (Input.GetKey(AButton)) { WipeScene(); InitGame(); } } else if (state == State.GameComplete) { redraw = true; } #endregion #region AI if (state == State.AIActions) { bool doTurn = false; if (map.HasVision(player.Position, turnEnt.Position)) { if (Time.time > nextAIMove) { nextAIMove = Time.time + timeBetweenAIMoves; doTurn = true; } } else doTurn = true; if (doTurn) turnEnt.DoAITurn(map, player); if (turnEnt.AP < Entity.MOVE_AP_COST) { Debug.Log("turn ends for " + turnEnt.Name); NextTurn(); } } #endregion if (redraw) { CheckPlayerHasVisionOnEnemy(); CheckEnemiesHaveVisionOnPlayer(); CheckForItemsInRange(); if (state == State.GameStarting) DisplayMissionGUI(); else if (state == State.AIActions) DisplayAITurnGUI(); else if (state == State.GameOver) DisplayGameOverGUI(); else if (state == State.GameComplete) DisplayGameCompleteGUI(); else DisplayPlayerTurnGUI(); } } void CheckForItemsInRange() { itemInRange = false; foreach (var item in items) { if (Vector2.Distance(player.Position, item.Position) <= 1.01f) itemInRange = true; } } void CheckForDeadEntities() { var deadEnts = new List<Entity>(); foreach (var ent in entities) if (ent.State == EntState.Dead) deadEnts.Add(ent); foreach (var dead in deadEnts) KillEntity(dead); } void KillEntity(Entity ent) { // add blood? if (ent != player) { SpawnItem(ent.Weapon.Name, ent.Position); entitiesInSight.Remove(ent); entities.Remove(ent); // remove ent from turn stack // temp push/pop it to another stack // don't push the dead ent back var tempStack = new Stack<Entity>(); while (entsToProcess.Count > 0) { if (entsToProcess.Peek() != ent) tempStack.Push(entsToProcess.Pop()); else { // skipped dead ent, we can push back from temp now entsToProcess.Pop(); break; } } while (tempStack.Count > 0) entsToProcess.Push(tempStack.Pop()); Destroy(ent.gameObject); } else { state = State.GameOver; GetComponent<AudioSource>().PlayOneShot(missionFailSound); } } void MoveOverlayToNextTarget(int direction) { playerTargeting += direction; if (playerTargeting < 0) playerTargeting = entitiesInSight.Count - 1; if (playerTargeting > entitiesInSight.Count - 1) playerTargeting = 0; overlay.SetPosition(entitiesInSight[playerTargeting].Position); } void InitTargeting() { entitiesInSight = new List<Entity>(); foreach (var e in entities) { if (e == player) continue; if (map.HasVision(player.Position, e.Position) && Vector2.Distance(player.Position, e.Position) < player.Weapon.MaxRange) entitiesInSight.Add(e); } if (entitiesInSight.Count > 0) { playerTargeting = 0; state = State.PlayerTarget; overlay.SetOverlayMode(OverlayMode.Targeting); overlay.SetHidden(false); overlay.SetPosition(entitiesInSight[playerTargeting].Position); } else state = State.PlayerSelectAction; } void AttemptMove(Entity ent, Vector2 move) { var check = ent.Position + move; if (ent.AP >= Entity.MOVE_AP_COST && map.IsInBounds(check) && !map.IsCover(check) && !EntityAt(check)) ent.Walk(move); map.UpdateEntities(entities); if (exitEnabled && PlayerOnExit()) state = State.MissionComplete; else { CentreCameraOnEntity(player); if (ent.AP == 0) NextTurn(); } } bool PlayerOnExit() { foreach (var exit in exits) if (player.Position == exit.Position) return true; return false; } bool EntityAt(Vector2 pos) { foreach (var ent in entities) if (ent.Position == pos) return true; return false; } void CentreCameraOnEntity(Entity ent) { var pos = ent.Position; Camera.main.transform.position = (new Vector3(pos.x, pos.y, 0) * TileSize * Scale); Camera.main.transform.position += new Vector3(0, 0, -10); } void CheckEnemiesHaveVisionOnPlayer() { foreach (var e in entities) { if (e == player) continue; if (map.HasVision(e.Position, player.Position)) { if (e.State == EntState.Investigate) { e.State = EntState.Active; e.SetEntityStateTex(); } if (e.State == EntState.Idle) { e.State = EntState.Awake; e.SetEntityStateTex(); } e.Goal = player.Position; } } } bool CheckPlayerHasVisionOnEnemy() { enemyInSight = false; foreach (var e in entities) { if (e == player) continue; if (map.HasVision(player.Position, e.Position)) { enemyInSight = true; e.InSight = true; } else { e.InSight = false; } } return false; } }
/******************************************************************** 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. *********************************************************************/ #region license /* DirectShowLib - Provide access to DirectShow interfaces via .NET Copyright (C) 2006 http://sourceforge.net/projects/directshownet/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion using System; using System.Runtime.InteropServices; #if !USING_NET11 using System.Runtime.InteropServices.ComTypes; #endif namespace DirectShowLib.BDA { #region Declarations /// <summary> /// From CLSID_TIFLoad /// </summary> [ComImport, Guid("14EB8748-1753-4393-95AE-4F7E7A87AAD6")] public class TIFLoad { } #endregion #region Interfaces #if ALLOW_UNTESTED_INTERFACES [ComImport, Guid("DFEF4A68-EE61-415f-9CCB-CD95F2F98A3A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IBDA_TIF_REGISTRATION { [PreserveSig] int RegisterTIFEx( [In] IPin pTIFInputPin, [In, Out] ref int ppvRegistrationContext, [In, Out, MarshalAs(UnmanagedType.Interface)] ref object ppMpeg2DataControl ); [PreserveSig] int UnregisterTIF([In] int pvRegistrationContext); } [ComImport, Guid("F9BAC2F9-4149-4916-B2EF-FAA202326862"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMPEG2_TIF_CONTROL { [PreserveSig] int RegisterTIF( [In, MarshalAs(UnmanagedType.Interface)] object pUnkTIF, [In, Out] ref int ppvRegistrationContext ); [PreserveSig] int UnregisterTIF([In] int pvRegistrationContext); [PreserveSig] int AddPIDs( [In] int ulcPIDs, [In] ref int pulPIDs ); [PreserveSig] int DeletePIDs( [In] int ulcPIDs, [In] ref int pulPIDs ); [PreserveSig] int GetPIDCount([Out] out int pulcPIDs); [PreserveSig] int GetPIDs( [Out] out int pulcPIDs, [Out] out int pulPIDs ); } [ComImport, Guid("A3B152DF-7A90-4218-AC54-9830BEE8C0B6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITuneRequestInfo { [PreserveSig] int GetLocatorData([In] ITuneRequest Request); [PreserveSig] int GetComponentData([In] ITuneRequest CurrentRequest); [PreserveSig] int CreateComponentList([In] ITuneRequest CurrentRequest); [PreserveSig] int GetNextProgram( [In] ITuneRequest CurrentRequest, [Out] out ITuneRequest TuneRequest ); [PreserveSig] int GetPreviousProgram( [In] ITuneRequest CurrentRequest, [Out] out ITuneRequest TuneRequest ); [PreserveSig] int GetNextLocator( [In] ITuneRequest CurrentRequest, [Out] out ITuneRequest TuneRequest ); [PreserveSig] int GetPreviousLocator( [In] ITuneRequest CurrentRequest, [Out] out ITuneRequest TuneRequest ); } [ComImport, Guid("EFDA0C80-F395-42c3-9B3C-56B37DEC7BB7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IGuideDataEvent { [PreserveSig] int GuideDataAcquired(); [PreserveSig] int ProgramChanged([In] object varProgramDescriptionID); [PreserveSig] int ServiceChanged([In] object varProgramDescriptionID); [PreserveSig] int ScheduleEntryChanged([In] object varProgramDescriptionID); [PreserveSig] int ProgramDeleted([In] object varProgramDescriptionID); [PreserveSig] int ServiceDeleted([In] object varProgramDescriptionID); [PreserveSig] int ScheduleDeleted([In] object varProgramDescriptionID); } [ComImport, Guid("88EC5E58-BB73-41d6-99CE-66C524B8B591"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IGuideDataProperty { [PreserveSig] int get_Name([Out, MarshalAs(UnmanagedType.BStr)] out string pbstrName); [PreserveSig] int get_Language([Out] out int idLang); [PreserveSig] int get_Value([Out] out object pvar); } [ComImport, Guid("AE44423B-4571-475c-AD2C-F40A771D80EF"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumGuideDataProperties { [PreserveSig] int Next( [In] int celt, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] IGuideDataProperty [] ppprop, [Out] out int pcelt ); [PreserveSig] int Skip([In] int celt); [PreserveSig] int Reset(); [PreserveSig] int Clone([Out] out IEnumGuideDataProperties ppenum); } [ComImport, Guid("1993299C-CED6-4788-87A3-420067DCE0C7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumTuneRequests { [PreserveSig] int Next( [In] int celt, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ITuneRequest[] ppprop, [Out] out int pcelt ); [PreserveSig] int Skip([In] int celt); [PreserveSig] int Reset(); [PreserveSig] int Clone([Out] out IEnumTuneRequests ppenum); } [ComImport, Guid("61571138-5B01-43cd-AEAF-60B784A0BF93"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IGuideData { [PreserveSig] int GetServices([Out] out IEnumTuneRequests ppEnumTuneRequests); [PreserveSig] int GetServiceProperties( [In] ITuneRequest pTuneRequest, [Out] out IEnumGuideDataProperties ppEnumProperties ); [PreserveSig] #if USING_NET11 int GetGuideProgramIDs([Out] out UCOMIEnumVARIANT pEnumPrograms); #else int GetGuideProgramIDs([Out] out IEnumVARIANT pEnumPrograms); #endif [PreserveSig] int GetProgramProperties( [In] object varProgramDescriptionID, [Out] out IEnumGuideDataProperties ppEnumProperties ); [PreserveSig] #if USING_NET11 int GetScheduleEntryIDs([Out] out UCOMIEnumVARIANT pEnumScheduleEntries); #else int GetScheduleEntryIDs([Out] out IEnumVARIANT pEnumScheduleEntries); #endif [PreserveSig] int GetScheduleEntryProperties( [In] object varScheduleEntryDescriptionID, [Out] out IEnumGuideDataProperties ppEnumProperties ); } [ComImport, Guid("4764ff7c-fa95-4525-af4d-d32236db9e38"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IGuideDataLoader { [PreserveSig] int Init([In] IGuideData pGuideStore); [PreserveSig] int Terminate(); } #endif #endregion }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved. *******************************************************************************/ using UnityEngine; using System.Collections; using RSUnityToolkit; /// <summary> /// This class draw the video feed of the selected image type on the associated game object /// </summary> public class DrawImages : MonoBehaviour { #region Public Fields /// <summary> /// The outputs stream (depth, color, etc) /// </summary> public PXCMCapture.StreamType StreamOut = PXCMCapture.StreamType.STREAM_TYPE_COLOR; #endregion #region Private Fields private PXCMSizeI32 size=new PXCMSizeI32(); private Texture2D _texture=null; private PXCMCapture.StreamType _lastSetStream; #endregion #region Private methods /// <summary> /// Sets the sense option according to the Stream field /// </summary> private void SetSenseOptions() { switch (StreamOut) { case PXCMCapture.StreamType.STREAM_TYPE_COLOR: SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.VideoColorStream); break; case PXCMCapture.StreamType.STREAM_TYPE_DEPTH: SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.VideoDepthStream); break; case PXCMCapture.StreamType.STREAM_TYPE_IR: SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.VideoIRStream); break; } } /// <summary> /// Unsets the sense option according to the Stream field /// </summary> private void UnsetSenseOptions() { switch (_lastSetStream) { case PXCMCapture.StreamType.STREAM_TYPE_COLOR: SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.VideoColorStream); break; case PXCMCapture.StreamType.STREAM_TYPE_DEPTH: SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.VideoDepthStream); break; case PXCMCapture.StreamType.STREAM_TYPE_IR: SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.VideoIRStream); break; } } /// <summary> /// Sets the texture for the associated game object with the given image /// </summary> /// <param name='image'> /// Image. /// </param> private void SetTexture(PXCMImage image) { if (image == null) { return; } if (_texture==null) { /* Save size and preallocate the Texture2D */ size.width=image.info.width; size.height=image.info.height; _texture = new Texture2D((int)size.width, (int)size.height, TextureFormat.ARGB32, false); /* Associate the texture to the game object */ GetComponent<Renderer>().sharedMaterial.mainTexture = _texture; } /* Retrieve the image data */ PXCMImage.ImageData data; pxcmStatus sts=image.AcquireAccess(PXCMImage.Access.ACCESS_READ,PXCMImage.PixelFormat.PIXEL_FORMAT_RGB32,out data); if ( sts >= pxcmStatus.PXCM_STATUS_NO_ERROR) { data.ToTexture2D(0, _texture); image.ReleaseAccess(data); /* and display it */ _texture.Apply(); } } #endregion #region Unity's overridden methods // Initializaition void Start () { var senseManager = GameObject.FindObjectOfType(typeof(SenseToolkitManager)); if (senseManager == null) { Debug.LogWarning("Sense Manager Object not found and was added automatically"); senseManager = (GameObject)Instantiate(Resources.Load("SenseManager")); senseManager.name = "SenseManager"; } /* Reset image size */ size.width=size.height=0; _lastSetStream = StreamOut; SetSenseOptions(); } // Update is called once per frame void Update () { if (SenseToolkitManager.Instance == null) { return; } if (_lastSetStream != StreamOut) { _texture = null; UnsetSenseOptions(); SetSenseOptions(); _lastSetStream = StreamOut; } if (SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.VideoColorStream) || SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.VideoDepthStream) || SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.VideoIRStream)) { if ( !SenseToolkitManager.Instance.Initialized ) return; if (SenseToolkitManager.Instance.Initialized) { PXCMImage image = null; if (StreamOut == PXCMCapture.StreamType.STREAM_TYPE_COLOR) { image = SenseToolkitManager.Instance.ImageRgbOutput; } if (StreamOut == PXCMCapture.StreamType.STREAM_TYPE_DEPTH) { image = SenseToolkitManager.Instance.ImageDepthOutput; } if (StreamOut == PXCMCapture.StreamType.STREAM_TYPE_IR) { image = SenseToolkitManager.Instance.ImageIROutput; } SetTexture(image); } } } // On Enable Set Sense Options void OnEnable() { if (SenseToolkitManager.Instance == null) { return; } SetSenseOptions(); } // On Disable unset Sense Options void OnDisable() { UnsetSenseOptions(); } #endregion }
#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; #if !(PORTABLE || PORTABLE40 || NET35 || NET20) using System.Numerics; #endif using System.Reflection; using System.Collections; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { #if (NETFX_CORE || PORTABLE || PORTABLE40) internal enum MemberTypes { Property = 0, Field = 1, Event = 2, Method = 3, Other = 4 } #endif #if NETFX_CORE || PORTABLE [Flags] internal enum BindingFlags { Default = 0, IgnoreCase = 1, DeclaredOnly = 2, Instance = 4, Static = 8, Public = 16, NonPublic = 32, FlattenHierarchy = 64, InvokeMethod = 256, CreateInstance = 512, GetField = 1024, SetField = 2048, GetProperty = 4096, SetProperty = 8192, PutDispProperty = 16384, ExactBinding = 65536, PutRefDispProperty = 32768, SuppressChangeType = 131072, OptionalParamBinding = 262144, IgnoreReturn = 16777216 } #endif internal static class ReflectionUtils { public static readonly Type[] EmptyTypes; static ReflectionUtils() { #if !(NETFX_CORE || PORTABLE40 || PORTABLE) EmptyTypes = Type.EmptyTypes; #else EmptyTypes = new Type[0]; #endif } public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null && m.IsVirtual) return true; m = propertyInfo.GetSetMethod(); if (m != null && m.IsVirtual) return true; return false; } public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null) return m.GetBaseDefinition(); m = propertyInfo.GetSetMethod(); if (m != null) return m.GetBaseDefinition(); return null; } public static bool IsPublic(PropertyInfo property) { if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) return true; if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) return true; return false; } public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder) { string fullyQualifiedTypeName; #if !(NET20 || NET35) if (binder != null) { string assemblyName, typeName; binder.BindToName(t, out assemblyName, out typeName); fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName); } else { fullyQualifiedTypeName = t.AssemblyQualifiedName; } #else fullyQualifiedTypeName = t.AssemblyQualifiedName; #endif switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return RemoveAssemblyDetails(fullyQualifiedTypeName); case FormatterAssemblyStyle.Full: return fullyQualifiedTypeName; default: throw new ArgumentOutOfRangeException(); } } private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) { StringBuilder builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) bindingFlags = bindingFlags | BindingFlags.NonPublic; return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any()); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) ? Nullable.GetUnderlyingType(t) : t; } public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition) { if (!type.IsGenericType()) return false; Type t = type.GetGenericTypeDefinition(); return (t == genericInterfaceDefinition); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface()) { if (type.IsGenericType()) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (Type i in type.GetInterfaces()) { if (i.IsGenericType()) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType()) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType() == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } if (typeof(IEnumerable).IsAssignableFrom(type)) { return null; } throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; case MemberTypes.Method: return ((MethodInfo)member).ReturnType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo, EventInfo or MethodInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo)member).GetGetMethod().Invoke(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).GetSetMethod().Invoke(target, new object[]{ value }); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) { switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsLiteral) return false; if (fieldInfo.IsInitOnly && !canSetReadOnly) return false; if (nonPublic) return true; if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List<MemberInfo> targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count); foreach (var groupedMember in targetMembers.GroupBy(m => m.Name)) { int count = groupedMember.Count(); IList<MemberInfo> members = groupedMember.ToList(); if (count == 1) { distinctMembers.Add(members.First()); } else { IList<MemberInfo> resolvedMembers = new List<MemberInfo>(); foreach (MemberInfo memberInfo in members) { // this is a bit hacky // if the hiding property is hiding a base property and it is virtual // then this ensures the derived property gets used if (resolvedMembers.Count == 0) resolvedMembers.Add(memberInfo); else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item") resolvedMembers.Add(memberInfo); } distinctMembers.AddRange(resolvedMembers); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType() != MemberTypes.Property) return false; PropertyInfo propertyInfo = (PropertyInfo)memberInfo; if (!IsVirtual(propertyInfo)) return false; Type declaringType = propertyInfo.DeclaringType; if (!declaringType.IsGenericType()) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(object attributeProvider) where T : Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(object attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return (attributes != null) ? attributes.FirstOrDefault() : null; } #if !(NETFX_CORE || PORTABLE) public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute { Attribute[] a = GetAttributes(attributeProvider, typeof(T), inherit); T[] attributes = a as T[]; if (attributes != null) return attributes; return a.Cast<T>().ToArray(); } public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit) { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); object provider = attributeProvider; // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (provider is Type) { Type t = (Type)provider; object[] a = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit); Attribute[] attributes = a.Cast<Attribute>().ToArray(); #if (NET20 || NET35) // ye olde .NET GetCustomAttributes doesn't respect the inherit argument if (inherit && t.BaseType != null) attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray(); #endif return attributes; } if (provider is Assembly) { Assembly a = (Assembly)provider; return (attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a); } if (provider is MemberInfo) { MemberInfo m = (MemberInfo)provider; return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit); } #if !PORTABLE40 if (provider is Module) { Module m = (Module)provider; return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit); } #endif if (provider is ParameterInfo) { ParameterInfo p = (ParameterInfo)provider; return (attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit); } #if !PORTABLE40 ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider; object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit); return (Attribute[])result; #else throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); #endif } #else public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute { return GetAttributes(attributeProvider, typeof(T), inherit).Cast<T>().ToArray(); } public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit) { if (provider is Type) { Type t = (Type)provider; return (attributeType != null) ? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray() : t.GetTypeInfo().GetCustomAttributes(inherit).ToArray(); } if (provider is Assembly) { Assembly a = (Assembly)provider; return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray(); } if (provider is MemberInfo) { MemberInfo m = (MemberInfo)provider; return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray(); } if (provider is Module) { Module m = (Module)provider; return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray(); } if (provider is ParameterInfo) { ParameterInfo p = (ParameterInfo)provider; return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray(); } throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); } #endif public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch (memberInfo.MemberType()) { case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)memberInfo; Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(); return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); default: return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault(); } } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); #if !(NETFX_CORE || PORTABLE) // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); #endif return fieldInfos.Cast<FieldInfo>(); } #if !(NETFX_CORE || PORTABLE) private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType()) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } #endif public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr)); // GetProperties on an interface doesn't return properties from its interfaces if (targetType.IsInterface()) { foreach (Type i in targetType.GetInterfaces()) { propertyInfos.AddRange(i.GetProperties(bindingAttr)); } } GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); // a base class private getter/setter will be inaccessable unless the property was gotten from the base class for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); propertyInfos[i] = declaredMember; } } return propertyInfos; } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result // also find base properties that have been hidden by subtype properties with the same name while ((targetType = targetType.BaseType()) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr)) { PropertyInfo subTypeProperty = propertyInfo; if (!IsPublic(subTypeProperty)) { // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name); if (index == -1) { initialProperties.Add(subTypeProperty); } else { PropertyInfo childProperty = initialProperties[index]; // don't replace public child with private base if (!IsPublic(childProperty)) { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = subTypeProperty; } } } else { if (!subTypeProperty.IsVirtual()) { int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.DeclaringType == subTypeProperty.DeclaringType); if (index == -1) initialProperties.Add(subTypeProperty); } else { int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.IsVirtual() && p.GetBaseDefinition() != null && p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.DeclaringType)); if (index == -1) initialProperties.Add(subTypeProperty); } } } } } public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) { bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Any(info => info.Name == method && // check that the method overrides the original on DynamicObjectProxy info.DeclaringType != methodDeclaringType && info.GetBaseDefinition().DeclaringType == methodDeclaringType ); return isMethodOverriden; } public static object GetDefaultValue(Type type) { if (!type.IsValueType()) return null; switch (ConvertUtils.GetTypeCode(type)) { case PrimitiveTypeCode.Boolean: return false; case PrimitiveTypeCode.Char: case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: return 0; case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: return 0L; case PrimitiveTypeCode.Single: return 0f; case PrimitiveTypeCode.Double: return 0.0; case PrimitiveTypeCode.Decimal: return 0m; case PrimitiveTypeCode.DateTime: return new DateTime(); #if !(PORTABLE || PORTABLE40 || NET35 || NET20) case PrimitiveTypeCode.BigInteger: return new BigInteger(); #endif case PrimitiveTypeCode.Guid: return new Guid(); #if !NET20 case PrimitiveTypeCode.DateTimeOffset: return new DateTimeOffset(); #endif } if (IsNullable(type)) return null; // possibly use IL initobj for perf here? return Activator.CreateInstance(type); } } }
/* * 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.Specialized; using System.Threading; using System.Collections.Generic; using Apache.NMS.Stomp.Commands; using Apache.NMS.Stomp.Util; using Apache.NMS.Util; namespace Apache.NMS.Stomp { public enum AckType { ConsumedAck = 1, // Message consumed, discard IndividualAck = 2 // Only the given message is to be treated as consumed. } /// <summary> /// An object capable of receiving messages from some destination /// </summary> public class MessageConsumer : IMessageConsumer, IDispatcher { private readonly MessageTransformation messageTransformation; private readonly MessageDispatchChannel unconsumedMessages = new MessageDispatchChannel(); private readonly LinkedList<MessageDispatch> dispatchedMessages = new LinkedList<MessageDispatch>(); private readonly ConsumerInfo info; private Session session; private MessageAck pendingAck = null; private readonly Atomic<bool> started = new Atomic<bool>(); private readonly Atomic<bool> deliveringAcks = new Atomic<bool>(); protected bool disposed = false; private int deliveredCounter = 0; private int additionalWindowSize = 0; private long redeliveryDelay = 0; private int dispatchedCount = 0; private volatile bool synchronizationRegistered = false; private bool clearDispatchList = false; private bool inProgressClearRequiredFlag; private event MessageListener listener; private IRedeliveryPolicy redeliveryPolicy; private Exception failureError; // Constructor internal to prevent clients from creating an instance. internal MessageConsumer(Session session, ConsumerId id, Destination destination, string name, string selector, int prefetch, bool noLocal) { if(destination == null) { throw new InvalidDestinationException("Consumer cannot receive on Null Destinations."); } this.session = session; this.redeliveryPolicy = this.session.Connection.RedeliveryPolicy; this.messageTransformation = this.session.Connection.MessageTransformation; this.info = new ConsumerInfo(); this.info.ConsumerId = id; this.info.Destination = Destination.Transform(destination); this.info.SubscriptionName = name; this.info.Selector = selector; this.info.PrefetchSize = prefetch; this.info.MaximumPendingMessageLimit = session.Connection.PrefetchPolicy.MaximumPendingMessageLimit; this.info.NoLocal = noLocal; this.info.DispatchAsync = session.DispatchAsync; this.info.Retroactive = session.Retroactive; this.info.Exclusive = session.Exclusive; this.info.Priority = session.Priority; this.info.AckMode = session.AcknowledgementMode; // If the destination contained a URI query, then use it to set public properties // on the ConsumerInfo if(destination.Options != null) { // Get options prefixed with "consumer.*" StringDictionary options = URISupport.GetProperties(destination.Options, "consumer."); // Extract out custom extension options "consumer.nms.*" StringDictionary customConsumerOptions = URISupport.ExtractProperties(options, "nms."); URISupport.SetProperties(this.info, options); URISupport.SetProperties(this, customConsumerOptions, "nms."); } } ~MessageConsumer() { Dispose(false); } #region Property Accessors public ConsumerId ConsumerId { get { return info.ConsumerId; } } public ConsumerInfo ConsumerInfo { get { return this.info; } } public int PrefetchSize { get { return this.info.PrefetchSize; } } public IRedeliveryPolicy RedeliveryPolicy { get { return this.redeliveryPolicy; } set { this.redeliveryPolicy = value; } } // Custom Options private bool ignoreExpiration = false; public bool IgnoreExpiration { get { return ignoreExpiration; } set { ignoreExpiration = value; } } #endregion #region IMessageConsumer Members private ConsumerTransformerDelegate consumerTransformer; public ConsumerTransformerDelegate ConsumerTransformer { get { return this.consumerTransformer; } set { this.consumerTransformer = value; } } public event MessageListener Listener { add { CheckClosed(); if(this.PrefetchSize == 0) { throw new NMSException("Cannot set Asynchronous Listener on a Consumer with a zero Prefetch size"); } bool wasStarted = this.session.Started; if(wasStarted == true) { this.session.Stop(); } listener += value; this.session.Redispatch(this.unconsumedMessages); if(wasStarted == true) { this.session.Start(); } } remove { listener -= value; } } public IMessage Receive() { CheckClosed(); CheckMessageListener(); MessageDispatch dispatch = this.Dequeue(TimeSpan.FromMilliseconds(-1)); if(dispatch == null) { return null; } BeforeMessageIsConsumed(dispatch); AfterMessageIsConsumed(dispatch, false); return CreateStompMessage(dispatch); } public IMessage Receive(TimeSpan timeout) { CheckClosed(); CheckMessageListener(); MessageDispatch dispatch = this.Dequeue(timeout); if(dispatch == null) { return null; } BeforeMessageIsConsumed(dispatch); AfterMessageIsConsumed(dispatch, false); return CreateStompMessage(dispatch); } public IMessage ReceiveNoWait() { CheckClosed(); CheckMessageListener(); MessageDispatch dispatch = this.Dequeue(TimeSpan.Zero); if(dispatch == null) { return null; } BeforeMessageIsConsumed(dispatch); AfterMessageIsConsumed(dispatch, false); return CreateStompMessage(dispatch); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if(disposed) { return; } if(disposing) { // Dispose managed code here. } try { Close(); } catch { // Ignore network errors. } disposed = true; } public void Close() { if(!this.unconsumedMessages.Closed) { if(this.session.IsTransacted && this.session.TransactionContext.InTransaction) { this.session.TransactionContext.AddSynchronization(new ConsumerCloseSynchronization(this)); } else { this.DoClose(); } } } internal void DoClose() { if(!this.unconsumedMessages.Closed) { Tracer.Debug("Closing down the Consumer"); if(!this.session.IsTransacted) { lock(this.dispatchedMessages) { dispatchedMessages.Clear(); } } this.unconsumedMessages.Close(); this.session.DisposeOf(this.info.ConsumerId); RemoveInfo removeCommand = new RemoveInfo(); removeCommand.ObjectId = this.info.ConsumerId; this.session.Connection.Oneway(removeCommand); this.session = null; Tracer.Debug("Consumer instnace Closed."); } } #endregion protected void DoIndividualAcknowledge(Message message) { MessageDispatch dispatch = null; lock(this.dispatchedMessages) { foreach(MessageDispatch originalDispatch in this.dispatchedMessages) { if(originalDispatch.Message.MessageId.Equals(message.MessageId)) { dispatch = originalDispatch; this.dispatchedMessages.Remove(originalDispatch); break; } } } if(dispatch == null) { Tracer.DebugFormat("Attempt to Ack MessageId[{0}] failed because the original dispatch is not in the Dispatch List", message.MessageId); return; } MessageAck ack = new MessageAck(); ack.AckType = (byte) AckType.IndividualAck; ack.ConsumerId = this.info.ConsumerId; ack.Destination = dispatch.Destination; ack.LastMessageId = dispatch.Message.MessageId; ack.MessageCount = 1; Tracer.Debug("Sending Individual Ack for MessageId: " + ack.LastMessageId.ToString()); this.session.SendAck(ack); } protected void DoNothingAcknowledge(Message message) { } protected void DoClientAcknowledge(Message message) { this.CheckClosed(); Tracer.Debug("Sending Client Ack:"); this.session.Acknowledge(); } public void Start() { if(this.unconsumedMessages.Closed) { return; } this.started.Value = true; this.unconsumedMessages.Start(); this.session.Executor.Wakeup(); } public void Stop() { this.started.Value = false; this.unconsumedMessages.Stop(); } internal void InProgressClearRequired() { inProgressClearRequiredFlag = true; // deal with delivered messages async to avoid lock contention with in progress acks clearDispatchList = true; } internal void ClearMessagesInProgress() { if(inProgressClearRequiredFlag) { // Called from a thread in the ThreadPool, so we wait until we can // get a lock on the unconsumed list then we clear it. lock(this.unconsumedMessages) { if(inProgressClearRequiredFlag) { if(Tracer.IsDebugEnabled) { Tracer.Debug(this.ConsumerId + " clearing dispatched list (" + this.unconsumedMessages.Count + ") on transport interrupt"); } this.unconsumedMessages.Clear(); this.synchronizationRegistered = false; // allow dispatch on this connection to resume this.session.Connection.TransportInterruptionProcessingComplete(); this.inProgressClearRequiredFlag = false; } } } } public void DeliverAcks() { MessageAck ack = null; if(this.deliveringAcks.CompareAndSet(false, true)) { if(pendingAck != null && pendingAck.AckType == (byte) AckType.ConsumedAck) { ack = pendingAck; pendingAck = null; } if(pendingAck != null) { MessageAck ackToSend = ack; try { this.session.SendAck(ackToSend); } catch(Exception e) { Tracer.DebugFormat("{0} : Failed to send ack, {1}", this.info.ConsumerId, e); } } else { this.deliveringAcks.Value = false; } } } public void Dispatch(MessageDispatch dispatch) { MessageListener listener = this.listener; try { lock(this.unconsumedMessages.SyncRoot) { if(this.clearDispatchList) { // we are reconnecting so lets flush the in progress messages this.clearDispatchList = false; this.unconsumedMessages.Clear(); if(this.pendingAck != null) { // on resumption a pending delivered ack will be out of sync with // re-deliveries. if(Tracer.IsDebugEnabled) { Tracer.Debug("removing pending delivered ack on transport interupt: " + pendingAck); } this.pendingAck = null; } } if(!this.unconsumedMessages.Closed) { if(listener != null && this.unconsumedMessages.Running) { Message message = CreateStompMessage(dispatch); this.BeforeMessageIsConsumed(dispatch); try { bool expired = (!IgnoreExpiration && message.IsExpired()); if(!expired) { listener(message); } this.AfterMessageIsConsumed(dispatch, expired); } catch(Exception e) { if(this.session.IsAutoAcknowledge || this.session.IsIndividualAcknowledge) { // Redeliver the message } else { // Transacted or Client ack: Deliver the next message. this.AfterMessageIsConsumed(dispatch, false); } Tracer.Error(this.info.ConsumerId + " Exception while processing message: " + e); } } else { this.unconsumedMessages.Enqueue(dispatch); } } } if(++dispatchedCount % 1000 == 0) { dispatchedCount = 0; Thread.Sleep((int)1); } } catch(Exception e) { this.session.Connection.OnSessionException(this.session, e); } } public bool Iterate() { if(this.listener != null) { MessageDispatch dispatch = this.unconsumedMessages.DequeueNoWait(); if(dispatch != null) { try { Message message = CreateStompMessage(dispatch); BeforeMessageIsConsumed(dispatch); listener(message); AfterMessageIsConsumed(dispatch, false); } catch(NMSException e) { this.session.Connection.OnSessionException(this.session, e); } return true; } } return false; } /// <summary> /// Used to get an enqueued message from the unconsumedMessages list. The /// amount of time this method blocks is based on the timeout value. if /// timeout == Timeout.Infinite then it blocks until a message is received. /// if timeout == 0 then it it tries to not block at all, it returns a /// message if it is available if timeout > 0 then it blocks up to timeout /// amount of time. Expired messages will consumed by this method. /// </summary> private MessageDispatch Dequeue(TimeSpan timeout) { DateTime deadline = DateTime.Now; if(timeout > TimeSpan.Zero) { deadline += timeout; } while(true) { MessageDispatch dispatch = this.unconsumedMessages.Dequeue(timeout); // Grab a single date/time for calculations to avoid timing errors. DateTime dispatchTime = DateTime.Now; if(dispatch == null) { if(timeout > TimeSpan.Zero && !this.unconsumedMessages.Closed) { if(dispatchTime > deadline) { // Out of time. timeout = TimeSpan.Zero; } else { // Adjust the timeout to the remaining time. timeout = deadline - dispatchTime; } } else { if(this.failureError != null) { throw NMSExceptionSupport.Create(FailureError); } else { return null; } } } else if(dispatch.Message == null) { return null; } else if(!IgnoreExpiration && dispatch.Message.IsExpired()) { Tracer.DebugFormat("{0} received expired message: {1}", info.ConsumerId, dispatch.Message.MessageId); BeforeMessageIsConsumed(dispatch); AfterMessageIsConsumed(dispatch, true); // Refresh the dispatch time dispatchTime = DateTime.Now; if(timeout > TimeSpan.Zero && !this.unconsumedMessages.Closed) { if(dispatchTime > deadline) { // Out of time. timeout = TimeSpan.Zero; } else { // Adjust the timeout to the remaining time. timeout = deadline - dispatchTime; } } } else { return dispatch; } } } public void BeforeMessageIsConsumed(MessageDispatch dispatch) { lock(this.dispatchedMessages) { this.dispatchedMessages.AddFirst(dispatch); } if(this.session.IsTransacted) { this.AckLater(dispatch); } } public void AfterMessageIsConsumed(MessageDispatch dispatch, bool expired) { if(this.unconsumedMessages.Closed) { return; } if(expired == true) { lock(this.dispatchedMessages) { this.dispatchedMessages.Remove(dispatch); } // TODO - Not sure if we need to ack this in stomp. // AckLater(dispatch, AckType.ConsumedAck); } else { if(this.session.IsTransacted) { // Do nothing. } else if(this.session.IsAutoAcknowledge) { if(this.deliveringAcks.CompareAndSet(false, true)) { lock(this.dispatchedMessages) { // If a Recover was called in the async handler then // we don't want to send an ack otherwise the broker will // think we consumed the message. if (this.dispatchedMessages.Count > 0) { MessageAck ack = new MessageAck(); ack.AckType = (byte) AckType.ConsumedAck; ack.ConsumerId = this.info.ConsumerId; ack.Destination = dispatch.Destination; ack.LastMessageId = dispatch.Message.MessageId; ack.MessageCount = 1; this.session.SendAck(ack); } } this.deliveringAcks.Value = false; this.dispatchedMessages.Clear(); } } else if(this.session.IsClientAcknowledge || this.session.IsIndividualAcknowledge) { // Do nothing. } else { throw new NMSException("Invalid session state."); } } } private MessageAck MakeAckForAllDeliveredMessages() { lock(this.dispatchedMessages) { if(this.dispatchedMessages.Count == 0) { return null; } MessageDispatch dispatch = this.dispatchedMessages.First.Value; MessageAck ack = new MessageAck(); ack.AckType = (byte) AckType.ConsumedAck; ack.ConsumerId = this.info.ConsumerId; ack.Destination = dispatch.Destination; ack.LastMessageId = dispatch.Message.MessageId; ack.MessageCount = this.dispatchedMessages.Count; ack.FirstMessageId = this.dispatchedMessages.Last.Value.Message.MessageId; return ack; } } private void AckLater(MessageDispatch dispatch) { // Don't acknowledge now, but we may need to let the broker know the // consumer got the message to expand the pre-fetch window if(this.session.IsTransacted) { this.session.DoStartTransaction(); if(!synchronizationRegistered) { this.synchronizationRegistered = true; this.session.TransactionContext.AddSynchronization(new MessageConsumerSynchronization(this)); } } this.deliveredCounter++; MessageAck oldPendingAck = pendingAck; pendingAck = new MessageAck(); pendingAck.AckType = (byte) AckType.ConsumedAck; pendingAck.ConsumerId = this.info.ConsumerId; pendingAck.Destination = dispatch.Destination; pendingAck.LastMessageId = dispatch.Message.MessageId; pendingAck.MessageCount = deliveredCounter; if(this.session.IsTransacted && this.session.TransactionContext.InTransaction) { pendingAck.TransactionId = this.session.TransactionContext.TransactionId; } if(oldPendingAck == null) { pendingAck.FirstMessageId = pendingAck.LastMessageId; } if((0.5 * this.info.PrefetchSize) <= (this.deliveredCounter - this.additionalWindowSize)) { this.session.SendAck(pendingAck); this.pendingAck = null; this.deliveredCounter = 0; this.additionalWindowSize = 0; } } internal void Acknowledge() { lock(this.dispatchedMessages) { // Acknowledge all messages so far. MessageAck ack = MakeAckForAllDeliveredMessages(); if(ack == null) { return; // no msgs } if(this.session.IsTransacted) { this.session.DoStartTransaction(); ack.TransactionId = this.session.TransactionContext.TransactionId; } this.session.SendAck(ack); this.pendingAck = null; // Adjust the counters this.deliveredCounter = Math.Max(0, this.deliveredCounter - this.dispatchedMessages.Count); this.additionalWindowSize = Math.Max(0, this.additionalWindowSize - this.dispatchedMessages.Count); if(!this.session.IsTransacted) { this.dispatchedMessages.Clear(); } } } internal void Commit() { lock(this.dispatchedMessages) { this.dispatchedMessages.Clear(); } this.redeliveryDelay = 0; } internal void Rollback() { lock(this.unconsumedMessages.SyncRoot) { lock(this.dispatchedMessages) { Tracer.DebugFormat("Rollback started, rolling back {0} message", dispatchedMessages.Count); if(this.dispatchedMessages.Count == 0) { return; } // Only increase the redelivery delay after the first redelivery.. MessageDispatch lastMd = this.dispatchedMessages.First.Value; int currentRedeliveryCount = lastMd.Message.RedeliveryCounter; redeliveryDelay = this.redeliveryPolicy.RedeliveryDelay(currentRedeliveryCount); foreach(MessageDispatch dispatch in this.dispatchedMessages) { // Allow the message to update its internal to reflect a Rollback. dispatch.Message.OnMessageRollback(); } if(this.redeliveryPolicy.MaximumRedeliveries >= 0 && lastMd.Message.RedeliveryCounter > this.redeliveryPolicy.MaximumRedeliveries) { this.redeliveryDelay = 0; } else { // stop the delivery of messages. this.unconsumedMessages.Stop(); foreach(MessageDispatch dispatch in this.dispatchedMessages) { this.unconsumedMessages.EnqueueFirst(dispatch); } if(redeliveryDelay > 0 && !this.unconsumedMessages.Closed) { Tracer.DebugFormat("Rollback delayed for {0} seconds", redeliveryDelay); DateTime deadline = DateTime.Now.AddMilliseconds(redeliveryDelay); ThreadPool.QueueUserWorkItem(this.RollbackHelper, deadline); } else { Start(); } } this.deliveredCounter -= this.dispatchedMessages.Count; this.dispatchedMessages.Clear(); } } // Only redispatch if there's an async listener otherwise a synchronous // consumer will pull them from the local queue. if(this.listener != null) { this.session.Redispatch(this.unconsumedMessages); } } private void RollbackHelper(Object arg) { try { TimeSpan waitTime = (DateTime) arg - DateTime.Now; if(waitTime.CompareTo(TimeSpan.Zero) > 0) { Thread.Sleep((int)waitTime.TotalMilliseconds); } this.Start(); } catch(Exception e) { if(!this.unconsumedMessages.Closed) { this.session.Connection.OnSessionException(this.session, e); } } } private Message CreateStompMessage(MessageDispatch dispatch) { Message message = dispatch.Message.Clone() as Message; if(this.ConsumerTransformer != null) { IMessage transformed = this.consumerTransformer(this.session, this, message); if(transformed != null) { message = this.messageTransformation.TransformMessage<Message>(transformed); } } message.Connection = this.session.Connection; if(this.session.IsClientAcknowledge) { message.Acknowledger += new AcknowledgeHandler(DoClientAcknowledge); } else if(this.session.IsIndividualAcknowledge) { message.Acknowledger += new AcknowledgeHandler(DoIndividualAcknowledge); } else { message.Acknowledger += new AcknowledgeHandler(DoNothingAcknowledge); } return message; } private void CheckClosed() { if(this.unconsumedMessages.Closed) { throw new NMSException("The Consumer has been Closed"); } } private void CheckMessageListener() { if(this.listener != null) { throw new NMSException("Cannot perform a Synchronous Receive when there is a registered asynchronous listener."); } } public Exception FailureError { get { return this.failureError; } set { this.failureError = value; } } #region Nested ISyncronization Types class MessageConsumerSynchronization : ISynchronization { private readonly MessageConsumer consumer; public MessageConsumerSynchronization(MessageConsumer consumer) { this.consumer = consumer; } public void BeforeEnd() { this.consumer.Acknowledge(); this.consumer.synchronizationRegistered = false; } public void AfterCommit() { this.consumer.Commit(); this.consumer.synchronizationRegistered = false; } public void AfterRollback() { this.consumer.Rollback(); this.consumer.synchronizationRegistered = false; } } class ConsumerCloseSynchronization : ISynchronization { private readonly MessageConsumer consumer; public ConsumerCloseSynchronization(MessageConsumer consumer) { this.consumer = consumer; } public void BeforeEnd() { } public void AfterCommit() { this.consumer.DoClose(); } public void AfterRollback() { this.consumer.DoClose(); } } #endregion } }
// 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 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="UserDataServiceClient"/> instances.</summary> public sealed partial class UserDataServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="UserDataServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="UserDataServiceSettings"/>.</returns> public static UserDataServiceSettings GetDefault() => new UserDataServiceSettings(); /// <summary>Constructs a new <see cref="UserDataServiceSettings"/> object with default settings.</summary> public UserDataServiceSettings() { } private UserDataServiceSettings(UserDataServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); UploadUserDataSettings = existing.UploadUserDataSettings; OnCopy(existing); } partial void OnCopy(UserDataServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>UserDataServiceClient.UploadUserData</c> and <c>UserDataServiceClient.UploadUserDataAsync</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 UploadUserDataSettings { 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="UserDataServiceSettings"/> object.</returns> public UserDataServiceSettings Clone() => new UserDataServiceSettings(this); } /// <summary> /// Builder class for <see cref="UserDataServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class UserDataServiceClientBuilder : gaxgrpc::ClientBuilderBase<UserDataServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public UserDataServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public UserDataServiceClientBuilder() { UseJwtAccessWithScopes = UserDataServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref UserDataServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<UserDataServiceClient> task); /// <summary>Builds the resulting client.</summary> public override UserDataServiceClient Build() { UserDataServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<UserDataServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<UserDataServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private UserDataServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return UserDataServiceClient.Create(callInvoker, Settings); } private async stt::Task<UserDataServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return UserDataServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => UserDataServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => UserDataServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => UserDataServiceClient.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>UserDataService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage user data uploads. /// </remarks> public abstract partial class UserDataServiceClient { /// <summary> /// The default endpoint for the UserDataService 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 UserDataService scopes.</summary> /// <remarks> /// The default UserDataService 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="UserDataServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="UserDataServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="UserDataServiceClient"/>.</returns> public static stt::Task<UserDataServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new UserDataServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="UserDataServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="UserDataServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="UserDataServiceClient"/>.</returns> public static UserDataServiceClient Create() => new UserDataServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="UserDataServiceClient"/> 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="UserDataServiceSettings"/>.</param> /// <returns>The created <see cref="UserDataServiceClient"/>.</returns> internal static UserDataServiceClient Create(grpccore::CallInvoker callInvoker, UserDataServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } UserDataService.UserDataServiceClient grpcClient = new UserDataService.UserDataServiceClient(callInvoker); return new UserDataServiceClientImpl(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 UserDataService client</summary> public virtual UserDataService.UserDataServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Uploads the given user data. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// [UserDataError]() /// </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 UploadUserDataResponse UploadUserData(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Uploads the given user data. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// [UserDataError]() /// </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<UploadUserDataResponse> UploadUserDataAsync(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Uploads the given user data. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// [UserDataError]() /// </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<UploadUserDataResponse> UploadUserDataAsync(UploadUserDataRequest request, st::CancellationToken cancellationToken) => UploadUserDataAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>UserDataService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage user data uploads. /// </remarks> public sealed partial class UserDataServiceClientImpl : UserDataServiceClient { private readonly gaxgrpc::ApiCall<UploadUserDataRequest, UploadUserDataResponse> _callUploadUserData; /// <summary> /// Constructs a client wrapper for the UserDataService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="UserDataServiceSettings"/> used within this client.</param> public UserDataServiceClientImpl(UserDataService.UserDataServiceClient grpcClient, UserDataServiceSettings settings) { GrpcClient = grpcClient; UserDataServiceSettings effectiveSettings = settings ?? UserDataServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callUploadUserData = clientHelper.BuildApiCall<UploadUserDataRequest, UploadUserDataResponse>(grpcClient.UploadUserDataAsync, grpcClient.UploadUserData, effectiveSettings.UploadUserDataSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callUploadUserData); Modify_UploadUserDataApiCall(ref _callUploadUserData); 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_UploadUserDataApiCall(ref gaxgrpc::ApiCall<UploadUserDataRequest, UploadUserDataResponse> call); partial void OnConstruction(UserDataService.UserDataServiceClient grpcClient, UserDataServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC UserDataService client</summary> public override UserDataService.UserDataServiceClient GrpcClient { get; } partial void Modify_UploadUserDataRequest(ref UploadUserDataRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Uploads the given user data. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// [UserDataError]() /// </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 UploadUserDataResponse UploadUserData(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UploadUserDataRequest(ref request, ref callSettings); return _callUploadUserData.Sync(request, callSettings); } /// <summary> /// Uploads the given user data. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [OfflineUserDataJobError]() /// [QuotaError]() /// [RequestError]() /// [UserDataError]() /// </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<UploadUserDataResponse> UploadUserDataAsync(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UploadUserDataRequest(ref request, ref callSettings); return _callUploadUserData.Async(request, callSettings); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Windows.Forms; using XenAdmin.Actions; using XenAdmin.Controls; using XenAdmin.Dialogs; using XenAPI; using System.Linq; using System.IO; using XenAdmin.Alerts; using XenAdmin.Core; using XenAdmin.Wizards.PatchingWizard.PlanActions; namespace XenAdmin.Wizards.PatchingWizard { public enum WizardMode { SingleUpdate, AutomatedUpdates, NewVersion } /// <summary> /// Remember that equals for patches don't work across connections because /// we are not allow to override equals. YOU SHOULD NOT USE ANY OPERATION THAT IMPLIES CALL EQUALS OF Pool_patch or Host_patch /// You should do it manually or use delegates. /// </summary> public partial class PatchingWizard : UpdateUpgradeWizard { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly PatchingWizard_PatchingPage PatchingWizard_PatchingPage; private readonly PatchingWizard_SelectPatchPage PatchingWizard_SelectPatchPage; private readonly PatchingWizard_ModePage PatchingWizard_ModePage; private readonly PatchingWizard_SelectServers PatchingWizard_SelectServers; private readonly PatchingWizard_UploadPage PatchingWizard_UploadPage; private readonly PatchingWizard_PrecheckPage PatchingWizard_PrecheckPage; private readonly PatchingWizard_FirstPage PatchingWizard_FirstPage; private readonly PatchingWizard_AutomatedUpdatesPage PatchingWizard_AutomatedUpdatesPage; public PatchingWizard() { InitializeComponent(); PatchingWizard_PatchingPage = new PatchingWizard_PatchingPage(); PatchingWizard_SelectPatchPage = new PatchingWizard_SelectPatchPage(); PatchingWizard_ModePage = new PatchingWizard_ModePage(); PatchingWizard_SelectServers = new PatchingWizard_SelectServers(); PatchingWizard_UploadPage = new PatchingWizard_UploadPage(); PatchingWizard_PrecheckPage = new PatchingWizard_PrecheckPage(); PatchingWizard_FirstPage = new PatchingWizard_FirstPage(); PatchingWizard_AutomatedUpdatesPage = new PatchingWizard_AutomatedUpdatesPage(); AddPage(PatchingWizard_FirstPage); AddPage(PatchingWizard_SelectPatchPage); AddPage(PatchingWizard_SelectServers); AddPage(PatchingWizard_UploadPage); AddPage(PatchingWizard_PrecheckPage); AddPage(PatchingWizard_ModePage); AddPage(PatchingWizard_PatchingPage); } public void AddAlert(XenServerPatchAlert alert) { PatchingWizard_SelectPatchPage.SelectDownloadAlert(alert); PatchingWizard_SelectPatchPage.UpdateAlertFromWeb = alert; PatchingWizard_SelectServers.UpdateAlertFromWeb = alert; PatchingWizard_PrecheckPage.UpdateAlert = alert; PatchingWizard_UploadPage.SelectedUpdateAlert = alert; } public void AddFile(string path) { PatchingWizard_SelectPatchPage.FilePath = path; } public void SelectServers(List<Host> selectedServers) { PatchingWizard_SelectServers.SelectServers(selectedServers); PatchingWizard_SelectServers.DisableUnselectedServers(); } protected override void UpdateWizardContent(XenTabPage senderPage) { var prevPageType = senderPage.GetType(); if (prevPageType == typeof(PatchingWizard_SelectPatchPage)) { var wizardMode = PatchingWizard_SelectPatchPage.WizardMode; var wizardIsInAutomatedUpdatesMode = wizardMode == WizardMode.AutomatedUpdates; var updateType = wizardIsInAutomatedUpdatesMode ? UpdateType.Legacy : PatchingWizard_SelectPatchPage.SelectedUpdateType; var selectedPatchFilePath = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedPatchFilePath; var alertFromWeb = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.UpdateAlertFromWeb; var alertFromFileOnDisk = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.AlertFromFileOnDisk; var fileFromDiskHasUpdateXml = !wizardIsInAutomatedUpdatesMode && PatchingWizard_SelectPatchPage.FileFromDiskHasUpdateXml; PatchingWizard_SelectServers.WizardMode = wizardMode; PatchingWizard_SelectServers.SelectedUpdateType = updateType; PatchingWizard_SelectServers.UpdateAlertFromWeb = alertFromWeb; PatchingWizard_SelectServers.AlertFromFileOnDisk = alertFromFileOnDisk; PatchingWizard_SelectServers.FileFromDiskHasUpdateXml = fileFromDiskHasUpdateXml; RemovePage(PatchingWizard_UploadPage); RemovePage(PatchingWizard_ModePage); RemovePage(PatchingWizard_PatchingPage); RemovePage(PatchingWizard_AutomatedUpdatesPage); if (wizardMode == WizardMode.SingleUpdate) { AddAfterPage(PatchingWizard_SelectServers, PatchingWizard_UploadPage); AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_ModePage); AddAfterPage(PatchingWizard_ModePage, PatchingWizard_PatchingPage); } else // AutomatedUpdates or NewVersion { AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_AutomatedUpdatesPage); } PatchingWizard_UploadPage.SelectedUpdateType = updateType; PatchingWizard_UploadPage.SelectedPatchFilePath = selectedPatchFilePath; PatchingWizard_UploadPage.SelectedUpdateAlert = alertFromWeb ?? alertFromFileOnDisk; PatchingWizard_UploadPage.PatchFromDisk = PatchingWizard_SelectPatchPage.PatchFromDisk; PatchingWizard_ModePage.SelectedUpdateType = updateType; PatchingWizard_PrecheckPage.WizardMode = wizardMode; PatchingWizard_PrecheckPage.PoolUpdate = null; //reset the PoolUpdate property; it will be updated on leaving the Upload page, if this page is visible PatchingWizard_PrecheckPage.UpdateAlert = alertFromWeb ?? alertFromFileOnDisk; PatchingWizard_AutomatedUpdatesPage.WizardMode = wizardMode; PatchingWizard_AutomatedUpdatesPage.UpdateAlert = alertFromWeb ?? alertFromFileOnDisk; PatchingWizard_AutomatedUpdatesPage.PatchFromDisk = PatchingWizard_SelectPatchPage.PatchFromDisk; PatchingWizard_PatchingPage.SelectedUpdateType = updateType; PatchingWizard_PatchingPage.SelectedPatchFilePatch = selectedPatchFilePath; } else if (prevPageType == typeof(PatchingWizard_SelectServers)) { var selectedServers = PatchingWizard_SelectServers.SelectedServers; var selectedPools = PatchingWizard_SelectServers.SelectedPools; var applyUpdatesToNewVersion = PatchingWizard_SelectServers.ApplyUpdatesToNewVersion; PatchingWizard_PrecheckPage.SelectedServers = selectedServers; PatchingWizard_PrecheckPage.ApplyUpdatesToNewVersion = applyUpdatesToNewVersion; PatchingWizard_ModePage.SelectedPools = selectedPools; PatchingWizard_ModePage.SelectedServers = selectedServers; PatchingWizard_PatchingPage.SelectedServers = selectedServers; PatchingWizard_PatchingPage.SelectedPools = selectedPools; PatchingWizard_UploadPage.SelectedServers = selectedServers; PatchingWizard_UploadPage.SelectedPools = selectedPools; PatchingWizard_AutomatedUpdatesPage.SelectedPools = selectedPools; PatchingWizard_AutomatedUpdatesPage.ApplyUpdatesToNewVersion = applyUpdatesToNewVersion; } else if (prevPageType == typeof(PatchingWizard_UploadPage)) { var patch = PatchingWizard_UploadPage.Patch; var update = PatchingWizard_UploadPage.PoolUpdate; var suppPackVdis = PatchingWizard_UploadPage.SuppPackVdis; PatchingWizard_PrecheckPage.Patch = patch; PatchingWizard_PrecheckPage.PoolUpdate = update; var srsWithUploadedUpdates = new Dictionary<Pool_update, Dictionary<Host, SR>>(); foreach (var mapping in PatchingWizard_UploadPage.PatchMappings) { if (mapping is PoolUpdateMapping pum) srsWithUploadedUpdates[pum.Pool_update] = pum.SrsWithUploadedUpdatesPerHost; else if (mapping is SuppPackMapping spm && spm.Pool_update != null) srsWithUploadedUpdates[spm.Pool_update] = spm.SrsWithUploadedUpdatesPerHost; } PatchingWizard_PrecheckPage.SrUploadedUpdates = srsWithUploadedUpdates; PatchingWizard_ModePage.Patch = patch; PatchingWizard_ModePage.PoolUpdate = update; PatchingWizard_PatchingPage.Patch = patch; PatchingWizard_PatchingPage.PoolUpdate = update; PatchingWizard_PatchingPage.SuppPackVdis = suppPackVdis; } else if (prevPageType == typeof(PatchingWizard_ModePage)) { PatchingWizard_PatchingPage.ManualTextInstructions = PatchingWizard_ModePage.ManualTextInstructions; PatchingWizard_PatchingPage.IsAutomaticMode = PatchingWizard_ModePage.IsAutomaticMode; PatchingWizard_PatchingPage.RemoveUpdateFile = PatchingWizard_ModePage.RemoveUpdateFile; } else if (prevPageType == typeof(PatchingWizard_PrecheckPage)) { PatchingWizard_PatchingPage.PrecheckProblemsActuallyResolved = PatchingWizard_PrecheckPage.PrecheckProblemsActuallyResolved; PatchingWizard_PatchingPage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost; PatchingWizard_ModePage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost; PatchingWizard_AutomatedUpdatesPage.PrecheckProblemsActuallyResolved = PatchingWizard_PrecheckPage.PrecheckProblemsActuallyResolved; } } protected override void OnCancel(ref bool cancel) { base.OnCancel(ref cancel); if (cancel) return; RunMultipleActions(Messages.REVERT_WIZARD_CHANGES, Messages.REVERTING_WIZARD_CHANGES, Messages.REVERTED_WIZARD_CHANGES, GetUnwindChangesActions(PatchingWizard_PrecheckPage.PrecheckProblemsActuallyResolved)); CleanUploadedPatches(true); RemoveDownloadedPatches(); } protected override void FinishWizard() { CleanUploadedPatches(); RemoveDownloadedPatches(); Updates.CheckServerPatches(); base.FinishWizard(); } private void CleanUploadedPatches(bool forceCleanSelectedPatch = false) { var list = new List<AsyncAction>(); foreach (var mapping in PatchingWizard_UploadPage.PatchMappings) { Pool_patch patch = null; if (mapping is PoolPatchMapping patchMapping) patch = patchMapping.Pool_patch; else if (mapping is OtherLegacyMapping legacyMapping) patch = legacyMapping.Pool_patch; if (patch != null) { // exclude the selected patch; either the user wants to keep it or it has already been cleared in the patching page if (PatchingWizard_UploadPage.Patch == null || !string.Equals(patch.uuid, PatchingWizard_UploadPage.Patch.uuid, StringComparison.OrdinalIgnoreCase) || forceCleanSelectedPatch) { var action = GetCleanActionForPoolPatch(patch); if (action != null) list.Add(action); } continue; } if (mapping is PoolUpdateMapping updateMapping) { var action = GetCleanActionForPoolUpdate(updateMapping.Pool_update); if (action != null) list.Add(action); continue; } if (mapping is SuppPackMapping suppPackMapping) { if (suppPackMapping.Pool_update!= null) { var action = GetCleanActionForPoolUpdate(suppPackMapping.Pool_update); if (action != null) list.Add(action); } else list.AddRange(GetRemoveVdiActions(suppPackMapping.SuppPackVdis.Values.ToList())); } } RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, list); } private AsyncAction GetCleanActionForPoolPatch(Pool_patch patch) { if (patch == null || patch.Connection == null || !patch.Connection.IsConnected) return null; if (patch.HostsAppliedTo().Count == 0) return new RemovePatchAction(patch); return new DelegatedAsyncAction(patch.Connection, Messages.REMOVE_PATCH, "", "", session => Pool_patch.async_pool_clean(session, patch.opaque_ref)); } private AsyncAction GetCleanActionForPoolUpdate(Pool_update update) { if (update == null || update.Connection == null || !update.Connection.IsConnected) return null; return new DelegatedAsyncAction(update.Connection, Messages.REMOVE_PATCH, "", "", session => { try { Pool_update.pool_clean(session, update.opaque_ref); if (!update.AppliedOnHosts().Any()) Pool_update.destroy(session, update.opaque_ref); } catch (Failure f) { log.Error("Clean up failed", f); } }); } private List<AsyncAction> GetRemoveVdiActions(List<VDI> vdisToRemove) { var list = new List<AsyncAction>(); if (vdisToRemove != null) foreach (var vdi in vdisToRemove) { if (vdi.Connection != null && vdi.Connection.IsConnected) list.Add(new DestroyDiskAction(vdi)); } return list; } private void RemoveDownloadedPatches() { List<string> listOfDownloadedFiles = new List<string>(); listOfDownloadedFiles.AddRange(PatchingWizard_AutomatedUpdatesPage.AllDownloadedPatches.Values); // AutomatedUpdates or NewVersion listOfDownloadedFiles.AddRange(PatchingWizard_UploadPage.AllDownloadedPatches.Values); //SingleUpdate listOfDownloadedFiles.AddRange(PatchingWizard_SelectPatchPage.UnzippedUpdateFiles); foreach (string downloadedPatch in listOfDownloadedFiles) { try { if (File.Exists(downloadedPatch)) { File.Delete(downloadedPatch); } } catch { log.DebugFormat("Could not remove downloaded patch {0} ", downloadedPatch); } } } private void RunMultipleActions(string title, string startDescription, string endDescription, List<AsyncAction> subActions) { if (subActions != null && subActions.Count > 0) { using (MultipleAction multipleAction = new MultipleAction(xenConnection, title, startDescription, endDescription, subActions, false, true)) { using (var dialog = new ActionProgressDialog(multipleAction, ProgressBarStyle.Blocks)) dialog.ShowDialog(Program.MainWindow); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace Microsoft.Azure.KeyVault { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Models; using System.Security.Cryptography.X509Certificates; /// <summary> /// Extension methods for KeyVaultClient. /// </summary> public static partial class KeyVaultClientExtensions { #region Key Crypto Operations /// <summary> /// Encrypts a single block of data. The amount of data that may be encrypted is determined /// by the target key type and the encryption algorithm. /// </summary> /// <param name="keyIdentifier">The full key identifier</param> /// <param name="algorithm">The algorithm. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <param name="plainText">The plain text</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The encrypted text</returns> public static async Task<KeyOperationResult> EncryptAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] plainText, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (plainText == null) throw new ArgumentNullException("plainText"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.EncryptWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, plainText, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Decrypts a single block of encrypted data /// </summary> /// <param name="keyIdentifier">The full key identifier</param> /// <param name="algorithm">The algorithm. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <param name="cipherText">The cipher text</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The decryption result</returns> public static async Task<KeyOperationResult> DecryptAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] cipherText, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (cipherText == null) throw new ArgumentNullException("cipherText"); var keyId = new KeyIdentifier(keyIdentifier); // TODO: should we allow or not allow in the Key Identifier the version to be empty? using (var _result = await operations.DecryptWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, cipherText, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a signature from a digest using the specified key in the vault /// </summary> /// <param name="keyIdentifier"> The global key identifier of the signing key </param> /// <param name="algorithm">The signing algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. </param> /// <param name="digest">The digest value to sign</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The signature value</returns> public static async Task<KeyOperationResult> SignAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] digest, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (digest == null) throw new ArgumentNullException("digest"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.SignWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, digest, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Verifies a signature using the specified key /// </summary> /// <param name="keyIdentifier"> The global key identifier of the key used for signing </param> /// <param name="algorithm"> The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm.</param> /// <param name="digest"> The digest used for signing </param> /// <param name="signature"> The signature to be verified </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> true if the signature is verified, false otherwise. </returns> public static async Task<bool> VerifyAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (digest == null) throw new ArgumentNullException("digest"); if (signature == null) throw new ArgumentNullException("signature"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.VerifyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, digest, signature, null, cancellationToken).ConfigureAwait(false)) { var verifyResult = _result.Body; return (verifyResult.Value == true) ? true : false; } } /// <summary> /// Wraps a symmetric key using the specified key /// </summary> /// <param name="keyIdentifier"> The global key identifier of the key used for wrapping </param> /// <param name="algorithm"> The wrap algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm.</param> /// <param name="key"> The symmetric key </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> The wrapped symmetric key </returns> public static async Task<KeyOperationResult> WrapKeyAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] key, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (key == null) throw new ArgumentNullException("key"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.WrapKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, key, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Unwraps a symmetric key using the specified key in the vault /// that has initially been used for wrapping the key. /// </summary> /// <param name="keyIdentifier"> The global key identifier of the wrapping/unwrapping key </param> /// <param name="algorithm">The unwrap algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm.</param> /// <param name="wrappedKey">The wrapped symmetric key</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The unwrapped symmetric key</returns> public static async Task<KeyOperationResult> UnwrapKeyAsync(this IKeyVaultClient operations, string keyIdentifier, string algorithm, byte[] wrappedKey, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); if (string.IsNullOrEmpty(algorithm)) throw new ArgumentNullException("algorithm"); if (wrappedKey == null) throw new ArgumentNullException("wrappedKey"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.UnwrapKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, algorithm, wrappedKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } #endregion #region Key Management /// <summary> /// Retrieves the public portion of a key plus its attributes /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A KeyBundle of the key and its attributes</returns> public static async Task<KeyBundle> GetKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); using (var _result = await operations.GetKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieves the public portion of a key plus its attributes /// </summary> /// <param name="keyIdentifier">The key identifier</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A KeyBundle of the key and its attributes</returns> public static async Task<KeyBundle> GetKeyAsync(this IKeyVaultClient operations, string keyIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.GetKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Key Attributes associated with the specified key /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="keyOps">Json web key operations. For more information on possible key operations, see JsonWebKeyOperation.</param> /// <param name="attributes">The new attributes for the key. For more information on key attributes, see KeyAttributes.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <returns> The updated key </returns> public static async Task<KeyBundle> UpdateKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, string[] keyOps = null, KeyAttributes attributes = null, Dictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); using (var _result = await operations.UpdateKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, string.Empty, keyOps, attributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the Key Attributes associated with the specified key /// </summary> /// <param name="keyIdentifier">The key identifier</param> /// <param name="keyOps">Json web key operations. For more information, see JsonWebKeyOperation.</param> /// <param name="attributes">The new attributes for the key. For more information on key attributes, see KeyAttributes.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> The updated key </returns> public static async Task<KeyBundle> UpdateKeyAsync(this IKeyVaultClient operations, string keyIdentifier, string[] keyOps = null, KeyAttributes attributes = null, Dictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(keyIdentifier)) throw new ArgumentNullException("keyIdentifier"); var keyId = new KeyIdentifier(keyIdentifier); using (var _result = await operations.UpdateKeyWithHttpMessagesAsync(keyId.Vault, keyId.Name, keyId.Version ?? string.Empty, keyOps, attributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Imports a key into the specified vault /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="keyBundle"> Key bundle </param> /// <param name="importToHardware">Whether to import as a hardware key (HSM) or software key </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> Imported key bundle to the vault </returns> public static async Task<KeyBundle> ImportKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, KeyBundle keyBundle, bool? importToHardware = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); if (keyBundle == null) throw new ArgumentNullException("keyBundle"); using (var _result = await operations.ImportKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, keyBundle.Key, importToHardware, keyBundle.Attributes, keyBundle.Tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } #endregion #region Secret Management /// <summary> /// Gets a secret. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the secrets.</param> /// <param name="secretName">The name the secret in the given vault.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the secret</returns> public static async Task<SecretBundle> GetSecretAsync(this IKeyVaultClient operations, string vaultBaseUrl, string secretName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(secretName)) throw new ArgumentNullException("secretName"); using (var _result = await operations.GetSecretWithHttpMessagesAsync(vaultBaseUrl, secretName, string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a secret. /// </summary> /// <param name="secretIdentifier">The URL for the secret.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the secret</returns> public static async Task<SecretBundle> GetSecretAsync(this IKeyVaultClient operations, string secretIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(secretIdentifier)) throw new ArgumentNullException("secretIdentifier"); var secretId = new SecretIdentifier(secretIdentifier); using (var _result = await operations.GetSecretWithHttpMessagesAsync(secretId.Vault, secretId.Name, secretId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the attributes associated with the specified secret /// </summary> /// <param name="secretIdentifier">The URL of the secret</param> /// <param name="contentType">Type of the secret value such as password.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="secretAttributes">Attributes for the secret. For more information on possible attributes, see SecretAttributes.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the updated secret</returns> public static async Task<SecretBundle> UpdateSecretAsync(this IKeyVaultClient operations, string secretIdentifier, string contentType = null, SecretAttributes secretAttributes = null, Dictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(secretIdentifier)) throw new ArgumentNullException("secretIdentifier"); var secretId = new SecretIdentifier(secretIdentifier); using (var _result = await operations.UpdateSecretWithHttpMessagesAsync(secretId.Vault, secretId.Name, secretId.Version, contentType, secretAttributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } #endregion #region Recovery Management /// <summary> /// Recovers the deleted secret. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted secret, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered secret</returns> public static async Task<SecretBundle> RecoverDeletedSecretAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var secretRecoveryId = new DeletedSecretIdentifier(recoveryId); using (var _result = await operations.RecoverDeletedSecretWithHttpMessagesAsync(secretRecoveryId.Vault, secretRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Recovers the deleted key. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted key, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered key</returns> public static async Task<KeyBundle> RecoverDeletedKeyAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var keyRecoveryId = new DeletedKeyIdentifier(recoveryId); using (var _result = await operations.RecoverDeletedKeyWithHttpMessagesAsync(keyRecoveryId.Vault, keyRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Purges the deleted secret immediately. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted secret, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered secret</returns> public static async Task PurgeDeletedSecretAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var secretRecoveryId = new DeletedSecretIdentifier(recoveryId); using (var _result = await operations.PurgeDeletedSecretWithHttpMessagesAsync(secretRecoveryId.Vault, secretRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return; } } /// <summary> /// Purges the deleted key immediately. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted key, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered key</returns> public static async Task PurgeDeletedKeyAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) throw new ArgumentNullException(nameof(recoveryId)); var keyRecoveryId = new DeletedKeyIdentifier(recoveryId); using (var _result = await operations.PurgeDeletedKeyWithHttpMessagesAsync(keyRecoveryId.Vault, keyRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return; } } #endregion #region Certificate Management /// <summary> /// Gets a certificate. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate.</param> /// <param name="certificateName">The name of the certificate in the given vault.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The retrieved certificate</returns> public static async Task<CertificateBundle> GetCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrEmpty(certificateName)) throw new ArgumentNullException("certificateName"); using (var _result = await operations.GetCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a certificate. /// </summary> /// <param name="certificateIdentifier">The URL for the certificate.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The retrieved certificate</returns> public static async Task<CertificateBundle> GetCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(certificateIdentifier)) throw new ArgumentNullException("certificateIdentifier"); var certId = new CertificateIdentifier(certificateIdentifier); using (var _result = await operations.GetCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a certificate version. /// </summary> /// <param name="certificateIdentifier">The URL for the certificate.</param> /// <param name='certificatePolicy'>The management policy for the certificate.</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The updated certificate.</returns> public static async Task<CertificateBundle> UpdateCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = null, IDictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(certificateIdentifier)) throw new ArgumentNullException("certificateIdentifier"); var certId = new CertificateIdentifier(certificateIdentifier); using (var _result = await operations.UpdateCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Imports a new certificate version. If this is the first version, the certificate resource is created. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param> /// <param name="certificateName">The name of the certificate</param> /// <param name="certificateCollection">The certificate collection with the private key</param> /// <param name="certificatePolicy">The management policy for the certificate</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>Imported certificate bundle to the vault.</returns> public static async Task<CertificateBundle> ImportCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, X509Certificate2Collection certificateCollection, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes = null, IDictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrWhiteSpace(certificateName)) throw new ArgumentNullException("certificateName"); if (null == certificateCollection) throw new ArgumentNullException("certificateCollection"); var base64EncodedCertificate = Convert.ToBase64String(certificateCollection.Export(X509ContentType.Pfx)); using (var _result = await operations.ImportCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken)) { return _result.Body; } } /// <summary> /// Merges a certificate or a certificate chain with a key pair existing on the server. /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param> /// <param name="certificateName">The name of the certificate</param> /// <param name="x509Certificates">The certificate or the certificte chain to merge</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the merged certificate.</returns> public static async Task<CertificateBundle> MergeCertificateAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, X509Certificate2Collection x509Certificates, CertificateAttributes certificateAttributes = null, IDictionary<string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrWhiteSpace(certificateName)) throw new ArgumentNullException("certificateName"); if (x509Certificates == null || x509Certificates.Count == 0) throw new ArgumentException("x509Certificates"); var X5C = new List<byte[]>(); foreach (var cert in x509Certificates) { X5C.Add(cert.Export(X509ContentType.Cert)); } using (var _result = await operations.MergeCertificateWithHttpMessagesAsync(vaultBaseUrl, certificateName, X5C, certificateAttributes, tags, null, cancellationToken)) { return _result.Body; } } /// <summary> /// Gets the Base64 pending certificate signing request (PKCS-10) /// </summary> /// <param name="vaultBaseUrl">The URL for the vault containing the certificate</param> /// <param name="certificateName">The name of the certificate</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The pending certificate signing request as Base64 encoded string.</returns> public static async Task<string> GetPendingCertificateSigningRequestAsync(this IKeyVaultClient operations, string vaultBaseUrl, string certificateName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(vaultBaseUrl)) throw new ArgumentNullException("vaultBaseUrl"); if (string.IsNullOrWhiteSpace(certificateName)) throw new ArgumentNullException("certificateName"); using (var _result = await operations.GetPendingCertificateSigningRequestWithHttpMessagesAsync(vaultBaseUrl, certificateName, null, cancellationToken)) { return _result.Body; } } #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 Xunit; namespace System.Collections.Tests { public static class DictionaryBaseTests { private static FooKey CreateKey(int i) { return new FooKey(i, i.ToString()); } private static FooValue CreateValue(int i) { return new FooValue(i, i.ToString()); } private static MyDictionary CreateDictionary(int count) { var dictionary = new MyDictionary(); for (int i = 0; i < count; i++) { dictionary.Add(CreateKey(i), CreateValue(i)); } return dictionary; } [Fact] public static void TestAdd() { var dictBase = new MyDictionary(); for (int i = 0; i < 100; i++) { FooKey key = CreateKey(i); dictBase.Add(key, CreateValue(i)); Assert.True(dictBase.Contains(key)); } Assert.Equal(100, dictBase.Count); for (int i = 0; i < dictBase.Count; i++) { Assert.Equal(CreateValue(i), dictBase[CreateKey(i)]); } FooKey nullKey = CreateKey(101); dictBase.Add(nullKey, null); Assert.Equal(null, dictBase[nullKey]); } [Fact] public static void TestRemove() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < 100; i++) { FooKey key = CreateKey(i); dictBase.Remove(key); Assert.False(dictBase.Contains(key)); } Assert.Equal(0, dictBase.Count); dictBase.Remove(new FooKey()); // Doesn't exist, but doesn't throw } [Fact] public static void TestContains() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { Assert.True(dictBase.Contains(CreateKey(i))); } Assert.False(dictBase.Contains(new FooKey())); } [Fact] public static void TestKeys() { MyDictionary dictBase = CreateDictionary(100); ICollection keys = dictBase.Keys; Assert.Equal(dictBase.Count, keys.Count); foreach (FooKey key in keys) { Assert.True(dictBase.Contains(key)); } } [Fact] public static void TestValues() { MyDictionary dictBase = CreateDictionary(100); ICollection values = dictBase.Values; Assert.Equal(dictBase.Count, values.Count); foreach (FooValue value in values) { FooKey key = CreateKey(value.IntValue); Assert.Equal(value, dictBase[key]); } } [Fact] public static void TestIndexer_Get() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { Assert.Equal(CreateValue(i), dictBase[CreateKey(i)]); } Assert.Equal(null, dictBase[new FooKey()]); } [Fact] public static void TestIndexer_Get_Invalid() { var dictBase = new MyDictionary(); Assert.Throws<ArgumentNullException>(() => dictBase[null]); } [Fact] public static void TestIndexer_Set() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { FooKey key = CreateKey(i); FooValue value = CreateValue(dictBase.Count - i - 1); dictBase[key] = value; Assert.Equal(value, dictBase[key]); } FooKey nonExistentKey = CreateKey(101); dictBase[nonExistentKey] = null; Assert.Equal(101, dictBase.Count); // Should add a key/value pair if the key Assert.Equal(null, dictBase[nonExistentKey]); } [Fact] public static void TestIndexer_Set_Invalid() { var dictBase = new MyDictionary(); Assert.Throws<ArgumentNullException>(() => dictBase[null] = new FooValue()); } [Fact] public static void TestClear() { MyDictionary dictBase = CreateDictionary(100); dictBase.Clear(); Assert.Equal(0, dictBase.Count); } [Fact] public static void TestCopyTo() { MyDictionary dictBase = CreateDictionary(100); // Basic var entries = new DictionaryEntry[dictBase.Count]; dictBase.CopyTo(entries, 0); Assert.Equal(dictBase.Count, entries.Length); for (int i = 0; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } // With index entries = new DictionaryEntry[dictBase.Count * 2]; dictBase.CopyTo(entries, dictBase.Count); Assert.Equal(dictBase.Count * 2, entries.Length); for (int i = dictBase.Count; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } } [Fact] public static void TestCopyTo_Invalid() { MyDictionary dictBase = CreateDictionary(100); Assert.Throws<ArgumentNullException>(() => dictBase.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentOutOfRangeException>(() => dictBase.CopyTo(new DictionaryEntry[100], -1)); // Index < 0 Assert.Throws<ArgumentException>(() => dictBase.CopyTo(new DictionaryEntry[100], 100)); // Index >= count Assert.Throws<ArgumentException>(() => dictBase.CopyTo(new DictionaryEntry[100], 50)); // Index + array.Count >= count } [Fact] public static void TestGetEnumerator_IDictionaryEnumerator() { MyDictionary dictBase = CreateDictionary(100); IDictionaryEnumerator enumerator = dictBase.GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { DictionaryEntry entry1 = (DictionaryEntry)enumerator.Current; DictionaryEntry entry2 = enumerator.Entry; Assert.Equal(entry1.Key, entry2.Key); Assert.Equal(entry1.Value, entry2.Value); Assert.Equal(enumerator.Key, entry1.Key); Assert.Equal(enumerator.Value, entry1.Value); Assert.Equal(enumerator.Value, dictBase[(FooKey)enumerator.Key]); count++; } Assert.Equal(dictBase.Count, count); } [Fact] public static void TestGetEnumerator_IDictionaryEnumerator_Invalid() { MyDictionary dictBase = CreateDictionary(100); IDictionaryEnumerator enumerator = dictBase.GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Index > dictionary.Count while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); } [Fact] public static void TestGetEnumerator_IEnumerator() { MyDictionary dictBase = CreateDictionary(100); IEnumerator enumerator = ((IEnumerable)dictBase).GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal((FooValue)entry.Value, dictBase[(FooKey)entry.Key]); count++; } Assert.Equal(dictBase.Count, count); } [Fact] public static void TestGetEnumerator_IEnumerator_Invalid() { MyDictionary dictBase = CreateDictionary(100); IEnumerator enumerator = ((IEnumerable)dictBase).GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index >= dictionary.Count while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public static void TestSyncRoot() { // SyncRoot should be the reference to the underlying dictionary, not to MyDictionary var dictBase = new MyDictionary(); object syncRoot = dictBase.SyncRoot; Assert.NotEqual(syncRoot, dictBase); Assert.Equal(dictBase.SyncRoot, dictBase.SyncRoot); } [Fact] public static void TestIDictionaryProperties() { var dictBase = new MyDictionary(); Assert.False(dictBase.IsFixedSize); Assert.False(dictBase.IsReadOnly); Assert.False(dictBase.IsSynchronized); } [Fact] public static void TestAdd_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, "hello"); Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnInsertCalled); Assert.True(dictBase.OnInsertCompleteCalled); Assert.True(dictBase.Contains(f)); } [Fact] public static void TestAdd_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); // Throw OnInsert dictBase = new OnMethodCalledDictionary(); dictBase.OnInsertThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); // Throw OnInsertComplete dictBase = new OnMethodCalledDictionary(); dictBase.OnInsertCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); } [Fact] public static void TestRemove_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateCalled = false; dictBase.Remove(f); Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnRemoveCalled); Assert.True(dictBase.OnRemoveCompleteCalled); Assert.False(dictBase.Contains(f)); } [Fact] public static void TestRemove_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); // Throw OnRemove dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnRemoveThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); // Throw OnRemoveComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnRemoveCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); } [Fact] public static void TestClear_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.Clear(); Assert.True(dictBase.OnClearCalled); Assert.True(dictBase.OnClearCompleteCalled); Assert.Equal(0, dictBase.Count); } [Fact] public static void TestClear_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; dictBase.Clear(); Assert.Equal(0, dictBase.Count); // Throw OnClear dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnClearThrow = true; Assert.Throws<Exception>(() => dictBase.Clear()); Assert.Equal(1, dictBase.Count); // Throw OnClearComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnClearCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Clear()); Assert.Equal(0, dictBase.Count); } [Fact] public static void TestSet_New_Called() { var f = new FooKey(1, "1"); var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateCalled = false; dictBase[f] = "hello"; Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnSetCalled); Assert.True(dictBase.OnSetCompleteCalled); Assert.Equal(1, dictBase.Count); Assert.Equal("hello", dictBase[f]); } [Fact] public static void TestSet_New_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); // Throw OnSet dictBase = new OnMethodCalledDictionary(); dictBase.OnSetThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); // Throw OnSetComplete dictBase = new OnMethodCalledDictionary(); dictBase.OnSetCompleteThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); } [Fact] public static void TestSet_Existing_Called() { var f = new FooKey(1, "1"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(new FooKey(), ""); dictBase.OnValidateCalled = false; dictBase[f] = "hello"; Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnSetCalled); Assert.True(dictBase.OnSetCompleteCalled); Assert.Equal("hello", dictBase[f]); } [Fact] public static void TestSet_Existing_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); // Throw OnSet dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnSetThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); // Throw OnSetComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnSetCompleteThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); } // DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here private class MyDictionary : DictionaryBase { public void Add(FooKey key, FooValue value) { Dictionary.Add(key, value); } public FooValue this[FooKey key] { get { return (FooValue)Dictionary[key]; } set { Dictionary[key] = value; } } public bool IsSynchronized { get { return Dictionary.IsSynchronized; } } public object SyncRoot { get { return Dictionary.SyncRoot; } } public bool Contains(FooKey key) { return Dictionary.Contains(key); } public void Remove(FooKey key) { Dictionary.Remove(key); } public bool IsFixedSize { get { return Dictionary.IsFixedSize; } } public bool IsReadOnly { get { return Dictionary.IsReadOnly; } } public ICollection Keys { get { return Dictionary.Keys; } } public ICollection Values { get { return Dictionary.Values; } } } private class FooKey : IComparable { public FooKey() { } public FooKey(int i, string str) { _intValue = i; _stringValue = str; } private int _intValue; public int IntValue { get { return _intValue; } set { _intValue = value; } } private string _stringValue; public string StringValue { get { return _stringValue; } set { _stringValue = value; } } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is FooKey)) return false; if ((((FooKey)obj).IntValue == _intValue) && (((FooKey)obj).StringValue == _stringValue)) return true; return false; } public override int GetHashCode() { return _intValue; } public int CompareTo(object obj) { if (!(obj is FooKey)) throw new ArgumentException("obj must be type FooKey"); FooKey temp = (FooKey)obj; if (temp.IntValue > _intValue) return -1; else if (temp.IntValue < _intValue) return 1; else return 0; } } private class FooValue : IComparable { public FooValue() { } public FooValue(int intValue, string stringValue) { _intValue = intValue; _stringValue = stringValue; } private int _intValue; public int IntValue { get { return _intValue; } set { _intValue = value; } } private string _stringValue; public string StringValue { get { return _stringValue; } set { _stringValue = value; } } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is FooValue)) return false; if ((((FooValue)obj).IntValue == _intValue) && (((FooValue)obj).StringValue == _stringValue)) return true; return false; } public override int GetHashCode() { return _intValue; } public int CompareTo(object obj) { if (!(obj is FooValue)) throw new ArgumentException("obj must be type FooValue"); FooValue temp = (FooValue)obj; if (temp.IntValue > _intValue) return -1; else if (temp.IntValue < _intValue) return 1; else return 0; } } // DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here private class OnMethodCalledDictionary : DictionaryBase { public bool OnValidateCalled; public bool OnSetCalled; public bool OnSetCompleteCalled; public bool OnInsertCalled; public bool OnInsertCompleteCalled; public bool OnClearCalled; public bool OnClearCompleteCalled; public bool OnRemoveCalled; public bool OnRemoveCompleteCalled; public bool OnValidateThrow; public bool OnSetThrow; public bool OnSetCompleteThrow; public bool OnInsertThrow; public bool OnInsertCompleteThrow; public bool OnClearThrow; public bool OnClearCompleteThrow; public bool OnRemoveThrow; public bool OnRemoveCompleteThrow; public void Add(FooKey key, string value) { Dictionary.Add(key, value); } public string this[FooKey key] { get { return (string)Dictionary[key]; } set { Dictionary[key] = value; } } public bool Contains(FooKey key) { return Dictionary.Contains(key); } public void Remove(FooKey key) { Dictionary.Remove(key); } protected override void OnSet(object key, object oldValue, object newValue) { Assert.True(OnValidateCalled); Assert.Equal(oldValue, this[(FooKey)key]); OnSetCalled = true; if (OnSetThrow) throw new Exception("OnSet"); } protected override void OnInsert(object key, object value) { Assert.True(OnValidateCalled); Assert.NotEqual(value, this[(FooKey)key]); OnInsertCalled = true; if (OnInsertThrow) throw new Exception("OnInsert"); } protected override void OnClear() { OnClearCalled = true; if (OnClearThrow) throw new Exception("OnClear"); } protected override void OnRemove(object key, object value) { Assert.True(OnValidateCalled); Assert.Equal(value, this[(FooKey)key]); OnRemoveCalled = true; if (OnRemoveThrow) throw new Exception("OnRemove"); } protected override void OnValidate(object key, object value) { OnValidateCalled = true; if (OnValidateThrow) throw new Exception("OnValidate"); } protected override void OnSetComplete(object key, object oldValue, object newValue) { Assert.True(OnSetCalled); Assert.Equal(newValue, this[(FooKey)key]); OnSetCompleteCalled = true; if (OnSetCompleteThrow) throw new Exception("OnSetComplete"); } protected override void OnInsertComplete(object key, object value) { Assert.True(OnInsertCalled); Assert.Equal(value, this[(FooKey)key]); OnInsertCompleteCalled = true; if (OnInsertCompleteThrow) throw new Exception("OnInsertComplete"); } protected override void OnClearComplete() { Assert.True(OnClearCalled); OnClearCompleteCalled = true; if (OnClearCompleteThrow) throw new Exception("OnClearComplete"); } protected override void OnRemoveComplete(object key, object value) { Assert.True(OnRemoveCalled); Assert.False(Contains((FooKey)key)); OnRemoveCompleteCalled = true; if (OnRemoveCompleteThrow) throw new Exception("OnRemoveComplete"); } } } }
using System.Collections; using System.Web.Mvc; using MvcContrib.FluentHtml.Behaviors; using MvcContrib.FluentHtml.Elements; using System.Collections.Generic; namespace MvcContrib.FluentHtml { /// <summary> /// Extensions to IViewDataContainer /// </summary> public static class ViewDataContainerExtensions { /// <summary> /// Generate an HTML input element of type 'text' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static TextBox TextBox(this IViewDataContainer view, string name) { return new TextBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'password' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static Password Password(this IViewDataContainer view, string name) { return new Password(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML select element and set its selected value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static Select Select(this IViewDataContainer view, string name) { return new Select(name, null, view.GetBehaviors()).Selected(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML select element with a multiselect attribute = 'true' and set its selected /// values from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static MultiSelect MultiSelect(this IViewDataContainer view, string name) { return new MultiSelect(name, null, view.GetBehaviors()).Selected(view.ViewData.Eval(name) as IEnumerable); } /// <summary> /// Generate an HTML input element of type 'hidden' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static Hidden Hidden(this IViewDataContainer view, string name) { return new Hidden(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML textarea element and set the value from ViewData. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static TextArea TextArea(this IViewDataContainer view, string name) { return new TextArea(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'checkbox' and set checked from ViewData based on the name provided. /// The checkbox element has an accompanying input element of type 'hidden' to support binding upon form post. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static CheckBox CheckBox(this IViewDataContainer view, string name) { var checkbox = new CheckBox(name, null, view.GetBehaviors()).Value(true); var chkd = view.ViewData.Eval(name) as bool?; if (chkd.HasValue) { checkbox.Checked(chkd.Value); } return checkbox; } /// <summary> /// Generate a list of HTML input elements of type 'checkbox' and set its value from the ViewModel based on the expression provided. /// Each checkbox element has an accompanying input element of type 'hidden' to support binding upon form post. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static CheckBoxList CheckBoxList(this IViewDataContainer view, string name) { return new CheckBoxList(name, null, view.GetBehaviors()).Selected(view.ViewData.Eval(name) as IEnumerable); } /// <summary> /// Generate an HTML input element of type 'submit.' /// </summary> /// <param name="view">The view.</param> /// <param name="text">Value of the 'value' and 'name' attributes. Also used to derive the 'id' attribute.</param> public static SubmitButton SubmitButton(this IViewDataContainer view, string text) { return new SubmitButton(text, view.GetBehaviors()); } /// <summary> /// Generate an HTML input element of type 'button.' /// </summary> /// <param name="view">The view.</param> /// <param name="text">Value of the 'value' and 'name' attributes. Also used to derive the 'id' attribute.</param> public static Button Button(this IViewDataContainer view, string text) { return new Button(text, view.GetBehaviors()); } /// <summary> /// Generate an HTML input element of type 'reset.' /// </summary> /// <param name="view">The view.</param> /// <param name="text">Value of the 'value' and 'name' attributes. Also used to derive the 'id' attribute.</param> public static ResetButton ResetButton(this IViewDataContainer view, string text) { return new ResetButton(text, view.GetBehaviors()); } /// <summary> /// Generate an HTML label element; /// </summary> /// <param name="view">The view.</param> /// <param name="forName">The id of the target element to point to in the 'for' attribute.</param> public static Label Label(this IViewDataContainer view, string forName) { return new Label(forName, null, view.GetBehaviors()).Value(view.ViewData.Eval(forName)); } /// <summary> /// Generate an HTML span element. /// </summary> /// <param name="view">The view.</param> /// <param name="value">The inner text.</param> public static Literal Literal(this IViewDataContainer view, object value) { return view.Literal("", value); } /// <summary> /// Generate an HTML span element. /// </summary> /// <param name="view">The view.</param> /// <param name="name">The name of the element.</param> /// <param name="value">The inner text.</param> public static Literal Literal(this IViewDataContainer view, string name, object value) { return new Literal(name, null, view.GetBehaviors()).Value(value); } /// <summary> /// Generate an HTML span element and an HTML input element of type 'hidden' and set the inner text /// of the span and the value of the hidden input element from ViewData based on the specified name. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static FormLiteral FormLiteral(this IViewDataContainer view, string name) { return new FormLiteral(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'file' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static FileUpload FileUpload(this IViewDataContainer view, string name) { return new FileUpload(name, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'radio.' /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the of the input elements. Also used to derive the 'id' attributes.</param> public static RadioButton RadioButton(this IViewDataContainer view, string name) { return new RadioButton(name, null, view.GetBehaviors()); } /// <summary> /// Generate a set of HTML input elements of type 'radio' -- each wrapped inside a label. The whole thing is wrapped in an HTML /// div element. The values of the input elements and he label text are taken from the options specified. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the of the input elements. Also used to derive the 'id' attributes.</param> public static RadioSet RadioSet(this IViewDataContainer view, string name) { return new RadioSet(name, null, view.GetBehaviors()).Selected(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'number' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static NumberBox NumberBox(this IViewDataContainer view, string name) { return new NumberBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'search' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static SearchBox SearchBox(this IViewDataContainer view, string name) { return new SearchBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'range' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static RangeBox RangeBox(this IViewDataContainer view, string name) { return new RangeBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'tel' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'name' attribute of the element. Also used to derive the 'id' attribute.</param> public static TelephoneBox TelephoneBox(this IViewDataContainer view, string name) { return new TelephoneBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'date' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static DatePicker DatePicker(this IViewDataContainer view, string name) { return new DatePicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'month' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static MonthPicker MonthPicker(this IViewDataContainer view, string name) { return new MonthPicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'week' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static WeekPicker WeekPicker(this IViewDataContainer view, string name) { return new WeekPicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'datetime' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static DateTimePicker DateTimePicker(this IViewDataContainer view, string name) { return new DateTimePicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'datetime-local' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static DateTimeLocalPicker DateTimeLocalPicker(this IViewDataContainer view, string name) { return new DateTimeLocalPicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'time' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static TimePicker TimePicker(this IViewDataContainer view, string name) { return new TimePicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'color' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static ColorPicker ColorPicker(this IViewDataContainer view, string name) { return new ColorPicker(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'url' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static UrlBox UrlBox(this IViewDataContainer view, string name) { return new UrlBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML input element of type 'url' and set its value from ViewData based on the name provided. /// </summary> /// <param name="view">The view.</param> /// <param name="name">Value of the 'date' attribute of the element. Also used to derive the 'id' attribute.</param> public static EmailBox EmailBox(this IViewDataContainer view, string name) { return new EmailBox(name, null, view.GetBehaviors()).Value(view.ViewData.Eval(name)); } /// <summary> /// Generate an HTML datalist element. /// </summary> /// <param name="view">The view.</param> public static DataList DataList(this IViewDataContainer view, string id) { return new DataList(id, view.GetBehaviors()); } public static IEnumerable<IBehaviorMarker> GetBehaviors(this IViewDataContainer view) { var behaviorsContainer = view as IBehaviorsContainer; return behaviorsContainer == null ? null : behaviorsContainer.Behaviors; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Runtime.ExceptionServices; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using MICore; using System.Globalization; using Microsoft.Win32; namespace Microsoft.MIDebugEngine { // AD7Engine is the primary entrypoint object for the sample engine. // // It implements: // // IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session, // from creating breakpoints to setting and clearing exceptions. // // IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs. // // IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each // process only contains one program, it is implemented on the engine. // // IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee. [ComVisible(true)] [Guid("0fc2f352-2fc1-4f80-8736-51cd1ab28f16")] sealed public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugEngineProgram2, IDebugMemoryBytes2, IDebugEngine110 { // used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load. private EngineCallback _engineCallback; // The sample debug engine is split into two parts: a managed front-end and a mixed-mode back end. DebuggedProcess is the primary // object in the back-end. AD7Engine holds a reference to it. private DebuggedProcess _debuggedProcess; // This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging // api requires thread affinity to several operations. private WorkerThread _pollThread; // This object manages breakpoints in the sample engine. private BreakpointManager _breakpointManager; // A unique identifier for the program being debugged. private Guid _ad7ProgramId; private string _registryRoot; private IDebugSettingsCallback110 _settingsCallback; public AD7Engine() { //This call is to initialize the global service provider while we are still on the main thread. //Do not remove this this, even though the return value goes unused. var globalProvider = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider; _breakpointManager = new BreakpointManager(this); } ~AD7Engine() { if (_pollThread != null) { _pollThread.Close(); } } internal EngineCallback Callback { get { return _engineCallback; } } internal DebuggedProcess DebuggedProcess { get { return _debuggedProcess; } } internal uint CurrentRadix() { uint radix; if (_settingsCallback != null && _settingsCallback.GetDisplayRadix(out radix) == Constants.S_OK) { if (radix != _debuggedProcess.MICommandFactory.Radix) { _debuggedProcess.WorkerThread.RunOperation(async () => { await _debuggedProcess.MICommandFactory.SetRadix(radix); }); } } return _debuggedProcess.MICommandFactory.Radix; } internal bool ProgramCreateEventSent { get; private set; } public string GetAddressDescription(ulong ip) { return EngineUtils.GetAddressDescription(_debuggedProcess, ip); } public object GetMetric(string metric) { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(_registryRoot + @"\AD7Metrics\Engine\" + EngineConstants.EngineId.ToUpper(CultureInfo.InvariantCulture))) { if (key == null) { return null; } return key.GetValue(metric); } } #region IDebugEngine2 Members // Attach the debug engine to a program. int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason) { Debug.Assert(_ad7ProgramId == Guid.Empty); if (celtPrograms != 1) { Debug.Fail("SampleEngine only expects to see one program in a process"); throw new ArgumentException(); } try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(rgpPrograms[0]); EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out _ad7ProgramId)); // Attach can either be called to attach to a new process, or to complete an attach // to a launched process if (_pollThread == null) { // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(); _engineCallback = new EngineCallback(this, ad7Callback); // Complete the win32 attach on the poll thread _pollThread.RunOperation(new Operation(delegate { throw new NotImplementedException(); })); _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; } else { if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { Debug.Fail("Asked to attach to a process while we are debugging"); return Constants.E_FAIL; } } AD7EngineCreateEvent.Send(this); AD7ProgramCreateEvent.Send(this); this.ProgramCreateEventSent = true; return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run. // This is normally called in response to the user clicking on the pause button in the debugger. // When the break is complete, an AsyncBreakComplete event will be sent back to the debugger. int IDebugEngine2.CauseBreak() { return ((IDebugProgram2)this).CauseBreak(); } // Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM, // was received and processed. The only event the sample engine sends in this fashion is Program Destroy. // It responds to that event by shutting down the engine. int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 eventObject) { try { if (eventObject is AD7ProgramCreateEvent) { Exception exception = null; try { // At this point breakpoints and exception settings have been sent down, so we can resume the target _pollThread.RunOperation(() => { return _debuggedProcess.ResumeFromLaunch(); }); } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } if (exception != null) { // If something goes wrong, report the error and then stop debugging. The SDM will drop errors // from ContinueFromSynchronousEvent, so we want to deal with them ourself. SendStartDebuggingError(exception); _debuggedProcess.Terminate(); } return Constants.S_OK; } else if (eventObject is AD7ProgramDestroyEvent) { Dispose(); } else { Debug.Fail("Unknown syncronious event"); } } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } private void Dispose() { WorkerThread pollThread = _pollThread; DebuggedProcess debuggedProcess = _debuggedProcess; _engineCallback = null; _debuggedProcess = null; _pollThread = null; _ad7ProgramId = Guid.Empty; debuggedProcess?.Close(); pollThread?.Close(); } // Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to // a location in the debuggee. int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP) { Debug.Assert(_breakpointManager != null); ppPendingBP = null; try { _breakpointManager.CreatePendingBreakpoint(pBPRequest, out ppPendingBP); } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } // Informs a DE that the program specified has been atypically terminated and that the DE should // clean up all references to the program and send a program destroy event. int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram) { // Tell the SDM that the engine knows that the program is exiting, and that the // engine will send a program destroy. We do this because the Win32 debug api will always // tell us that the process exited, and otherwise we have a race condition. return (AD7_HRESULT.E_PROGRAM_DESTROY_PENDING); } // Gets the GUID of the DE. int IDebugEngine2.GetEngineId(out Guid guidEngine) { guidEngine = new Guid(EngineConstants.EngineId); return Constants.S_OK; } // Removes the list of exceptions the IDE has set for a particular run-time architecture or language. int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType) { _debuggedProcess?.ExceptionManager.RemoveAllSetExceptions(guidType); return Constants.S_OK; } // Removes the specified exception so it is no longer handled by the debug engine. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException) { _debuggedProcess?.ExceptionManager.RemoveSetException(ref pException[0]); return Constants.S_OK; } // Specifies how the DE should handle a given exception. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.SetException(EXCEPTION_INFO[] pException) { _debuggedProcess?.ExceptionManager.SetException(ref pException[0]); return Constants.S_OK; } // Sets the locale of the DE. // This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that // strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented. int IDebugEngine2.SetLocale(ushort wLangID) { return Constants.S_OK; } // A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality. // This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric. int IDebugEngine2.SetMetric(string pszMetric, object varValue) { // The sample engine does not need to understand any metric settings. return Constants.S_OK; } // Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored // This allows the debugger to tell the engine where that location is. int IDebugEngine2.SetRegistryRoot(string registryRoot) { _registryRoot = registryRoot; Logger.EnsureInitialized(registryRoot); return Constants.S_OK; } #endregion #region IDebugEngineLaunch2 Members // Determines if a process can be terminated. int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_OK; } else { return Constants.S_FALSE; } } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Launches a process by means of the debug engine. // Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger // to the suspended program. However, there are circumstances in which the debug engine may need to launch a program // (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language), // in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method // The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state. int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process) { Debug.Assert(_pollThread == null); Debug.Assert(_engineCallback == null); Debug.Assert(_debuggedProcess == null); Debug.Assert(_ad7ProgramId == Guid.Empty); process = null; _engineCallback = new EngineCallback(this, ad7Callback); Exception exception; try { // Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop LaunchOptions launchOptions = LaunchOptions.GetInstance(_registryRoot, exe, args, dir, options, _engineCallback, TargetEngine.Native); // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(); var cancellationTokenSource = new CancellationTokenSource(); using (cancellationTokenSource) { _pollThread.RunOperation(ResourceStrings.InitializingDebugger, cancellationTokenSource, (MICore.WaitLoop waitLoop) => { try { _debuggedProcess = new DebuggedProcess(true, launchOptions, _engineCallback, _pollThread, _breakpointManager, this, _registryRoot); } finally { // If there is an exception from the DebuggeedProcess constructor, it is our responsibility to dispose the DeviceAppLauncher, // otherwise the DebuggedProcess object takes ownership. if (_debuggedProcess == null && launchOptions.DeviceAppLauncher != null) { launchOptions.DeviceAppLauncher.Dispose(); } } _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; return _debuggedProcess.Initialize(waitLoop, cancellationTokenSource.Token); }); } EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process)); return Constants.S_OK; } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } // If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and then // return E_ABORT. Logger.Flush(); SendStartDebuggingError(exception); Dispose(); return Constants.E_ABORT; } private void SendStartDebuggingError(Exception exception) { if (exception is OperationCanceledException) { return; // don't show a message in this case } string description = EngineUtils.GetExceptionDescription(exception); string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnableToStartDebugging, description); var initializationException = exception as MIDebuggerInitializeFailedException; if (initializationException != null) { string outputMessage = string.Join("\r\n", initializationException.OutputLines) + "\r\n"; // NOTE: We can't write to the output window by sending an AD7 event because this may be called before the session create event VsOutputWindow.WriteLaunchError(outputMessage); } _engineCallback.OnErrorImmediate(message); } // Resume a process launched by IDebugEngineLaunch2.LaunchSuspended int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); Debug.Assert(_ad7ProgramId == Guid.Empty); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } // Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach // which will complete the hookup with AD7 IDebugPort2 port; EngineUtils.RequireOk(process.GetPort(out port)); IDebugDefaultPort2 defaultPort = (IDebugDefaultPort2)port; IDebugPortNotify2 portNotify; EngineUtils.RequireOk(defaultPort.GetPortNotify(out portNotify)); EngineUtils.RequireOk(portNotify.AddProgramNode(new AD7ProgramNode(_debuggedProcess.Id))); if (_ad7ProgramId == Guid.Empty) { Debug.Fail("Unexpected problem -- IDebugEngine2.Attach wasn't called"); return Constants.E_FAIL; } // NOTE: We wait for the program create event to be continued before we really resume the process return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // This function is used to terminate a process that the SampleEngine launched // The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method. int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } _pollThread.RunOperation(() => _debuggedProcess.CmdTerminate()); _debuggedProcess.Terminate(); return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } #endregion #region IDebugProgram2 Members // Determines if a debug engine (DE) can detach from the program. public int CanDetach() { // The sample engine always supports detach return Constants.S_OK; } // The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering // breakmode. public int CauseBreak() { _pollThread.RunOperation(() => _debuggedProcess.CmdBreak()); return Constants.S_OK; } // Continue is called from the SDM when it wants execution to continue in the debugee // but have stepping state remain. An example is when a tracepoint is executed, // and the debugger does not want to actually enter break mode. public int Continue(IDebugThread2 pThread) { AD7Thread thread = (AD7Thread)pThread; _pollThread.RunOperation(() => _debuggedProcess.Continue(thread.GetDebuggedThread())); return Constants.S_OK; } // Detach is called when debugging is stopped and the process was attached to (as opposed to launched) // or when one of the Detach commands are executed in the UI. public int Detach() { _breakpointManager.ClearBoundBreakpoints(); _pollThread.RunOperation(new Operation(delegate { _debuggedProcess.Detach(); })); return Constants.S_OK; } // Enumerates the code contexts for a given position in a source file. public int EnumCodeContexts(IDebugDocumentPosition2 docPosition, out IEnumDebugCodeContexts2 ppEnum) { string documentName; EngineUtils.CheckOk(docPosition.GetFileName(out documentName)); // Get the location in the document TEXT_POSITION[] startPosition = new TEXT_POSITION[1]; TEXT_POSITION[] endPosition = new TEXT_POSITION[1]; EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition)); List<IDebugCodeContext2> codeContexts = new List<IDebugCodeContext2>(); List<ulong> addresses = null; uint line = startPosition[0].dwLine + 1; _debuggedProcess.WorkerThread.RunOperation(async () => { addresses = await DebuggedProcess.StartAddressesForLine(documentName, line); }); if (addresses != null && addresses.Count > 0) { foreach (var a in addresses) { var codeCxt = new AD7MemoryAddress(this, a, null); TEXT_POSITION pos; pos.dwLine = line; pos.dwColumn = 0; MITextPosition textPosition = new MITextPosition(documentName, pos, pos); codeCxt.SetDocumentContext(new AD7DocumentContext(textPosition, codeCxt)); codeContexts.Add(codeCxt); } if (codeContexts.Count > 0) { ppEnum = new AD7CodeContextEnum(codeContexts.ToArray()); return Constants.S_OK; } } ppEnum = null; return Constants.E_FAIL; } // EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which // function to step into. This is not something that the SampleEngine supports. public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext) { pathEnum = null; safetyContext = null; return Constants.E_NOTIMPL; } // EnumModules is called by the debugger when it needs to enumerate the modules in the program. public int EnumModules(out IEnumDebugModules2 ppEnum) { DebuggedModule[] modules = _debuggedProcess.GetModules(); AD7Module[] moduleObjects = new AD7Module[modules.Length]; for (int i = 0; i < modules.Length; i++) { moduleObjects[i] = new AD7Module(modules[i], _debuggedProcess); } ppEnum = new Microsoft.MIDebugEngine.AD7ModuleEnum(moduleObjects); return Constants.S_OK; } // EnumThreads is called by the debugger when it needs to enumerate the threads in the program. public int EnumThreads(out IEnumDebugThreads2 ppEnum) { DebuggedThread[] threads = null; DebuggedProcess.WorkerThread.RunOperation(async () => threads = await DebuggedProcess.ThreadCache.GetThreads()); AD7Thread[] threadObjects = new AD7Thread[threads.Length]; for (int i = 0; i < threads.Length; i++) { Debug.Assert(threads[i].Client != null); threadObjects[i] = (AD7Thread)threads[i].Client; } ppEnum = new Microsoft.MIDebugEngine.AD7ThreadEnum(threadObjects); return Constants.S_OK; } // The properties returned by this method are specific to the program. If the program needs to return more than one property, // then the IDebugProperty2 object returned by this method is a container of additional properties and calling the // IDebugProperty2::EnumChildren method returns a list of all properties. // A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface. // An IDE might display the additional program properties through a generic property browser user interface. // The sample engine does not support this public int GetDebugProperty(out IDebugProperty2 ppProperty) { throw new NotImplementedException(); } // The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context. // The sample engine does not support dissassembly so it returns E_NOTIMPL // In order for this to be called, the Disassembly capability must be set in the registry for this Engine public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream) { disassemblyStream = new AD7DisassemblyStream(dwScope, codeContext); return Constants.S_OK; } // This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL public int GetENCUpdate(out object update) { // The sample engine does not participate in managed edit & continue. update = null; return Constants.S_OK; } // Gets the name and identifier of the debug engine (DE) running this program. public int GetEngineInfo(out string engineName, out Guid engineGuid) { engineName = ResourceStrings.EngineName; engineGuid = new Guid(EngineConstants.EngineId); return Constants.S_OK; } // The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory // that was allocated when the program was executed. public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { ppMemoryBytes = this; return Constants.S_OK; } // Gets the name of the program. // The name returned by this method is always a friendly, user-displayable name that describes the program. public int GetName(out string programName) { // The Sample engine uses default transport and doesn't need to customize the name of the program, // so return NULL. programName = null; return Constants.S_OK; } // Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach // or IDebugEngine2::Attach methods. This allows identification of the program across debugger components. public int GetProgramId(out Guid guidProgramId) { Debug.Assert(_ad7ProgramId != Guid.Empty); guidProgramId = _ad7ProgramId; return Constants.S_OK; } public int Step(IDebugThread2 pThread, enum_STEPKIND kind, enum_STEPUNIT unit) { AD7Thread thread = (AD7Thread)pThread; _debuggedProcess.WorkerThread.RunOperation(() => _debuggedProcess.Step(thread.GetDebuggedThread().Id, kind, unit)); return Constants.S_OK; } // Terminates the program. public int Terminate() { // Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate // the process in IDebugEngineLaunch2.TerminateProcess return Constants.S_OK; } // Writes a dump to a file. public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) { // The sample debugger does not support creating or reading mini-dumps. return Constants.E_NOTIMPL; } #endregion #region IDebugProgram3 Members // ExecuteOnThread is called when the SDM wants execution to continue and have // stepping state cleared. public int ExecuteOnThread(IDebugThread2 pThread) { AD7Thread thread = (AD7Thread)pThread; _pollThread.RunOperation(() => _debuggedProcess.Execute(thread.GetDebuggedThread())); return Constants.S_OK; } #endregion #region IDebugEngineProgram2 Members // Stops all threads running in this program. // This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program // is received, this method is called on this program. The implementation of this method should be asynchronous; // that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be // as simple as calling the IDebugProgram2::CauseBreak method on this program. // // The sample engine only supports debugging native applications and therefore only has one program per-process public int Stop() { throw new NotImplementedException(); } // WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging // the same process. The sample engine doesn't cooperate with other engines, so it has nothing // to do here. public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch) { return Constants.S_OK; } // WatchForThreadStep is used to cooperate between two different engines debugging the same process. // The sample engine doesn't cooperate with other engines, so it has nothing to do here. public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame) { return Constants.S_OK; } #endregion #region IDebugMemoryBytes2 Members public int GetSize(out ulong pqwSize) { throw new NotImplementedException(); } public int ReadAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory, out uint pdwRead, ref uint pdwUnreadable) { pdwUnreadable = 0; AD7MemoryAddress addr = (AD7MemoryAddress)pStartContext; uint bytesRead = 0; int hr = Constants.S_OK; DebuggedProcess.WorkerThread.RunOperation(async () => { bytesRead = await DebuggedProcess.ReadProcessMemory(addr.Address, dwCount, rgbMemory); }); if (bytesRead == uint.MaxValue) { bytesRead = 0; } if (bytesRead < dwCount) // copied from Concord { // assume 4096 sized pages: ARM has 4K or 64K pages uint pageSize = 4096; ulong readEnd = addr.Address + bytesRead; ulong nextPageStart = (readEnd + pageSize - 1) / pageSize * pageSize; if (nextPageStart == readEnd) { nextPageStart = readEnd + pageSize; } // if we have crossed a page boundry - Unreadable = bytes till end of page uint maxUnreadable = dwCount - bytesRead; if (addr.Address + dwCount > nextPageStart) { pdwUnreadable = (uint)Math.Min(maxUnreadable, nextPageStart - readEnd); } else { pdwUnreadable = (uint)Math.Min(maxUnreadable, pageSize); } } pdwRead = bytesRead; return hr; } public int WriteAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory) { throw new NotImplementedException(); } #endregion #region IDebugEngine110 public int SetMainThreadSettingsCallback110(IDebugSettingsCallback110 pCallback) { _settingsCallback = pCallback; return Constants.S_OK; } #endregion #region Deprecated interface methods // These methods are not called by the Visual Studio debugger, so they don't need to be implemented int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs) { Debug.Fail("This function is not called by the debugger"); programs = null; return Constants.E_NOTIMPL; } public int Attach(IDebugEventCallback2 pCallback) { Debug.Fail("This function is not called by the debugger"); return Constants.E_NOTIMPL; } public int GetProcess(out IDebugProcess2 process) { Debug.Fail("This function is not called by the debugger"); process = null; return Constants.E_NOTIMPL; } public int Execute() { Debug.Fail("This function is not called by the debugger."); return Constants.E_NOTIMPL; } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using appMpower.Db; using PlatformBenchmarks; namespace appMpower { public static class RawDb { private const int MaxBatch = 500; private static Random _random = new Random(); private static string[] _queriesMultipleRows = new string[MaxBatch + 1]; private static readonly object[] _cacheKeys = Enumerable.Range(0, 10001).Select((i) => new CacheKey(i)).ToArray(); private static readonly appMpower.Memory.MemoryCache _cache = new appMpower.Memory.MemoryCache( new appMpower.Memory.MemoryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMinutes(60) }); public static async Task<World> LoadSingleQueryRow() { var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var (pooledCommand, _) = CreateReadCommand(pooledConnection); var world = await ReadSingleRow(pooledCommand); pooledCommand.Release(); pooledConnection.Release(); return world; } public static async Task<World[]> LoadMultipleQueriesRows(int count) { var worlds = new World[count]; var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var (pooledCommand, dbDataParameter) = CreateReadCommand(pooledConnection); for (int i = 0; i < count; i++) { worlds[i] = await ReadSingleRow(pooledCommand); dbDataParameter.Value = _random.Next(1, 10001); } pooledCommand.Release(); pooledConnection.Release(); return worlds; } public static async Task<List<Fortune>> LoadFortunesRows() { var fortunes = new List<Fortune>(); var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var pooledCommand = new PooledCommand("SELECT * FROM fortune", pooledConnection); var dataReader = await pooledCommand.ExecuteReaderAsync(CommandBehavior.SingleResult & CommandBehavior.SequentialAccess); while (dataReader.Read()) { fortunes.Add(new Fortune ( id: dataReader.GetInt32(0), #if MYSQL //MariaDB ODBC connector does not correctly support Japanese characters in combination with default ADO.NET; //as a solution we custom read this string message: ReadColumn(dataReader, 1) #else message: dataReader.GetString(1) #endif )); } dataReader.Close(); pooledCommand.Release(); pooledConnection.Release(); fortunes.Add(new Fortune(id: 0, message: "Additional fortune added at request time.")); fortunes.Sort(); return fortunes; } public static async Task<World[]> LoadMultipleUpdatesRows(int count) { var worlds = new World[count]; var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var (queryCommand, dbDataParameter) = CreateReadCommand(pooledConnection); for (int i = 0; i < count; i++) { worlds[i] = await ReadSingleRow(queryCommand); dbDataParameter.Value = _random.Next(1, 10001); } queryCommand.Release(); var updateCommand = new PooledCommand(PlatformBenchmarks.BatchUpdateString.Query(count), pooledConnection); var ids = PlatformBenchmarks.BatchUpdateString.Ids; var randoms = PlatformBenchmarks.BatchUpdateString.Randoms; #if !MYSQL var jds = PlatformBenchmarks.BatchUpdateString.Jds; #endif for (int i = 0; i < count; i++) { var randomNumber = _random.Next(1, 10001); updateCommand.CreateParameter(ids[i], DbType.Int32, worlds[i].Id); updateCommand.CreateParameter(randoms[i], DbType.Int32, randomNumber); worlds[i].RandomNumber = randomNumber; } #if !MYSQL for (int i = 0; i < count; i++) { updateCommand.CreateParameter(jds[i], DbType.Int32, worlds[i].Id); } #endif await updateCommand.ExecuteNonQueryAsync(); updateCommand.Release(); pooledConnection.Release(); return worlds; } private static (PooledCommand pooledCommand, IDbDataParameter dbDataParameter) CreateReadCommand(PooledConnection pooledConnection) { var pooledCommand = new PooledCommand("SELECT * FROM world WHERE id=?", pooledConnection); var dbDataParameter = pooledCommand.CreateParameter("@Id", DbType.Int32, _random.Next(1, 10001)); return (pooledCommand, dbDataParameter); } private static async Task<World> ReadSingleRow(PooledCommand pooledCommand) { var dataReader = await pooledCommand.ExecuteReaderAsync(CommandBehavior.SingleRow & CommandBehavior.SequentialAccess); dataReader.Read(); var world = new World { Id = dataReader.GetInt32(0), RandomNumber = dataReader.GetInt32(1) }; dataReader.Close(); return world; } public static async Task<World[]> ReadMultipleRows(int count) { int j = 0; var ids = PlatformBenchmarks.BatchUpdateString.Ids; var worlds = new World[count]; string queryString; if (_queriesMultipleRows[count] != null) { queryString = _queriesMultipleRows[count]; } else { var stringBuilder = PlatformBenchmarks.StringBuilderCache.Acquire(); for (int i = 0; i < count; i++) { stringBuilder.Append("SELECT * FROM world WHERE id=?;"); } queryString = _queriesMultipleRows[count] = PlatformBenchmarks.StringBuilderCache.GetStringAndRelease(stringBuilder); } var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var pooledCommand = new PooledCommand(queryString, pooledConnection); for (int i = 0; i < count; i++) { pooledCommand.CreateParameter(ids[i], DbType.Int32, _random.Next(1, 10001)); } var dataReader = await pooledCommand.ExecuteReaderAsync(CommandBehavior.Default & CommandBehavior.SequentialAccess); do { dataReader.Read(); worlds[j] = new World { Id = dataReader.GetInt32(0), RandomNumber = dataReader.GetInt32(1) }; j++; } while (await dataReader.NextResultAsync()); dataReader.Close(); pooledCommand.Release(); pooledConnection.Release(); return worlds; } public static string ReadColumn(DbDataReader dbDataReader, int column) { long size = dbDataReader.GetBytes(column, 0, null, 0, 0); //get the length of data byte[] values = new byte[size]; int bufferSize = 64; long bytesRead = 0; int currentPosition = 0; while (bytesRead < size) { bytesRead += dbDataReader.GetBytes(column, currentPosition, values, currentPosition, bufferSize); currentPosition += bufferSize; } return System.Text.Encoding.Default.GetString(values); } public static async Task PopulateCache() { var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var (pooledCommand, dbDataParameter) = CreateReadCommand(pooledConnection); using (pooledCommand) { var cacheKeys = _cacheKeys; var cache = _cache; for (var i = 1; i < 10001; i++) { dbDataParameter.Value = i; cache.Set<CachedWorld>(cacheKeys[i], await ReadSingleRow(pooledCommand)); } } pooledCommand.Release(); pooledConnection.Release(); } public static Task<CachedWorld[]> LoadCachedQueries(int count) { var result = new CachedWorld[count]; var cacheKeys = _cacheKeys; var cache = _cache; var random = _random; for (var i = 0; i < result.Length; i++) { var id = random.Next(1, 10001); var key = cacheKeys[id]; if (cache.TryGetValue(key, out object cached)) { result[i] = (CachedWorld)cached; } else { //return LoadUncachedQueries(id, i, count, this, result); return LoadUncachedQueries(id, i, count, result); } } return Task.FromResult(result); } //static async Task<CachedWorld[]> LoadUncachedQueries(int id, int i, int count, RawDb rawdb, CachedWorld[] result) static async Task<CachedWorld[]> LoadUncachedQueries(int id, int i, int count, CachedWorld[] result) { var pooledConnection = await PooledConnections.GetConnection(DataProvider.ConnectionString); pooledConnection.Open(); var (pooledCommand, dbDataParameter) = CreateReadCommand(pooledConnection); using (pooledCommand) { Func<ICacheEntry, Task<CachedWorld>> create = async (entry) => { return await ReadSingleRow(pooledCommand); }; var cacheKeys = _cacheKeys; var key = cacheKeys[id]; dbDataParameter.Value = id; for (; i < result.Length; i++) { result[i] = await _cache.GetOrCreateAsync<CachedWorld>(key, create); id = _random.Next(1, 10001); dbDataParameter.Value = id; key = cacheKeys[id]; } pooledCommand.Release(); pooledConnection.Release(); } return result; } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising 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; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.Windows.Forms; using System.ComponentModel.Design; using System.Drawing.Text; namespace Controls { /// <summary> /// Summary description for GroupBoxEx. /// </summary> [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] public class GroupBoxEx : System.Windows.Forms.ScrollableControl { private const int headerMargin = 5; private GraphicsPath headerPath = new GraphicsPath(); private Color headerColor = Color.Gray; private int cornerRadius = 10; private bool dividerAbove = true; private bool antiAliasText = true; private bool drawLeftDivider = true; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public GroupBoxEx() { //this.SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); // This call is required by the Windows.Forms Form Designer. InitializeComponent(); this.DoubleBuffered = true; // TODO: Add any initialization after the InitializeComponent call //CreateGraphicsPath(); } /*private void CreateGraphicsPath() { int cornerDiameter = cornerRadius * 2; headerPath.Reset(); int headerHeight = (int)this.CreateGraphics().MeasureString("Ij", this.Font).Height + (headerMargin * 2); if(dividerAbove) { headerPath.AddLine(0, headerHeight, 0, cornerRadius); headerPath.AddArc(0, 0, cornerDiameter, cornerDiameter, 180, 90); headerPath.AddLine(cornerRadius, 0, this.Width, 0); } else { } }*/ private void Draw(Graphics g) { int headerHeight = (int)g.MeasureString("Ij", this.Font).Height + (headerMargin * 2); LinearGradientBrush horizHeaderGradient = new LinearGradientBrush(new Point(cornerRadius - 1, 0), new Point(this.Width, 0), headerColor, Color.FromArgb(0, headerColor.R, headerColor.G, headerColor.B)); LinearGradientBrush vertHeaderGradient; Pen headerPen = new Pen(headerColor); // Draw header if(dividerAbove) { vertHeaderGradient = new LinearGradientBrush(new Point(0, cornerRadius), new Point(0, headerHeight), headerColor, Color.FromArgb(0, headerColor.R, headerColor.G, headerColor.B)); if(drawLeftDivider) { g.FillRectangle(horizHeaderGradient, cornerRadius, 0, this.Width - cornerRadius, 1); g.FillRectangle(vertHeaderGradient, 0, cornerRadius, 1, headerHeight - cornerRadius); g.SmoothingMode = SmoothingMode.AntiAlias; g.DrawArc(headerPen, 0, 0, cornerRadius * 2, cornerRadius * 2, 180, 90); } else { g.FillRectangle(horizHeaderGradient, cornerRadius - 1, 0, this.Width - cornerRadius, 1); horizHeaderGradient = new LinearGradientBrush(new Point(0, 0), new Point(cornerRadius, 0), Color.FromArgb(0, headerColor.R, headerColor.G, headerColor.B), headerColor); g.FillRectangle(horizHeaderGradient, 0, 0, cornerRadius, 1); } } else { vertHeaderGradient = new LinearGradientBrush(new Point(0, 0), new Point(0, headerHeight - cornerRadius + 1), Color.FromArgb(0, headerColor.R, headerColor.G, headerColor.B), headerColor); if(drawLeftDivider) { g.FillRectangle(horizHeaderGradient, cornerRadius, headerHeight, this.Width - cornerRadius, 1); g.FillRectangle(vertHeaderGradient, 0, 0, 1, headerHeight - cornerRadius + 1); g.SmoothingMode = SmoothingMode.AntiAlias; g.DrawArc(headerPen, 0, headerHeight - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90); } else { g.FillRectangle(horizHeaderGradient, cornerRadius - 1, headerHeight, this.Width - cornerRadius, 1); horizHeaderGradient = new LinearGradientBrush(new Point(0, 0), new Point(cornerRadius, 0), Color.FromArgb(0, headerColor.R, headerColor.G, headerColor.B), headerColor); g.FillRectangle(horizHeaderGradient, 0, headerHeight, cornerRadius, 1); } } // Draw Text if (antiAliasText) { g.TextRenderingHint = TextRenderingHint.AntiAlias; using (SolidBrush textBrush = new SolidBrush(this.ForeColor)) { g.DrawString(this.Text, this.Font, textBrush, headerMargin, headerMargin); } } else { g.TextRenderingHint = TextRenderingHint.SystemDefault; TextRenderer.DrawText(g, this.Text, this.Font, new Point(headerMargin, headerMargin), this.ForeColor); } horizHeaderGradient.Dispose(); vertHeaderGradient.Dispose(); } public bool DividerAbove { get { return dividerAbove; } set { dividerAbove = value; this.Invalidate(); } } public bool AntiAliasText { get { return antiAliasText; } set { antiAliasText = value; this.Invalidate(); } } public bool DrawLeftDivider { get { return drawLeftDivider; } set { drawLeftDivider = value; this.Invalidate(); } } protected override void OnPaint(PaintEventArgs e) { Draw(e.Graphics); } protected override void OnResize(EventArgs e) { base.OnResize(e); this.Invalidate(); } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override string Text { get { return base.Text; } set { base.Text = value; this.Invalidate(); } } public Color HeaderColor { get { return headerColor; } set { headerColor = value; this.Invalidate(); } } public int CornerRadius { get { return cornerRadius; } set { cornerRadius = value; this.Invalidate(); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // GroupBoxEx // this.Name = "GroupBoxEx"; this.Size = new System.Drawing.Size(304, 192); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using Bigvgames.Models; using Bigvgames.Models.AccountViewModels; using Bigvgames.Services; namespace Bigvgames.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
/* Copyright (c) 2005-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Runtime.InteropServices; using System.Diagnostics; using Pchp.Core; using System.Xml; using Pchp.Core.Utilities; using System.Text.RegularExpressions; namespace Pchp.Library.DateTime { /// <summary> /// Provides timezone information for PHP functions. /// </summary> [PhpExtension("date")] public static class PhpTimeZone { private const string EnvVariableName = "TZ"; [DebuggerDisplay("{PhpName} - {Info}")] private struct TimeZoneInfoItem { /// <summary> /// Comparer of <see cref="TimeZoneInfoItem"/>, comparing its <see cref="TimeZoneInfoItem.PhpName"/>. /// </summary> public class Comparer : IComparer<TimeZoneInfoItem> { public int Compare(TimeZoneInfoItem x, TimeZoneInfoItem y) { return StringComparer.OrdinalIgnoreCase.Compare(x.PhpName, y.PhpName); } } /// <summary> /// PHP time zone name. /// </summary> public readonly string PhpName; /// <summary> /// Actual <see cref="TimeZoneInfo"/> from .NET. /// </summary> public readonly TimeZoneInfo Info; /// <summary> /// Abbreviation. If more than one, separated with comma. /// </summary> public readonly string Abbreviation; /// <summary> /// Not listed item used only as an alias for another time zone. /// </summary> public readonly bool IsAlias; /// <summary> /// Gets value indicating the given abbreviation can be used for this timezone. /// </summary> public bool HasAbbreviation(string abbr) { if (!string.IsNullOrEmpty(abbr) && Abbreviation != null) { // Abbreviation.Split(new[] { ',' }).Contains(abbr, StringComparer.OrdinalIgnoreCase); int index = 0; while ((index = Abbreviation.IndexOf(abbr, index, StringComparison.OrdinalIgnoreCase)) >= 0) { int end = index + abbr.Length; if (index == 0 || Abbreviation[index - 1] == ',') { if (end == Abbreviation.Length || Abbreviation[end] == ',') { return true; } } // index++; } } return false; } internal TimeZoneInfoItem(string/*!*/phpName, TimeZoneInfo/*!*/info, string abbreviation, bool isAlias) { // TODO: alter the ID with php-like name //if (!phpName.Equals(info.Id, StringComparison.OrdinalIgnoreCase)) //{ // info = TimeZoneInfo.CreateCustomTimeZone(phpName, info.BaseUtcOffset, info.DisplayName, info.StandardName, info.DaylightName, info.GetAdjustmentRules()); //} // this.PhpName = phpName; this.Info = info; this.Abbreviation = abbreviation; this.IsAlias = isAlias; } } #region timezones /// <summary> /// PHP time zone database. /// </summary> private readonly static Lazy<TimeZoneInfoItem[]>/*!!*/s_lazyTimeZones = new Lazy<TimeZoneInfoItem[]>( InitializeTimeZones, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication); private static TimeZoneInfoItem[]/*!!*/InitializeTimeZones() { // read list of initial timezones var sortedTZ = new SortedSet<TimeZoneInfoItem>(ReadTimeZones(), new TimeZoneInfoItem.Comparer()); // add additional time zones: sortedTZ.Add(new TimeZoneInfoItem("UTC", TimeZoneInfo.Utc, "utc", false)); sortedTZ.Add(new TimeZoneInfoItem("Etc/UTC", TimeZoneInfo.Utc, "utc", true)); sortedTZ.Add(new TimeZoneInfoItem("Etc/GMT-0", TimeZoneInfo.Utc, "gmt", true)); sortedTZ.Add(new TimeZoneInfoItem("GMT", TimeZoneInfo.Utc, "gmt", true)); sortedTZ.Add(new TimeZoneInfoItem("GMT0", TimeZoneInfo.Utc, "gmt", true)); sortedTZ.Add(new TimeZoneInfoItem("UCT", TimeZoneInfo.Utc, "utc", true)); sortedTZ.Add(new TimeZoneInfoItem("Universal", TimeZoneInfo.Utc, "utc", true)); sortedTZ.Add(new TimeZoneInfoItem("Zulu", TimeZoneInfo.Utc, "utc", true)); //sortedTZ.Add(new TimeZoneInfoItem("MET", sortedTZ.First(t => t.PhpName == "Europe/Rome").Info, null, true)); //sortedTZ.Add(new TimeZoneInfoItem("WET", sortedTZ.First(t => t.PhpName == "Europe/Berlin").Info, null, true)); //{ "PRC" //{ "ROC" //{ "ROK" // W-SU = //{ "Poland" //{ "Portugal" //{ "PRC" //{ "ROC" //{ "ROK" //{ "Singapore" = Asia/Singapore //{ "Turkey" // return sortedTZ.ToArray(); } static bool IsAlias(string id) { // whether to not display such tz within timezone_identifiers_list() var isphpname = id.IndexOf('/') >= 0 || id.IndexOf("GMT", StringComparison.Ordinal) >= 0 && id.IndexOf(' ') < 0; return !isphpname; } static Dictionary<string, string> LoadAbbreviations() { var abbrs = new Dictionary<string, string>(512); // timezone_id => abbrs using (var abbrsstream = new System.IO.StreamReader(typeof(PhpTimeZone).Assembly.GetManifestResourceStream("Pchp.Library.Resources.abbreviations.txt"))) { string line; while ((line = abbrsstream.ReadLine()) != null) { if (string.IsNullOrEmpty(line) || line[0] == '#') continue; var idx = line.IndexOf(' '); if (idx > 0) { // abbreviation[space]timezone_id var abbr = line.Remove(idx); // abbreviation var tz = line.Substring(idx + 1); // timezone_id if (abbrs.TryGetValue(tz, out var oldabbr)) { // more abbrs for a single tz if (oldabbr.IndexOf(abbr) >= 0) continue; // the list contains duplicities .. abbr = oldabbr + "," + abbr; } abbrs[tz] = abbr; } } } return abbrs; } static IEnumerable<string[]> LoadKnownTimeZones() { // collect php time zone names and match them with Windows TZ IDs: using (var xml = XmlReader.Create(new System.IO.StreamReader(typeof(PhpTimeZone).Assembly.GetManifestResourceStream("Pchp.Library.Resources.WindowsTZ.xml")))) { while (xml.Read()) { switch (xml.NodeType) { case XmlNodeType.Element: if (xml.Name == "mapZone") { // <mapZone other="Dateline Standard Time" type="Etc/GMT+12"/> var winId = xml.GetAttribute("other"); var phpIds = xml.GetAttribute("type"); if (string.IsNullOrEmpty(phpIds)) { yield return new[] { winId }; } else if (phpIds.IndexOf(' ') < 0) { yield return new[] { winId, phpIds }; } else { var list = new List<string>(4) { winId }; list.AddRange(phpIds.Split(' ')); yield return list.ToArray(); } } break; } } } // other time zones: yield return new[] { "US/Alaska", "Alaskan Standard Time" }; //yield return new[] { "US/Aleutian", (???) }; yield return new[] { "US/Arizona", "US Mountain Standard Time" }; yield return new[] { "US/Central", "Central Standard Time" }; yield return new[] { "East-Indiana", "US Eastern Standard Time" }; yield return new[] { "Eastern", "Eastern Standard Time" }; yield return new[] { "US/Hawaii", "Hawaiian Standard Time" }; // "US/Indiana-Starke" // "US/Michigan" yield return new[] { "US/Mountain", "Mountain Standard Time" }; yield return new[] { "US/Pacific", "Pacific Standard Time" }; yield return new[] { "US/Pacific-New", "Pacific Standard Time" }; yield return new[] { "US/Samoa", "Samoa Standard Time" }; } static IEnumerable<TimeZoneInfoItem>/*!!*/ReadTimeZones() { // map of time zones: var tzdict = TimeZoneInfo .GetSystemTimeZones() .ToDictionary(tz => tz.Id, StringComparer.OrdinalIgnoreCase); // add aliases and knonwn time zones from bundled XML: foreach (var names in LoadKnownTimeZones()) { TimeZoneInfo tz = null; for (int i = 0; i < names.Length; i++) { if (tzdict.TryGetValue(names[i], out tz)) { break; } } // update the map of known time zones: if (tz != null) { for (int i = 0; i < names.Length; i++) { tzdict[names[i]] = tz; } } } // prepare abbreviations var abbrs = LoadAbbreviations(); // yield return all discovered time zones: foreach (var pair in tzdict) { abbrs.TryGetValue(pair.Key, out var abbreviation); yield return new TimeZoneInfoItem(pair.Key, pair.Value, abbreviation, IsAlias(pair.Key)); } } #endregion /// <summary> /// Gets the current time zone for PHP date-time library functions. Associated with the current context. /// </summary> /// <remarks>It returns the time zone set by date_default_timezone_set PHP function. /// If no time zone was set, the time zone is determined in following order: /// 1. the time zone set in configuration /// 2. the time zone of the current system /// 3. default UTC time zone</remarks> internal static TimeZoneInfo GetCurrentTimeZone(Context ctx) { // if timezone is set by date_default_timezone_set(), return it var info = ctx.TryGetProperty<TimeZoneInfo>(); if (info == null) { // default timezone was not set, use & cache the current timezone info = ctx.GetStatic<CurrentTimeZoneCache>().TimeZone; } // return info; } internal static void SetCurrentTimeZone(Context ctx, TimeZoneInfo value) { ctx.SetProperty(value); } #region CurrentTimeZoneCache /// <summary> /// Cache of current TimeZone with auto-update ability. /// </summary> private class CurrentTimeZoneCache { public CurrentTimeZoneCache() { } #if DEBUG internal CurrentTimeZoneCache(TimeZoneInfo timezone) { this._timeZone = timezone; this._changedFunc = (_) => false; } #endif /// <summary> /// Get the TimeZone set by the current process. Depends on environment variable, or local configuration, or system time zone. /// </summary> public TimeZoneInfo TimeZone { get { if (_timeZone == null || _changedFunc == null || _changedFunc(_timeZone) == true) _timeZone = DetermineTimeZone(out _changedFunc); // get the current timezone, update the function that determines, if the timezone has to be rechecked. return _timeZone; } } private TimeZoneInfo _timeZone; /// <summary> /// Function that determines if the current timezone should be rechecked. /// </summary> private Func<TimeZoneInfo/*!*/, bool> _changedFunc; /// <summary> /// Finds out the time zone in the way how PHP does. /// </summary> private static TimeZoneInfo DetermineTimeZone(out Func<TimeZoneInfo, bool> changedFunc) { TimeZoneInfo result; //// check environment variable: //string env_tz = System.Environment.GetEnvironmentVariable(EnvVariableName); //if (!string.IsNullOrEmpty(env_tz)) //{ // result = GetTimeZone(env_tz); // if (result != null) // { // // recheck the timezone only if the environment variable changes // changedFunc = (timezone) => !String.Equals(timezone.StandardName, System.Environment.GetEnvironmentVariable(EnvVariableName), StringComparison.OrdinalIgnoreCase); // // return the timezone set in environment // return result; // } // PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone_env", env_tz)); //} //// check configuration: //LibraryConfiguration config = LibraryConfiguration.Local; //if (config.Date.TimeZone != null) //{ // // recheck the timezone only if the local configuration changes, ignore the environment variable from this point at all // changedFunc = (timezone) => LibraryConfiguration.Local.Date.TimeZone != timezone; // return config.Date.TimeZone; //} // convert current system time zone to PHP zone: result = SystemToPhpTimeZone(TimeZoneInfo.Local); // UTC: if (result == null) result = DateTimeUtils.UtcTimeZone;// GetTimeZone("UTC"); //PhpException.Throw(PhpError.Strict, LibResources.GetString("using_implicit_timezone", result.Id)); // recheck the timezone when the TimeZone in local configuration is set changedFunc = (timezone) => false;//LibraryConfiguration.Local.Date.TimeZone != null; return result; } } #endregion ///// <summary> ///// Gets/sets/resets legacy configuration setting "date.timezone". ///// </summary> //internal static object GsrTimeZone(LibraryConfiguration/*!*/ local, LibraryConfiguration/*!*/ @default, object value, IniAction action) //{ // string result = (local.Date.TimeZone != null) ? local.Date.TimeZone.StandardName : null; // switch (action) // { // case IniAction.Set: // { // string name = Core.Convert.ObjectToString(value); // TimeZoneInfo zone = GetTimeZone(name); // if (zone == null) // { // PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_timezone", name)); // } // else // { // local.Date.TimeZone = zone; // } // break; // } // case IniAction.Restore: // local.Date.TimeZone = @default.Date.TimeZone; // break; // } // return result; //} /// <summary> /// Gets an instance of <see cref="TimeZone"/> corresponding to specified PHP name for time zone. /// </summary> /// <param name="phpName">PHP time zone name.</param> /// <returns>The time zone or a <B>null</B> reference.</returns> internal static TimeZoneInfo GetTimeZone(string/*!*/ phpName) { if (string.IsNullOrEmpty(phpName)) { return null; } // simple binary search (not the Array.BinarySearch) var timezones = PhpTimeZone.s_lazyTimeZones.Value; int a = 0, b = timezones.Length - 1; while (a <= b) { int x = (a + b) >> 1; int comparison = StringComparer.OrdinalIgnoreCase.Compare(timezones[x].PhpName, phpName); if (comparison == 0) return timezones[x].Info; if (comparison < 0) a = x + 1; else //if (comparison > 0) b = x - 1; } // try custom offset or a known abbreviation: var dt = new DateInfo(); var _ = 0; if (dt.SetTimeZone(phpName, ref _)) { // +00:00 // -00:00 // abbr return dt.ResolveTimeZone(); } // return null; } /// <summary> /// Tries to match given <paramref name="systemTimeZone"/> to our fixed <see cref="s_timezones"/>. /// </summary> static TimeZoneInfo SystemToPhpTimeZone(TimeZoneInfo systemTimeZone) { if (systemTimeZone == null) return null; var tzns = s_lazyTimeZones.Value; for (int i = 0; i < tzns.Length; i++) { var tz = tzns[i].Info; if (tz != null && tz.DisplayName.Equals(systemTimeZone.DisplayName, StringComparison.OrdinalIgnoreCase)) // TODO: && tz.HasSameRules(systemTimeZone)) return tz; } return null; } #region date_default_timezone_get, date_default_timezone_set public static bool date_default_timezone_set(Context ctx, string zoneName) { var zone = GetTimeZone(zoneName); if (zone == null) { PhpException.Throw(PhpError.Notice, Resources.LibResources.unknown_timezone, zoneName); return false; } SetCurrentTimeZone(ctx, zone); return true; } public static string date_default_timezone_get(Context ctx) { var timezone = GetCurrentTimeZone(ctx); return (timezone != null) ? timezone.Id : null; } #endregion #region date_timezone_get, date_timezone_set /// <summary> /// Alias to <see cref="DateTimeInterface.getTimezone"/>. /// </summary> public static DateTimeZone date_timezone_get(DateTimeInterface dt) => dt.getTimezone(); /// <summary> /// Alias to <see cref="DateTime.setTimezone(DateTimeZone)"/>. /// </summary> public static DateTime date_timezone_set(DateTime dt, DateTimeZone timezone) => dt.setTimezone(timezone); #endregion #region timezone_identifiers_list, timezone_version_get, timezone_abbreviations_list, timezone_name_from_abbr static readonly Dictionary<string, int> s_what = new Dictionary<string, int>(10, StringComparer.OrdinalIgnoreCase) { {"africa", DateTimeZone.AFRICA}, {"america", DateTimeZone.AMERICA}, {"antarctica", DateTimeZone.ANTARCTICA}, {"artic", DateTimeZone.ARCTIC}, {"asia", DateTimeZone.ASIA}, {"atlantic", DateTimeZone.ATLANTIC}, {"australia", DateTimeZone.AUSTRALIA}, {"europe", DateTimeZone.EUROPE}, {"indian", DateTimeZone.INDIAN}, {"pacific", DateTimeZone.PACIFIC}, {"etc", DateTimeZone.UTC}, }; /// <summary> /// Gets zone constant. /// </summary> static int GuessWhat(TimeZoneInfoItem tz) { int slash = tz.PhpName.IndexOf('/'); if (slash > 0) { s_what.TryGetValue(tz.PhpName.Remove(slash), out int code); return code; } else { return 0; } } /// <summary> /// Returns a numerically indexed array containing all defined timezone identifiers. /// </summary> public static PhpArray timezone_identifiers_list(int what = DateTimeZone.ALL, string country = null) { if ((what & DateTimeZone.PER_COUNTRY) == DateTimeZone.PER_COUNTRY || !string.IsNullOrEmpty(country)) { throw new NotImplementedException(); } var timezones = PhpTimeZone.s_lazyTimeZones.Value; // copy names to PHP array: var array = new PhpArray(timezones.Length); for (int i = 0; i < timezones.Length; i++) { if (timezones[i].IsAlias) { continue; } if (what == DateTimeZone.ALL || what == DateTimeZone.ALL_WITH_BC || (what & GuessWhat(timezones[i])) != 0) { array.Add(timezones[i].PhpName); } } // return array; } /// <summary> /// Gets the version of used the time zone database. /// </summary> public static string timezone_version_get() { //try //{ // using (var reg = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones")) // return reg.GetValue("TzVersion", 0).ToString() + ".system"; //} //catch { } // no windows update installed return "0.system"; } /// <summary> /// Returns associative array containing dst, offset and the timezone name. /// Alias to <see cref="DateTimeZone.listAbbreviations"/>. /// </summary> [return: NotNull] public static PhpArray timezone_abbreviations_list() { var timezones = PhpTimeZone.s_lazyTimeZones.Value; var result = new PhpArray(); // for (int i = 0; i < timezones.Length; i++) { var tz = timezones[i]; var abbrs = tz.Abbreviation; if (abbrs != null) { foreach (var abbr in abbrs.Split(new[] { ',' })) { if (!result.TryGetValue(abbr, out var tzs)) tzs = new PhpArray(); tzs.Array.Add(new PhpArray(3) { {"dst", tz.Info.SupportsDaylightSavingTime }, {"offset", (long)tz.Info.BaseUtcOffset.TotalSeconds }, {"timezone_id", tz.PhpName }, }); result[abbr] = tzs; } } } // return result; } /// <summary> /// Returns the timezone name from abbreviation. /// </summary> [return: CastToFalse] public static string timezone_name_from_abbr(string abbr, int gmtOffset = -1, int isdst = -1) { var timezones = PhpTimeZone.s_lazyTimeZones.Value; string result = null; // candidate if (string.IsNullOrEmpty(abbr) && gmtOffset == -1) { // not specified return null; // FALSE } // for (int i = 0; i < timezones.Length; i++) { var tz = timezones[i]; if (tz.IsAlias) { continue; } // if {abbr} is specified => {abbrs} must contain it, otherwise do not check this timezone var matchesabbr = tz.HasAbbreviation(abbr); // offset is ignored if (gmtOffset == -1) { if (matchesabbr) { result = tz.PhpName; break; } continue; } // resolve dst delta (if needed) TimeSpan dstdelta; if (isdst >= 0) // dst taken into account { dstdelta = tz.Info.SupportsDaylightSavingTime ? tz.Info.GetAdjustmentRules().Select(r => r.DaylightDelta).FirstOrDefault(r => r.Ticks != 0) : default; if (dstdelta.Ticks == 0) { continue; } } else { dstdelta = default; } // offset must match var matchesoffset = (tz.Info.BaseUtcOffset + dstdelta).TotalSeconds == gmtOffset; if (matchesoffset) { if (matchesabbr || string.IsNullOrEmpty(abbr)) return tz.PhpName; // offset matches but not the abbreviation // in case nothing else is found use this as the result result ??= tz.PhpName; } } // return result; } #endregion #region timezone_open, timezone_offset_get /// <summary> /// Alias of new <see cref="DateTimeZone"/> /// </summary> [return: CastToFalse] public static DateTimeZone timezone_open(string timezone) { var tz = GetTimeZone(timezone); if (tz == null) return null; return new DateTimeZone(tz); } /// <summary> /// Alias of <see cref="DateTimeZone.getOffset"/> /// </summary> [return: CastToFalse] public static int timezone_offset_get(DateTimeZone timezone, Library.DateTime.DateTime datetime) { return (timezone != null) ? timezone.getOffset(datetime) : -1; } [return: CastToFalse] public static PhpArray timezone_transitions_get(DateTimeZone timezone, int timestamp_begin = 0, int timestamp_end = 0) { return timezone?.getTransitions(timestamp_begin, timestamp_end); } #endregion #region timezone_location_get /// <summary> /// Returns location information for a timezone. /// </summary> [return: CastToFalse] public static PhpArray timezone_location_get(DateTimeZone @object) => @object.getLocation(); #endregion /// <summary> /// Alias to <see cref="DateTimeZone.getName"/> /// </summary> public static string timezone_name_get(DateTimeZone @object) => @object.getName(); } }
// // AudioCdDisc.cs // // Author: // Aaron Bockover <abockover@novell.com> // Alex Launi <alex.launi@canonical.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Threading; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Unix; using MusicBrainz; using Hyena; using Banshee.Base; using Banshee.Hardware; using Banshee.Collection; using Banshee.Collection.Database; namespace Banshee.OpticalDisc.AudioCd { public class AudioCdDiscModel : DiscModel { // 44.1 kHz sample rate * 16 bit channel resolution * 2 channels (stereo) private const long PCM_FACTOR = 176400; public event EventHandler MetadataQueryStarted; public event EventHandler MetadataQueryFinished; public event EventHandler EnabledCountChanged; private bool metadata_query_success; private DateTime metadata_query_start_time; public bool MetadataQuerySuccess { get { return metadata_query_success; } } private TimeSpan duration; public TimeSpan Duration { get { return duration; } } private long file_size; public long FileSize { get { return file_size; } } public AudioCdDiscModel (IDiscVolume volume) : base (volume) { disc_title = Catalog.GetString ("Audio CD"); MusicBrainzService.UserAgent = Banshee.Web.Browser.UserAgent; } public void NotifyUpdated () { OnReloaded (); } public override void LoadModelFromDisc () { Clear (); LocalDisc mb_disc = LocalDisc.GetFromDevice (Volume.DeviceNode); if (mb_disc == null) { throw new ApplicationException ("Could not read contents of the disc. Platform may not be supported."); } TimeSpan[] durations = mb_disc.GetTrackDurations (); for (int i = 0, n = durations.Length; i < n; i++) { AudioCdTrackInfo track = new AudioCdTrackInfo (this, Volume.DeviceNode, i); track.TrackNumber = i + 1; track.TrackCount = n; track.DiscNumber = 1; track.Duration = durations[i]; track.ArtistName = ArtistInfo.UnknownArtistName; track.AlbumTitle = AlbumInfo.UnknownAlbumTitle; track.TrackTitle = String.Format (Catalog.GetString ("Track {0}"), track.TrackNumber); track.FileSize = PCM_FACTOR * (uint)track.Duration.TotalSeconds; Add (track); duration += track.Duration; file_size += track.FileSize; } EnabledCount = Count; Reload (); ThreadPool.QueueUserWorkItem (LoadDiscMetadata, mb_disc); } private void LoadDiscMetadata (object state) { try { LocalDisc mb_disc = (LocalDisc)state; OnMetadataQueryStarted (mb_disc); Release release = Release.Query (mb_disc).First (); if (release == null || release.Score < 100) { OnMetadataQueryFinished (false); return; } var tracks = release.GetTracks (); if (tracks.Count != Count) { OnMetadataQueryFinished (false); return; } disc_title = release.GetTitle (); int disc_number = 1; int i = 0; foreach (Disc disc in release.GetDiscs ()) { i++; if (disc.Id == mb_disc.Id) { disc_number = i; } } DateTime release_date = DateTime.MaxValue; foreach (Event release_event in release.GetEvents ()) { if (release_event.Date != null) { try { // Handle "YYYY" dates var date_str = release_event.Date; DateTime date = DateTime.Parse ( date_str.Length > 4 ? date_str : date_str + "-01", ApplicationContext.InternalCultureInfo ); if (date < release_date) { release_date = date; } } catch { } } } DatabaseArtistInfo artist = new DatabaseArtistInfo (); var mb_artist = release.GetArtist (); artist.Name = mb_artist.GetName (); artist.NameSort = mb_artist.GetSortName (); artist.MusicBrainzId = mb_artist.Id; bool is_compilation = false; DatabaseAlbumInfo album = new DatabaseAlbumInfo (); album.Title = disc_title; album.ArtistName = artist.Name; album.MusicBrainzId = release.Id; album.ReleaseDate = release_date == DateTime.MaxValue ? DateTime.MinValue : release_date; i = 0; foreach (Track track in tracks) { AudioCdTrackInfo model_track = (AudioCdTrackInfo)this[i++]; var mb_track_artist = track.GetArtist (); model_track.MusicBrainzId = track.Id; model_track.TrackTitle = track.GetTitle (); model_track.ArtistName = mb_track_artist.GetName (); model_track.AlbumTitle = disc_title; model_track.DiscNumber = disc_number; model_track.Album = album; model_track.Artist = new DatabaseArtistInfo (); model_track.Artist.Name = model_track.ArtistName; model_track.Artist.NameSort = mb_track_artist.GetSortName (); model_track.Artist.MusicBrainzId = mb_track_artist.Id; if (release_date != DateTime.MinValue) { model_track.Year = release_date.Year; } if (!is_compilation && mb_track_artist.Id != artist.MusicBrainzId) { is_compilation = true; } } if (is_compilation) { album.IsCompilation = true; for (i = 0; i < tracks.Count; i++) { AudioCdTrackInfo model_track = (AudioCdTrackInfo)this[i]; model_track.IsCompilation = true; model_track.AlbumArtist = artist.Name; model_track.AlbumArtistSort = artist.NameSort; } } OnMetadataQueryFinished (true); } catch (Exception ex) { Log.DebugException (ex); OnMetadataQueryFinished (false); } } private void OnMetadataQueryStarted (LocalDisc mb_disc) { metadata_query_success = false; metadata_query_start_time = DateTime.Now; Log.InformationFormat ("Querying MusicBrainz for Disc Release ({0})", mb_disc.Id); ThreadAssist.ProxyToMain (delegate { EventHandler handler = MetadataQueryStarted; if (handler != null) { handler (this, EventArgs.Empty); } }); } private void OnMetadataQueryFinished (bool success) { metadata_query_success = success; Log.InformationFormat ("Query finished (success: {0}, {1} seconds)", success, (DateTime.Now - metadata_query_start_time).TotalSeconds); ThreadAssist.ProxyToMain (delegate { Reload (); EventHandler handler = MetadataQueryFinished; if (handler != null) { handler (this, EventArgs.Empty); } }); } private void OnEnabledCountChanged () { EventHandler handler = EnabledCountChanged; if (handler != null) { handler (this, EventArgs.Empty); } } private string disc_title; public override string Title { get { return disc_title; } } private int enabled_count; public int EnabledCount { get { return enabled_count; } internal set { enabled_count = value; OnEnabledCountChanged (); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the ConTurnosCantidadDemandaRechazada class. /// </summary> [Serializable] public partial class ConTurnosCantidadDemandaRechazadaCollection : ReadOnlyList<ConTurnosCantidadDemandaRechazada, ConTurnosCantidadDemandaRechazadaCollection> { public ConTurnosCantidadDemandaRechazadaCollection() {} } /// <summary> /// This is Read-only wrapper class for the CON_TurnosCantidadDemandaRechazada view. /// </summary> [Serializable] public partial class ConTurnosCantidadDemandaRechazada : ReadOnlyRecord<ConTurnosCantidadDemandaRechazada>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_TurnosCantidadDemandaRechazada", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarCantidadDemanda = new TableSchema.TableColumn(schema); colvarCantidadDemanda.ColumnName = "cantidadDemanda"; colvarCantidadDemanda.DataType = DbType.Int32; colvarCantidadDemanda.MaxLength = 0; colvarCantidadDemanda.AutoIncrement = false; colvarCantidadDemanda.IsNullable = true; colvarCantidadDemanda.IsPrimaryKey = false; colvarCantidadDemanda.IsForeignKey = false; colvarCantidadDemanda.IsReadOnly = false; schema.Columns.Add(colvarCantidadDemanda); TableSchema.TableColumn colvarFechaRegistro = new TableSchema.TableColumn(schema); colvarFechaRegistro.ColumnName = "fechaRegistro"; colvarFechaRegistro.DataType = DbType.DateTime; colvarFechaRegistro.MaxLength = 0; colvarFechaRegistro.AutoIncrement = false; colvarFechaRegistro.IsNullable = false; colvarFechaRegistro.IsPrimaryKey = false; colvarFechaRegistro.IsForeignKey = false; colvarFechaRegistro.IsReadOnly = false; schema.Columns.Add(colvarFechaRegistro); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_TurnosCantidadDemandaRechazada",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ConTurnosCantidadDemandaRechazada() { SetSQLProps(); SetDefaults(); MarkNew(); } public ConTurnosCantidadDemandaRechazada(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ConTurnosCantidadDemandaRechazada(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ConTurnosCantidadDemandaRechazada(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>("idEfector"); } set { SetColumnValue("idEfector", value); } } [XmlAttribute("CantidadDemanda")] [Bindable(true)] public int? CantidadDemanda { get { return GetColumnValue<int?>("cantidadDemanda"); } set { SetColumnValue("cantidadDemanda", value); } } [XmlAttribute("FechaRegistro")] [Bindable(true)] public DateTime FechaRegistro { get { return GetColumnValue<DateTime>("fechaRegistro"); } set { SetColumnValue("fechaRegistro", value); } } #endregion #region Columns Struct public struct Columns { public static string IdEfector = @"idEfector"; public static string CantidadDemanda = @"cantidadDemanda"; public static string FechaRegistro = @"fechaRegistro"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using OpenTK.Graphics.OpenGL; using nzy3D.Colors; using nzy3D.Maths; using nzy3D.Glut; using nzy3D.Plot3D.Rendering.View; using nzy3D.Plot3D.Text; using nzy3D.Plot3D.Text.Align; namespace nzy3D.Plot3D.Text.Renderers { /// <summary> /// A <see cref="TextBillboardRenderer"/> allows writing 2d text always facing the Camera of a 3d Scene. /// <br/> /// TextBillboard provides the pixel definition of all characters of /// the ASCII alphabet. A default bitmap (plain rectangle) /// is provided for unrecognized characters /// (those that do not have an ASCII code). /// The bitmap library is static, and thus no overhead is /// generated by the use of several instances of TextBillboard. /// <br/> /// It is however not necessary to have an instance of TextBillboard /// for each drawn string. /// <br/> /// <code> /// String s = new String("2d text in 3d Scene");<br/> /// TextBillboard txt = new TextBillboard();<br/> /// BoundingBox3d box;<br/> /// <br/> /// txt.drawText(gl, s, Coord3d.ORIGIN, Halign.LEFT, Valign.GROUND, Color.BLACK);<br/> /// box = txt.drawText(gl, glu, cam, s, Coord3d.ORIGIN, Halign.LEFT, Valign.GROUND, Color.BLACK);<br/> /// </code> /// <br/> /// <b>Layout constants</b> /// <br/> /// As demonstrated in the previous example, the <see cref="TextBillboardRenderer"/> handles /// vertical and horizontal layout of text according to the given text coordinate. /// <br/> /// The following picture illustrates the text layout when using /// the various layout constants /// <img src="plot3d/primitives/doc-files/TextBillboardBillboard-1.gif"/> /// @author Martin Pernollet /// </summary> public class TextBillboardRenderer : AbstractTextRenderer, ITextRenderer { // px heigth private static int charHeight = 13; // px width private static int charWidth = 8; // px between 2 characters private static int charOffset = 2; public TextBillboardRenderer() : base() { } public override void drawSimpleText(Rendering.View.Camera cam, string s, Maths.Coord3d position, Colors.Color color) { GL.Color3(color.r, color.g, color.b); GL.RasterPos3(position.x, position.y, position.z); printString(s, Halign.RIGHT, Valign.GROUND); } public override Maths.BoundingBox3d drawText(Rendering.View.Camera cam, string s, Maths.Coord3d position, Align.Halign halign, Align.Valign valign, Colors.Color color, Maths.Coord2d screenOffset, Maths.Coord3d sceneOffset) { GL.Color3(color.r, color.g, color.b); GL.RasterPos3(position.x, position.y, position.z); BillBoardSize dims = printString(s, halign, valign); Coord3d posScreen = cam.ModelToScreen(position); Coord3d botLeft = new Coord3d(); Coord3d topRight = new Coord3d(); botLeft.x = posScreen.x + dims.xoffset; botLeft.y = posScreen.y + dims.yoffset; botLeft.z = posScreen.z; topRight.x = botLeft.x + dims.xoffset; topRight.y = botLeft.y + dims.yoffset; topRight.z = botLeft.z; BoundingBox3d txtBounds = new BoundingBox3d(); txtBounds.@add(cam.ScreenToModel(botLeft)); txtBounds.@add(cam.ScreenToModel(topRight)); return txtBounds; } private BillBoardSize printString(string s, Halign halign, Valign valign) { char[] acodes = s.ToCharArray(); int nchar = s.Length; float xorig = 0; float yorig = 2; float xmove = charWidth + charOffset; float ymove = 0; // Compute horizontal alignment switch (halign) { case Align.Halign.RIGHT: xorig = xorig; break; case Align.Halign.CENTER: xorig = nchar * xmove / 2; break; case Align.Halign.LEFT: xorig = nchar * xmove; break; default: throw new Exception("Horizontal alignement constant unknown: " + halign); } // Compute vertical alignment switch (valign) { case Align.Valign.TOP: yorig = 0; break; case Align.Valign.GROUND: yorig = yorig; break; case Align.Valign.CENTER: yorig = charHeight / 2; break; case Align.Valign.BOTTOM: yorig = charHeight; break; default: throw new Exception("Vertical alignement constant unknown: " + valign); } // Draw the bitmaps GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); int idx = 0; for (int c = 0; c <= acodes.Length - 1; c++) { idx = (int)(acodes[c]) - 32; if (idx < 0 | idx >= ascii.Length) { GL.Bitmap(charWidth, charHeight, xorig, yorig, xmove, ymove, nonascii); } else { GL.Bitmap(charWidth, charHeight, xorig, yorig, xmove, ymove, ascii[idx]); } } return new BillBoardSize(xmove * nchar, charHeight, -xorig, -yorig); } private class BillBoardSize { public float width; public float height; public float xoffset; public float yoffset; public BillBoardSize(float width, float height, float xoffset, float yoffset) { this.width = width; this.height = height; this.xoffset = xoffset; this.yoffset = yoffset; } } // each of the 95 line is a letter, each of the (charHeight) byte of a line represent a raw of (charWidth) pixels private static byte[][] ascii = { new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x18, 0x18, 0x0, 0x0, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x36, 0x36, 0x36, 0x36 }, new byte[] { 0x0, 0x0, 0x0, 0x66, 0x66, 0xff, 0x66, 0x66, 0xff, 0x66, 0x66, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x18, 0x7e, 0xff, 0x1b, 0x1f, 0x7e, 0xf8, 0xd8, 0xff, 0x7e, 0x18 }, new byte[] { 0x0, 0x0, 0xe, 0x1b, 0xdb, 0x6e, 0x30, 0x18, 0xc, 0x76, 0xdb, 0xd8, 0x70 }, new byte[] { 0x0, 0x0, 0x7f, 0xc6, 0xcf, 0xd8, 0x70, 0x70, 0xd8, 0xcc, 0xcc, 0x6c, 0x38 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x18, 0x1c, 0xc, 0xe }, new byte[] { 0x0, 0x0, 0xc, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0xc }, new byte[] { 0x0, 0x0, 0x30, 0x18, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0x18, 0x30 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x99, 0x5a, 0x3c, 0xff, 0x3c, 0x5a, 0x99, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x0, 0x18, 0x18, 0x18, 0xff, 0xff, 0x18, 0x18, 0x18, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x30, 0x18, 0x1c, 0x1c, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x0, 0x38, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x60, 0x60, 0x30, 0x30, 0x18, 0x18, 0xc, 0xc, 0x6, 0x6, 0x3, 0x3 }, new byte[] { 0x0, 0x0, 0x3c, 0x66, 0xc3, 0xe3, 0xf3, 0xdb, 0xcf, 0xc7, 0xc3, 0x66, 0x3c }, new byte[] { 0x0, 0x0, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x38, 0x18 }, new byte[] { 0x0, 0x0, 0xff, 0xc0, 0xc0, 0x60, 0x30, 0x18, 0xc, 0x6, 0x3, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0x3, 0x3, 0x7, 0x7e, 0x7, 0x3, 0x3, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0xc, 0xc, 0xc, 0xc, 0xc, 0xff, 0xcc, 0x6c, 0x3c, 0x1c, 0xc }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0x3, 0x3, 0x7, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0xff }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0xc3, 0xc3, 0xc7, 0xfe, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0x30, 0x30, 0x30, 0x30, 0x18, 0xc, 0x6, 0x3, 0x3, 0x3, 0xff }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0xc3, 0xc3, 0xe7, 0x7e, 0xe7, 0xc3, 0xc3, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0x3, 0x3, 0x3, 0x7f, 0xe7, 0xc3, 0xc3, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0x0, 0x38, 0x38, 0x0, 0x0, 0x38, 0x38, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x30, 0x18, 0x1c, 0x1c, 0x0, 0x0, 0x1c, 0x1c, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x6, 0xc, 0x18, 0x30, 0x60, 0xc0, 0x60, 0x30, 0x18, 0xc, 0x6 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0x0, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x60, 0x30, 0x18, 0xc, 0x6, 0x3, 0x6, 0xc, 0x18, 0x30, 0x60 }, new byte[] { 0x0, 0x0, 0x18, 0x0, 0x0, 0x18, 0x18, 0xc, 0x6, 0x3, 0xc3, 0xc3, 0x7e }, new byte[] { 0x0, 0x0, 0x3f, 0x60, 0xcf, 0xdb, 0xd3, 0xdd, 0xc3, 0x7e, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18 }, new byte[] { 0x0, 0x0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0xfc, 0xce, 0xc7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc7, 0xce, 0xfc }, new byte[] { 0x0, 0x0, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xc0, 0xff }, new byte[] { 0x0, 0x0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xff }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0xc3, 0xc3, 0xcf, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3 }, new byte[] { 0x0, 0x0, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e }, new byte[] { 0x0, 0x0, 0x7c, 0xee, 0xc6, 0x6, 0x6, 0x6, 0x6, 0x6, 0x6, 0x6, 0x6 }, new byte[] { 0x0, 0x0, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xe0, 0xf0, 0xd8, 0xcc, 0xc6, 0xc3 }, new byte[] { 0x0, 0x0, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0 }, new byte[] { 0x0, 0x0, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xdb, 0xff, 0xff, 0xe7, 0xc3 }, new byte[] { 0x0, 0x0, 0xc7, 0xc7, 0xcf, 0xcf, 0xdf, 0xdb, 0xfb, 0xf3, 0xf3, 0xe3, 0xe3 }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe }, new byte[] { 0x0, 0x0, 0x3f, 0x6e, 0xdf, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c }, new byte[] { 0x0, 0x0, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0x3, 0x3, 0x7, 0x7e, 0xe0, 0xc0, 0xc0, 0xe7, 0x7e }, new byte[] { 0x0, 0x0, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff }, new byte[] { 0x0, 0x0, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3 }, new byte[] { 0x0, 0x0, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3 }, new byte[] { 0x0, 0x0, 0xc3, 0xe7, 0xff, 0xff, 0xdb, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3 }, new byte[] { 0x0, 0x0, 0xc3, 0x66, 0x66, 0x3c, 0x3c, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3 }, new byte[] { 0x0, 0x0, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3 }, new byte[] { 0x0, 0x0, 0xff, 0xc0, 0xc0, 0x60, 0x30, 0x7e, 0xc, 0x6, 0x3, 0x3, 0xff }, new byte[] { 0x0, 0x0, 0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c }, new byte[] { 0x0, 0x3, 0x3, 0x6, 0x6, 0xc, 0xc, 0x18, 0x18, 0x30, 0x30, 0x60, 0x60 }, new byte[] { 0x0, 0x0, 0x3c, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0x3c }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc3, 0x66, 0x3c, 0x18 }, new byte[] { 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x18, 0x38, 0x30, 0x70 }, new byte[] { 0x0, 0x0, 0x7f, 0xc3, 0xc3, 0x7f, 0x3, 0xc3, 0x7e, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xfe, 0xc3, 0xc3, 0xc3, 0xc3, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0 }, new byte[] { 0x0, 0x0, 0x7e, 0xc3, 0xc0, 0xc0, 0xc0, 0xc3, 0x7e, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x7f, 0xc3, 0xc3, 0xc3, 0xc3, 0x7f, 0x3, 0x3, 0x3, 0x3, 0x3 }, new byte[] { 0x0, 0x0, 0x7f, 0xc0, 0xc0, 0xfe, 0xc3, 0xc3, 0x7e, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x30, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x33, 0x1e }, new byte[] { 0x7e, 0xc3, 0x3, 0x3, 0x7f, 0xc3, 0xc3, 0xc3, 0x7e, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0 }, new byte[] { 0x0, 0x0, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x0, 0x0, 0x18, 0x0 }, new byte[] { 0x38, 0x6c, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0x0, 0x0, 0xc, 0x0 }, new byte[] { 0x0, 0x0, 0xc6, 0xcc, 0xf8, 0xf0, 0xd8, 0xcc, 0xc6, 0xc0, 0xc0, 0xc0, 0xc0 }, new byte[] { 0x0, 0x0, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78 }, new byte[] { 0x0, 0x0, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xfe, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xfc, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0xc0, 0xc0, 0xc0, 0xfe, 0xc3, 0xc3, 0xc3, 0xc3, 0xfe, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x3, 0x3, 0x3, 0x7f, 0xc3, 0xc3, 0xc3, 0xc3, 0x7f, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xe0, 0xfe, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xfe, 0x3, 0x3, 0x7e, 0xc0, 0xc0, 0x7f, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x1c, 0x36, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x0 }, new byte[] { 0x0, 0x0, 0x7e, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3, 0xc3, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xc3, 0xe7, 0xff, 0xdb, 0xc3, 0xc3, 0xc3, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xc3, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0xc3, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0xc0, 0x60, 0x60, 0x30, 0x18, 0x3c, 0x66, 0x66, 0xc3, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xff, 0x60, 0x30, 0x18, 0xc, 0x6, 0xff, 0x0, 0x0, 0x0, 0x0 }, new byte[] { 0x0, 0x0, 0xf, 0x18, 0x18, 0x18, 0x38, 0xf0, 0x38, 0x18, 0x18, 0x18, 0xf }, new byte[] { 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18 }, new byte[] { 0x0, 0x0, 0xf0, 0x18, 0x18, 0x18, 0x1c, 0xf, 0x1c, 0x18, 0x18, 0x18, 0xf0 }, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x8f, 0xf1, 0x60, 0x0, 0x0, 0x0 } }; private static byte[] nonascii = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using NQuery.Runtime; namespace NQuery.Compilation { internal sealed class Binder { private IErrorReporter _errorReporter; private static readonly Dictionary<string, Type> _typeShortCutTable = CreateShortCutTable(); private static readonly MethodInfo _unaryOperatorPlaceholder = GetSpecialBuiltInOperator("Placeholder", typeof(DBNull)); private static readonly MethodInfo _binaryOperatorPlaceholder = GetSpecialBuiltInOperator("Placeholder", typeof(DBNull), typeof(DBNull)); private static readonly MethodInfo _generalEqualityOperator = GetSpecialBuiltInOperator("op_Equality", typeof(object), typeof(object)); private static readonly MethodInfo _generalInequalityOperator = GetSpecialBuiltInOperator("op_Inequality", typeof(object), typeof(object)); private static readonly MethodInfo _enumBitAndOperator = GetSpecialBuiltInOperator("op_BitwiseAnd", typeof(Enum), typeof(Enum)); private static readonly MethodInfo _enumBitOrOperator = GetSpecialBuiltInOperator("op_BitwiseOr", typeof(Enum), typeof(Enum)); public Binder(IErrorReporter errorReporter) { _errorReporter = errorReporter; } #region Static Initializers private static Dictionary<string, Type> CreateShortCutTable() { Dictionary<string, Type> result = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); result.Add("BYTE", typeof(Byte)); result.Add("SBYTE", typeof(SByte)); result.Add("CHAR", typeof(Char)); result.Add("INT16", typeof(Int16)); result.Add("UINT16", typeof(UInt16)); result.Add("INT32", typeof(Int32)); result.Add("UINT32", typeof(UInt32)); result.Add("INT64", typeof(Int64)); result.Add("UINT64", typeof(UInt64)); result.Add("SINGLE", typeof(Single)); result.Add("DOUBLE", typeof(Double)); result.Add("DECIMAL", typeof(Decimal)); result.Add("STRING", typeof(String)); result.Add("OBJECT", typeof(Object)); result.Add("BOOL", typeof(Boolean)); result.Add("BOOLEAN", typeof(Boolean)); result.Add("DATETIME", typeof(DateTime)); result.Add("TIMESPAN", typeof(TimeSpan)); result.Add("BIGINT", typeof(Int64)); result.Add("BINARY", typeof(Byte[])); result.Add("BIT", typeof(Boolean)); //result.Add("CHAR", typeof(String)); //result.Add("DATETIME", typeof(DateTime)); //result.Add("DECIMAL", typeof(Decimal)); result.Add("FLOAT", typeof(Double)); result.Add("IMAGE", typeof(Byte[])); result.Add("INT", typeof(Int32)); result.Add("MONEY", typeof(Decimal)); result.Add("NCHAR", typeof(String)); result.Add("NTEXT", typeof(String)); result.Add("NUMERIC", typeof(Decimal)); result.Add("NVARCHAR", typeof(String)); result.Add("REAL", typeof(Single)); result.Add("SMALLDATETIME", typeof(DateTime)); result.Add("SMALLINT", typeof(Int16)); result.Add("SMALLMONEY", typeof(Decimal)); result.Add("SQL_VARIANT", typeof(Object)); result.Add("TEXT", typeof(String)); result.Add("TIMESTAMP", typeof(Byte[])); result.Add("TINYINT", typeof(Byte)); result.Add("UNIQUEIDENTIFIER", typeof(Guid)); result.Add("VARBINARY", typeof(Byte[])); result.Add("VARCHAR", typeof(String)); result.Add("XML", typeof(String)); return result; } private static MethodInfo GetSpecialBuiltInOperator(string methodName, params Type[] parameterTypes) { MethodInfo result = typeof(BuiltInOperators).GetMethod(methodName, parameterTypes); if (result == null) throw ExceptionBuilder.InternalError( "Could not found special method {0}.{1}({2})", typeof(BuiltInOperators).FullName, methodName, FormattingHelpers.FormatTypeList(parameterTypes) ); return result; } #endregion #region Conversion Methods public static PrimitiveType GetPrimitiveType(Type type) { if (type == typeof(Boolean)) return PrimitiveType.Boolean; if (type == typeof(Byte)) return PrimitiveType.Byte; if (type == typeof(SByte)) return PrimitiveType.SByte; if (type == typeof(Char)) return PrimitiveType.Char; if (type == typeof(Int16)) return PrimitiveType.Int16; if (type == typeof(UInt16)) return PrimitiveType.UInt16; if (type == typeof(Int32)) return PrimitiveType.Int32; if (type == typeof(UInt32)) return PrimitiveType.UInt32; if (type == typeof(Int64)) return PrimitiveType.Int64; if (type == typeof(UInt64)) return PrimitiveType.UInt64; if (type == typeof(Single)) return PrimitiveType.Single; if (type == typeof(Double)) return PrimitiveType.Double; if (type == typeof(Decimal)) return PrimitiveType.Decimal; if (type == typeof(String)) return PrimitiveType.String; if (type == typeof(Object)) return PrimitiveType.Object; if (type == typeof(DBNull)) return PrimitiveType.Null; return PrimitiveType.None; } public static bool ConversionNeeded(Type fromType, Type targetType) { if (fromType == targetType) return false; // NULL does not need any conversion. if (fromType == typeof(DBNull) || targetType == typeof(DBNull)) return false; // Check if fromType is derived from targetType. In this // case no conversion is needed. Type baseType = fromType.BaseType; while (baseType != null) { if (baseType == targetType) return false; baseType = baseType.BaseType; } if (fromType.IsInterface && targetType == typeof(object)) { // Though interfaces are not derived from System.Object, they are // compatible to it. return false; } if (targetType.IsInterface) { // Check if fromType implements targetType. In this // case no conversion is needed. if (ArrayHelpers.Contains(fromType.GetInterfaces(), targetType)) return false; } return true; } public bool ConversionExists(Type fromType, Type targetType, bool allowExplicit) { if (!ConversionNeeded(fromType, targetType)) return true; return allowExplicit && (AllowsDownCast(fromType, targetType) || GetExplicitConversionMethod(fromType, targetType) != null) || GetImplicitConversionMethod(fromType, targetType) != null; } public Type ChooseBetterTypeConversion(Type type1, Type type2) { // Make sure that boxing is better than converting if (type1 == typeof(object)) return type1; if (type2 == typeof(object)) return type2; // Make sure every type is better than NULL if (type1 == typeof(DBNull)) return type2; if (type2 == typeof(DBNull)) return type1; if (ConversionNeeded(type1, type2)) { // Check if type2 is the "better" type. // // That is the case if and only if // an implicit conversion from type1 --> type2 exists // and no implicit conversion from type2 --> type1 exists. if (ConversionExists(type1, type2, false) && !ConversionExists(type2, type1, false)) return type2; } return type1; } private ExpressionNode ConvertExpressionIfRequired(ExpressionNode expression, Type targetType, bool enableDownCast) { if (expression.ExpressionType == typeof(DBNull)) return LiteralExpression.FromTypedNull(targetType); if (ConversionNeeded(expression.ExpressionType, targetType)) { MethodInfo methodInfo = GetImplicitConversionMethod(expression.ExpressionType, targetType); if (methodInfo == null) methodInfo = GetExplicitConversionMethod(expression.ExpressionType, targetType); if (methodInfo != null) { CastExpression result = new CastExpression(expression, targetType); result.ConvertMethod = methodInfo; return result; } if (enableDownCast && AllowsDownCast(expression.ExpressionType, targetType)) { CastExpression result = new CastExpression(expression, targetType); return result; } // Conversion not possible, report an error. _errorReporter.CannotCast(expression, targetType); } return expression; } public ExpressionNode ConvertExpressionIfRequired(ExpressionNode expression, Type targetType) { return ConvertExpressionIfRequired(expression, targetType, false); } public ExpressionNode ConvertOrDowncastExpressionIfRequired(ExpressionNode expression, Type targetType) { return ConvertExpressionIfRequired(expression, targetType, true); } private static bool AllowsDownCast(Type sourceType, Type targetType) { if (targetType.IsSubclassOf(sourceType)) return true; if (targetType.IsInterface) return true; return false; } #endregion #region General Overload Resolution Helpers private static int TypeHierachyDistance(Type baseType, Type type) { int distance = 0; while (type != null && type != baseType) { distance++; type = type.BaseType; } return distance; } private int CompareConversions(Type source, Type type1, Type type2) { PrimitiveType ptSource = GetPrimitiveType(source); PrimitiveType ptType1 = GetPrimitiveType(type1); PrimitiveType ptType2 = GetPrimitiveType(type2); if (ptSource != PrimitiveType.None && ptType1 != PrimitiveType.None && ptType2 != PrimitiveType.None) { // All types are pimitive types, compare them in the predefined way. return CompareConversions(ptSource, ptType1, ptType2); } else { // At least one type is a custom type. bool type1IsAssignableFromSource = type1.IsAssignableFrom(source); bool type2IsAssignableFromSource = type2.IsAssignableFrom(source); if (type1IsAssignableFromSource && !type2IsAssignableFromSource) { return -1; } else if (!type1IsAssignableFromSource && type2IsAssignableFromSource) { return 1; } else if (type1IsAssignableFromSource && type2IsAssignableFromSource) { // Both are assignable. See which one is better. // // First we ensure that classes are always preferred over interfaces. if (!type1.IsInterface && type2.IsInterface) { return -1; } else if (type1.IsInterface && !type2.IsInterface) { return 1; } // Both are interfaces or both are classes. To determine which one // is better we assume that the 'closest' one (according to the // type hierarchy) to the source type is better. int type1Distance = TypeHierachyDistance(source, type1); int type2Distance = TypeHierachyDistance(source, type2); return type1Distance - type2Distance; } else { // The class hierarachy does not help. They can only be compatible by // custom casting operators. // // We check whaht kind of (implicit or explicit) to determine which one // is better. CastingOperatorType sourceToType1; if (GetImplicitConversionMethod(source, type1) != null) sourceToType1 = CastingOperatorType.Implicit; else sourceToType1 = CastingOperatorType.Explicit; CastingOperatorType sourceToType2; if (GetImplicitConversionMethod(source, type2) != null) sourceToType2 = CastingOperatorType.Implicit; else sourceToType2 = CastingOperatorType.Explicit; if (sourceToType1 == sourceToType2) { // Both are implicit or both implicit -- neither is better. return 0; } if (sourceToType1 == CastingOperatorType.Implicit) { // An implicit conversion from source to type1 exists, but only an // explicit conversion from source to type2 exists -- type1 is better. return -1; } else { // It is the other way around -- type2 is better. return 1; } } } } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static int CompareConversions(PrimitiveType source, PrimitiveType type1, PrimitiveType type2) { // If type1 and type2 are equal neither are better if (type1 == type2) return 0; // If source is type1, type1 is better if (source == type1) return -1; // If source is type2, type2 is better if (source == type2) return 1; // Make sure we prefer System.Object for NULL values if (source == PrimitiveType.Null) { if (type1 == PrimitiveType.Object) return -1; if (type1 == PrimitiveType.Object) return 1; return 0; } // Make sure we prefer everything over generic System.Object if (type1 == PrimitiveType.Object) return 1; if (type2 == PrimitiveType.Object) return -1; // Make sure we prefer signed before unsigned if (type1 == PrimitiveType.SByte && (type2 == PrimitiveType.Byte || type2 == PrimitiveType.UInt16 || type2 == PrimitiveType.UInt32 || type2 == PrimitiveType.UInt64)) return -1; if (type2 == PrimitiveType.SByte && (type1 == PrimitiveType.Byte || type1 == PrimitiveType.UInt16 || type1 == PrimitiveType.UInt32 || type1 == PrimitiveType.UInt64)) return 1; if (type1 == PrimitiveType.Int16 && (type2 == PrimitiveType.UInt16 || type2 == PrimitiveType.UInt32 || type2 == PrimitiveType.UInt64)) return -1; if (type2 == PrimitiveType.Int16 && (type1 == PrimitiveType.UInt16 || type1 == PrimitiveType.UInt32 || type1 == PrimitiveType.UInt64)) return 1; if (type1 == PrimitiveType.Int32 && (type2 == PrimitiveType.UInt32 || type2 == PrimitiveType.UInt64)) return -1; if (type2 == PrimitiveType.Int32 && (type1 == PrimitiveType.UInt32 || type1 == PrimitiveType.UInt64)) return 1; if (type1 == PrimitiveType.Int64 && type2 == PrimitiveType.UInt64) return -1; if (type2 == PrimitiveType.Int64 && type1 == PrimitiveType.UInt64) return 1; if (source == PrimitiveType.Byte || source == PrimitiveType.Int16 || source == PrimitiveType.Int32 || source == PrimitiveType.Int64 || source == PrimitiveType.SByte || source == PrimitiveType.UInt16 || source == PrimitiveType.UInt32 || source == PrimitiveType.UInt64) { // Make sure we prefer ints before reals if (type1 == PrimitiveType.Int64 && (type2 == PrimitiveType.Single || type2 == PrimitiveType.Double)) return -1; if (type2 == PrimitiveType.Int64 && (type1 == PrimitiveType.Single || type1 == PrimitiveType.Double)) return 1; } if (source == PrimitiveType.Byte || source == PrimitiveType.Int16 || source == PrimitiveType.Int32 || source == PrimitiveType.Int64 || source == PrimitiveType.SByte || source == PrimitiveType.UInt16 || source == PrimitiveType.UInt32 || source == PrimitiveType.UInt64 || source == PrimitiveType.Single || source == PrimitiveType.Double) { // Make sure if source is a number and the conversion is string we prefer the // other conversion (which can't be a string anymore) if (type1 == PrimitiveType.String) return 1; if (type2 == PrimitiveType.String) return -1; } return 0; } private int CompareFunctions(Type[] argumentTypes, Type[] function1ParameterTypes, Type[] function2ParameterTypes) { int conversionSum = 0; for (int i = 0; i < argumentTypes.Length; i++) { conversionSum += CompareConversions( argumentTypes[i], function1ParameterTypes[i], function2ParameterTypes[i] ); } return conversionSum; } #endregion #region Implicit/Explicit Casting Operator Helpers private MethodInfo GetImplicitConversionMethod(Type sourceType, Type targetType) { return GetConversionMethod(CastingOperatorType.Implicit, sourceType, targetType); } private MethodInfo GetExplicitConversionMethod(Type sourceType, Type targetType) { return GetConversionMethod(CastingOperatorType.Explicit, sourceType, targetType); } private MethodInfo GetConversionMethod(CastingOperatorType castingOperatorType, Type sourceType, Type targetType) { MethodInfo targetFromSource; MethodInfo sourceToTarget; // First search the target type for a suitable conversion method. targetFromSource = GetConversionMethod(OperatorMethodCache.GetOperatorMethods(targetType, castingOperatorType), sourceType, targetType); // Secondly search the source type for a suitable conversion method. sourceToTarget = GetConversionMethod(OperatorMethodCache.GetOperatorMethods(sourceType, castingOperatorType), sourceType, targetType); if (sourceToTarget == null && targetFromSource == null) { // Ok, no custom casting operators found. Look in the built-in conversions. return BuiltInConversions.GetConversion(castingOperatorType, sourceType, targetType); } else { // Now we might have two possible methods. We found an ambiguous match in that case. if (targetFromSource != sourceToTarget && targetFromSource != null && sourceToTarget != null) { // Ambiguous match, we don't know what to do. _errorReporter.AmbiguousOperator(castingOperatorType, targetFromSource, sourceToTarget); return targetFromSource; } if (targetFromSource != null) return targetFromSource; else return sourceToTarget; } } private static MethodInfo GetConversionMethod(IEnumerable<MethodInfo> candidates, Type sourceType, Type targetType) { MethodInfo lastMatchMethod = null; Type lastMatchParameterType = null; foreach (MethodInfo methodInfo in candidates) { Type parameterType = methodInfo.GetParameters()[0].ParameterType; if (methodInfo.ReturnType == targetType && parameterType.IsAssignableFrom(sourceType)) { if (lastMatchParameterType == null || parameterType.IsSubclassOf(lastMatchParameterType)) { lastMatchMethod = methodInfo; lastMatchParameterType = parameterType; } } } return lastMatchMethod; } #endregion #region Bind Invocations private InvocableBinding[] GetApplicableInvocables(IEnumerable<InvocableBinding> invocables, Type[] argumentTypes, bool allowExplicit) { List<InvocableBinding> applicableFunctionList = new List<InvocableBinding>(); foreach (InvocableBinding invocableBinding in invocables) { Type[] parameterTypes = invocableBinding.GetParameterTypes(); if (parameterTypes.Length == argumentTypes.Length) { for (int i = 0; i < parameterTypes.Length; i++) { if (!ConversionExists(argumentTypes[i], parameterTypes[i], allowExplicit)) goto nextBinding; } applicableFunctionList.Add(invocableBinding); } nextBinding: ; } return applicableFunctionList.ToArray(); } public InvocableBinding BindInvocation(InvocableBinding[] candidates, Type[] argumentTypes) { // Get applicable invocables // First we check if we can find any candidates if we only allow implicit conversions. InvocableBinding[] applicableInvocables = GetApplicableInvocables(candidates, argumentTypes, false); if (applicableInvocables == null || applicableInvocables.Length == 0) { // We could not find any candiate, lets see wether we find candidates // if we also allow explicit conversions. applicableInvocables = GetApplicableInvocables(candidates, argumentTypes, true); if (applicableInvocables == null || applicableInvocables.Length == 0) return null; } // Now select the best one InvocableBinding bestInvocable = applicableInvocables[0]; InvocableBinding lastEquallyGoodInvocable = null; for (int i = 1; i < applicableInvocables.Length; i++) { InvocableBinding invocable = applicableInvocables[i]; int comparisonResult = CompareFunctions(argumentTypes, bestInvocable.GetParameterTypes(), invocable.GetParameterTypes()); if (comparisonResult == 0) { lastEquallyGoodInvocable = invocable; } else if (comparisonResult > 0) { lastEquallyGoodInvocable = null; bestInvocable = invocable; } } // Ok, now check that our best function is really the best one if (lastEquallyGoodInvocable != null) { // We have also a function that is equally good. -- The call is ambiguous. _errorReporter.AmbiguousInvocation(bestInvocable, lastEquallyGoodInvocable, argumentTypes); // Return first to avoid cascading errors. return bestInvocable; } return bestInvocable; } #endregion #region Bind Operator Helper Methods [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] [SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")] private sealed class InvocationIsAmbiguousException : Exception { private MethodInfo _method1; private MethodInfo _method2; public InvocationIsAmbiguousException(MethodInfo method1, MethodInfo method2) { _method1 = method1; _method2 = method2; } public MethodInfo Method1 { get { return _method1; } } public MethodInfo Method2 { get { return _method2; } } } private MethodInfo[] GetApplicableMethods(IEnumerable<MethodInfo> functions, Type[] argumentTypes, bool allowExplicit) { List<MethodInfo> applicableFunctionList = new List<MethodInfo>(); foreach (MethodInfo method in functions) { ParameterInfo[] methodParameters = method.GetParameters(); if (methodParameters.Length == argumentTypes.Length) { for (int i = 0; i < methodParameters.Length; i++) { if (!ConversionExists(argumentTypes[i], methodParameters[i].ParameterType, allowExplicit)) goto nextBinding; } applicableFunctionList.Add(method); } nextBinding: ; } return applicableFunctionList.ToArray(); } private static Type[] GetParamterTypes(MethodInfo methodInfo) { ParameterInfo[] parameterInfos = methodInfo.GetParameters(); Type[] result = new Type[parameterInfos.Length]; for (int i = 0; i < parameterInfos.Length; i++) result[i] = parameterInfos[i].ParameterType; return result; } private MethodInfo BindMethodInfo(IEnumerable<MethodInfo> candidates, Type[] argumentTypes) { // First we check if we can find any candidates if we only allow implicit conversions. MethodInfo[] applicableFunctions = GetApplicableMethods(candidates, argumentTypes, false); if (applicableFunctions == null || applicableFunctions.Length == 0) { // We could not find any candiate, lets see wether we find candidates // if we also allow explicit conversions. applicableFunctions = GetApplicableMethods(candidates, argumentTypes, true); if (applicableFunctions == null || applicableFunctions.Length == 0) return null; } // Now select the best one MethodInfo bestFunction = applicableFunctions[0]; MethodInfo lastEquallyGoodFunction = null; for (int i = 1; i < applicableFunctions.Length; i++) { MethodInfo function = applicableFunctions[i]; int comparisonResult = CompareFunctions(argumentTypes, GetParamterTypes(bestFunction), GetParamterTypes(function)); if (comparisonResult == 0) { // Special handling for builtin operators: // // The builtin operators must not be used if an equally good or // better overload is present. if (bestFunction.DeclaringType == typeof(BuiltInOperators)) { // The new function is equally good, but the current best // function is from BuiltinOperators. The new function // is better than the current one. bestFunction = function; } else if (function.DeclaringType == typeof(BuiltInOperators)) { // The new, equally good function is from the BuiltinOperators. // Just ignore it. } else { // The new functions is not from the BuiltinOperators and // it is equally good. Remeber this functions for possible // ambguity error message. lastEquallyGoodFunction = function; } } else if (comparisonResult > 0) { lastEquallyGoodFunction = null; bestFunction = function; } } // Ok, now check that our best function is really the best one if (lastEquallyGoodFunction != null) { // We have also a function that is equally good. -- The call is ambiguous. throw new InvocationIsAmbiguousException(bestFunction, lastEquallyGoodFunction); } return bestFunction; } #endregion #region Bind Operator Methods public MethodInfo BindOperator(UnaryOperator op, Type operandType) { if (operandType == typeof(DBNull)) return _unaryOperatorPlaceholder; try { List<MethodInfo> methodList = new List<MethodInfo>(); // Get user defined operator methodList.AddRange(OperatorMethodCache.GetOperatorMethods(operandType, op)); // Get the operator method from the buitlin ones methodList.AddRange(OperatorMethodCache.GetOperatorMethods(typeof(BuiltInOperators), op)); MethodInfo[] methods = methodList.ToArray(); return BindMethodInfo(methods, new Type[] {operandType}); } catch (InvocationIsAmbiguousException ex) { _errorReporter.AmbiguousOperator(op, operandType, ex.Method1, ex.Method2); // Avoid cascading errors return ex.Method1; } } public MethodInfo BindOperator(BinaryOperator op, Type leftOperandType, Type rightOperandType) { if (leftOperandType == typeof(DBNull) || rightOperandType == typeof(DBNull)) return _binaryOperatorPlaceholder; MethodInfo result; try { List<MethodInfo> methodList = new List<MethodInfo>(); // Get the operator method from left... methodList.AddRange(OperatorMethodCache.GetOperatorMethods(leftOperandType, op)); if (leftOperandType != rightOperandType) { List<Type> declaringTypes = new List<Type>(); foreach (MethodInfo info in methodList) { if (!declaringTypes.Contains(info.DeclaringType)) declaringTypes.Add(info.DeclaringType); } foreach (MethodInfo rightOperatorMethod in OperatorMethodCache.GetOperatorMethods(rightOperandType, op)) { if (!declaringTypes.Contains(rightOperatorMethod.DeclaringType)) methodList.Add(rightOperatorMethod); } } // ...from the builtin ones. methodList.AddRange(OperatorMethodCache.GetOperatorMethods(typeof(BuiltInOperators), op)); // Perform overload resolution. MethodInfo[] methods = methodList.ToArray(); result = BindMethodInfo(methods, new Type[] {leftOperandType, rightOperandType}); } catch (InvocationIsAmbiguousException ex) { _errorReporter.AmbiguousOperator(op, leftOperandType, rightOperandType, ex.Method1, ex.Method2); // Avoid cascading errors result = ex.Method1; } // Due to the lack of generic operator methods we have to manually some rules here. // // 1. = and <>. There exists an operator method op_X(object, object) that would allow // comparing any type to any other type. This is not correct. We want to enforce // that both type are compatible (or if any operand is an interface). // 2. & and | for enums. There exists an operator method op_X(Enum, Enum) that would allow // combining any enum with any other enum. This is not correct. We want to enforce // that both enums are the same. if (result == _generalEqualityOperator || result == _generalInequalityOperator) { if (!leftOperandType.IsAssignableFrom(rightOperandType) && !rightOperandType.IsAssignableFrom(leftOperandType) && !leftOperandType.IsInterface && !rightOperandType.IsInterface) return null; } else if (result == _enumBitAndOperator || result == _enumBitOrOperator) { if (leftOperandType != rightOperandType) return null; } return result; } #endregion #region Bind Type private static void SplitTypeName(string typeName, out string qualifiedTypeName, out string assemblyName) { string[] parts = typeName.Split(','); qualifiedTypeName = parts[0].Trim(); if (parts.Length == 2) assemblyName = parts[1].Trim(); else assemblyName = null; } private static void AddTypes(ICollection<Type> target, Assembly assembly, string typeName, bool caseSensitive) { Type[] exportedTypes; try { exportedTypes = assembly.GetExportedTypes(); } catch (FileNotFoundException) { // Caused by dynamic assemblies such as the Reshaper Unit Testing Framework. return; } StringComparison comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; foreach (Type type in exportedTypes) { if (String.Compare(type.FullName, typeName, comparison) == 0) target.Add(type); } } public Type BindType(string assemblyQualifiedTypeName, bool caseSensitive) { string qualifiedTypeName; string assemblyName; SplitTypeName(assemblyQualifiedTypeName, out qualifiedTypeName, out assemblyName); if (!caseSensitive && assemblyName == null) { // First we try the shortcuts. Type primitiveType; if (_typeShortCutTable.TryGetValue(qualifiedTypeName, out primitiveType)) return primitiveType; } List<Type> typeList = new List<Type>(); if (assemblyName != null) { Assembly assembly; try { assembly = Assembly.Load(assemblyName); } catch (FileNotFoundException ex) { _errorReporter.CannotLoadTypeAssembly(assemblyName, ex); return null; } catch (FileLoadException ex) { _errorReporter.CannotLoadTypeAssembly(assemblyName, ex); return null; } catch (BadImageFormatException ex) { _errorReporter.CannotLoadTypeAssembly(assemblyName, ex); return null; } AddTypes(typeList, assembly, qualifiedTypeName, caseSensitive); } else { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) AddTypes(typeList, assembly, qualifiedTypeName, caseSensitive); } if (typeList.Count == 0) return null; if (typeList.Count > 1) { Type[] types = typeList.ToArray(); _errorReporter.AmbiguousType(assemblyQualifiedTypeName, types); } return typeList[0]; } #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.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ConstructorInitializerSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParameters() { var markup = @" class BaseClass { public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base($$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base($$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn1() { var markup = @" class BaseClass { public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base($$2, 3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base($$2, 3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn2() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlComentsOn2() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestThisInvocation() { var markup = @" class Foo { public Foo(int a, int b) { } public Foo() [|: this(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1), new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1), }; Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParen() { var markup = @" class Foo { public Foo(int a, int b) { } public Foo() [|: this(2, $$ |]}"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1), new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1), }; Test(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestCurrentParameterName() { var markup = @" class Foo { public Foo(int a, int b) { } public Foo() : this(b: 2, a: $$ }"; VerifyCurrentParameterName(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerParens() { var markup = @" class Foo { public Foo(int a) { } public Foo() : this($$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), new SignatureHelpTestItem("Foo(int a)", string.Empty, string.Empty, currentParameterIndex: 0), }; Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerComma() { var markup = @" class Foo { public Foo(int a, int b) { } public Foo() : this(2,$$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1), new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1), }; Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestNoInvocationOnSpace() { var markup = @" class Foo { public Foo(int a, int b) { } public Foo() : this(2, $$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_ConstructorInitializer_BrowsableStateAlways() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_ConstructorInitializer_BrowsableStateNever() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_ConstructorInitializer_BrowsableStateMixed() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public BaseClass(int x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public BaseClass(int x, int y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class Secret { public Secret(int secret) { } } #endif class SuperSecret : Secret { public SuperSecret(int secret) : base($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class Secret { public Secret(int secret) { } } #endif #if BAR class SuperSecret : Secret { public SuperSecret(int secret) : base($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [WorkItem(1067933)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokedWithNoToken() { var markup = @" // foo($$"; Test(markup); } [WorkItem(1082601)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithBadParameterList() { var markup = @" class BaseClass { public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base{$$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems); } } }
// **************************************************************************** // Copyright (C) 2000-2001 Microsoft Corporation. All rights reserved. // // CONTENTS // Activity interface // // DESCRIPTION // // REVISIONS // Date Ver By Remarks // ~~~~~~~~~~ ~~~ ~~~~~~~~ ~~~~~~~~~~~~~~ // 03/19/04 1.0 MayankM interfaces // **************************************************************************** namespace System.Workflow.ComponentModel { using System; using System.IO; using System.Text; using System.ComponentModel; using System.ComponentModel.Design; using System.CodeDom; using System.ComponentModel.Design.Serialization; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Security.Principal; using System.Security.Cryptography; using Microsoft.CSharp; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Serialization; using System.Collections.ObjectModel; using System.Runtime.Serialization; using System.Threading; [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public interface IDynamicPropertyTypeProvider { Type GetPropertyType(IServiceProvider serviceProvider, string propertyName); AccessTypes GetAccessType(IServiceProvider serviceProvider, string propertyName); } internal interface ISupportWorkflowChanges { void OnActivityAdded(ActivityExecutionContext rootContext, Activity addedActivity); void OnActivityRemoved(ActivityExecutionContext rootContext, Activity removedActivity); void OnWorkflowChangesCompleted(ActivityExecutionContext rootContext); } internal interface ISupportAlternateFlow { IList<Activity> AlternateFlowActivities { get; } } [AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] internal sealed class ActivityExecutorAttribute : Attribute { private string executorTypeName = string.Empty; public ActivityExecutorAttribute(Type executorType) { if (executorType != null) this.executorTypeName = executorType.AssemblyQualifiedName; } public ActivityExecutorAttribute(string executorTypeName) { this.executorTypeName = executorTypeName; } public string ExecutorTypeName { get { return this.executorTypeName; } } } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public enum ActivityExecutionStatus : byte { Initialized = 0, Executing = 1, Canceling = 2, Closed = 3, Compensating = 4, Faulting = 5 } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public enum ActivityExecutionResult : byte { None = 0, Succeeded = 1, Canceled = 2, Compensated = 3, Faulted = 4, Uninitialized = 5 } internal interface IDependencyObjectAccessor { //This method is invoked during the definition creation time void InitializeDefinitionForRuntime(DependencyObject parentDependencyObject); //This is invoked for every instance (not necessarily activating) void InitializeInstanceForRuntime(IWorkflowCoreRuntime workflowCoreRuntime); //This is invoked for every activating instance void InitializeActivatingInstanceForRuntime(DependencyObject parentDependencyObject, IWorkflowCoreRuntime workflowCoreRuntime); T[] GetInvocationList<T>(DependencyProperty dependencyEvent); } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public interface IStartWorkflow { Guid StartWorkflow(Type workflowType, Dictionary<string, object> namedArgumentValues); } internal interface IWorkflowCoreRuntime : IServiceProvider { // context information Activity RootActivity { get; } Activity CurrentActivity { get; } Activity CurrentAtomicActivity { get; } IDisposable SetCurrentActivity(Activity activity); void ScheduleItem(SchedulableItem item, bool isInAtomicTransaction, bool transacted, bool queueInTransaction); void ActivityStatusChanged(Activity activity, bool transacted, bool committed); void RaiseException(Exception e, Activity activity, string responsibleActivity); void RaiseActivityExecuting(Activity activity); void RaiseHandlerInvoking(Delegate delegateHandler); void RaiseHandlerInvoked(); Guid StartWorkflow(Type workflowType, Dictionary<string, object> namedArgumentValues); // context activity related int GetNewContextActivityId(); void RegisterContextActivity(Activity activity); void UnregisterContextActivity(Activity activity); Activity LoadContextActivity(ActivityExecutionContextInfo contextInfo, Activity outerContextActivity); void SaveContextActivity(Activity contextActivity); Activity GetContextActivityForId(int id); Object GetService(Activity currentActivity, Type serviceType); void PersistInstanceState(Activity activity); //Dynamic change notifications bool OnBeforeDynamicChange(IList<WorkflowChangeAction> changes); void OnAfterDynamicChange(bool updateSucceeded, IList<WorkflowChangeAction> changes); bool IsDynamicallyUpdated { get; } // root level access Guid InstanceID { get; } bool SuspendInstance(string suspendDescription); void TerminateInstance(Exception e); bool Resume(); void CheckpointInstanceState(Activity currentActivity); void RequestRevertToCheckpointState(Activity currentActivity, EventHandler<EventArgs> callbackHandler, EventArgs callbackData, bool suspendOnRevert, string suspendReason); void DisposeCheckpointState(); // User Tracking void Track(string key, object data); // Timer Events WaitCallback ProcessTimersCallback { get; } } internal interface ITimerService { void ScheduleTimer(WaitCallback callback, Guid workflowInstanceId, DateTime whenUtc, Guid timerId); void CancelTimer(Guid timerId); } [Serializable()] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class WorkflowTerminatedException : Exception { private WorkflowTerminatedException(SerializationInfo info, StreamingContext context) : base(info, context) { } public WorkflowTerminatedException() : base(SR.GetString(SR.Error_WorkflowTerminated)) { } public WorkflowTerminatedException(string message) : base(message) { } public WorkflowTerminatedException(string message, Exception exception) : base(message, exception) { } } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public interface ICompensatableActivity { ActivityExecutionStatus Compensate(ActivityExecutionContext executionContext); } #region Class AlternateFlowActivityAttribute [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false)] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class AlternateFlowActivityAttribute : Attribute { } #endregion #region Class SupportsTransactionAttribute [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] internal sealed class SupportsTransactionAttribute : Attribute { } #endregion #region Class SupportsSynchronizationAttribute [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] internal sealed class SupportsSynchronizationAttribute : Attribute { } #endregion #region Class PersistOnCloseAttribute [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class PersistOnCloseAttribute : Attribute { } #endregion }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace NotJavaScript.Tree { public interface gType { string str(); bool Suitable(Environment E, gType X); } public class Type_Boolean : gType { public string str() { return "bool"; } public bool Suitable(Environment E, gType X) { return X is Type_Boolean; } } public class Type_Integer : gType { public string str() { return "int"; } public bool Suitable(Environment E, gType X) { return X is Type_Integer; } } public class Type_Real : gType { public string str() { return "real"; } public bool Suitable(Environment E, gType X) { return X is Type_Integer || X is Type_Real; } } public class Type_String : gType { public string str() { return "string"; } public bool Suitable(Environment E, gType X) { return X is Type_String || X is Type_Real || X is Type_Integer || X is Type_Boolean; } } public class Type_Unknown : gType { public string str() { return "???"; } public bool Suitable(Environment E, gType X) { return false; } } public class Type_Unit : gType { public string str() { return "U"; } public bool Suitable(Environment E, gType X) { if (X is Type_Unit) return true; if (X is Type_Tuple) { if ((X as Type_Tuple).Empty()) return true; } return false; } } public class Type_ContractByName : gType { public string Name; public Type_ContractByName(string n) { Name = n; } public bool Suitable(Environment E, gType X) { if(E.Contracts.ContainsKey(Name)) { return E.Contracts[Name].Suitable(E, X); } throw new Exception("Could not find Contract Type:" + Name); return false; } public string str() { return "" + Name +""; } } public class Type_ContractByMembers : gType { public SortedDictionary<string, gType> Members; public Type_ContractByMembers() { Members = new SortedDictionary<string, gType>(); } public void Map(string x, gType t) { Members.Add(x, t); } public bool Suitable(Environment E, gType X) { gType Y = X; if (Y is Type_ContractByName) { string name = (Y as Type_ContractByName).Name; if(E.Contracts.ContainsKey(name)) { Y = E.Contracts[name]; } else { return false; } } if (Y is Type_ContractByMembers) { Type_ContractByMembers R = Y as Type_ContractByMembers; foreach (string x in Members.Keys) { if (R.Members.ContainsKey(x)) { if (!Members[x].Suitable(E, R.Members[x])) { return false; } } else { return false; } } return true; } return false; } public string str() { string z = "{"; foreach (string x in Members.Keys) { z += x + " " + Members[x].str() + ";"; } z += "}"; return z; } public string str2(string N) { string z = "constract " + N + " {"; foreach (string x in Members.Keys) { z += x + " " + Members[x].str() + ";"; } z += "}"; return z; } } public class Type_ArrayOf : gType { public gType Base; public Type_ArrayOf(gType b) { Base = b; } public bool Suitable(Environment E, gType X) { if (X is Type_ArrayOf) { return Base.Suitable(E,(X as Type_ArrayOf).Base); } return false; } public string str() { return Base.str() + "[]"; } } public class Type_Tuple : gType { List<gType> Args; public Type_Tuple() { Args = new List<gType>(); } public void Add(gType x) { Args.Add(x); } public bool Empty() { return Args.Count == 0; } public gType Reduce() { if (Args.Count == 0) return new Type_Unit(); if (Args.Count == 1) return Args[0]; return this; } public int Arity() { return Args.Count; } public bool Suitable(Environment E, gType X) { if (Empty()) { if (X is Type_Unit) return true; } if (X is Type_Tuple) { List<gType> Xargs = (X as Type_Tuple).Args; if (Args.Count == Xargs.Count) { for (int k = 0; k < Args.Count; k++) { if (!Args[k].Suitable(E, Xargs[k])) return false; } return true; } } return false; } public string str() { string x = ""; int k = 0; foreach(gType T in Args) { if(k > 0) x+= ","; x += T.str(); k++; } return "(" + x + ")"; } }; public class Type_Functional : gType { public gType Inputs; public gType Output; public Type_Functional(gType I, gType O) { Inputs = I; if (I is Type_Tuple) { Inputs = (I as Type_Tuple).Reduce(); } Output = O; } public bool Suitable(Environment E, gType X) { if(X is Type_Functional) { return (Inputs.Suitable(E, (X as Type_Functional).Inputs)) && (Output.Suitable(E, (X as Type_Functional).Output)); } return false; } public int Arity() { if (Inputs is Type_Unit) return 0; if (Inputs is Type_Tuple) { return (Inputs as Type_Tuple).Arity(); } return 1; } public string str() { return Inputs.str() + "->" + Output.str(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using System.Runtime.Versioning; namespace System.Xml.Xsl.Runtime { using Reflection; /// <summary> /// The context of a query consists of all user-provided information which influences the operation of the /// query. The context manages the following information: /// /// 1. Input data sources, including the default data source if one exists /// 2. Extension objects /// 3. External parameters /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class XmlQueryContext { private readonly XmlQueryRuntime _runtime; private readonly XPathNavigator _defaultDataSource; private readonly XmlResolver _dataSources; private readonly Hashtable _dataSourceCache; private readonly XsltArgumentList _argList; private XmlExtensionFunctionTable _extFuncsLate; private readonly WhitespaceRuleLookup _wsRules; private readonly QueryReaderSettings _readerSettings; // If we create reader out of stream we will use these settings /// <summary> /// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately). /// </summary> internal XmlQueryContext(XmlQueryRuntime runtime, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules) { _runtime = runtime; _dataSources = dataSources; _dataSourceCache = new Hashtable(); _argList = argList; _wsRules = wsRules; if (defaultDataSource is XmlReader) { _readerSettings = new QueryReaderSettings((XmlReader)defaultDataSource); } else { // Consider allowing users to set DefaultReaderSettings in XsltArgumentList // readerSettings = argList.DefaultReaderSettings; _readerSettings = new QueryReaderSettings(new NameTable()); } if (defaultDataSource is string) { // Load the default document from a Uri _defaultDataSource = GetDataSource(defaultDataSource as string, null); if (_defaultDataSource == null) throw new XslTransformException(SR.XmlIl_UnknownDocument, defaultDataSource as string); } else if (defaultDataSource != null) { _defaultDataSource = ConstructDocument(defaultDataSource, null, null); } } //----------------------------------------------- // Input data sources //----------------------------------------------- /// <summary> /// Returns the name table that should be used in the query to atomize search names and to load /// new documents. /// </summary> public XmlNameTable QueryNameTable { get { return _readerSettings.NameTable; } } /// <summary> /// Returns the name table used by the default data source, or null if there is no default data source. /// </summary> public XmlNameTable DefaultNameTable { get { return _defaultDataSource != null ? _defaultDataSource.NameTable : null; } } /// <summary> /// Return the document which is queried by default--i.e. no data source is explicitly selected in the query. /// </summary> public XPathNavigator DefaultDataSource { get { // Throw exception if there is no default data source to return if (_defaultDataSource == null) throw new XslTransformException(SR.XmlIl_NoDefaultDocument, string.Empty); return _defaultDataSource; } } /// <summary> /// Fetch the data source specified by "uriRelative" and "uriBase" from the XmlResolver that the user provided. /// If the resolver returns a stream or reader, create an instance of XPathDocument. If the resolver returns an /// XPathNavigator, return the navigator. Throw an exception if no data source was found. /// </summary> public XPathNavigator GetDataSource(string uriRelative, string uriBase) { object input; Uri uriResolvedBase, uriResolved; XPathNavigator nav = null; try { // If the data source has already been retrieved, then return the data source from the cache. uriResolvedBase = (uriBase != null) ? _dataSources.ResolveUri(null, uriBase) : null; uriResolved = _dataSources.ResolveUri(uriResolvedBase, uriRelative); if (uriResolved != null) nav = _dataSourceCache[uriResolved] as XPathNavigator; if (nav == null) { // Get the entity from the resolver and ensure it is cached as a document input = _dataSources.GetEntity(uriResolved, null, null); if (input != null) { // Construct a document from the entity and add the document to the cache nav = ConstructDocument(input, uriRelative, uriResolved); _dataSourceCache.Add(uriResolved, nav); } } } catch (XslTransformException) { // Don't need to wrap XslTransformException throw; } catch (Exception e) { if (!XmlException.IsCatchableException(e)) { throw; } throw new XslTransformException(e, SR.XmlIl_DocumentLoadError, uriRelative); } return nav; } /// <summary> /// Ensure that "dataSource" is cached as an XPathDocument and return a navigator over the document. /// </summary> private XPathNavigator ConstructDocument(object dataSource, string uriRelative, Uri uriResolved) { Debug.Assert(dataSource != null, "GetType() below assumes dataSource is not null"); Stream stream = dataSource as Stream; if (stream != null) { // Create document from stream XmlReader reader = _readerSettings.CreateReader(stream, uriResolved != null ? uriResolved.ToString() : null); try { // Create WhitespaceRuleReader if whitespace should be stripped return new XPathDocument(WhitespaceRuleReader.CreateReader(reader, _wsRules), XmlSpace.Preserve).CreateNavigator(); } finally { // Always close reader that was opened here reader.Close(); } } else if (dataSource is XmlReader) { // Create document from reader // Create WhitespaceRuleReader if whitespace should be stripped return new XPathDocument(WhitespaceRuleReader.CreateReader(dataSource as XmlReader, _wsRules), XmlSpace.Preserve).CreateNavigator(); } else if (dataSource is IXPathNavigable) { if (_wsRules != null) throw new XslTransformException(SR.XmlIl_CantStripNav, string.Empty); return (dataSource as IXPathNavigable).CreateNavigator(); } Debug.Assert(uriRelative != null, "Relative URI should not be null"); throw new XslTransformException(SR.XmlIl_CantResolveEntity, uriRelative, dataSource.GetType().ToString()); } //----------------------------------------------- // External parameters //----------------------------------------------- /// <summary> /// Get a named parameter from the external argument list. Return null if no argument list was provided, or if /// there is no parameter by that name. /// </summary> public object GetParameter(string localName, string namespaceUri) { return (_argList != null) ? _argList.GetParam(localName, namespaceUri) : null; } //----------------------------------------------- // Extension objects //----------------------------------------------- /// <summary> /// Return the extension object that is mapped to the specified namespace, or null if no object is mapped. /// </summary> public object GetLateBoundObject(string namespaceUri) { return (_argList != null) ? _argList.GetExtensionObject(namespaceUri) : null; } /// <summary> /// Return true if the late bound object identified by "namespaceUri" contains a method that matches "name". /// </summary> public bool LateBoundFunctionExists(string name, string namespaceUri) { object instance; if (_argList == null) return false; instance = _argList.GetExtensionObject(namespaceUri); if (instance == null) return false; return new XmlExtensionFunction(name, namespaceUri, -1, instance.GetType(), XmlQueryRuntime.LateBoundFlags).CanBind(); } /// <summary> /// Get a late-bound extension object from the external argument list. Bind to a method on the object and invoke it, /// passing "args" as arguments. /// </summary> public IList<XPathItem> InvokeXsltLateBoundFunction(string name, string namespaceUri, IList<XPathItem>[] args) { object instance; object[] objActualArgs; XmlQueryType xmlTypeFormalArg; Type clrTypeFormalArg; object objRet; // Get external object instance from argument list (throw if either the list or the instance doesn't exist) instance = (_argList != null) ? _argList.GetExtensionObject(namespaceUri) : null; if (instance == null) throw new XslTransformException(SR.XmlIl_UnknownExtObj, namespaceUri); // Bind to a method on the instance object if (_extFuncsLate == null) _extFuncsLate = new XmlExtensionFunctionTable(); // Bind to the instance, looking for a matching method (throws if no matching method) XmlExtensionFunction extFunc = _extFuncsLate.Bind(name, namespaceUri, args.Length, instance.GetType(), XmlQueryRuntime.LateBoundFlags); // Create array which will contain the actual arguments objActualArgs = new object[args.Length]; for (int i = 0; i < args.Length; i++) { // 1. Assume that the input value can only have one of the following 5 Xslt types: // xs:double, xs:string, xs:boolean, node* (can be rtf) // 2. Convert each Rtf value to a NodeSet containing one node. Now the value may only have one of the 4 Xslt types. // 3. Convert from one of the 4 Xslt internal types to the Xslt internal type which is closest to the formal // argument's Xml type (inferred from the Clr type of the formal argument). xmlTypeFormalArg = extFunc.GetXmlArgumentType(i); switch (xmlTypeFormalArg.TypeCode) { case XmlTypeCode.Boolean: objActualArgs[i] = XsltConvert.ToBoolean(args[i]); break; case XmlTypeCode.Double: objActualArgs[i] = XsltConvert.ToDouble(args[i]); break; case XmlTypeCode.String: objActualArgs[i] = XsltConvert.ToString(args[i]); break; case XmlTypeCode.Node: if (xmlTypeFormalArg.IsSingleton) objActualArgs[i] = XsltConvert.ToNode(args[i]); else objActualArgs[i] = XsltConvert.ToNodeSet(args[i]); break; case XmlTypeCode.Item: objActualArgs[i] = args[i]; break; default: Debug.Fail("This XmlTypeCode should never be inferred from a Clr type: " + xmlTypeFormalArg.TypeCode); break; } // 4. Change the Clr representation to the Clr type of the formal argument clrTypeFormalArg = extFunc.GetClrArgumentType(i); if (xmlTypeFormalArg.TypeCode == XmlTypeCode.Item || !clrTypeFormalArg.IsAssignableFrom(objActualArgs[i].GetType())) objActualArgs[i] = _runtime.ChangeTypeXsltArgument(xmlTypeFormalArg, objActualArgs[i], clrTypeFormalArg); } // 1. Invoke the late bound method objRet = extFunc.Invoke(instance, objActualArgs); // 2. Convert to IList<XPathItem> if (objRet == null && extFunc.ClrReturnType == XsltConvert.VoidType) return XmlQueryNodeSequence.Empty; return (IList<XPathItem>)_runtime.ChangeTypeXsltResult(XmlQueryTypeFactory.ItemS, objRet); } //----------------------------------------------- // Event //----------------------------------------------- /// <summary> /// Fire the XsltMessageEncounteredEvent, passing the specified text as the message. /// </summary> public void OnXsltMessageEncountered(string message) { XsltMessageEncounteredEventHandler onMessage = (_argList != null) ? _argList.xsltMessageEncountered : null; if (onMessage != null) onMessage(this, new XmlILQueryEventArgs(message)); } } /// <summary> /// Simple implementation of XsltMessageEncounteredEventArgs. /// </summary> internal class XmlILQueryEventArgs : XsltMessageEncounteredEventArgs { private readonly string _message; public XmlILQueryEventArgs(string message) { _message = message; } public override string Message { get { return _message; } } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameManager : MonoBehaviour { public GameObject tablet; // These are set in the Unity Editor // Mana public Slider manaSlider; public int manaDownAmount; public int manaRechargeAmount; private int shots; private int highScore; public int tabletsDelivered; public GameObject player; public GameObject lightning; public GameObject monkey; public GameObject house; public GameObject house2; public GameObject house3; public GameObject house4; public GameObject mainCamera; private int tabletLives; private float monkeySpawnRate; private float houseSpawnRate; private long monkeySpawnTime; private long houseSpawnTime; private bool gameRunning = false; private bool isServiceReady; // Use this for initialization void Start () { // GameCircle AGSClient.ServiceReadyEvent += serviceReadyHandler; AGSClient.ServiceNotReadyEvent += serviceNotReadyHandler; bool usesLeaderboards = true; bool usesAchievements = true; bool usesWhispersync = false; AGSClient.Init (usesLeaderboards, usesAchievements, usesWhispersync); isServiceReady = AGSClient.IsServiceReady(); if (isServiceReady) { AGSAchievementsClient.UpdateAchievementSucceededEvent += updateAchievementSucceeded; AGSAchievementsClient.UpdateAchievementFailedEvent += updateAchievementFailed; AGSAchievementsClient.UpdateAchievementProgress ("enter_game_achievment", 50.0f); } } void Update() { } void FixedUpdate () { if (!gameRunning) return; manaSlider.value += manaRechargeAmount * Time.fixedDeltaTime * 3; monkeySpawnRate *= .9999999F; houseSpawnRate *= 1.0000001F; monkeySpawnTime --; if (monkeySpawnTime <= 0) { spawnMonkey (); monkeySpawnTime = (long) (100 + Random.value * monkeySpawnRate * 400F); } houseSpawnTime --; if (houseSpawnTime <= 0) { spawnHouse (); houseSpawnTime = (long) (50 + Random.value * houseSpawnRate * 200F); } } void gameStart() { tabletLives = 10; shots = 0; player.GetComponent<Rotator> ().rotateSpeed = 0; player.GetComponent<CharacterBehavior> ().setHealth (3); player.transform.rotation = Quaternion.identity; tabletsDelivered = 0; monkeySpawnTime = 400; houseSpawnTime = 200; monkeySpawnRate = 1; houseSpawnRate = 1; gameRunning = true; } public GameObject getTablet() { return tablet; } public int getScore() { return highScore; } void OnGUI() { GUI.skin.label.fontSize = 20; GUI.skin.button.fontSize = 20; int lives = 0; if (player != null) { lives = player.GetComponent<BaeZeusScript> ().getHealth(); } GUI.Label(new Rect(Screen.width /2 - Screen.width/16, Screen.height/16, Screen.width/4, Screen.height/4), "Score: " + tabletsDelivered + "\n" + "Tablets Left: " + tabletLives + "\n" + "Lives Left: " + lives); if (!gameRunning) { if(GUI.Button(new Rect(Screen.width /4, 3*Screen.height/8, Screen.width/2, Screen.height/4), "Start" + "\n" + "Tap to drop a tablet in the chimney" + "\n" + "Swipe right to throw lightning" + "\n" + "And don't get hit!")) { gameStart(); } } } // Right now activated when TestButton is clicked!! public void shootMana(){ if (gameRunning) { if (manaSlider.value > manaDownAmount) { manaSlider.value -= manaDownAmount; Debug.Log (++shots); throwLightning (); } else { Debug.Log ("No Mana left"); shots = 0; } } } public void destroyTabletOffScreen(TabletBehavior tb) { Destroy (tb.gameObject); tabletLives --; if (tabletLives == 0) { endGame(); } } public void tap() { dropTablet (); } void dropTablet() { if (gameRunning) { GameObject tablet = (GameObject)Instantiate (getTablet (), player.transform.position, Quaternion.identity); Rigidbody2D rb2d = tablet.GetComponent<Rigidbody2D> (); rb2d.velocity = new Vector3 (0.0F, -5.0F, 0.0F); } } void throwLightning() { Animator anim = player.GetComponent<Animator> (); anim.SetBool ("ThrowLightning", true); Debug.Log ("Throwing the lightening!"); GameObject lighting = (GameObject) Instantiate(this.lightning, player.transform.position, Quaternion.identity); //Rigidbody2D rb2d = lightning.GetComponent<Rigidbody2D> (); //rb2d.velocity = new Vector3(0.0F, -5.0F, 0.0F); } void spawnMonkey() { GameObject monkey = (GameObject) Instantiate(this.monkey, mainCamera.transform.position + new Vector3 (15.0F, 4.0F, 10.0F), Quaternion.identity); } void spawnHouse() { int houseChoose = (int)Random.Range (1, 4); switch(houseChoose) { case 1 : GameObject house = (GameObject) Instantiate(this.house, mainCamera.transform.position + new Vector3 (20.0F, -5.0F, 10.0F), Quaternion.identity); break; case 2: GameObject house2 = (GameObject) Instantiate(this.house2, mainCamera.transform.position + new Vector3 (20.0F, -5.0F, 10.0F), Quaternion.identity); break; case 3: GameObject house3 = (GameObject) Instantiate(this.house3, mainCamera.transform.position + new Vector3 (20.0F, -5.0F, 10.0F), Quaternion.identity); break; case 4: GameObject house4 = (GameObject) Instantiate(this.house4, mainCamera.transform.position + new Vector3 (20.0F, -5.0F, 10.0F), Quaternion.identity); break; } } //Game Circle private void serviceNotReadyHandler (string error) { Debug.Log("Service is not ready"); } //Game Circle private void serviceReadyHandler () { Debug.Log("Service is ready"); } private void updateAchievementSucceeded(string achievementId) { Debug.Log ("Ya Achievement!!!"); } private void updateAchievementFailed(string achievementId, string error) { Debug.Log ("Sad no achievement"); } private void submitScoreSucceeded(string leaderboardId){ Debug.Log ("Score uploaded: " + shots + " to: " + leaderboardId); } private void submitScoreFailed(string leaderboardId, string error){ } public void endGame() { gameRunning = false; if (tabletsDelivered > highScore) highScore = tabletsDelivered; if (tabletsDelivered > 5) { if (isServiceReady) { AGSAchievementsClient.UpdateAchievementSucceededEvent += updateAchievementSucceeded; AGSAchievementsClient.UpdateAchievementFailedEvent += updateAchievementFailed;; AGSAchievementsClient.UpdateAchievementProgress("tablets_achievment",50.0f); } } if (isServiceReady) { AGSLeaderboardsClient.SubmitScoreSucceededEvent += submitScoreSucceeded; AGSLeaderboardsClient.SubmitScoreFailedEvent += submitScoreFailed; AGSLeaderboardsClient.SubmitScore("tablets_leaderboard",tabletsDelivered); } GameObject[] respawns; respawns = GameObject.FindGameObjectsWithTag("Enemy"); foreach(GameObject go in respawns) { Destroy(go); } } }
// -- FILE ------------------------------------------------------------------ // name : DurationTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Globalization; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class DurationTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void YearTest() { int currentYear = ClockProxy.Clock.Now.Year; Calendar calendar = DateDiff.SafeCurrentInfo.Calendar; Assert.Equal( Duration.Year( currentYear ), new TimeSpan( calendar.GetDaysInYear( currentYear ), 0, 0, 0 ) ); Assert.Equal( Duration.Year( currentYear + 1 ), new TimeSpan( calendar.GetDaysInYear( currentYear + 1 ), 0, 0, 0 ) ); Assert.Equal( Duration.Year( currentYear - 1 ), new TimeSpan( calendar.GetDaysInYear( currentYear - 1 ), 0, 0, 0 ) ); Assert.Equal( Duration.Year( calendar, currentYear ), new TimeSpan( calendar.GetDaysInYear( currentYear ), 0, 0, 0 ) ); Assert.Equal( Duration.Year( calendar, currentYear + 1 ), new TimeSpan( calendar.GetDaysInYear( currentYear + 1 ), 0, 0, 0 ) ); Assert.Equal( Duration.Year( calendar, currentYear - 1 ), new TimeSpan( calendar.GetDaysInYear( currentYear - 1 ), 0, 0, 0 ) ); } // YearTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void HalfyearTest() { int currentYear = ClockProxy.Clock.Now.Year; Calendar calendar = DateDiff.SafeCurrentInfo.Calendar; foreach ( YearHalfyear yearHalfyear in Enum.GetValues( typeof( YearHalfyear ) ) ) { YearMonth[] halfyearMonths = TimeTool.GetMonthsOfHalfyear( yearHalfyear ); TimeSpan duration = TimeSpan.Zero; foreach ( YearMonth halfyearMonth in halfyearMonths ) { int monthDays = calendar.GetDaysInMonth( currentYear, (int)halfyearMonth ); duration = duration.Add( new TimeSpan( monthDays, 0, 0, 0 ) ); } Assert.Equal( Duration.Halfyear( currentYear, yearHalfyear ), duration ); Assert.Equal( Duration.Halfyear( calendar, currentYear, yearHalfyear ), duration ); } } // HalfyearTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void QuarterTest() { int currentYear = ClockProxy.Clock.Now.Year; Calendar calendar = DateDiff.SafeCurrentInfo.Calendar; foreach ( YearQuarter yearQuarter in Enum.GetValues( typeof( YearQuarter ) ) ) { YearMonth[] quarterMonths = TimeTool.GetMonthsOfQuarter( yearQuarter ); TimeSpan duration = TimeSpan.Zero; foreach ( YearMonth quarterMonth in quarterMonths ) { int monthDays = calendar.GetDaysInMonth( currentYear, (int)quarterMonth ); duration = duration.Add( new TimeSpan( monthDays, 0, 0, 0 ) ); } Assert.Equal( Duration.Quarter( currentYear, yearQuarter ), duration ); Assert.Equal( Duration.Quarter( calendar, currentYear, yearQuarter ), duration ); } } // QuarterTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void MonthTest() { DateTime now = ClockProxy.Clock.Now; int currentYear = now.Year; Calendar calendar = DateDiff.SafeCurrentInfo.Calendar; foreach ( YearMonth yearMonth in Enum.GetValues( typeof( YearMonth ) ) ) { Assert.Equal( Duration.Month( currentYear, yearMonth ), new TimeSpan( calendar.GetDaysInMonth( currentYear, (int)yearMonth ), 0, 0, 0 ) ); Assert.Equal( Duration.Month( calendar, currentYear, yearMonth ), new TimeSpan( calendar.GetDaysInMonth( currentYear, (int)yearMonth ), 0, 0, 0 ) ); } } // MonthTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void WeekTest() { Assert.Equal( Duration.Week, new TimeSpan( TimeSpec.DaysPerWeek * 1, 0, 0, 0 ) ); Assert.Equal( Duration.Weeks( 0 ), TimeSpan.Zero ); Assert.Equal( Duration.Weeks( 1 ), new TimeSpan( TimeSpec.DaysPerWeek * 1, 0, 0, 0 ) ); Assert.Equal( Duration.Weeks( 2 ), new TimeSpan( TimeSpec.DaysPerWeek * 2, 0, 0, 0 ) ); Assert.Equal( Duration.Weeks( -1 ), new TimeSpan( TimeSpec.DaysPerWeek * -1, 0, 0, 0 ) ); Assert.Equal( Duration.Weeks( -2 ), new TimeSpan( TimeSpec.DaysPerWeek * -2, 0, 0, 0 ) ); } // WeekTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void DayTest() { Assert.Equal( Duration.Day, new TimeSpan( 1, 0, 0, 0 ) ); Assert.Equal( Duration.Days( 0 ), TimeSpan.Zero ); Assert.Equal( Duration.Days( 1 ), new TimeSpan( 1, 0, 0, 0 ) ); Assert.Equal( Duration.Days( 2 ), new TimeSpan( 2, 0, 0, 0 ) ); Assert.Equal( Duration.Days( -1 ), new TimeSpan( -1, 0, 0, 0 ) ); Assert.Equal( Duration.Days( -2 ), new TimeSpan( -2, 0, 0, 0 ) ); Assert.Equal( Duration.Days( 1, 23 ), new TimeSpan( 1, 23, 0, 0 ) ); Assert.Equal( Duration.Days( 1, 23, 22 ), new TimeSpan( 1, 23, 22, 0 ) ); Assert.Equal( Duration.Days( 1, 23, 22, 18 ), new TimeSpan( 1, 23, 22, 18 ) ); Assert.Equal( Duration.Days( 1, 23, 22, 18, 875 ), new TimeSpan( 1, 23, 22, 18, 875 ) ); } // DayTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void HourTest() { Assert.Equal( Duration.Hour, new TimeSpan( 1, 0, 0 ) ); Assert.Equal( Duration.Hours( 0 ), TimeSpan.Zero ); Assert.Equal( Duration.Hours( 1 ), new TimeSpan( 1, 0, 0 ) ); Assert.Equal( Duration.Hours( 2 ), new TimeSpan( 2, 0, 0 ) ); Assert.Equal( Duration.Hours( -1 ), new TimeSpan( -1, 0, 0 ) ); Assert.Equal( Duration.Hours( -2 ), new TimeSpan( -2, 0, 0 ) ); Assert.Equal( Duration.Hours( 23 ), new TimeSpan( 0, 23, 0, 0 ) ); Assert.Equal( Duration.Hours( 23, 22 ), new TimeSpan( 0, 23, 22, 0 ) ); Assert.Equal( Duration.Hours( 23, 22, 18 ), new TimeSpan( 0, 23, 22, 18 ) ); Assert.Equal( Duration.Hours( 23, 22, 18, 875 ), new TimeSpan( 0, 23, 22, 18, 875 ) ); } // HourTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void MinuteTest() { Assert.Equal( Duration.Minute, new TimeSpan( 0, 1, 0 ) ); Assert.Equal( Duration.Minutes( 0 ), TimeSpan.Zero ); Assert.Equal( Duration.Minutes( 1 ), new TimeSpan( 0, 1, 0 ) ); Assert.Equal( Duration.Minutes( 2 ), new TimeSpan( 0, 2, 0 ) ); Assert.Equal( Duration.Minutes( -1 ), new TimeSpan( 0, -1, 0 ) ); Assert.Equal( Duration.Minutes( -2 ), new TimeSpan( 0, -2, 0 ) ); Assert.Equal( Duration.Minutes( 22 ), new TimeSpan( 0, 0, 22, 0 ) ); Assert.Equal( Duration.Minutes( 22, 18 ), new TimeSpan( 0, 0, 22, 18 ) ); Assert.Equal( Duration.Minutes( 22, 18, 875 ), new TimeSpan( 0, 0, 22, 18, 875 ) ); } // MinuteTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void SecondTest() { Assert.Equal( Duration.Second, new TimeSpan( 0, 0, 1 ) ); Assert.Equal( Duration.Seconds( 0 ), TimeSpan.Zero ); Assert.Equal( Duration.Seconds( 1 ), new TimeSpan( 0, 0, 1 ) ); Assert.Equal( Duration.Seconds( 2 ), new TimeSpan( 0, 0, 2 ) ); Assert.Equal( Duration.Seconds( -1 ), new TimeSpan( 0, 0, -1 ) ); Assert.Equal( Duration.Seconds( -2 ), new TimeSpan( 0, 0, -2 ) ); Assert.Equal( Duration.Seconds( 18 ), new TimeSpan( 0, 0, 0, 18 ) ); Assert.Equal( Duration.Seconds( 18, 875 ), new TimeSpan( 0, 0, 0, 18, 875 ) ); } // SecondTest // ---------------------------------------------------------------------- [Trait("Category", "Duration")] [Fact] public void MillisecondTest() { Assert.Equal( Duration.Millisecond, new TimeSpan( 0, 0, 0, 0, 1 ) ); Assert.Equal( Duration.Milliseconds( 0 ), TimeSpan.Zero ); Assert.Equal( Duration.Milliseconds( 1 ), new TimeSpan( 0, 0, 0, 0, 1 ) ); Assert.Equal( Duration.Milliseconds( 2 ), new TimeSpan( 0, 0, 0, 0, 2 ) ); Assert.Equal( Duration.Milliseconds( -1 ), new TimeSpan( 0, 0, 0, 0, -1 ) ); Assert.Equal( Duration.Milliseconds( -2 ), new TimeSpan( 0, 0, 0, 0, -2 ) ); } // MillisecondTest } // class DurationTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
//#define REREAD_STATE_AFTER_WRITE_FAILED using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Storage; using Orleans.TestingHost; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; using Orleans.Runtime.Configuration; using TesterInternal; using TestExtensions; using Orleans.Hosting; // ReSharper disable RedundantAssignment // ReSharper disable UnusedVariable // ReSharper disable InconsistentNaming namespace UnitTests.StorageTests { /// <summary> /// PersistenceGrainTests - Run with only local unit test silo -- no external dependency on Azure storage /// </summary> public class PersistenceGrainTests_Local : OrleansTestingBase, IClassFixture<PersistenceGrainTests_Local.Fixture>, IDisposable { public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.Options.InitialSilosCount = 1; builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.Globals.RegisterStorageProvider<MockStorageProvider>(MockStorageProviderName1); legacy.ClusterConfiguration.Globals.RegisterStorageProvider<MockStorageProvider>(MockStorageProviderName2, new Dictionary<string, string> {{"Config1", "1"}, {"Config2", "2"}}); legacy.ClusterConfiguration.Globals.RegisterStorageProvider<ErrorInjectionStorageProvider>(ErrorInjectorProviderName); legacy.ClusterConfiguration.Globals.RegisterStorageProvider<MockStorageProvider>(MockStorageProviderNameLowerCase); }); builder.AddSiloBuilderConfigurator<SiloConfigurator>(); } private class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore"); } } } const string MockStorageProviderName1 = "test1"; const string MockStorageProviderName2 = "test2"; const string MockStorageProviderNameLowerCase = "lowercase"; const string ErrorInjectorProviderName = "ErrorInjector"; private readonly ITestOutputHelper output; protected TestCluster HostedCluster { get; } public PersistenceGrainTests_Local(ITestOutputHelper output, Fixture fixture) { this.output = output; HostedCluster = fixture.HostedCluster; SetErrorInjection(ErrorInjectorProviderName, ErrorInjectionPoint.None); ResetMockStorageProvidersHistory(); } public void Dispose() { SetErrorInjection(ErrorInjectorProviderName, ErrorInjectionPoint.None); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Silo_StorageProvidersLoaded() { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); foreach (var silo in silos) { var testHooks = this.HostedCluster.Client.GetTestHooks(silo); ICollection<string> providers = await testHooks.GetStorageProviderNames(); Assert.NotNull(providers); // Null provider manager Assert.True(providers.Count > 0, "Some providers loaded"); Assert.True(testHooks.HasStorageProvider(MockStorageProviderName1).Result, $"provider {MockStorageProviderName1} on silo {silo.Name} should be registered"); Assert.True(testHooks.HasStorageProvider(MockStorageProviderName2).Result, $"provider {MockStorageProviderName2} on silo {silo.Name} should be registered"); Assert.True(testHooks.HasStorageProvider(MockStorageProviderNameLowerCase).Result, $"provider {MockStorageProviderNameLowerCase} on silo {silo.Name} should be registered"); Assert.True(testHooks.HasStorageProvider(ErrorInjectorProviderName).Result, $"provider {ErrorInjectorProviderName} on silo {silo.Name} should be registered"); } } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public void Persistence_Silo_StorageProvider_Name_Missing() { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); var silo = silos.First(); const string providerName = "NotPresent"; Assert.False(this.HostedCluster.Client.GetTestHooks(silo).HasStorageProvider(providerName).Result, $"provider {providerName} on silo {silo.Name} should not be registered"); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_CheckStateInit() { Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); bool ok = await grain.CheckStateInit(); Assert.True(ok, "CheckStateInit OK"); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_CheckStorageProvider() { Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); string providerType = await grain.CheckProviderType(); Assert.Equal(typeof(MockStorageProvider).FullName, providerType); // StorageProvider provider type } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Init() { Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoSomething(); //request InitCount on providers on all silos in this cluster IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); object[] replies = await mgmtGrain.SendControlCommandToProvider(typeof(MockStorageProvider).FullName, MockStorageProviderName1, (int)MockStorageProvider.Commands.InitCount, null); Assert.Contains(1, replies); // StorageProvider #Init } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Activate_StoredValue() { const string providerName = MockStorageProviderName1; string grainType = typeof(PersistenceTestGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(guid); // Store initial value in storage int initialValue = 567; SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", initialValue); int readValue = await grain.GetValue(); Assert.Equal(initialValue, readValue); // Read previously stored value } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Generics")] public async Task Persistence_Grain_Activate_StoredValue_Generic() { const string providerName = MockStorageProviderName1; string grainType = typeof(PersistenceTestGenericGrain<int>).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); var grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGenericGrain<int>>(guid); // Store initial value in storage int initialValue = 567; SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", initialValue); int readValue = await grain.GetValue(); Assert.Equal(initialValue, readValue); // Read previously stored value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Activate_Error() { const string providerName = ErrorInjectorProviderName; string grainType = typeof(PersistenceProviderErrorGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); // Store initial value in storage int initialValue = 567; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", initialValue); SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); await Assert.ThrowsAsync<StorageProviderInjectedError>(() => grain.GetValue()); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Read() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoSomething(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Write() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_ReRead() { const string providerName = MockStorageProviderName1; string grainType = typeof(PersistenceTestGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(guid); await grain.DoSomething(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", 42); await grain.DoRead(); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(42, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_Read_Write() { Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IMemoryStorageTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(guid); int val = await grain.GetValue(); Assert.Equal(0, val); // Initial value await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // Value after Write-1 await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // Value after Write-2 val = await grain.DoRead(); Assert.Equal(2, val); // Value after Re-Read } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_Delete() { Guid id = Guid.NewGuid(); var grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id); await grain.DoWrite(1); await grain.DoDelete(); int val = await grain.GetValue(); // Should this throw instead? Assert.Equal(0, val); // Value after Delete await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // Value after Delete + New Write } [Fact, TestCategory("Stress"), TestCategory("CorePerf"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_Stress_Read() { const int numIterations = 10000; Stopwatch sw = Stopwatch.StartNew(); Task<int>[] promises = new Task<int>[numIterations]; for (int i = 0; i < numIterations; i++) { IMemoryStorageTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IMemoryStorageTestGrain>(Guid.NewGuid()); int idx = i; // Capture Func<Task<int>> asyncFunc = async () => { await grain.DoWrite(idx); return await grain.DoRead(); }; promises[i] = Task.Run(asyncFunc); } await Task.WhenAll(promises); TimeSpan elapsed = sw.Elapsed; double tps = (numIterations * 2) / elapsed.TotalSeconds; // One Read and one Write per iteration output.WriteLine("{0} Completed Read-Write operations in {1} at {2} TPS", numIterations, elapsed, tps); for (int i = 0; i < numIterations; i++) { int expectedVal = i; Assert.Equal(expectedVal, promises[i].Result); // "Returned value - Read @ #" + i } } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Write() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Delete() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); int initialReadCount = providerState.ProviderStateForTest.ReadCount; int initialWriteCount = providerState.ProviderStateForTest.WriteCount; int initialDeleteCount = providerState.ProviderStateForTest.DeleteCount; await grain.DoDelete(); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(initialDeleteCount + 1, providerState.ProviderStateForTest.DeleteCount); // StorageProvider #Deletes Assert.Null(providerState.LastStoredGrainState); // Store-AfterDelete-Empty int val = await grain.GetValue(); // Returns current in-memory null data without re-read. providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update state Assert.Equal(0, val); // Value after Delete Assert.Equal(initialReadCount, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update state Assert.Equal(initialReadCount, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(initialWriteCount + 1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Read_Error() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(id); var val = await grain.GetValue(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes try { await grain.DoReadError(true); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { Exception e = ae.GetBaseException(); if (e is ApplicationException) { // Expected error } else { throw e; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 try { await grain.DoReadError(false); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { Exception e = ae.GetBaseException(); if (e is ApplicationException) { // Expected error } else { throw e; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_Write_Error() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(id); await grain.DoWrite(1); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(1, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(2); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoWriteError(3, true); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); // update provider state Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(2, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(2, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoWriteError(4, false); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(3, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes Assert.Equal(4, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_ReRead_Error() { const string providerName = "test1"; string grainType = typeof(PersistenceErrorGrain).FullName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceErrorGrain>(guid); var val = await grain.GetValue(); var providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(1, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes SetStoredValue(providerName, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", 42); await grain.DoRead(); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(0, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(42, providerState.LastStoredGrainState.Field1); // Store-Field1 await grain.DoWrite(43); providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoReadError(true); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(2, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1 try { await grain.DoReadError(false); } catch (ApplicationException) { // Expected error } catch (AggregateException ae) { if (ae.GetBaseException() is ApplicationException) { // Expected error } else { throw; } } providerState = GetStateForStorageProviderInUse(providerName, typeof(MockStorageProvider).FullName); Assert.Equal(3, providerState.ProviderStateForTest.ReadCount); // StorageProvider #Reads-2 Assert.Equal(1, providerState.ProviderStateForTest.WriteCount); // StorageProvider #Writes-2 Assert.Equal(43, providerState.LastStoredGrainState.Field1); // Store-Field1 } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_BeforeRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); CheckStorageProviderErrors(grain.DoRead); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_AfterRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 52; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.AfterRead); CheckStorageProviderErrors(grain.DoRead); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value int newVal = 53; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value await grain.DoRead(); // Force re-read expectedVal = newVal; val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_BeforeWrite() { Guid id = Guid.NewGuid(); string providerName = ErrorInjectorProviderName; IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id); var val = await grain.GetValue(); int expectedVal = 62; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 const int attemptedVal3 = 63; SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite); CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal3)); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 #if REREAD_STATE_AFTER_WRITE_FAILED Assert.Equal(expectedVal, val); // Last value written successfully #else Assert.Equal(attemptedVal3, val); // Last value attempted to be written is still in memory #endif } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_InconsistentStateException_DeactivatesGrain() { Guid id = Guid.NewGuid(); string providerName = ErrorInjectorProviderName; IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id); var val = await grain.GetValue(); int expectedVal = 62; var originalActivationId = await grain.GetActivationId(); await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 const int attemptedVal3 = 63; SetErrorInjection(providerName, new ErrorInjectionBehavior { ErrorInjectionPoint = ErrorInjectionPoint.BeforeWrite, ExceptionType = typeof(InconsistentStateException) }); CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal3), typeof(InconsistentStateException)); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 Assert.NotEqual(originalActivationId, await grain.GetActivationId()); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); // Stored value unchanged providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 // The value should not have changed. Assert.Equal(expectedVal, val); } /// <summary> /// Tests that deactivations caused by an <see cref="InconsistentStateException"/> only affect the grain which /// the exception originated from. /// </summary> /// <returns></returns> [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_InconsistentStateException_DeactivatesOnlyCurrentGrain() { var target = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(Guid.NewGuid()); var proxy = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorProxyGrain>(Guid.NewGuid()); // Record the original activation ids. var targetActivationId = await target.GetActivationId(); var proxyActivationId = await proxy.GetActivationId(); // Cause an inconsistent state exception. this.SetErrorInjection(ErrorInjectorProviderName, new ErrorInjectionBehavior { ErrorInjectionPoint = ErrorInjectionPoint.BeforeWrite, ExceptionType = typeof(InconsistentStateException) }); this.CheckStorageProviderErrors(() => proxy.DoWrite(63, target), typeof(InconsistentStateException)); // The target should have been deactivated by the exception. Assert.NotEqual(targetActivationId, await target.GetActivationId()); // The grain which called the target grain should not have been deactivated. Assert.Equal(proxyActivationId, await proxy.GetActivationId()); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_AfterWrite() { Guid id = Guid.NewGuid(); string providerName = ErrorInjectorProviderName; IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(id); var val = await grain.GetValue(); int expectedVal = 82; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 const int attemptedVal4 = 83; SetErrorInjection(providerName, ErrorInjectionPoint.AfterWrite); CheckStorageProviderErrors(() => grain.DoWrite(attemptedVal4)); // Stored value has changed expectedVal = attemptedVal4; providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_BeforeReRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); int expectedVal = 72; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value expectedVal = 73; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); CheckStorageProviderErrors(grain.DoRead); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Provider_Error_AfterReRead() { string grainType = typeof(PersistenceProviderErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceProviderErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceProviderErrorGrain>(guid); var val = await grain.GetValue(); int expectedVal = 92; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(); Assert.Equal(expectedVal, val); // Returned value expectedVal = 93; await grain.DoWrite(expectedVal); var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 expectedVal = 94; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); SetErrorInjection(providerName, ErrorInjectionPoint.AfterRead); CheckStorageProviderErrors(grain.DoRead); SetErrorInjection(providerName, ErrorInjectionPoint.None); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Error_Handled_Read() { string grainType = typeof(PersistenceUserHandledErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value int newVal = expectedVal + 1; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal); SetErrorInjection(providerName, ErrorInjectionPoint.BeforeRead); val = await grain.DoRead(true); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.None); expectedVal = newVal; SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", newVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Error_Handled_Write() { string grainType = typeof(PersistenceUserHandledErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value int newVal = expectedVal + 1; SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite); await grain.DoWrite(newVal, true); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value SetErrorInjection(providerName, ErrorInjectionPoint.None); expectedVal = newVal; await grain.DoWrite(newVal, false); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Error_NotHandled_Write() { string grainType = typeof(PersistenceUserHandledErrorGrain).FullName; string providerName = ErrorInjectorProviderName; Guid guid = Guid.NewGuid(); string id = guid.ToString("N"); IPersistenceUserHandledErrorGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceUserHandledErrorGrain>(guid); var val = await grain.GetValue(); // Activate grain int expectedVal = 42; SetErrorInjection(providerName, ErrorInjectionPoint.None); SetStoredValue(providerName, typeof(ErrorInjectionStorageProvider).FullName, grainType, grain, "Field1", expectedVal); val = await grain.DoRead(false); Assert.Equal(expectedVal, val); // Returned value after read int newVal = expectedVal + 1; SetErrorInjection(providerName, ErrorInjectionPoint.BeforeWrite); CheckStorageProviderErrors(() => grain.DoWrite(newVal, false)); val = await grain.GetValue(); // Stored value unchanged var providerState = GetStateForStorageProviderInUse(providerName, typeof(ErrorInjectionStorageProvider).FullName); Assert.Equal(expectedVal, providerState.LastStoredGrainState.Field1); // Store-Field1 #if REREAD_STATE_AFTER_WRITE_FAILED Assert.Equal(expectedVal, val); // After failed write: Last value written successfully #else Assert.Equal(newVal, val); // After failed write: Last value attempted to be written is still in memory #endif SetErrorInjection(providerName, ErrorInjectionPoint.None); expectedVal = newVal; await grain.DoWrite(newVal, false); val = await grain.GetValue(); Assert.Equal(expectedVal, val); // Returned value after good write } [Fact, TestCategory("Stress"), TestCategory("CorePerf"), TestCategory("Persistence")] public async Task Persistence_Provider_Loop_Read() { const int numIterations = 100; string grainType = typeof(PersistenceTestGrain).FullName; Task<int>[] promises = new Task<int>[numIterations]; for (int i = 0; i < numIterations; i++) { int expectedVal = i; IPersistenceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceTestGrain>(Guid.NewGuid()); Guid guid = grain.GetPrimaryKey(); string id = guid.ToString("N"); SetStoredValue(MockStorageProviderName1, typeof(MockStorageProvider).FullName, grainType, grain, "Field1", expectedVal); // Update state data behind grain promises[i] = grain.DoRead(); } await Task.WhenAll(promises); for (int i = 0; i < numIterations; i++) { int expectedVal = i; Assert.Equal(expectedVal, promises[i].Result); // "Returned value - Read @ #" + i } } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_BadProvider() { IBadProviderTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IBadProviderTestGrain>(Guid.NewGuid()); var oex = await Assert.ThrowsAsync<BadGrainStorageConfigException>(() => grain.DoSomething()); } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public void OrleansException_BadProvider() { string msg1 = "BadProvider"; string msg2 = "Wrapper"; string msg3 = "Aggregate"; var bpce = new BadProviderConfigException(msg1); var oe = new OrleansException(msg2, bpce); var ae = new AggregateException(msg3, oe); Assert.NotNull(ae.InnerException); // AggregateException.InnerException should not be null Assert.IsAssignableFrom<OrleansException>(ae.InnerException); Exception exc = ae.InnerException; Assert.NotNull(exc.InnerException); // OrleansException.InnerException should not be null Assert.IsAssignableFrom<BadProviderConfigException>(exc.InnerException); exc = ae.GetBaseException(); Assert.NotNull(exc.InnerException); // BaseException.InnerException should not be null Assert.IsAssignableFrom<BadProviderConfigException>(exc.InnerException); Assert.Equal(msg3, ae.Message); // "AggregateException.Message should be '{0}'", msg3 Assert.Equal(msg2, exc.Message); // "OrleansException.Message should be '{0}'", msg2 Assert.Equal(msg1, exc.InnerException.Message); // "InnerException.Message should be '{0}'", msg1 } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("MemoryStore")] public async Task MemoryStore_UserGrain_Read_Write() { Guid id = Guid.NewGuid(); IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(id); string name = id.ToString(); await grain.SetName(name); string readName = await grain.GetName(); Assert.Equal(name, readName); // Read back previously set name Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); string name1 = id1.ToString(); string name2 = id2.ToString(); IUser friend1 = this.HostedCluster.GrainFactory.GetGrain<IUser>(id1); IUser friend2 = this.HostedCluster.GrainFactory.GetGrain<IUser>(id2); await friend1.SetName(name1); await friend2.SetName(name2); var readName1 = await friend1.GetName(); var readName2 = await friend2.GetName(); Assert.Equal(name1, readName1); // Friend #1 Name Assert.Equal(name2, readName2); // Friend #2 Name await grain.AddFriend(friend1); await grain.AddFriend(friend2); var friends = await grain.GetFriends(); Assert.Equal(2, friends.Count); // Number of friends Assert.Equal(name1, await friends[0].GetName()); // GetFriends - Friend #1 Name Assert.Equal(name2, await friends[1].GetName()); // GetFriends - Friend #2 Name } [Fact, TestCategory("Functional"), TestCategory("Persistence")] public async Task Persistence_Grain_NoState() { const string providerName = MockStorageProviderName1; Guid id = Guid.NewGuid(); IPersistenceNoStateTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IPersistenceNoStateTestGrain>(id); await grain.DoSomething(); Assert.True(HasStorageProvider(providerName)); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Serialization")] public void Serialize_GrainState_DeepCopy() { // NOTE: This test requires Silo to be running & Client init so that grain references can be resolved before serialization. IUser[] grains = new IUser[3]; grains[0] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); grains[1] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); grains[2] = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); GrainStateContainingGrainReferences initialState = new GrainStateContainingGrainReferences(); foreach (var g in grains) { initialState.GrainList.Add(g); initialState.GrainDict.Add(g.GetPrimaryKey().ToString(), g); } var copy = (GrainStateContainingGrainReferences)this.HostedCluster.SerializationManager.DeepCopy(initialState); Assert.NotSame(initialState.GrainDict, copy.GrainDict); // Dictionary Assert.NotSame(initialState.GrainList, copy.GrainList); // List } [Fact, TestCategory("Persistence"), TestCategory("Serialization"), TestCategory("CorePerf"), TestCategory("Stress")] public async Task Serialize_GrainState_DeepCopy_Stress() { int num = 100; int loops = num * 100; GrainStateContainingGrainReferences[] states = new GrainStateContainingGrainReferences[num]; for (int i = 0; i < num; i++) { IUser grain = this.HostedCluster.GrainFactory.GetGrain<IUser>(Guid.NewGuid()); states[i] = new GrainStateContainingGrainReferences(); states[i].GrainList.Add(grain); states[i].GrainDict.Add(grain.GetPrimaryKey().ToString(), grain); } List<Task> tasks = new List<Task>(); for (int i = 0; i < loops; i++) { int idx = random.Next(num); tasks.Add(Task.Run(() => { var copy = this.HostedCluster.SerializationManager.DeepCopy(states[idx]); })); tasks.Add(Task.Run(() => { var other = this.HostedCluster.SerializationManager.RoundTripSerializationForTesting(states[idx]); })); } await Task.WhenAll(tasks); //Task copyTask = Task.Run(() => //{ // for (int i = 0; i < loops; i++) // { // int idx = random.Next(num); // var copy = states[idx].DeepCopy(); // } //}); //Task serializeTask = Task.Run(() => //{ // for (int i = 0; i < loops; i++) // { // int idx = random.Next(num); // var other = SerializationManager.RoundTripSerializationForTesting(states[idx]); // } //}); //await Task.WhenAll(copyTask, serializeTask); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task ReentrentGrainWithState() { Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); IReentrentGrainWithState grain1 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id1); IReentrentGrainWithState grain2 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id2); await Task.WhenAll(grain1.Setup(grain2), grain2.Setup(grain1)); Task t11 = grain1.Test1(); Task t12 = grain1.Test2(); Task t21 = grain2.Test1(); Task t22 = grain2.Test2(); await Task.WhenAll(t11, t12, t21, t22); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task NonReentrentStressGrainWithoutState() { Guid id1 = Guid.NewGuid(); INonReentrentStressGrainWithoutState grain1 = this.HostedCluster.GrainFactory.GetGrain<INonReentrentStressGrainWithoutState>(id1); await grain1.Test1(); } private const bool DoStart = true; // Task.Delay tests fail (Timeout) unless True [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task ReentrentGrain_Task_Delay() { Guid id1 = Guid.NewGuid(); IReentrentGrainWithState grain1 = this.HostedCluster.GrainFactory.GetGrain<IReentrentGrainWithState>(id1); await grain1.Task_Delay(DoStart); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task NonReentrentGrain_Task_Delay() { Guid id1 = Guid.NewGuid(); INonReentrentStressGrainWithoutState grain1 = this.HostedCluster.GrainFactory.GetGrain<INonReentrentStressGrainWithoutState>(id1); await grain1.Task_Delay(DoStart); } [Fact, TestCategory("Functional"), TestCategory("Persistence"), TestCategory("Scheduler"), TestCategory("Reentrancy")] public async Task StateInheritanceTest() { Guid id1 = Guid.NewGuid(); IStateInheritanceTestGrain grain = this.HostedCluster.GrainFactory.GetGrain<IStateInheritanceTestGrain>(id1); await grain.SetValue(1); int val = await grain.GetValue(); Assert.Equal(1, val); } // ---------- Utility functions ---------- private void SetStoredValue(string providerName, string providerTypeFullName, string grainType, IGrain grain, string fieldName, int newValue) { IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); // set up SetVal func args var args = new MockStorageProvider.SetValueArgs { Val = newValue, Name = "Field1", GrainType = grainType, GrainReference = (GrainReference) grain, StateType = typeof(PersistenceTestGrainState) }; mgmtGrain.SendControlCommandToProvider(providerTypeFullName, providerName, (int)MockStorageProvider.Commands.SetValue, args).Wait(); } private void SetErrorInjection(string providerName, ErrorInjectionPoint errorInjectionPoint) { SetErrorInjection(providerName, new ErrorInjectionBehavior { ErrorInjectionPoint = errorInjectionPoint }); } private void SetErrorInjection(string providerName, ErrorInjectionBehavior errorInjectionBehavior) { ErrorInjectionStorageProvider.SetErrorInjection(providerName, errorInjectionBehavior, this.HostedCluster.GrainFactory); } private void CheckStorageProviderErrors(Func<Task> taskFunc, Type expectedException = null) { StackTrace at = new StackTrace(); TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(15); try { taskFunc().WithTimeout(timeout).GetAwaiter().GetResult(); if (ErrorInjectionStorageProvider.DoInjectErrors) { string msg = "StorageProviderInjectedError exception should have been thrown " + at; output.WriteLine("Assertion failed: {0}", msg); Assert.True(false, msg); } } catch (Exception e) { output.WriteLine("Exception caught: {0}", e); var baseException = e.GetBaseException(); if (baseException is OrleansException && baseException.InnerException != null) { baseException = baseException.InnerException; } Assert.IsAssignableFrom(expectedException ?? typeof(StorageProviderInjectedError), baseException); //if (exc is StorageProviderInjectedError) //{ // //Expected error //} //else //{ // output.WriteLine("Unexpected exception: {0}", exc); // Assert.True(false, exc.ToString()); //} } } private bool HasStorageProvider(string providerName) { foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) { if (this.HostedCluster.Client.GetTestHooks(siloHandle).HasStorageProvider(providerName).Result) { return true; } } return false; } private ProviderState GetStateForStorageProviderInUse(string providerName, string providerTypeFullName, bool okNull = false) { ProviderState providerState = new ProviderState(); IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); object[] replies = mgmtGrain.SendControlCommandToProvider(providerTypeFullName, providerName, (int)MockStorageProvider.Commands.GetProvideState, null).Result; object[] replies2 = mgmtGrain.SendControlCommandToProvider(providerTypeFullName, providerName, (int)MockStorageProvider.Commands.GetLastState, null).Result; for(int i = 0; i < replies.Length; i++) { MockStorageProvider.StateForTest state = (MockStorageProvider.StateForTest)replies[i]; PersistenceTestGrainState grainState = (PersistenceTestGrainState)replies2[i]; if (state.ReadCount > 0) { providerState.ProviderStateForTest = state; providerState.LastStoredGrainState = grainState; return providerState; } } return providerState; } class ProviderState { public MockStorageProvider.StateForTest ProviderStateForTest { get; set; } public PersistenceTestGrainState LastStoredGrainState { get; set; } } private void ResetMockStorageProvidersHistory() { var mockStorageProviders = new[] { MockStorageProviderName1, MockStorageProviderName2, MockStorageProviderNameLowerCase }; foreach (var siloHandle in this.HostedCluster.GetActiveSilos().ToList()) { foreach (var providerName in mockStorageProviders) { if (!this.HostedCluster.Client.GetTestHooks(siloHandle).HasStorageProvider(providerName).Result) continue; IManagementGrain mgmtGrain = this.HostedCluster.GrainFactory.GetGrain<IManagementGrain>(0); object[] replies = mgmtGrain.SendControlCommandToProvider(typeof(MockStorageProvider).FullName, providerName, (int)MockStorageProvider.Commands.ResetHistory, null).Result; } } } } } // ReSharper restore RedundantAssignment // ReSharper restore UnusedVariable // ReSharper restore InconsistentNaming
namespace XenAdmin.TabPages { partial class VMStoragePage { /// <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) { // Deregister listeners. VM = null; if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VMStoragePage)); this.AddButton = new System.Windows.Forms.Button(); this.EditButton = new System.Windows.Forms.Button(); this.AttachButton = new System.Windows.Forms.Button(); this.RightButtonSeparator = new System.Windows.Forms.Panel(); this.LeftButtonSeparator = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.dataGridViewStorage = new System.Windows.Forms.DataGridView(); this.ColumnDevicePosition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSR = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSRVolume = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnReadOnly = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnPriority = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnActive = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDevicePath = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.DeactivateButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DeactivateButton = new System.Windows.Forms.Button(); this.MoveButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.MoveButton = new System.Windows.Forms.Button(); this.DeleteButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DeleteDriveButton = new System.Windows.Forms.Button(); this.DetachButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DetachDriveButton = new System.Windows.Forms.Button(); this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.gradientPanel1 = new XenAdmin.Controls.GradientPanel.GradientPanel(); this.TitleLabel = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); this.DeactivateButtonContainer.SuspendLayout(); this.MoveButtonContainer.SuspendLayout(); this.DeleteButtonContainer.SuspendLayout(); this.DetachButtonContainer.SuspendLayout(); this.gradientPanel1.SuspendLayout(); this.SuspendLayout(); // // AddButton // resources.ApplyResources(this.AddButton, "AddButton"); this.AddButton.Name = "AddButton"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.AddButton_Click); // // EditButton // resources.ApplyResources(this.EditButton, "EditButton"); this.EditButton.Name = "EditButton"; this.EditButton.UseVisualStyleBackColor = true; this.EditButton.Click += new System.EventHandler(this.EditButton_Click); // // AttachButton // resources.ApplyResources(this.AttachButton, "AttachButton"); this.AttachButton.Name = "AttachButton"; this.AttachButton.UseVisualStyleBackColor = true; this.AttachButton.Click += new System.EventHandler(this.AttachButton_Click); // // RightButtonSeparator // this.RightButtonSeparator.BackColor = System.Drawing.SystemColors.ControlDarkDark; resources.ApplyResources(this.RightButtonSeparator, "RightButtonSeparator"); this.RightButtonSeparator.Name = "RightButtonSeparator"; // // LeftButtonSeparator // this.LeftButtonSeparator.BackColor = System.Drawing.SystemColors.ControlDarkDark; resources.ApplyResources(this.LeftButtonSeparator, "LeftButtonSeparator"); this.LeftButtonSeparator.Name = "LeftButtonSeparator"; // // panel1 // this.panel1.Controls.Add(this.panel2); this.panel1.Controls.Add(this.multipleDvdIsoList1); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // panel2 // resources.ApplyResources(this.panel2, "panel2"); this.panel2.Controls.Add(this.dataGridViewStorage); this.panel2.Controls.Add(this.flowLayoutPanel1); this.panel2.MaximumSize = new System.Drawing.Size(900, 400); this.panel2.Name = "panel2"; // // dataGridViewStorage // this.dataGridViewStorage.AllowUserToAddRows = false; this.dataGridViewStorage.AllowUserToDeleteRows = false; this.dataGridViewStorage.AllowUserToResizeRows = false; this.dataGridViewStorage.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridViewStorage.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridViewStorage.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridViewStorage.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnDevicePosition, this.ColumnName, this.ColumnDesc, this.ColumnSR, this.ColumnSRVolume, this.ColumnSize, this.ColumnReadOnly, this.ColumnPriority, this.ColumnActive, this.ColumnDevicePath}); resources.ApplyResources(this.dataGridViewStorage, "dataGridViewStorage"); this.dataGridViewStorage.Name = "dataGridViewStorage"; this.dataGridViewStorage.ReadOnly = true; this.dataGridViewStorage.RowHeadersVisible = false; this.dataGridViewStorage.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridViewStorage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.TheHeaderListBox_DataGridView_MouseUp); this.dataGridViewStorage.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.TheHeaderListBox_CellMouseDoubleClick); this.dataGridViewStorage.SelectionChanged += new System.EventHandler(this.TheHeaderListBox_SelectedIndexChanged); // // ColumnDevicePosition // this.ColumnDevicePosition.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnDevicePosition, "ColumnDevicePosition"); this.ColumnDevicePosition.Name = "ColumnDevicePosition"; this.ColumnDevicePosition.ReadOnly = true; // // ColumnName // this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnName, "ColumnName"); this.ColumnName.Name = "ColumnName"; this.ColumnName.ReadOnly = true; // // ColumnDesc // this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnDesc, "ColumnDesc"); this.ColumnDesc.Name = "ColumnDesc"; this.ColumnDesc.ReadOnly = true; // // ColumnSR // this.ColumnSR.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSR, "ColumnSR"); this.ColumnSR.Name = "ColumnSR"; this.ColumnSR.ReadOnly = true; // // ColumnSRVolume // this.ColumnSRVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSRVolume, "ColumnSRVolume"); this.ColumnSRVolume.Name = "ColumnSRVolume"; this.ColumnSRVolume.ReadOnly = true; // // ColumnSize // this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSize, "ColumnSize"); this.ColumnSize.Name = "ColumnSize"; this.ColumnSize.ReadOnly = true; // // ColumnReadOnly // this.ColumnReadOnly.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnReadOnly, "ColumnReadOnly"); this.ColumnReadOnly.Name = "ColumnReadOnly"; this.ColumnReadOnly.ReadOnly = true; // // ColumnPriority // this.ColumnPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnPriority, "ColumnPriority"); this.ColumnPriority.Name = "ColumnPriority"; this.ColumnPriority.ReadOnly = true; // // ColumnActive // this.ColumnActive.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnActive, "ColumnActive"); this.ColumnActive.Name = "ColumnActive"; this.ColumnActive.ReadOnly = true; // // ColumnDevicePath // this.ColumnDevicePath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnDevicePath, "ColumnDevicePath"); this.ColumnDevicePath.Name = "ColumnDevicePath"; this.ColumnDevicePath.ReadOnly = true; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.AddButton); this.flowLayoutPanel1.Controls.Add(this.AttachButton); this.flowLayoutPanel1.Controls.Add(this.RightButtonSeparator); this.flowLayoutPanel1.Controls.Add(this.DeactivateButtonContainer); this.flowLayoutPanel1.Controls.Add(this.MoveButtonContainer); this.flowLayoutPanel1.Controls.Add(this.EditButton); this.flowLayoutPanel1.Controls.Add(this.LeftButtonSeparator); this.flowLayoutPanel1.Controls.Add(this.DeleteButtonContainer); this.flowLayoutPanel1.Controls.Add(this.DetachButtonContainer); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.MaximumSize = new System.Drawing.Size(900, 35); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // DeactivateButtonContainer // this.DeactivateButtonContainer.Controls.Add(this.DeactivateButton); resources.ApplyResources(this.DeactivateButtonContainer, "DeactivateButtonContainer"); this.DeactivateButtonContainer.Name = "DeactivateButtonContainer"; // // DeactivateButton // resources.ApplyResources(this.DeactivateButton, "DeactivateButton"); this.DeactivateButton.Name = "DeactivateButton"; this.DeactivateButton.UseVisualStyleBackColor = true; this.DeactivateButton.Click += new System.EventHandler(this.DeactivateButton_Click); // // MoveButtonContainer // this.MoveButtonContainer.Controls.Add(this.MoveButton); resources.ApplyResources(this.MoveButtonContainer, "MoveButtonContainer"); this.MoveButtonContainer.Name = "MoveButtonContainer"; // // MoveButton // resources.ApplyResources(this.MoveButton, "MoveButton"); this.MoveButton.Name = "MoveButton"; this.MoveButton.UseVisualStyleBackColor = true; this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click); // // DeleteButtonContainer // this.DeleteButtonContainer.Controls.Add(this.DeleteDriveButton); resources.ApplyResources(this.DeleteButtonContainer, "DeleteButtonContainer"); this.DeleteButtonContainer.Name = "DeleteButtonContainer"; // // DeleteDriveButton // resources.ApplyResources(this.DeleteDriveButton, "DeleteDriveButton"); this.DeleteDriveButton.Name = "DeleteDriveButton"; this.DeleteDriveButton.UseVisualStyleBackColor = true; this.DeleteDriveButton.Click += new System.EventHandler(this.DeleteDriveButton_Click); // // DetachButtonContainer // this.DetachButtonContainer.Controls.Add(this.DetachDriveButton); resources.ApplyResources(this.DetachButtonContainer, "DetachButtonContainer"); this.DetachButtonContainer.Name = "DetachButtonContainer"; // // DetachDriveButton // resources.ApplyResources(this.DetachDriveButton, "DetachDriveButton"); this.DetachDriveButton.Name = "DetachDriveButton"; this.DetachDriveButton.UseVisualStyleBackColor = true; this.DetachDriveButton.Click += new System.EventHandler(this.DetachButton_Click); // // multipleDvdIsoList1 // resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1"); this.multipleDvdIsoList1.MaximumSize = new System.Drawing.Size(900, 36); this.multipleDvdIsoList1.Name = "multipleDvdIsoList1"; this.multipleDvdIsoList1.VM = null; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1"); this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2"); this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3"); this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4"); this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5"); this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.ReadOnly = true; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn6, "dataGridViewTextBoxColumn6"); this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; this.dataGridViewTextBoxColumn6.ReadOnly = true; // // dataGridViewTextBoxColumn7 // this.dataGridViewTextBoxColumn7.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn7, "dataGridViewTextBoxColumn7"); this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7"; this.dataGridViewTextBoxColumn7.ReadOnly = true; // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.dataGridViewTextBoxColumn8, "dataGridViewTextBoxColumn8"); this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8"; this.dataGridViewTextBoxColumn8.ReadOnly = true; // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn9, "dataGridViewTextBoxColumn9"); this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9"; this.dataGridViewTextBoxColumn9.ReadOnly = true; // // dataGridViewTextBoxColumn10 // this.dataGridViewTextBoxColumn10.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn10, "dataGridViewTextBoxColumn10"); this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10"; this.dataGridViewTextBoxColumn10.ReadOnly = true; // // gradientPanel1 // this.gradientPanel1.Controls.Add(this.TitleLabel); resources.ApplyResources(this.gradientPanel1, "gradientPanel1"); this.gradientPanel1.Name = "gradientPanel1"; this.gradientPanel1.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Tab; // // TitleLabel // resources.ApplyResources(this.TitleLabel, "TitleLabel"); this.TitleLabel.AutoEllipsis = true; this.TitleLabel.ForeColor = System.Drawing.Color.White; this.TitleLabel.Name = "TitleLabel"; // // VMStoragePage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.Controls.Add(this.panel1); this.Controls.Add(this.gradientPanel1); this.DoubleBuffered = true; this.Name = "VMStoragePage"; this.panel1.ResumeLayout(false); this.panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); this.DeactivateButtonContainer.ResumeLayout(false); this.MoveButtonContainer.ResumeLayout(false); this.DeleteButtonContainer.ResumeLayout(false); this.DetachButtonContainer.ResumeLayout(false); this.gradientPanel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion public System.Windows.Forms.Button AttachButton; public System.Windows.Forms.Button AddButton; private System.Windows.Forms.Button EditButton; public System.Windows.Forms.Button DetachDriveButton; public System.Windows.Forms.Button DeleteDriveButton; private System.Windows.Forms.Label TitleLabel; private XenAdmin.Controls.ToolTipContainer DetachButtonContainer; private XenAdmin.Controls.ToolTipContainer DeleteButtonContainer; private System.Windows.Forms.Panel RightButtonSeparator; private System.Windows.Forms.Panel LeftButtonSeparator; private XenAdmin.Controls.ToolTipContainer DeactivateButtonContainer; private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel1; public System.Windows.Forms.Button DeactivateButton; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.DataGridView dataGridViewStorage; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePosition; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSR; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSRVolume; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnReadOnly; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPriority; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnActive; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePath; private XenAdmin.Controls.ToolTipContainer MoveButtonContainer; private System.Windows.Forms.Button MoveButton; } }
// 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.Concurrent; using System.Globalization; using System.Reflection; namespace System.Runtime.Serialization.Formatters.Binary { internal sealed class ParseRecord { // Enums internal InternalParseTypeE _parseTypeEnum = InternalParseTypeE.Empty; internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty; internal InternalArrayTypeE _arrayTypeEnum = InternalArrayTypeE.Empty; internal InternalMemberTypeE _memberTypeEnum = InternalMemberTypeE.Empty; internal InternalMemberValueE _memberValueEnum = InternalMemberValueE.Empty; internal InternalObjectPositionE _objectPositionEnum = InternalObjectPositionE.Empty; // Object internal string _name; // Value internal string _value; internal object _varValue; // dt attribute internal string _keyDt; internal Type _dtType; internal InternalPrimitiveTypeE _dtTypeCode; // Object ID internal long _objectId; // Reference ID internal long _idRef; // Array // Array Element Type internal string _arrayElementTypeString; internal Type _arrayElementType; internal bool _isArrayVariant = false; internal InternalPrimitiveTypeE _arrayElementTypeCode; // Parsed array information internal int _rank; internal int[] _lengthA; internal int[] _lowerBoundA; // Array map for placing array elements in array internal int[] _indexMap; internal int _memberIndex; internal int _linearlength; internal int[] _rectangularMap; internal bool _isLowerBound; // MemberInfo accumulated during parsing of members internal ReadObjectInfo _objectInfo; // ValueType Fixup needed internal bool _isValueTypeFixup = false; // Created object internal object _newObj; internal object[] _objectA; //optimization, will contain object[] internal PrimitiveArray _primitiveArray; // for Primitive Soap arrays, optimization internal bool _isRegistered; // Used when registering nested classes internal object[] _memberData; // member data is collected here before populating internal SerializationInfo _si; internal int _consecutiveNullArrayEntryCount; internal ParseRecord() { } // Initialize ParseRecord. Called when reusing. internal void Init() { // Enums _parseTypeEnum = InternalParseTypeE.Empty; _objectTypeEnum = InternalObjectTypeE.Empty; _arrayTypeEnum = InternalArrayTypeE.Empty; _memberTypeEnum = InternalMemberTypeE.Empty; _memberValueEnum = InternalMemberValueE.Empty; _objectPositionEnum = InternalObjectPositionE.Empty; // Object _name = null; // Value _value = null; // dt attribute _keyDt = null; _dtType = null; _dtTypeCode = InternalPrimitiveTypeE.Invalid; // Object ID _objectId = 0; // Reference ID _idRef = 0; // Array // Array Element Type _arrayElementTypeString = null; _arrayElementType = null; _isArrayVariant = false; _arrayElementTypeCode = InternalPrimitiveTypeE.Invalid; // Parsed array information _rank = 0; _lengthA = null; _lowerBoundA = null; // Array map for placing array elements in array _indexMap = null; _memberIndex = 0; _linearlength = 0; _rectangularMap = null; _isLowerBound = false; // ValueType Fixup needed _isValueTypeFixup = false; _newObj = null; _objectA = null; _primitiveArray = null; _objectInfo = null; _isRegistered = false; _memberData = null; _si = null; _consecutiveNullArrayEntryCount = 0; } } // Implements a stack used for parsing internal sealed class SerStack { internal object[] _objects = new object[5]; internal string _stackId; internal int _top = -1; internal SerStack(string stackId) { _stackId = stackId; } // Push the object onto the stack internal void Push(object obj) { if (_top == (_objects.Length - 1)) { IncreaseCapacity(); } _objects[++_top] = obj; } // Pop the object from the stack internal object Pop() { if (_top < 0) { return null; } object obj = _objects[_top]; _objects[_top--] = null; return obj; } internal void IncreaseCapacity() { int size = _objects.Length * 2; object[] newItems = new object[size]; Array.Copy(_objects, 0, newItems, 0, _objects.Length); _objects = newItems; } // Gets the object on the top of the stack internal object Peek() => _top < 0 ? null : _objects[_top]; // Gets the second entry in the stack. internal object PeekPeek() => _top < 1 ? null : _objects[_top - 1]; // The number of entries in the stack internal bool IsEmpty() => _top <= 0; } // Implements a Growable array internal sealed class SizedArray : ICloneable { internal object[] _objects = null; internal object[] _negObjects = null; internal SizedArray() { _objects = new object[16]; _negObjects = new object[4]; } internal SizedArray(int length) { _objects = new object[length]; _negObjects = new object[length]; } private SizedArray(SizedArray sizedArray) { _objects = new object[sizedArray._objects.Length]; sizedArray._objects.CopyTo(_objects, 0); _negObjects = new object[sizedArray._negObjects.Length]; sizedArray._negObjects.CopyTo(_negObjects, 0); } public object Clone() => new SizedArray(this); internal object this[int index] { get { if (index < 0) { return -index > _negObjects.Length - 1 ? null : _negObjects[-index]; } else { return index > _objects.Length - 1 ? null : _objects[index]; } } set { if (index < 0) { if (-index > _negObjects.Length - 1) { IncreaseCapacity(index); } _negObjects[-index] = value; } else { if (index > _objects.Length - 1) { IncreaseCapacity(index); } _objects[index] = value; } } } internal void IncreaseCapacity(int index) { try { if (index < 0) { int size = Math.Max(_negObjects.Length * 2, (-index) + 1); object[] newItems = new object[size]; Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length); _negObjects = newItems; } else { int size = Math.Max(_objects.Length * 2, index + 1); object[] newItems = new object[size]; Array.Copy(_objects, 0, newItems, 0, _objects.Length); _objects = newItems; } } catch (Exception) { throw new SerializationException(SR.Serialization_CorruptedStream); } } } internal sealed class IntSizedArray : ICloneable { internal int[] _objects = new int[16]; internal int[] _negObjects = new int[4]; public IntSizedArray() { } private IntSizedArray(IntSizedArray sizedArray) { _objects = new int[sizedArray._objects.Length]; sizedArray._objects.CopyTo(_objects, 0); _negObjects = new int[sizedArray._negObjects.Length]; sizedArray._negObjects.CopyTo(_negObjects, 0); } public object Clone() => new IntSizedArray(this); internal int this[int index] { get { if (index < 0) { return -index > _negObjects.Length - 1 ? 0 : _negObjects[-index]; } else { return index > _objects.Length - 1 ? 0 : _objects[index]; } } set { if (index < 0) { if (-index > _negObjects.Length - 1) { IncreaseCapacity(index); } _negObjects[-index] = value; } else { if (index > _objects.Length - 1) { IncreaseCapacity(index); } _objects[index] = value; } } } internal void IncreaseCapacity(int index) { try { if (index < 0) { int size = Math.Max(_negObjects.Length * 2, (-index) + 1); int[] newItems = new int[size]; Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length); _negObjects = newItems; } else { int size = Math.Max(_objects.Length * 2, index + 1); int[] newItems = new int[size]; Array.Copy(_objects, 0, newItems, 0, _objects.Length); _objects = newItems; } } catch (Exception) { throw new SerializationException(SR.Serialization_CorruptedStream); } } } internal sealed class NameCache { private static readonly ConcurrentDictionary<string, object> s_ht = new ConcurrentDictionary<string, object>(); private string _name = null; internal object GetCachedValue(string name) { _name = name; object value; return s_ht.TryGetValue(name, out value) ? value : null; } internal void SetCachedValue(object value) => s_ht[_name] = value; } // Used to fixup value types. Only currently used for valuetypes which are array items. internal sealed class ValueFixup { internal ValueFixupEnum _valueFixupEnum = ValueFixupEnum.Empty; internal Array _arrayObj; internal int[] _indexMap; internal object _header = null; internal object _memberObject; internal ReadObjectInfo _objectInfo; internal string _memberName; internal ValueFixup(Array arrayObj, int[] indexMap) { _valueFixupEnum = ValueFixupEnum.Array; _arrayObj = arrayObj; _indexMap = indexMap; } internal ValueFixup(object memberObject, string memberName, ReadObjectInfo objectInfo) { _valueFixupEnum = ValueFixupEnum.Member; _memberObject = memberObject; _memberName = memberName; _objectInfo = objectInfo; } internal void Fixup(ParseRecord record, ParseRecord parent) { object obj = record._newObj; switch (_valueFixupEnum) { case ValueFixupEnum.Array: _arrayObj.SetValue(obj, _indexMap); break; case ValueFixupEnum.Header: throw new PlatformNotSupportedException(); case ValueFixupEnum.Member: if (_objectInfo._isSi) { _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName, record._objectId); } else { MemberInfo memberInfo = _objectInfo.GetMemberInfo(_memberName); if (memberInfo != null) { _objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId); } } break; } } } // Class used to transmit Enums from the XML and Binary Formatter class to the ObjectWriter and ObjectReader class internal sealed class InternalFE { internal FormatterTypeStyle _typeFormat; internal FormatterAssemblyStyle _assemblyFormat; internal TypeFilterLevel _securityLevel; internal InternalSerializerTypeE _serializerTypeEnum; } internal sealed class NameInfo { internal string _fullName; // Name from SerObjectInfo.GetType internal long _objectId; internal long _assemId; internal InternalPrimitiveTypeE _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid; internal Type _type; internal bool _isSealed; internal bool _isArray; internal bool _isArrayItem; internal bool _transmitTypeOnObject; internal bool _transmitTypeOnMember; internal bool _isParentTypeOnObject; internal InternalArrayTypeE _arrayEnum; private bool _sealedStatusChecked = false; internal NameInfo() { } internal void Init() { _fullName = null; _objectId = 0; _assemId = 0; _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid; _type = null; _isSealed = false; _transmitTypeOnObject = false; _transmitTypeOnMember = false; _isParentTypeOnObject = false; _isArray = false; _isArrayItem = false; _arrayEnum = InternalArrayTypeE.Empty; _sealedStatusChecked = false; } public bool IsSealed { get { if (!_sealedStatusChecked) { _isSealed = _type.IsSealed; _sealedStatusChecked = true; } return _isSealed; } } public string NIname { get { return _fullName ?? (_fullName = _type.FullName); } set { _fullName = value; } } } internal sealed class PrimitiveArray { private readonly InternalPrimitiveTypeE _code; private readonly bool[] _booleanA = null; private readonly char[] _charA = null; private readonly double[] _doubleA = null; private readonly short[] _int16A = null; private readonly int[] _int32A = null; private readonly long[] _int64A = null; private readonly sbyte[] _sbyteA = null; private readonly float[] _singleA = null; private readonly ushort[] _uint16A = null; private readonly uint[] _uint32A = null; private readonly ulong[] _uint64A = null; internal PrimitiveArray(InternalPrimitiveTypeE code, Array array) { _code = code; switch (code) { case InternalPrimitiveTypeE.Boolean: _booleanA = (bool[])array; break; case InternalPrimitiveTypeE.Char: _charA = (char[])array; break; case InternalPrimitiveTypeE.Double: _doubleA = (double[])array; break; case InternalPrimitiveTypeE.Int16: _int16A = (short[])array; break; case InternalPrimitiveTypeE.Int32: _int32A = (int[])array; break; case InternalPrimitiveTypeE.Int64: _int64A = (long[])array; break; case InternalPrimitiveTypeE.SByte: _sbyteA = (sbyte[])array; break; case InternalPrimitiveTypeE.Single: _singleA = (float[])array; break; case InternalPrimitiveTypeE.UInt16: _uint16A = (ushort[])array; break; case InternalPrimitiveTypeE.UInt32: _uint32A = (uint[])array; break; case InternalPrimitiveTypeE.UInt64: _uint64A = (ulong[])array; break; } } internal void SetValue(string value, int index) { switch (_code) { case InternalPrimitiveTypeE.Boolean: _booleanA[index] = bool.Parse(value); break; case InternalPrimitiveTypeE.Char: if ((value[0] == '_') && (value.Equals("_0x00_"))) { _charA[index] = char.MinValue; } else { _charA[index] = char.Parse(value); } break; case InternalPrimitiveTypeE.Double: _doubleA[index] = double.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.Int16: _int16A[index] = short.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.Int32: _int32A[index] = int.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.Int64: _int64A[index] = long.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.SByte: _sbyteA[index] = sbyte.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.Single: _singleA[index] = float.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.UInt16: _uint16A[index] = ushort.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.UInt32: _uint32A[index] = uint.Parse(value, CultureInfo.InvariantCulture); break; case InternalPrimitiveTypeE.UInt64: _uint64A[index] = ulong.Parse(value, CultureInfo.InvariantCulture); break; } } } }
#pragma warning disable 1587 #region Header /// /// JsonMapper.cs /// JSON to .Net object and object to JSON conversions. /// /// 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; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using Amazon.Util; using Amazon.Util.Internal; namespace ThirdParty.Json.LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; var typeInfo = TypeFactory.GetTypeInfo(type); if (typeInfo.GetInterface("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in typeInfo.GetProperties()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); var typeInfo = TypeFactory.GetTypeInfo(type); if (typeInfo.GetInterface("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in typeInfo.GetProperties()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in typeInfo.GetFields()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; var typeInfo = TypeFactory.GetTypeInfo(type); IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in typeInfo.GetProperties()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in typeInfo.GetFields()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } var typeInfoT1 = TypeFactory.GetTypeInfo(t1); var typeInfoT2 = TypeFactory.GetTypeInfo(t2); if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = typeInfoT1.GetMethod( "op_Implicit", new ITypeInfo[] { typeInfoT2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); var inst_typeInfo = TypeFactory.GetTypeInfo(inst_type); if (reader.Token == JsonToken.ArrayEnd) return null; //support for nullable types Type underlying_type = Nullable.GetUnderlyingType(inst_type); Type value_type = underlying_type ?? inst_type; if (reader.Token == JsonToken.Null) { if (inst_typeInfo.IsClass || underlying_type != null) { return null; } throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); var json_typeInfo = TypeFactory.GetTypeInfo(json_type); if (inst_typeInfo.IsAssignableFrom(json_typeInfo)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( value_type)) { ImporterFunc importer = custom_importers_table[json_type][value_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( value_type)) { ImporterFunc importer = base_importers_table[json_type][value_type]; return importer (reader.Value); } // Maybe it's an enum if (inst_typeInfo.IsEnum) return Enum.ToObject (value_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (value_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new List<object> (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (value_type); ObjectMetadata t_data = object_metadata[value_type]; instance = Activator.CreateInstance (value_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); // nij - added check to see if the item is not null. This is to handle arrays within arrays. // In those cases when the outer array read the inner array an item was returned back the current // reader.Token is at the ArrayEnd for the inner array. if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; base_exporters_table[typeof(float)] = delegate (object obj,JsonWriter writer){ writer.Write(Convert.ToDouble((float) obj)); }; base_exporters_table[typeof(Int64)] = delegate (object obj,JsonWriter writer){ writer.Write(Convert.ToDouble((Int64) obj)); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate(object input) { return Convert.ToSingle((float)(double)input); }; RegisterImporter(base_importers_table,typeof(double), typeof(float),importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); importer = delegate(object input) { return Convert.ToInt64 ((Int32)input); }; RegisterImporter (base_importers_table, typeof (Int32), typeof(Int64), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName(p_data.Info.Name); #if BCL||UNITY WriteValue(p_info.GetGetMethod().Invoke(obj, null), writer, writer_is_private, depth + 1); #elif PCL WriteValue(p_info.GetMethod.Invoke(obj, null), writer, writer_is_private, depth + 1); #endif } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
namespace Nancy { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using ModelBinding; using Nancy.Routing; using Nancy.Session; using Nancy.ViewEngines; using Nancy.Extensions; using Nancy.Validation; /// <summary> /// Contains the functionality for defining routes and actions in Nancy. /// </summary> /// <value>This is the core type in the entire framework and changes to this class should not be very frequent because it represents a change to the core API of the framework.</value> public abstract class NancyModule : IHideObjectMembers { private readonly List<Route> routes; /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> protected NancyModule() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> /// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param> protected NancyModule(string modulePath) { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.ModulePath = modulePath; this.routes = new List<Route>(); } /// <summary> /// <para> /// The post-request hook /// </para> /// <para> /// The post-request hook is called after the response is created by the route execution. /// It can be used to rewrite the response or add/remove items from the context. /// </para> /// </summary> public AfterPipeline After { get; protected set; } /// <summary> /// <para> /// The pre-request hook /// </para> /// <para> /// The PreRequest hook is called prior to executing a route. If any item in the /// pre-request pipeline returns a response then the route is not executed and the /// response is returned. /// </para> /// </summary> public BeforePipeline Before { get; protected set; } /// <summary> /// Gets or sets the current Nancy context /// </summary> /// <value>A <see cref="NancyContext"/> instance.</value> public NancyContext Context { get; set; } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for DELETE requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Delete { get { return new RouteBuilder("DELETE", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for GET requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> /// <remarks>These actions will also be used when a HEAD request is recieved.</remarks> public RouteBuilder Get { get { return new RouteBuilder("GET", this); } } /// <summary> /// Get the root path of the routes in the current module. /// </summary> /// <value>A <see cref="string"/> containing the root path of the module or <see langword="null"/> if no root path should be used.</value> /// <remarks>All routes will be relative to this root path.</remarks> public string ModulePath { get; private set; } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for OPTIONS requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Options { get { return new RouteBuilder("OPTIONS", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PATCH requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Patch { get { return new RouteBuilder("PATCH", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for POST requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Post { get { return new RouteBuilder("POST", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PUT requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Put { get { return new RouteBuilder("PUT", this); } } /// <summary> /// Gets or sets an <see cref="Request"/> instance that represents the current request. /// </summary> /// <value>An <see cref="Request"/> instance.</value> public Request Request { get { return this.Context.Request; } set { this.Context.Request = value; } } /// <summary> /// Gets all declared routes by the module. /// </summary> /// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value> public IEnumerable<Route> Routes { get { return this.routes.AsReadOnly(); } } /// <summary> /// An extension point for adding support for formatting response contents. /// </summary> /// <value>This property will always return <see langword="null" /> because it acts as an extension point.</value> /// <remarks>Extension methods to this property should always return <see cref="Response"/> or one of the types that can implicitly be types into a <see cref="Response"/>.</remarks> public IResponseFormatter Response { get; set; } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get { return this.Request.Session; } } /// <summary> /// Renders a view from inside a route handler. /// </summary> /// <value>A <see cref="ViewRenderer"/> instance that is used to determin which view that should be rendered.</value> public ViewRenderer View { get { return new ViewRenderer(this); } } /// <summary> /// The extension point for accessing the view engines in Nancy. /// </summary> /// <value>An <see cref="IViewFactory"/> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IViewFactory ViewFactory { get; set; } /// <summary> /// Gets or sets the model binder locator /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public IModelBinderLocator ModelBinderLocator { get; set; } /// <summary> /// Gets or sets the validator locator. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public IModelValidatorLocator ValidatorLocator { get; set; } /// <summary> /// Helper class for configuring a route handler in a module. /// </summary> public class RouteBuilder : IHideObjectMembers { private readonly string method; private readonly NancyModule parentModule; /// <summary> /// Initializes a new instance of the <see cref="RouteBuilder"/> class. /// </summary> /// <param name="method">The HTTP request method that the route should be available for.</param> /// <param name="parentModule">The <see cref="NancyModule"/> that the route is being configured for.</param> public RouteBuilder(string method, NancyModule parentModule) { this.method = method; this.parentModule = parentModule; } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, Response> this[string path] { set { this.AddRoute(path, null, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, Response> this[string path, Func<NancyContext, bool> condition] { set { this.AddRoute(path, condition, value); } } private void AddRoute(string path, Func<NancyContext, bool> condition, Func<object, Response> value) { var fullPath = string.Concat(this.parentModule.ModulePath, path); this.parentModule.routes.Add(new Route(this.method, fullPath, condition, value)); } } /// <summary> /// Helper class for rendering a view from a route handler. /// </summary> public class ViewRenderer : IHideObjectMembers { private readonly NancyModule module; /// <summary> /// Initializes a new instance of the <see cref="ViewRenderer"/> class. /// </summary> /// <param name="module">The <see cref="NancyModule"/> instance that is rendering the view.</param> public ViewRenderer(NancyModule module) { this.module = module; } /// <summary> /// Renders the view with its name resolved from the model type, and model defined by the <paramref name="model"/> parameter. /// </summary> /// <param name="model">The model that should be passed into the view.</param> /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns> /// <remarks>The view name is model.GetType().Name with any Model suffix removed.</remarks> public Response this[dynamic model] { get { return this.module.ViewFactory.RenderView(null, model, this.GetViewLocationContext()); } } /// <summary> /// Renders the view with the name defined by the <paramref name="viewName"/> parameter. /// </summary> /// <param name="viewName">The name of the view to render.</param> /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns> /// <remarks>The extension in the view name is optional. If it is omitted, then Nancy will try to resolve which of the available engines that should be used to render the view.</remarks> public Response this[string viewName] { get { return this.module.ViewFactory.RenderView(viewName, null, this.GetViewLocationContext()); } } /// <summary> /// Renders the view with the name and model defined by the <paramref name="viewName"/> and <paramref name="model"/> parameters. /// </summary> /// <param name="viewName">The name of the view to render.</param> /// <param name="model">The model that should be passed into the view.</param> /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns> /// <remarks>The extension in the view name is optional. If it is omitted, then Nancy will try to resolve which of the available engines that should be used to render the view.</remarks> public Response this[string viewName, dynamic model] { get { return this.module.ViewFactory.RenderView(viewName, model, this.GetViewLocationContext()); } } private ViewLocationContext GetViewLocationContext() { return new ViewLocationContext { ModulePath = module.ModulePath, ModuleName = module.GetModuleName(), Context = module.Context }; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation.Preprocessor; using Microsoft.DotNet.ProjectModel.Files; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resolution; using Microsoft.DotNet.ProjectModel.Utilities; using Microsoft.DotNet.Tools.Compiler; using NuGet.Frameworks; namespace Microsoft.DotNet.ProjectModel.Compilation { public class LibraryExporter { private readonly string _configuration; private readonly string _runtime; private readonly ProjectDescription _rootProject; private readonly string _buildBasePath; private readonly string _solutionRootPath; public LibraryExporter(ProjectDescription rootProject, LibraryManager manager, string configuration, string runtime, string buildBasePath, string solutionRootPath) { if (string.IsNullOrEmpty(configuration)) { throw new ArgumentNullException(nameof(configuration)); } LibraryManager = manager; _configuration = configuration; _runtime = runtime; _buildBasePath = buildBasePath; _solutionRootPath = solutionRootPath; _rootProject = rootProject; } public LibraryManager LibraryManager { get; } /// <summary> /// Gets all the exports specified by this project, including the root project itself /// </summary> public IEnumerable<LibraryExport> GetAllExports() { return ExportLibraries(_ => true); } /// <summary> /// Gets all exports required by the project, NOT including the project itself /// </summary> /// <returns></returns> public IEnumerable<LibraryExport> GetDependencies() { return GetDependencies(LibraryType.Unspecified); } /// <summary> /// Gets all exports required by the project, of the specified <see cref="LibraryType"/>, NOT including the project itself /// </summary> /// <returns></returns> public IEnumerable<LibraryExport> GetDependencies(LibraryType type) { // Export all but the main project return ExportLibraries(library => library != _rootProject && LibraryIsOfType(type, library)); } /// <summary> /// Retrieves a list of <see cref="LibraryExport"/> objects representing the assets /// required from other libraries to compile this project. /// </summary> private IEnumerable<LibraryExport> ExportLibraries(Func<LibraryDescription, bool> condition) { var seenMetadataReferences = new HashSet<string>(); // Iterate over libraries in the library manager foreach (var library in LibraryManager.GetLibraries()) { if (!condition(library)) { continue; } var compilationAssemblies = new List<LibraryAsset>(); var sourceReferences = new List<LibraryAsset>(); var analyzerReferences = new List<AnalyzerReference>(); var libraryExport = GetExport(library); // We need to filter out source references from non-root libraries, // so we rebuild the library export foreach (var reference in libraryExport.CompilationAssemblies) { if (seenMetadataReferences.Add(reference.Name)) { compilationAssemblies.Add(reference); } } // Source and analyzer references are not transitive if (library.Parents.Contains(_rootProject)) { sourceReferences.AddRange(libraryExport.SourceReferences); analyzerReferences.AddRange(libraryExport.AnalyzerReferences); } yield return LibraryExportBuilder.Create(library) .WithCompilationAssemblies(compilationAssemblies) .WithSourceReferences(sourceReferences) .WithRuntimeAssemblyGroups(libraryExport.RuntimeAssemblyGroups) .WithRuntimeAssets(libraryExport.RuntimeAssets) .WithNativeLibraryGroups(libraryExport.NativeLibraryGroups) .WithEmbedddedResources(libraryExport.EmbeddedResources) .WithAnalyzerReference(analyzerReferences) .WithResourceAssemblies(libraryExport.ResourceAssemblies) .Build(); } } /// <summary> /// Create a LibraryExport from LibraryDescription. /// /// When the library is not resolved the LibraryExport is created nevertheless. /// </summary> private LibraryExport GetExport(LibraryDescription library) { if (!library.Resolved) { // For a unresolved project reference returns a export with empty asset. return LibraryExportBuilder.Create(library).Build(); } var libraryType = library.Identity.Type; if (Equals(LibraryType.Package, libraryType) || Equals(LibraryType.MSBuildProject, libraryType)) { return ExportPackage((TargetLibraryWithAssets)library); } else if (Equals(LibraryType.Project, libraryType)) { return ExportProject((ProjectDescription)library); } else { return ExportFrameworkLibrary(library); } } private LibraryExport ExportPackage(TargetLibraryWithAssets library) { var builder = LibraryExportBuilder.Create(library); builder.AddNativeLibraryGroup(new LibraryAssetGroup(PopulateAssets(library, library.NativeLibraries))); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(PopulateAssets(library, library.RuntimeAssemblies))); builder.WithCompilationAssemblies(PopulateAssets(library, library.CompileTimeAssemblies)); if (library.Identity.Type.Equals(LibraryType.Package)) { builder.WithSourceReferences(GetSharedSources((PackageDescription) library)); builder.WithAnalyzerReference(GetAnalyzerReferences((PackageDescription) library)); } if (library.ContentFiles.Any()) { var parameters = PPFileParameters.CreateForProject(_rootProject.Project); Action<Stream, Stream> transform = (input, output) => PPFilePreprocessor.Preprocess(input, output, parameters); var sourceCodeLanguage = _rootProject.Project.GetSourceCodeLanguage(); var languageGroups = library.ContentFiles.GroupBy(file => file.CodeLanguage); var selectedGroup = languageGroups.FirstOrDefault(g => g.Key == sourceCodeLanguage) ?? languageGroups.FirstOrDefault(g => g.Key == null); if (selectedGroup != null) { foreach (var contentFile in selectedGroup) { if (contentFile.CodeLanguage != null && string.Compare(contentFile.CodeLanguage, sourceCodeLanguage, StringComparison.OrdinalIgnoreCase) != 0) { continue; } var fileTransform = contentFile.PPOutputPath != null ? transform : null; var fullPath = Path.Combine(library.Path, contentFile.Path); if (contentFile.BuildAction == BuildAction.Compile) { builder.AddSourceReference(LibraryAsset.CreateFromRelativePath(library.Path, contentFile.Path, fileTransform)); } else if (contentFile.BuildAction == BuildAction.EmbeddedResource) { builder.AddEmbedddedResource(LibraryAsset.CreateFromRelativePath(library.Path, contentFile.Path, fileTransform)); } if (contentFile.CopyToOutput) { builder.AddRuntimeAsset(new LibraryAsset(contentFile.Path, contentFile.OutputPath, fullPath, fileTransform)); } } } } if (library.RuntimeTargets.Any()) { foreach (var targetGroup in library.RuntimeTargets.GroupBy(t => t.Runtime)) { var runtime = new List<LibraryAsset>(); var native = new List<LibraryAsset>(); foreach (var lockFileRuntimeTarget in targetGroup) { if (string.Equals(lockFileRuntimeTarget.AssetType, "native", StringComparison.OrdinalIgnoreCase)) { native.Add(LibraryAsset.CreateFromRelativePath(library.Path, lockFileRuntimeTarget.Path)); } else if (string.Equals(lockFileRuntimeTarget.AssetType, "runtime", StringComparison.OrdinalIgnoreCase)) { runtime.Add(LibraryAsset.CreateFromRelativePath(library.Path, lockFileRuntimeTarget.Path)); } } if (runtime.Any()) { builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(targetGroup.Key, runtime.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.RelativePath)))); } if (native.Any()) { builder.AddNativeLibraryGroup(new LibraryAssetGroup(targetGroup.Key, native.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.RelativePath)))); } } } return builder.Build(); } private LibraryExport ExportProject(ProjectDescription project) { var builder = LibraryExportBuilder.Create(project); if (!string.IsNullOrEmpty(project.TargetFrameworkInfo?.AssemblyPath)) { // Project specifies a pre-compiled binary. We're done! var assemblyPath = ResolvePath(project.Project, _configuration, project.TargetFrameworkInfo.AssemblyPath); var pdbPath = Path.ChangeExtension(assemblyPath, "pdb"); var compileAsset = new LibraryAsset( project.Project.Name, Path.GetFileName(assemblyPath), assemblyPath); builder.AddCompilationAssembly(compileAsset); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { compileAsset })); if (File.Exists(pdbPath)) { builder.AddRuntimeAsset(new LibraryAsset(Path.GetFileName(pdbPath), Path.GetFileName(pdbPath), pdbPath)); } } else if (project.Project.Files.SourceFiles.Any()) { var outputPaths = project.GetOutputPaths(_buildBasePath, _solutionRootPath, _configuration, _runtime); var compilationAssembly = outputPaths.CompilationFiles.Assembly; var compilationAssemblyAsset = LibraryAsset.CreateFromAbsolutePath( outputPaths.CompilationFiles.BasePath, compilationAssembly); builder.AddCompilationAssembly(compilationAssemblyAsset); if (ExportsRuntime(project)) { var runtimeAssemblyAsset = LibraryAsset.CreateFromAbsolutePath( outputPaths.RuntimeFiles.BasePath, outputPaths.RuntimeFiles.Assembly); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { runtimeAssemblyAsset })); builder.WithRuntimeAssets(CollectAssets(outputPaths.RuntimeFiles)); } else { builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { compilationAssemblyAsset })); builder.WithRuntimeAssets(CollectAssets(outputPaths.CompilationFiles)); } } builder.WithSourceReferences(project.Project.Files.SharedFiles.Select(f => LibraryAsset.CreateFromAbsolutePath(project.Path, f) )); return builder.Build(); } private IEnumerable<LibraryAsset> CollectAssets(CompilationOutputFiles files) { var assemblyPath = files.Assembly; foreach (var path in files.All()) { if (string.Equals(assemblyPath, path)) { continue; } yield return LibraryAsset.CreateFromAbsolutePath(files.BasePath, path); } } private bool ExportsRuntime(ProjectDescription project) { return project == _rootProject && !string.IsNullOrWhiteSpace(_runtime) && project.Project.HasRuntimeOutput(_configuration); } private static string ResolvePath(Project project, string configuration, string path) { if (string.IsNullOrEmpty(path)) { return null; } path = PathUtility.GetPathWithDirectorySeparator(path); path = path.Replace("{configuration}", configuration); return Path.Combine(project.ProjectDirectory, path); } private LibraryExport ExportFrameworkLibrary(LibraryDescription library) { // We assume the path is to an assembly. Framework libraries only export compile-time stuff // since they assume the runtime library is present already var builder = LibraryExportBuilder.Create(library); if (!string.IsNullOrEmpty(library.Path)) { builder.WithCompilationAssemblies(new[] { new LibraryAsset(library.Identity.Name, null, library.Path) }); } return builder.Build(); } private IEnumerable<LibraryAsset> GetSharedSources(PackageDescription package) { return package .PackageLibrary .Files .Where(path => path.StartsWith("shared" + Path.DirectorySeparatorChar)) .Select(path => LibraryAsset.CreateFromRelativePath(package.Path, path)); } private IEnumerable<AnalyzerReference> GetAnalyzerReferences(PackageDescription package) { var analyzers = package .PackageLibrary .Files .Where(path => path.StartsWith("analyzers" + Path.DirectorySeparatorChar) && path.EndsWith(".dll")); var analyzerRefs = new List<AnalyzerReference>(); // See https://docs.nuget.org/create/analyzers-conventions for the analyzer // NuGet specification foreach (var analyzer in analyzers) { var specifiers = analyzer.Split(Path.DirectorySeparatorChar); var assemblyPath = Path.Combine(package.Path, analyzer); // $/analyzers/{Framework Name}{Version}/{Supported Architecture}/{Supported Programming Language}/{Analyzer}.dll switch (specifiers.Length) { // $/analyzers/{analyzer}.dll case 2: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: null, language: null, runtimeIdentifier: null )); break; // $/analyzers/{framework}/{analyzer}.dll case 3: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: null, runtimeIdentifier: null )); break; // $/analyzers/{framework}/{language}/{analyzer}.dll case 4: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: specifiers[2], runtimeIdentifier: null )); break; // $/analyzers/{framework}/{runtime}/{language}/{analyzer}.dll case 5: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: specifiers[3], runtimeIdentifier: specifiers[2] )); break; // Anything less than 2 specifiers or more than 4 is // illegal according to the specification and will be // ignored } } return analyzerRefs; } private IEnumerable<LibraryAsset> PopulateAssets(TargetLibraryWithAssets library, IEnumerable<LockFileItem> section) { foreach (var assemblyPath in section.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.Path))) { yield return LibraryAsset.CreateFromRelativePath(library.Path, assemblyPath.Path); } } private static bool LibraryIsOfType(LibraryType type, LibraryDescription library) { return type.Equals(LibraryType.Unspecified) || // No type filter was requested library.Identity.Type.Equals(type); // OR, library type matches requested type } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SocialApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/rpc/hk_management_svc.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Operations.RPC { /// <summary>Holder for reflection information generated from operations/rpc/hk_management_svc.proto</summary> public static partial class HkManagementSvcReflection { #region Descriptor /// <summary>File descriptor for operations/rpc/hk_management_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static HkManagementSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiZvcGVyYXRpb25zL3JwYy9oa19tYW5hZ2VtZW50X3N2Yy5wcm90bxIaaG9s", "bXMudHlwZXMub3BlcmF0aW9ucy5ycGMaG2dvb2dsZS9wcm90b2J1Zi9lbXB0", "eS5wcm90bxogaWFtL3N0YWZmX21lbWJlcl9pbmRpY2F0b3IucHJvdG8aNW9w", "ZXJhdGlvbnMvaG91c2VrZWVwaW5nL2hvdXNla2VlcGluZ19hc3NpZ25tZW50", "LnByb3RvGiVvcGVyYXRpb25zL3Jvb21zL3Jvb21faW5kaWNhdG9yLnByb3Rv", "GhtvcGVyYXRpb25zL3Jvb21zL3Jvb20ucHJvdG8aHXByaW1pdGl2ZS9wYl9s", "b2NhbF9kYXRlLnByb3RvIoABCixIb3VzZWtlZXBpbmdNYW5hZ2VtZW50U3Zj", "QXNzaWdubWVudHNSZXNwb25zZRJQCgthc3NpZ25tZW50cxgBIAMoCzI7Lmhv", "bG1zLnR5cGVzLm9wZXJhdGlvbnMuaG91c2VrZWVwaW5nLkhvdXNla2VlcGlu", "Z0Fzc2lnbm1lbnQiqgEKKkhvdXNla2VlcGluZ01hbmFnZW1lbnRTdmNBc3Np", "Z25tZW50UmVxdWVzdBI3Cghhc3NpZ25lZRgBIAEoCzIlLmhvbG1zLnR5cGVz", "LmlhbS5TdGFmZk1lbWJlckluZGljYXRvchJDCg5hc3NpZ25lZF9yb29tcxgC", "IAMoCzIrLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9vbXMuUm9vbUluZGlj", "YXRvciJgCitIb3VzZWtlZXBpbmdNYW5hZ2VtZW50U3ZjVXBkYXRlUm9vbXNS", "ZXF1ZXN0EjEKBXJvb21zGAEgAygLMiIuaG9sbXMudHlwZXMub3BlcmF0aW9u", "cy5yb29tcy5Sb29tMpcEChlIb3VzZWtlZXBpbmdNYW5hZ2VtZW50U3ZjEoQB", "ChRHZXRBc3NpZ25tZW50c0J5RGF0ZRIiLmhvbG1zLnR5cGVzLnByaW1pdGl2", "ZS5QYkxvY2FsRGF0ZRpILmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucnBjLkhv", "dXNla2VlcGluZ01hbmFnZW1lbnRTdmNBc3NpZ25tZW50c1Jlc3BvbnNlEn0K", "G0Fzc2lnbkhvdXNla2VlcGVyVG9Sb29tc05vdxJGLmhvbG1zLnR5cGVzLm9w", "ZXJhdGlvbnMucnBjLkhvdXNla2VlcGluZ01hbmFnZW1lbnRTdmNBc3NpZ25t", "ZW50UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRJ/ChxVcGRhdGVS", "b29tTWFpbnRlbmFuY2VSZXF1ZXN0EkcuaG9sbXMudHlwZXMub3BlcmF0aW9u", "cy5ycGMuSG91c2VrZWVwaW5nTWFuYWdlbWVudFN2Y1VwZGF0ZVJvb21zUmVx", "dWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRJzChBVcGRhdGVSb29tU3Rh", "dHVzEkcuaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMuSG91c2VrZWVwaW5n", "TWFuYWdlbWVudFN2Y1VwZGF0ZVJvb21zUmVxdWVzdBoWLmdvb2dsZS5wcm90", "b2J1Zi5FbXB0eUIdqgIaSE9MTVMuVHlwZXMuT3BlcmF0aW9ucy5SUENiBnBy", "b3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.IAM.StaffMemberIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.Housekeeping.HousekeepingAssignmentReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.HousekeepingManagementSvcAssignmentsResponse), global::HOLMS.Types.Operations.RPC.HousekeepingManagementSvcAssignmentsResponse.Parser, new[]{ "Assignments" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.HousekeepingManagementSvcAssignmentRequest), global::HOLMS.Types.Operations.RPC.HousekeepingManagementSvcAssignmentRequest.Parser, new[]{ "Assignee", "AssignedRooms" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.HousekeepingManagementSvcUpdateRoomsRequest), global::HOLMS.Types.Operations.RPC.HousekeepingManagementSvcUpdateRoomsRequest.Parser, new[]{ "Rooms" }, null, null, null) })); } #endregion } #region Messages public sealed partial class HousekeepingManagementSvcAssignmentsResponse : pb::IMessage<HousekeepingManagementSvcAssignmentsResponse> { private static readonly pb::MessageParser<HousekeepingManagementSvcAssignmentsResponse> _parser = new pb::MessageParser<HousekeepingManagementSvcAssignmentsResponse>(() => new HousekeepingManagementSvcAssignmentsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HousekeepingManagementSvcAssignmentsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.HkManagementSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcAssignmentsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcAssignmentsResponse(HousekeepingManagementSvcAssignmentsResponse other) : this() { assignments_ = other.assignments_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcAssignmentsResponse Clone() { return new HousekeepingManagementSvcAssignmentsResponse(this); } /// <summary>Field number for the "assignments" field.</summary> public const int AssignmentsFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.Housekeeping.HousekeepingAssignment> _repeated_assignments_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Operations.Housekeeping.HousekeepingAssignment.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.Housekeeping.HousekeepingAssignment> assignments_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.Housekeeping.HousekeepingAssignment>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Operations.Housekeeping.HousekeepingAssignment> Assignments { get { return assignments_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HousekeepingManagementSvcAssignmentsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HousekeepingManagementSvcAssignmentsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!assignments_.Equals(other.assignments_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= assignments_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { assignments_.WriteTo(output, _repeated_assignments_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += assignments_.CalculateSize(_repeated_assignments_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HousekeepingManagementSvcAssignmentsResponse other) { if (other == null) { return; } assignments_.Add(other.assignments_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { assignments_.AddEntriesFrom(input, _repeated_assignments_codec); break; } } } } } public sealed partial class HousekeepingManagementSvcAssignmentRequest : pb::IMessage<HousekeepingManagementSvcAssignmentRequest> { private static readonly pb::MessageParser<HousekeepingManagementSvcAssignmentRequest> _parser = new pb::MessageParser<HousekeepingManagementSvcAssignmentRequest>(() => new HousekeepingManagementSvcAssignmentRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HousekeepingManagementSvcAssignmentRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.HkManagementSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcAssignmentRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcAssignmentRequest(HousekeepingManagementSvcAssignmentRequest other) : this() { Assignee = other.assignee_ != null ? other.Assignee.Clone() : null; assignedRooms_ = other.assignedRooms_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcAssignmentRequest Clone() { return new HousekeepingManagementSvcAssignmentRequest(this); } /// <summary>Field number for the "assignee" field.</summary> public const int AssigneeFieldNumber = 1; private global::HOLMS.Types.IAM.StaffMemberIndicator assignee_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.IAM.StaffMemberIndicator Assignee { get { return assignee_; } set { assignee_ = value; } } /// <summary>Field number for the "assigned_rooms" field.</summary> public const int AssignedRoomsFieldNumber = 2; private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.Rooms.RoomIndicator> _repeated_assignedRooms_codec = pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Operations.Rooms.RoomIndicator.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.RoomIndicator> assignedRooms_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.RoomIndicator>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.RoomIndicator> AssignedRooms { get { return assignedRooms_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HousekeepingManagementSvcAssignmentRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HousekeepingManagementSvcAssignmentRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Assignee, other.Assignee)) return false; if(!assignedRooms_.Equals(other.assignedRooms_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (assignee_ != null) hash ^= Assignee.GetHashCode(); hash ^= assignedRooms_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (assignee_ != null) { output.WriteRawTag(10); output.WriteMessage(Assignee); } assignedRooms_.WriteTo(output, _repeated_assignedRooms_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (assignee_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Assignee); } size += assignedRooms_.CalculateSize(_repeated_assignedRooms_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HousekeepingManagementSvcAssignmentRequest other) { if (other == null) { return; } if (other.assignee_ != null) { if (assignee_ == null) { assignee_ = new global::HOLMS.Types.IAM.StaffMemberIndicator(); } Assignee.MergeFrom(other.Assignee); } assignedRooms_.Add(other.assignedRooms_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (assignee_ == null) { assignee_ = new global::HOLMS.Types.IAM.StaffMemberIndicator(); } input.ReadMessage(assignee_); break; } case 18: { assignedRooms_.AddEntriesFrom(input, _repeated_assignedRooms_codec); break; } } } } } public sealed partial class HousekeepingManagementSvcUpdateRoomsRequest : pb::IMessage<HousekeepingManagementSvcUpdateRoomsRequest> { private static readonly pb::MessageParser<HousekeepingManagementSvcUpdateRoomsRequest> _parser = new pb::MessageParser<HousekeepingManagementSvcUpdateRoomsRequest>(() => new HousekeepingManagementSvcUpdateRoomsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HousekeepingManagementSvcUpdateRoomsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.HkManagementSvcReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcUpdateRoomsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcUpdateRoomsRequest(HousekeepingManagementSvcUpdateRoomsRequest other) : this() { rooms_ = other.rooms_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingManagementSvcUpdateRoomsRequest Clone() { return new HousekeepingManagementSvcUpdateRoomsRequest(this); } /// <summary>Field number for the "rooms" field.</summary> public const int RoomsFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.Rooms.Room> _repeated_rooms_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Operations.Rooms.Room.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room> rooms_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room> Rooms { get { return rooms_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HousekeepingManagementSvcUpdateRoomsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HousekeepingManagementSvcUpdateRoomsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rooms_.Equals(other.rooms_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= rooms_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { rooms_.WriteTo(output, _repeated_rooms_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += rooms_.CalculateSize(_repeated_rooms_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HousekeepingManagementSvcUpdateRoomsRequest other) { if (other == null) { return; } rooms_.Add(other.rooms_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rooms_.AddEntriesFrom(input, _repeated_rooms_codec); break; } } } } } #endregion } #endregion Designer generated code
using System; using Epi; using System.Reflection; namespace Epi { /// <summary> /// Application Identity class /// </summary> public class ApplicationIdentity { readonly Version assemblyVersion; readonly Version assemblyInformationalVersion; readonly Version assemblyFileVersion; readonly string company; readonly string product; readonly string copyright; readonly string releaseDate; /// <summary> /// Constructor /// </summary> /// <param name="a">CLR Application</param> public ApplicationIdentity(Assembly a) { assemblyVersion = a.GetName().Version; object[] customAttributes; customAttributes = a.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); if (customAttributes.Length == 1) { assemblyInformationalVersion = new Version(((AssemblyInformationalVersionAttribute)customAttributes[0]).InformationalVersion); } customAttributes = a.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false); if (customAttributes.Length == 1) { assemblyFileVersion = new Version(((AssemblyFileVersionAttribute)customAttributes[0]).Version); } customAttributes = a.GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (customAttributes.Length == 1) { product = ((AssemblyProductAttribute)customAttributes[0]).Product; } customAttributes = a.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (customAttributes.Length == 1) { company = ((AssemblyCompanyAttribute)customAttributes[0]).Company; } customAttributes = a.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (customAttributes.Length == 1) { copyright = ((AssemblyCopyrightAttribute)customAttributes[0]).Copyright; } customAttributes = a.GetCustomAttributes(typeof(AssemblyReleaseDateAttribute), false); if (customAttributes.Length == 1) { releaseDate = ((AssemblyReleaseDateAttribute)customAttributes[0]).ReleaseDate; } } #region Public Properties /// <summary> /// Gets the version number of the application /// </summary> public string Version { get { return assemblyInformationalVersion.ToString(); } } /// <summary> /// Gets the version as an object /// </summary> public Version VersionObject { get { return assemblyInformationalVersion; } } /// <summary> /// Gets the build number of the application /// </summary> public string Build { get { return assemblyVersion.Build.ToString(); } } /// <summary> /// Gets the revision number of the application /// </summary> public string Revision { get { return assemblyVersion.Revision.ToString(); } } // /// <summary> // /// Gets the version release date if it is a release version. In development, returns today's date. // /// </summary> // public string VersionReleaseDate // { // get // { // //if (Global.IsInDevelopmentMode) // //{ // // return SharedStrings.DEV; // //} // //else // //{ // string releaseDate = System.Configuration.ConfigurationSettings.ApplicationIdentity[AppSettingKeys.VERSION_RELEASE_DATE]; // if (string.IsNullOrEmpty(releaseDate)) // { // return SharedStrings.DEV; // } // else // { //// $$$ TODO this is not locale neutral and will throw an error for other than US locale // return DateTime.Parse(releaseDate).ToShortDateString(); // } // //} // } // } /// <summary> /// App release date /// </summary> public string VersionReleaseDate { get { return releaseDate; } } /// <summary> /// Gets the application name /// </summary> public string AppName { get { return product; } } /// <summary> /// Gets the application suite name /// </summary> public string SuiteName { get { return product; } } /// <summary> /// Gets the company name /// </summary> public string Company { get { return company; } } /// <summary> /// Gets the company name /// </summary> public string Copyright { get { return copyright; } } #endregion Public Properties } /// <summary> /// Assembly Release Date Attribute /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class AssemblyReleaseDateAttribute : Attribute { private string releaseDate; /// <summary> /// Build date of assembly. /// </summary> public string ReleaseDate { get { return releaseDate; } set { releaseDate = value; } } /// <summary> /// Constructor /// </summary> /// <param name="releaseDate">Assembly release date.</param> public AssemblyReleaseDateAttribute(string releaseDate) { this.releaseDate = releaseDate; } } }
// 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.Linq; using System.Net.Sockets; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { public class HttpClientMiniStress : HttpClientTestBase { [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [MemberData(nameof(GetStressOptions))] public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); using (HttpClient client = CreateHttpClient()) { Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ => { CreateServerAndGet(client, completionOption, responseText); }); } } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); using (HttpClient client = CreateHttpClient()) { await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText)); } } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [MemberData(nameof(GetStressOptions))] public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ => { using (HttpClient client = CreateHttpClient()) { CreateServerAndGet(client, completionOption, responseText); } }); } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [MemberData(nameof(PostStressOptions))] public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes) { string responseText = CreateResponse(""); await ForCountAsync(numRequests, dop, async i => { using (HttpClient client = CreateHttpClient()) { await CreateServerAndPostAsync(client, numBytes, responseText); } }); } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [InlineData(1000000)] public void CreateAndDestroyManyClients(int numClients) { for (int i = 0; i < numClients; i++) { CreateHttpClient().Dispose(); } } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [InlineData(5000)] public async Task MakeAndFaultManyRequests(int numRequests) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { client.Timeout = Timeout.InfiniteTimeSpan; Task<string>[] tasks = (from i in Enumerable.Range(0, numRequests) select client.GetStringAsync(url)) .ToArray(); Assert.All(tasks, t => Assert.True(t.IsFaulted || t.Status == TaskStatus.WaitingForActivation, $"Unexpected status {t.Status}")); server.Dispose(); foreach (Task<string> task in tasks) { await Assert.ThrowsAnyAsync<HttpRequestException>(() => task); } } }, new LoopbackServer.Options { ListenBacklog = numRequests }); } public static IEnumerable<object[]> GetStressOptions() { foreach (int numRequests in new[] { 5000 }) // number of requests foreach (int dop in new[] { 1, 32 }) // number of threads foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead }) yield return new object[] { numRequests, dop, completionoption }; } private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText) { LoopbackServer.CreateServerAsync((server, url) => { Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption); server.AcceptConnectionAsync(connection => { while (!string.IsNullOrEmpty(connection.Reader.ReadLine())) ; connection.Writer.Write(responseText); connection.Socket.Shutdown(SocketShutdown.Send); return Task.CompletedTask; }).GetAwaiter().GetResult(); getAsync.GetAwaiter().GetResult().Dispose(); return Task.CompletedTask; }).GetAwaiter().GetResult(); } private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText) { await LoopbackServer.CreateServerAsync(async (server, url) => { Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption); await server.AcceptConnectionAsync(async connection => { while (!string.IsNullOrEmpty(await connection.Reader.ReadLineAsync().ConfigureAwait(false))) ; await connection.Writer.WriteAsync(responseText).ConfigureAwait(false); connection.Socket.Shutdown(SocketShutdown.Send); }); (await getAsync.ConfigureAwait(false)).Dispose(); }); } public static IEnumerable<object[]> PostStressOptions() { foreach (int numRequests in new[] { 5000 }) // number of requests foreach (int dop in new[] { 1, 32 }) // number of threads foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post yield return new object[] { numRequests, dop, numBytes }; } private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText) { await LoopbackServer.CreateServerAsync(async (server, url) => { var content = new ByteArrayContent(new byte[numBytes]); Task<HttpResponseMessage> postAsync = client.PostAsync(url, content); await server.AcceptConnectionAsync(async connection => { while (!string.IsNullOrEmpty(await connection.Reader.ReadLineAsync().ConfigureAwait(false))) ; for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, connection.Reader.Read()); await connection.Writer.WriteAsync(responseText).ConfigureAwait(false); connection.Socket.Shutdown(SocketShutdown.Send); }); (await postAsync.ConfigureAwait(false)).Dispose(); }); } [ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public async Task UnreadResponseMessage_Collectible() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Func<Task<WeakReference>> getAsync = () => client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ContinueWith(t => new WeakReference(t.Result)); Task<WeakReference> wrt = getAsync(); await server.AcceptConnectionAsync(async connection => { while (!string.IsNullOrEmpty(await connection.Reader.ReadLineAsync())) ; await connection.Writer.WriteAsync(CreateResponse(new string('a', 32 * 1024))); WeakReference wr = wrt.GetAwaiter().GetResult(); Assert.True(SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return !wr.IsAlive; }, 10 * 1000), "Response object should have been collected"); }); } }); } private static string CreateResponse(string asciiBody) => $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Type: text/plain\r\n" + $"Content-Length: {asciiBody.Length}\r\n" + "\r\n" + $"{asciiBody}"; private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync) { var sched = new ThreadPerTaskScheduler(); int nextAvailableIndex = 0; return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate { int index; while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count) { try { await bodyAsync(index); } catch { Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations throw; } } }, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap())); } private sealed class ThreadPerTaskScheduler : TaskScheduler { protected override void QueueTask(Task task) => Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task); protected override IEnumerable<Task> GetScheduledTasks() => null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Net.Sockets.Tests { public class DisposedSocket { private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static Socket GetDisposedSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { using (var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp)) { return socket; } } private static void TheAsyncCallback(IAsyncResult ar) { } [Fact] public void Available_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Available); } [Fact] public void IOControl_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(0, null, null)); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(IOControlCode.AsyncIO, null, null)); } [Fact] public void LocalEndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().LocalEndPoint); } [Fact] public void RemoteEndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().RemoteEndPoint); } [Fact] public void SetBlocking_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().Blocking = true; }); } [Fact] public void ExclusiveAddressUse_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ExclusiveAddressUse); } [Fact] public void SetExclusiveAddressUse_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().ExclusiveAddressUse = true; }); } [Fact] public void ReceiveBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveBufferSize); } [Fact] public void SetReceiveBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().ReceiveBufferSize = 1; }); } [Fact] public void SendBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendBufferSize); } [Fact] public void SetSendBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().SendBufferSize = 1; }); } [Fact] public void ReceiveTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveTimeout); } [Fact] public void SetReceiveTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().ReceiveTimeout = 1; }); } [Fact] public void SendTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTimeout); } [Fact] public void SetSendTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().SendTimeout = 1; }); } [Fact] public void LingerState_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().LingerState); } [Fact] public void SetLingerState_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().LingerState = new LingerOption(true, 1); }); } [Fact] public void NoDelay_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().NoDelay); } [Fact] public void SetNoDelay_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().NoDelay = true; }); } [Fact] public void Ttl_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).Ttl); } [Fact] public void SetTtl_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetwork).Ttl = 1; }); } [Fact] public void Ttl_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).Ttl); } [Fact] public void SetTtl_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetworkV6).Ttl = 1; }); } [Fact] public void DontFragment_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().DontFragment); } [Fact] public void SetDontFragment_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().DontFragment = true; }); } [Fact] public void MulticastLoopback_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).MulticastLoopback); } [Fact] public void SetMulticastLoopback_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetwork).MulticastLoopback = true; }); } [Fact] public void MulticastLoopback_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).MulticastLoopback); } [Fact] public void SetMulticastLoopback_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetworkV6).MulticastLoopback = true; }); } [Fact] public void EnableBroadcast_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EnableBroadcast); } [Fact] public void SetEnableBroadcast_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().EnableBroadcast = true; }); } [Fact] public void DualMode_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).DualMode); } [Fact] public void SetDualMode_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetworkV6).DualMode = true; }); } [Fact] public void Bind_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Bind(new IPEndPoint(IPAddress.Loopback, 0))); } [Fact] public void Connect_IPEndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void Connect_IPAddress_Port_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_Port_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect("localhost", 1)); } [Fact] public void Connect_IPAddresses_Port_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(new[] { IPAddress.Loopback }, 1)); } [Fact] public void Listen_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Listen(1)); } [Fact] public void Accept_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Accept()); } [Fact] public void Send_Buffer_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, s_buffer.Length, SocketFlags.None)); } [Fact] public void Send_Buffer_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, SocketFlags.None)); } [Fact] public void Send_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer)); } [Fact] public void Send_Buffer_Offset_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, 0, s_buffer.Length, SocketFlags.None)); } [Fact] public void Send_Buffer_Offset_Size_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers)); } [Fact] public void Send_Buffers_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers, SocketFlags.None)); } [Fact] public void Send_Buffers_SocketFlags_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers, SocketFlags.None, out errorCode)); } [Fact] public void SendTo_Buffer_Offset_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, 0, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_Buffer_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_Buffer_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void Receive_Buffer_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, s_buffer.Length, SocketFlags.None)); } [Fact] public void Receive_Buffer_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, SocketFlags.None)); } [Fact] public void Receive_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer)); } [Fact] public void Receive_Buffer_Offset_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, 0, s_buffer.Length, SocketFlags.None)); } [Fact] public void Receive_Buffer_Offset_Size_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers)); } [Fact] public void Receive_Buffers_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers, SocketFlags.None)); } [Fact] public void Receive_Buffers_SocketFlags_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers, SocketFlags.None, out errorCode)); } [Fact] public void ReceiveMessageFrom_Throws_ObjectDisposed() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveFrom_Buffer_Offset_Size_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote)); } [Fact] public void ReceiveFrom_Buffer_Size_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, s_buffer.Length, SocketFlags.None, ref remote)); } [Fact] public void ReceiveFrom_Buffer_SocketFlags_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, SocketFlags.None, ref remote)); } [Fact] public void ReceiveFrom_Buffer_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, ref remote)); } [Fact] public void Shutdown_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Shutdown(SocketShutdown.Both)); } [Fact] public void IOControl_Int_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(0, s_buffer, s_buffer)); } [Fact] public void IOControl_IOControlCode_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(IOControlCode.Flush, s_buffer, s_buffer)); } [Fact] public void SetSocketOption_Int_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, 0)); } [Fact] public void SetSocketOption_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, s_buffer)); } [Fact] public void SetSocketOption_Bool_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, true)); } [Fact] public void SetSocketOption_Object_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 1))); } [Fact] public void GetSocketOption_Int_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, 4)); } [Fact] public void GetSocketOption_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, s_buffer)); } [Fact] public void GetSocketOption_Object_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger)); } [Fact] public void Poll_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Poll(-1, SelectMode.SelectWrite)); } [Fact] public void AcceptAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().AcceptAsync(s_eventArgs)); } [Fact] public void ConnectAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ReceiveAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void SendAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendToAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendToAsync(s_eventArgs)); } [Fact] public void BeginConnect_EndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddress_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(IPAddress.Loopback, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect("localhost", 1, TheAsyncCallback, null)); } [Fact] public void EndConnect_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndConnect(null)); } [Fact] public void BeginSend_Buffer_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffer_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndSend_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSend(null)); } [Fact] public void BeginSendTo_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSendTo(s_buffer, 0, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } [Fact] public void EndSendTo_Throws_ObjectDisposedException() { // Behavior difference: EndSendTo_Throws_ObjectDisposed Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSendTo(null)); } [Fact] public void BeginReceive_Buffer_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffer_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndReceive_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_Throws_ObjectDisposedException() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void EndReceiveFrom_Throws_ObjectDisposedException() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceiveFrom(null, ref remote)); } [Fact] public void BeginReceiveMessageFrom_Throws_ObjectDisposedException() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void EndReceiveMessageFrom_Throws_ObjectDisposedException() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void BeginAccept_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginAccept(TheAsyncCallback, null)); } [Fact] public void EndAccept_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndAccept(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeInfos.NativeFormat; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.FieldInfos; using System.Reflection.Runtime.FieldInfos.NativeFormat; using System.Reflection.Runtime.MethodInfos; using System.Reflection.Runtime.BindingFlagSupport; using System.Reflection.Runtime.Modules; using Internal.Runtime.Augments; using Internal.Reflection.Augments; using Internal.Reflection.Core.Execution; using Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.General { internal sealed class ReflectionCoreCallbacksImplementation : ReflectionCoreCallbacks { internal ReflectionCoreCallbacksImplementation() { } public sealed override Assembly Load(AssemblyName assemblyRef, bool throwOnFileNotFound) { if (assemblyRef == null) throw new ArgumentNullException(nameof(assemblyRef)); if (throwOnFileNotFound) return RuntimeAssembly.GetRuntimeAssembly(assemblyRef.ToRuntimeAssemblyName()); else return RuntimeAssembly.GetRuntimeAssemblyIfExists(assemblyRef.ToRuntimeAssemblyName()); } public sealed override Assembly Load(byte[] rawAssembly, byte[] pdbSymbolStore) { if (rawAssembly == null) throw new ArgumentNullException(nameof(rawAssembly)); return RuntimeAssembly.GetRuntimeAssemblyFromByteArray(rawAssembly, pdbSymbolStore); } // // This overload of GetMethodForHandle only accepts handles for methods declared on non-generic types (the method, however, // can be an instance of a generic method.) To resolve handles for methods declared on generic types, you must pass // the declaring type explicitly using the two-argument overload of GetMethodFromHandle. // // This is a vestige from desktop generic sharing that got itself enshrined in the code generated by the C# compiler for Linq Expressions. // public sealed override MethodBase GetMethodFromHandle(RuntimeMethodHandle runtimeMethodHandle) { ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment; QMethodDefinition methodHandle; RuntimeTypeHandle declaringTypeHandle; RuntimeTypeHandle[] genericMethodTypeArgumentHandles; if (!executionEnvironment.TryGetMethodFromHandle(runtimeMethodHandle, out declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) throw new ArgumentException(SR.Argument_InvalidHandle); MethodBase methodBase = ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles); if (methodBase.DeclaringType.IsConstructedGenericType) // For compat with desktop, insist that the caller pass us the declaring type to resolve members of generic types. throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGeneric, methodBase)); return methodBase; } // // This overload of GetMethodHandle can handle all method handles. // public sealed override MethodBase GetMethodFromHandle(RuntimeMethodHandle runtimeMethodHandle, RuntimeTypeHandle declaringTypeHandle) { ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment; QMethodDefinition methodHandle; RuntimeTypeHandle[] genericMethodTypeArgumentHandles; if (!executionEnvironment.TryGetMethodFromHandleAndType(runtimeMethodHandle, declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) { // This may be a method declared on a non-generic type: this api accepts that too so try the other table. RuntimeTypeHandle actualDeclaringTypeHandle; if (!executionEnvironment.TryGetMethodFromHandle(runtimeMethodHandle, out actualDeclaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) throw new ArgumentException(SR.Argument_InvalidHandle); if (!actualDeclaringTypeHandle.Equals(declaringTypeHandle)) throw new ArgumentException(SR.Format(SR.Argument_ResolveMethodHandle, declaringTypeHandle.GetTypeForRuntimeTypeHandle(), actualDeclaringTypeHandle.GetTypeForRuntimeTypeHandle())); } MethodBase methodBase = ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles); return methodBase; } // // This overload of GetFieldForHandle only accepts handles for fields declared on non-generic types. To resolve handles for fields // declared on generic types, you must pass the declaring type explicitly using the two-argument overload of GetFieldFromHandle. // // This is a vestige from desktop generic sharing that got itself enshrined in the code generated by the C# compiler for Linq Expressions. // public sealed override FieldInfo GetFieldFromHandle(RuntimeFieldHandle runtimeFieldHandle) { ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment; FieldHandle fieldHandle; RuntimeTypeHandle declaringTypeHandle; if (!executionEnvironment.TryGetFieldFromHandle(runtimeFieldHandle, out declaringTypeHandle, out fieldHandle)) throw new ArgumentException(SR.Argument_InvalidHandle); FieldInfo fieldInfo = GetFieldInfo(declaringTypeHandle, fieldHandle); if (fieldInfo.DeclaringType.IsConstructedGenericType) // For compat with desktop, insist that the caller pass us the declaring type to resolve members of generic types. throw new ArgumentException(SR.Format(SR.Argument_FieldDeclaringTypeGeneric, fieldInfo)); return fieldInfo; } // // This overload of GetFieldHandle can handle all field handles. // public sealed override FieldInfo GetFieldFromHandle(RuntimeFieldHandle runtimeFieldHandle, RuntimeTypeHandle declaringTypeHandle) { ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment; FieldHandle fieldHandle; if (!executionEnvironment.TryGetFieldFromHandleAndType(runtimeFieldHandle, declaringTypeHandle, out fieldHandle)) { // This may be a field declared on a non-generic type: this api accepts that too so try the other table. RuntimeTypeHandle actualDeclaringTypeHandle; if (!executionEnvironment.TryGetFieldFromHandle(runtimeFieldHandle, out actualDeclaringTypeHandle, out fieldHandle)) throw new ArgumentException(SR.Argument_InvalidHandle); if (!actualDeclaringTypeHandle.Equals(declaringTypeHandle)) throw new ArgumentException(SR.Format(SR.Argument_ResolveFieldHandle, declaringTypeHandle.GetTypeForRuntimeTypeHandle(), actualDeclaringTypeHandle.GetTypeForRuntimeTypeHandle())); } FieldInfo fieldInfo = GetFieldInfo(declaringTypeHandle, fieldHandle); return fieldInfo; } public sealed override EventInfo GetImplicitlyOverriddenBaseClassEvent(EventInfo e) { return e.GetImplicitlyOverriddenBaseClassMember(); } public sealed override MethodInfo GetImplicitlyOverriddenBaseClassMethod(MethodInfo m) { return m.GetImplicitlyOverriddenBaseClassMember(); } public sealed override PropertyInfo GetImplicitlyOverriddenBaseClassProperty(PropertyInfo p) { return p.GetImplicitlyOverriddenBaseClassMember(); } private FieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle) { RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle(); NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo(); MetadataReader reader = definingTypeInfo.Reader; // RuntimeFieldHandles always yield FieldInfo's whose ReflectedType equals the DeclaringType. RuntimeTypeInfo reflectedType = contextTypeInfo; return NativeFormatRuntimeFieldInfo.GetRuntimeFieldInfo(fieldHandle, definingTypeInfo, contextTypeInfo, reflectedType); } [DebuggerHidden] [DebuggerStepThrough] public sealed override object ActivatorCreateInstance(Type type, bool nonPublic) { return ActivatorImplementation.CreateInstance(type, nonPublic); } [DebuggerHidden] [DebuggerStepThrough] public sealed override object ActivatorCreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { return ActivatorImplementation.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); } // V2 api: Creates open or closed delegates to static or instance methods - relaxed signature checking allowed. public sealed override Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure) { return CreateDelegateWorker(type, firstArgument, method, throwOnBindFailure, allowClosed: true); } // V1 api: Creates open delegates to static or instance methods - relaxed signature checking allowed. public sealed override Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) { // This API existed in v1/v1.1 and only expected to create open // instance delegates, so we forbid closed delegates for backward compatibility. // But we'll allow relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). return CreateDelegateWorker(type, null, method, throwOnBindFailure, allowClosed: false); } private static Delegate CreateDelegateWorker(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure, bool allowClosed) { if (type == null) throw new ArgumentNullException(nameof(type)); if (method == null) throw new ArgumentNullException(nameof(method)); if (!(type is RuntimeTypeInfo runtimeDelegateType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); if (!(method is RuntimeMethodInfo runtimeMethodInfo)) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method)); if (!runtimeDelegateType.IsDelegate) throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type)); Delegate result = runtimeMethodInfo.CreateDelegateNoThrowOnBindFailure(runtimeDelegateType, firstArgument, allowClosed); if (result == null) { if (throwOnBindFailure) throw new ArgumentException(SR.Arg_DlgtTargMeth); return null; } return result; } // V1 api: Creates closed delegates to instance methods only, relaxed signature checking disallowed. public sealed override Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) throw new ArgumentNullException(nameof(type)); if (target == null) throw new ArgumentNullException(nameof(target)); if (method == null) throw new ArgumentNullException(nameof(method)); if (!(type is RuntimeTypeInfo runtimeDelegateType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); if (!runtimeDelegateType.IsDelegate) throw new ArgumentException(SR.Arg_MustBeDelegate); RuntimeTypeInfo runtimeContainingType = target.GetType().CastToRuntimeTypeInfo(); RuntimeMethodInfo runtimeMethodInfo = LookupMethodForCreateDelegate(runtimeDelegateType, runtimeContainingType, method, isStatic: false, ignoreCase: ignoreCase); if (runtimeMethodInfo == null) { if (throwOnBindFailure) throw new ArgumentException(SR.Arg_DlgtTargMeth); return null; } return runtimeMethodInfo.CreateDelegateWithoutSignatureValidation(type, target, isStatic: false, isOpen: false); } // V1 api: Creates open delegates to static methods only, relaxed signature checking disallowed. public sealed override Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) throw new ArgumentNullException(nameof(type)); if (target == null) throw new ArgumentNullException(nameof(target)); if (target.ContainsGenericParameters) throw new ArgumentException(SR.Arg_UnboundGenParam); if (method == null) throw new ArgumentNullException(nameof(method)); if (!(type is RuntimeTypeInfo runtimeDelegateType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); if (!(target is RuntimeTypeInfo runtimeContainingType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target)); if (!runtimeDelegateType.IsDelegate) throw new ArgumentException(SR.Arg_MustBeDelegate); RuntimeMethodInfo runtimeMethodInfo = LookupMethodForCreateDelegate(runtimeDelegateType, runtimeContainingType, method, isStatic: true, ignoreCase: ignoreCase); if (runtimeMethodInfo == null) { if (throwOnBindFailure) throw new ArgumentException(SR.Arg_DlgtTargMeth); return null; } return runtimeMethodInfo.CreateDelegateWithoutSignatureValidation(type, target: null, isStatic: true, isOpen: true); } // // Helper for the V1/V1.1 Delegate.CreateDelegate() api. These apis take method names rather than MethodInfo and only expect to create open static delegates // or closed instance delegates. For backward compatibility, they don't allow relaxed signature matching (which could make the choice of target method ambiguous.) // private static RuntimeMethodInfo LookupMethodForCreateDelegate(RuntimeTypeInfo runtimeDelegateType, RuntimeTypeInfo containingType, string method, bool isStatic, bool ignoreCase) { Debug.Assert(runtimeDelegateType.IsDelegate); BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.ExactBinding; if (isStatic) { bindingFlags |= BindingFlags.Static; } else { bindingFlags |= BindingFlags.Instance | BindingFlags.DeclaredOnly; } if (ignoreCase) { bindingFlags |= BindingFlags.IgnoreCase; } RuntimeMethodInfo invokeMethod = runtimeDelegateType.GetInvokeMethod(); ParameterInfo[] parameters = invokeMethod.GetParametersNoCopy(); int numParameters = parameters.Length; Type[] parameterTypes = new Type[numParameters]; for (int i = 0; i < numParameters; i++) { parameterTypes[i] = parameters[i].ParameterType; } while (containingType != null) { MethodInfo methodInfo = containingType.GetMethod(method, 0, bindingFlags, null, parameterTypes, null); if (methodInfo != null && methodInfo.ReturnType.Equals(invokeMethod.ReturnType)) return (RuntimeMethodInfo)methodInfo; // This cast is safe since we already verified that containingType is runtime implemented. containingType = (RuntimeTypeInfo)(containingType.BaseType); } return null; } public sealed override Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError) { // Note: "throwOnError" is a vacuous parameter. Any errors due to the CLSID not being registered or the server not being found will happen // on the Activator.CreateInstance() call. GetTypeFromCLSID() merely wraps the data in a Type object without any validation. return RuntimeCLSIDTypeInfo.GetRuntimeCLSIDTypeInfo(clsid, server); } public sealed override IntPtr GetFunctionPointer(RuntimeMethodHandle runtimeMethodHandle, RuntimeTypeHandle declaringTypeHandle) { MethodBase method = GetMethodFromHandle(runtimeMethodHandle, declaringTypeHandle); switch (method) { case RuntimeMethodInfo methodInfo: return methodInfo.LdFtnResult; case RuntimeConstructorInfo constructorInfo: return constructorInfo.LdFtnResult; default: Debug.Fail("RuntimeMethodHandle should only return a methodbase implemented by the runtime."); throw new NotSupportedException(); } } public sealed override void RunModuleConstructor(Module module) { RuntimeAssembly assembly = (RuntimeAssembly)module.Assembly; assembly.RunModuleConstructor(); } public sealed override void MakeTypedReference(object target, FieldInfo[] flds, out Type type, out int offset) { if (target == null) throw new ArgumentNullException(nameof(target)); if (flds == null) throw new ArgumentNullException(nameof(flds)); if (flds.Length == 0) throw new ArgumentException(SR.Arg_ArrayZeroError); offset = 0; Type targetType = target.GetType(); for (int i = 0; i < flds.Length; i++) { if (!(flds[i] is RuntimeFieldInfo field)) throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo); if (field.IsInitOnly || field.IsStatic) throw new ArgumentException(SR.Argument_TypedReferenceInvalidField); // For proper handling of Nullable<T> don't change to something like 'IsAssignableFrom' // Currently we can't make a TypedReference to fields of Nullable<T>, which is fine. Type declaringType = field.DeclaringType; if (targetType != declaringType && !targetType.IsSubclassOf(declaringType)) throw new MissingMemberException(SR.MissingMemberTypeRef); // MissingMemberException is a strange exception to throw, but it is the compatible exception. Type fieldType = field.FieldType; if (fieldType.IsPrimitive) throw new ArgumentException(SR.Arg_TypeRefPrimitve); // This check exists for compatibility (why such an ad-hoc restriction?) if (i < (flds.Length - 1) && !fieldType.IsValueType) throw new MissingMemberException(SR.MissingMemberNestErr); // MissingMemberException is a strange exception to throw, but it is the compatible exception. targetType = fieldType; offset = checked(offset + field.Offset); } type = targetType; } public sealed override Assembly[] GetLoadedAssemblies() => RuntimeAssembly.GetLoadedAssemblies(); public sealed override EnumInfo GetEnumInfo(Type type) => type.CastToRuntimeTypeInfo().EnumInfo; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Moq; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Brokerages; using QuantConnect.Brokerages.GDAX; using QuantConnect.Interfaces; using QuantConnect.Orders; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; namespace QuantConnect.Tests.Brokerages.GDAX { [TestFixture] public class GDAXBrokerageTests { #region Declarations GDAXBrokerage _unit; Mock<IWebSocket> _wss = new Mock<IWebSocket>(); Mock<IRestClient> _rest = new Mock<IRestClient>(); Mock<IAlgorithm> _algo = new Mock<IAlgorithm>(); string _orderData; string _orderByIdData; string _openOrderData; string _matchData; string _accountsData; string _holdingData; string _tickerData; Symbol _symbol; const string _brokerId = "d0c5340b-6d6c-49d9-b567-48c4bfca13d2"; const string _matchBrokerId = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; AccountType _accountType = AccountType.Margin; #endregion [SetUp] public void Setup() { _unit = new GDAXBrokerage("wss://localhost", _wss.Object, _rest.Object, "abc", "MTIz", "pass", _algo.Object); _orderData = File.ReadAllText("TestData//gdax_order.txt"); _matchData = File.ReadAllText("TestData//gdax_match.txt"); _openOrderData = File.ReadAllText("TestData//gdax_openOrders.txt"); _accountsData = File.ReadAllText("TestData//gdax_accounts.txt"); _holdingData = File.ReadAllText("TestData//gdax_holding.txt"); _orderByIdData = File.ReadAllText("TestData//gdax_orderById.txt"); _tickerData = File.ReadAllText("TestData//gdax_ticker.txt"); _symbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/products/")))).Returns(new RestSharp.RestResponse { Content = File.ReadAllText("TestData//gdax_tick.txt"), StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/orders/" + _brokerId) || r.Resource.StartsWith("/orders/" + _matchBrokerId)))) .Returns(new RestSharp.RestResponse { Content = File.ReadAllText("TestData//gdax_orderById.txt"), StatusCode = HttpStatusCode.OK }); _algo.Setup(a => a.BrokerageModel.AccountType).Returns(_accountType); var rateMock = new Mock<IRestClient>(); _unit.RateClient = rateMock.Object; rateMock.Setup(r => r.Execute(It.IsAny<IRestRequest>())).Returns(new RestResponse { Content = @"{""base"":""USD"",""date"":""2001-01-01"",""rates"":{""GBP"":1.234 }}", StatusCode = HttpStatusCode.OK }); } private void SetupResponse(string body, HttpStatusCode httpStatus = HttpStatusCode.OK) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.StartsWith("/products/") && !r.Resource.StartsWith("/orders/" + _brokerId)))) .Returns(new RestSharp.RestResponse { Content = body, StatusCode = httpStatus }); } [Test] public void IsConnectedTest() { _wss.Setup(w => w.IsOpen).Returns(true); Assert.IsTrue(_unit.IsConnected); _wss.Setup(w => w.IsOpen).Returns(false); Assert.IsFalse(_unit.IsConnected); } [Test] public void ConnectTest() { _wss.Setup(m => m.Connect()).Callback(() => { _wss.Setup(m => m.IsOpen).Returns(true); }).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(false); _unit.Connect(); _wss.Verify(); } [Test] public void DisconnectTest() { _wss.Setup(m => m.Close()).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(true); _unit.Disconnect(); _wss.Verify(); } [TestCase(5.23512)] [TestCase(99)] public void OnMessageFillTest(decimal expectedQuantity) { string json = _matchData; string id = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; //not our order if (expectedQuantity == 99) { json = json.Replace(id, Guid.NewGuid().ToString()); } decimal orderQuantity = 6.1m; GDAXTestsHelpers.AddOrder(_unit, 1, id, orderQuantity); ManualResetEvent raised = new ManualResetEvent(false); decimal actualFee = 0; decimal actualQuantity = 0; _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual("BTCUSD", e.Symbol.Value); actualFee += e.OrderFee; actualQuantity += e.AbsoluteFillQuantity; Assert.IsTrue(actualQuantity != orderQuantity); Assert.AreEqual(OrderStatus.Filled, e.Status); Assert.AreEqual(expectedQuantity, e.FillQuantity); // fill quantity = 5.23512 // fill price = 400.23 // partial order fee = (400.23 * 5.23512 * 0.003) = 6.2857562328 Assert.AreEqual(6.2857562328m, actualFee); raised.Set(); }; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); // not our order, market order is completed even if not totally filled json = json.Replace(id, Guid.NewGuid().ToString()); _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); //if not our order should get no event Assert.AreEqual(raised.WaitOne(1000), expectedQuantity != 99); } [Test] public void GetAuthenticationTokenTest() { var actual = _unit.GetAuthenticationToken("", "POST", "http://localhost"); Assert.IsFalse(string.IsNullOrEmpty(actual.Signature)); Assert.IsFalse(string.IsNullOrEmpty(actual.Timestamp)); Assert.AreEqual("pass", actual.Passphrase); Assert.AreEqual("abc", actual.Key); } [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 1234.56, OrderType.StopMarket)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 1234.56, OrderType.StopMarket)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.Market)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.Limit)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.StopMarket)] public void PlaceOrderTest(string orderId, HttpStatusCode httpStatus, Orders.OrderStatus status, decimal quantity, decimal price, OrderType orderType) { var response = new { id = _brokerId, fill_fees = "0.11" }; SetupResponse(JsonConvert.SerializeObject(response), httpStatus); _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual(status, e.Status); if (orderId != null) { Assert.AreEqual("BTCUSD", e.Symbol.Value); Assert.That((quantity > 0 && e.Direction == Orders.OrderDirection.Buy) || (quantity < 0 && e.Direction == Orders.OrderDirection.Sell)); Assert.IsTrue(orderId == null || _unit.CachedOrderIDs.SelectMany(c => c.Value.BrokerId.Where(b => b == _brokerId)).Any()); } }; Order order = null; if (orderType == OrderType.Limit) { order = new Orders.LimitOrder(_symbol, quantity, price, DateTime.UtcNow); } else if (orderType == OrderType.Market) { order = new Orders.MarketOrder(_symbol, quantity, DateTime.UtcNow); } else { order = new Orders.StopMarketOrder(_symbol, quantity, price, DateTime.UtcNow); } bool actual = _unit.PlaceOrder(order); Assert.IsTrue(actual || (orderId == null && !actual)); } [Test] public void GetOpenOrdersTest() { SetupResponse(_openOrderData); _unit.CachedOrderIDs.TryAdd(1, new Orders.MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetOpenOrders(); Assert.AreEqual(2, actual.Count()); Assert.AreEqual(0.01, actual.First().Quantity); Assert.AreEqual(OrderDirection.Buy, actual.First().Direction); Assert.AreEqual(0.1, actual.First().Price); Assert.AreEqual(-1, actual.Last().Quantity); Assert.AreEqual(OrderDirection.Sell, actual.Last().Direction); Assert.AreEqual(1, actual.Last().Price); } [Test] public void GetTickTest() { var actual = _unit.GetTick(_symbol); Assert.AreEqual(333.98m, actual.BidPrice); Assert.AreEqual(333.99m, actual.AskPrice); Assert.AreEqual(5957.11914015, actual.Quantity); } [Test] public void GetCashBalanceTest() { SetupResponse(_accountsData); var actual = _unit.GetCashBalance(); Assert.AreEqual(2, actual.Count()); var usd = actual.Single(a => a.Symbol == "USD"); var btc = actual.Single(a => a.Symbol == "BTC"); Assert.AreEqual(80.2301373066930000m, usd.Amount); Assert.AreEqual(1, usd.ConversionRate); Assert.AreEqual(1.1, btc.Amount); Assert.AreEqual(333.985m, btc.ConversionRate); } [Test, Ignore("Holdings are now set to 0 swaps at the start of each launch. Not meaningful.")] public void GetAccountHoldingsTest() { SetupResponse(_holdingData); _unit.CachedOrderIDs.TryAdd(1, new Orders.MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetAccountHoldings(); Assert.AreEqual(0, actual.Count()); } [TestCase(HttpStatusCode.OK, HttpStatusCode.NotFound, false)] [TestCase(HttpStatusCode.OK, HttpStatusCode.OK, true)] public void CancelOrderTest(HttpStatusCode code, HttpStatusCode code2, bool expected) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("1")))).Returns(new RestSharp.RestResponse { StatusCode = code }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("2")))).Returns(new RestSharp.RestResponse { StatusCode = code2 }); var actual = _unit.CancelOrder(new Orders.LimitOrder { BrokerId = new List<string> { "1", "2" } }); Assert.AreEqual(expected, actual); } [Test] public void UpdateOrderTest() { Assert.Throws<NotSupportedException>(() => _unit.UpdateOrder(new LimitOrder())); } [Test] public void SubscribeTest() { string actual = null; string expected = "[\"BTC-USD\",\"BTC-ETH\"]"; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Ticks.Clear(); _unit.Subscribe(new[] { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX), Symbol.Create("GBPUSD", SecurityType.Crypto, Market.GDAX), Symbol.Create("BTCETH", SecurityType.Crypto, Market.GDAX)}); StringAssert.Contains(expected, actual); // spin for a few seconds, waiting for the GBPUSD tick var start = DateTime.UtcNow; var timeout = start.AddSeconds(5); while (_unit.Ticks.Count == 0 && DateTime.UtcNow < timeout) { Thread.Sleep(1); } // only rate conversion ticks are received during subscribe Assert.AreEqual(1, _unit.Ticks.Count); Assert.AreEqual("GBPUSD", _unit.Ticks[0].Symbol.Value); } [Test] public void UnsubscribeTest() { string actual = null; _wss.Setup(w => w.IsOpen).Returns(true); _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Unsubscribe(new List<Symbol> { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX) }); StringAssert.Contains("user", actual); StringAssert.Contains("heartbeat", actual); StringAssert.Contains("matches", actual); } [Test, Ignore("This test is obsolete, the 'ticker' channel is no longer used.")] public void OnMessageTickerTest() { string json = _tickerData; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); var actual = _unit.Ticks.First(); Assert.AreEqual("BTCUSD", actual.Symbol.Value); Assert.AreEqual(4388.005m, actual.Price); Assert.AreEqual(4388m, actual.BidPrice); Assert.AreEqual(4388.01m, actual.AskPrice); actual = _unit.Ticks.Last(); Assert.AreEqual("BTCUSD", actual.Symbol.Value); Assert.AreEqual(4388.01m, actual.Price); Assert.AreEqual(0.03m, actual.Quantity); } [Test] public void PollTickTest() { _unit.PollTick(Symbol.Create("GBPUSD", SecurityType.Crypto, Market.GDAX)); Thread.Sleep(1000); // conversion rates are inverted: value = 1 / 1.234 Assert.AreEqual(0.8103727714748784440842787682m, _unit.Ticks.First().Price); } [Test] public void ErrorTest() { string actual = null; // subscribe to invalid symbol const string expected = "[\"BTC-LTC\"]"; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Subscribe(new[] { Symbol.Create("BTCLTC", SecurityType.Crypto, Market.GDAX)}); StringAssert.Contains(expected, actual); BrokerageMessageType messageType = 0; _unit.Message += (sender, e) => { messageType = e.Type; }; const string json = "{\"type\":\"error\",\"message\":\"Failed to subscribe\",\"reason\":\"Invalid product ID provided\"}"; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); Assert.AreEqual(BrokerageMessageType.Warning, messageType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace IronPython.Runtime { public class ListGenericWrapper<T> : IList<T> { private IList<object> _value; public ListGenericWrapper(IList<object> value) { this._value = value; } #region IList<T> Members public int IndexOf(T item) { return _value.IndexOf(item); } public void Insert(int index, T item) { _value.Insert(index, item); } public void RemoveAt(int index) { _value.RemoveAt(index); } public T this[int index] { get { return (T)_value[index]; } set { this._value[index] = value; } } #endregion #region ICollection<T> Members public void Add(T item) { _value.Add(item); } public void Clear() { _value.Clear(); } public bool Contains(T item) { return _value.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { for (int i = 0; i < _value.Count; i++) { array[arrayIndex + i] = (T)_value[i]; } } public int Count { get { return _value.Count; } } public bool IsReadOnly { get { return _value.IsReadOnly; } } public bool Remove(T item) { return _value.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return new IEnumeratorOfTWrapper<T>(_value.GetEnumerator()); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return _value.GetEnumerator(); } #endregion } public class DictionaryGenericWrapper<K, V> : IDictionary<K, V> { private IDictionary<object, object> self; public DictionaryGenericWrapper(IDictionary<object, object> self) { this.self = self; } #region IDictionary<K,V> Members public void Add(K key, V value) { self.Add(key, value); } public bool ContainsKey(K key) { return self.ContainsKey(key); } public ICollection<K> Keys { get { List<K> res = new List<K>(); foreach (object o in self.Keys) { res.Add((K)o); } return res; } } public bool Remove(K key) { return self.Remove(key); } public bool TryGetValue(K key, out V value) { object outValue; if (self.TryGetValue(key, out outValue)) { value = (V)outValue; return true; } value = default(V); return false; } public ICollection<V> Values { get { List<V> res = new List<V>(); foreach (object o in self.Values) { res.Add((V)o); } return res; } } public V this[K key] { get { return (V)self[key]; } set { self[key] = value; } } #endregion #region ICollection<KeyValuePair<K,V>> Members public void Add(KeyValuePair<K, V> item) { self.Add(new KeyValuePair<object, object>(item.Key, item.Value)); } public void Clear() { self.Clear(); } public bool Contains(KeyValuePair<K, V> item) { return self.Contains(new KeyValuePair<object, object>(item.Key, item.Value)); } public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) { foreach (KeyValuePair<K, V> kvp in this) { array[arrayIndex++] = kvp; } } public int Count { get { return self.Count; } } public bool IsReadOnly { get { return self.IsReadOnly; } } public bool Remove(KeyValuePair<K, V> item) { return self.Remove(new KeyValuePair<object, object>(item.Key, item.Value)); } #endregion #region IEnumerable<KeyValuePair<K,V>> Members public IEnumerator<KeyValuePair<K, V>> GetEnumerator() { foreach (KeyValuePair<object, object> kv in self) { yield return new KeyValuePair<K, V>((K)kv.Key, (V)kv.Value); } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return self.GetEnumerator(); } #endregion } public class IEnumeratorOfTWrapper<T> : IEnumerator<T> { IEnumerator enumerable; public IEnumeratorOfTWrapper(IEnumerator enumerable) { this.enumerable = enumerable; } #region IEnumerator<T> Members public T Current { get { try { return (T)enumerable.Current; } catch (System.InvalidCastException iex) { throw new System.InvalidCastException(string.Format("Error in IEnumeratorOfTWrapper.Current. Could not cast: {0} in {1}", typeof(T).ToString(), enumerable.Current.GetType().ToString()), iex); } } } #endregion #region IDisposable Members public void Dispose() { } #endregion #region IEnumerator Members object IEnumerator.Current { get { return enumerable.Current; } } public bool MoveNext() { return enumerable.MoveNext(); } public void Reset() { enumerable.Reset(); } #endregion } [PythonType("enumerable_wrapper")] public class IEnumerableOfTWrapper<T> : IEnumerable<T>, IEnumerable { IEnumerable enumerable; public IEnumerableOfTWrapper(IEnumerable enumerable) { this.enumerable = enumerable; } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return new IEnumeratorOfTWrapper<T>(enumerable.GetEnumerator()); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
using System; using System.Text; /// <summary> /// GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32) /// </summary> public class EncodingGetBytes3 { #region Private Fileds private char[] testChar = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' }; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; return retVal; } #region Positive Test Cases public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32) with UTF8."); try { Encoding u8 = Encoding.UTF8; byte[] u8Bytes = u8.GetBytes(testChar, 4, 3); int u8ByteIndex = u8Bytes.GetLowerBound(0); if (u8.GetBytes(testChar, 4, 3, u8Bytes, u8ByteIndex) != 6) { TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32) with Unicode."); try { Encoding u16LE = Encoding.Unicode; byte[] u16LEBytes = u16LE.GetBytes(testChar, 4, 3); int u16LEByteIndex = u16LEBytes.GetLowerBound(0); if (u16LE.GetBytes(testChar, 4, 3, u16LEBytes, u16LEByteIndex) != 6) { TestLibrary.TestFramework.LogError("003.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32) with BigEndianUnicode."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] u16BEBytes = u16BE.GetBytes(testChar, 4, 3); int u16BEByteIndex = u16BEBytes.GetLowerBound(0); if (u16BE.GetBytes(testChar, 4, 3, u16BEBytes, u16BEByteIndex) != 6) { TestLibrary.TestFramework.LogError("004.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown."); try { char[] testNullChar = null; Encoding u7 = Encoding.UTF8; byte[] u7Bytes = u7.GetBytes(testChar, 4, 3); int u7ByteIndex = u7Bytes.GetLowerBound(0); int result = u7.GetBytes(testNullChar, 4, 3, u7Bytes, u7ByteIndex); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown."); try { Encoding u7 = Encoding.UTF8; byte[] u7Bytes = null; int u7ByteIndex = 1; int result = u7.GetBytes(testChar, 4, 3, u7Bytes, u7ByteIndex); TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown."); try { Encoding u7 = Encoding.UTF8; byte[] u7Bytes = u7.GetBytes(testChar, 4, 3); int u7ByteIndex = u7Bytes.GetLowerBound(0); int result = u7.GetBytes(testChar, -1, 3, u7Bytes, u7ByteIndex); TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown."); try { Encoding u7 = Encoding.UTF8; byte[] u7Bytes = u7.GetBytes(testChar, 4, 3); int u7ByteIndex = u7Bytes.GetLowerBound(0); int result = u7.GetBytes(testChar, 4, -1, u7Bytes, u7ByteIndex); TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException is not thrown."); try { Encoding u7 = Encoding.UTF8; byte[] u7Bytes = u7.GetBytes(testChar, 4, 3); int u7ByteIndex = u7Bytes.GetLowerBound(0); int result = u7.GetBytes(testChar, testChar.Length - 1, 3, u7Bytes, u7ByteIndex); TestLibrary.TestFramework.LogError("105.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("105.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException is not thrown."); try { Encoding u7 = Encoding.UTF8; byte[] u7Bytes = u7.GetBytes(testChar, 4, 3); int result = u7.GetBytes(testChar, 4, 3, u7Bytes, -1); TestLibrary.TestFramework.LogError("106.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentException is not thrown."); try { Encoding u7 = Encoding.UTF8; byte[] u7Bytes = u7.GetBytes(testChar, 4, 3); int u7ByteIndex = u7Bytes.GetLowerBound(0); int result = u7.GetBytes(testChar, 4, 3, u7Bytes, u7Bytes.Length - 1); TestLibrary.TestFramework.LogError("107.1", "ArgumentException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("107.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { EncodingGetBytes3 test = new EncodingGetBytes3(); TestLibrary.TestFramework.BeginTestCase("EncodingGetBytes3"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NPoco; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Runtime; using Umbraco.Cms.Infrastructure.Migrations.Install; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.Mappers; using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax; using Umbraco.Extensions; using MapperCollection = Umbraco.Cms.Infrastructure.Persistence.Mappers.MapperCollection; namespace Umbraco.Cms.Infrastructure.Runtime { public class SqlMainDomLock : IMainDomLock { private readonly string _lockId; private const string MainDomKeyPrefix = "Umbraco.Core.Runtime.SqlMainDom"; private const string UpdatedSuffix = "_updated"; private readonly ILogger<SqlMainDomLock> _logger; private readonly IOptions<GlobalSettings> _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IUmbracoDatabase _db; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private SqlServerSyntaxProvider _sqlServerSyntax; private bool _mainDomChanging = false; private readonly UmbracoDatabaseFactory _dbFactory; private bool _errorDuringAcquiring; private readonly object _locker = new object(); private bool _hasTable = false; private bool _acquireWhenTablesNotAvailable = false; public SqlMainDomLock( ILogger<SqlMainDomLock> logger, ILoggerFactory loggerFactory, IOptions<GlobalSettings> globalSettings, IOptionsMonitor<ConnectionStrings> connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator, IHostingEnvironment hostingEnvironment, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory, NPocoMapperCollection npocoMappers, string connectionStringName) { // unique id for our appdomain, this is more unique than the appdomain id which is just an INT counter to its safer _lockId = Guid.NewGuid().ToString(); _logger = logger; _globalSettings = globalSettings; _sqlServerSyntax = new SqlServerSyntaxProvider(_globalSettings); _hostingEnvironment = hostingEnvironment; _dbFactory = new UmbracoDatabaseFactory( loggerFactory.CreateLogger<UmbracoDatabaseFactory>(), loggerFactory, _globalSettings, new MapperCollection(() => Enumerable.Empty<BaseMapper>()), dbProviderFactoryCreator, databaseSchemaCreatorFactory, npocoMappers, connectionStringName); MainDomKey = MainDomKeyPrefix + "-" + (Environment.MachineName + MainDom.GetMainDomId(_hostingEnvironment)).GenerateHash<SHA1>(); } public SqlMainDomLock( ILogger<SqlMainDomLock> logger, ILoggerFactory loggerFactory, IOptions<GlobalSettings> globalSettings, IOptionsMonitor<ConnectionStrings> connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator, IHostingEnvironment hostingEnvironment, DatabaseSchemaCreatorFactory databaseSchemaCreatorFactory, NPocoMapperCollection npocoMappers) : this( logger, loggerFactory, globalSettings, connectionStrings, dbProviderFactoryCreator, hostingEnvironment, databaseSchemaCreatorFactory, npocoMappers, connectionStrings.CurrentValue.UmbracoConnectionString.ConnectionString ) { } public async Task<bool> AcquireLockAsync(int millisecondsTimeout) { if (!_dbFactory.Configured) { // if we aren't configured then we're in an install state, in which case we have no choice but to assume we can acquire return true; } if (!(_dbFactory.SqlContext.SqlSyntax is SqlServerSyntaxProvider sqlServerSyntaxProvider)) { throw new NotSupportedException("SqlMainDomLock is only supported for Sql Server"); } _sqlServerSyntax = sqlServerSyntaxProvider; _logger.LogDebug("Acquiring lock..."); var tempId = Guid.NewGuid().ToString(); IUmbracoDatabase db = null; try { db = _dbFactory.CreateDatabase(); _hasTable = db.HasTable(Cms.Core.Constants.DatabaseSchema.Tables.KeyValue); if (!_hasTable) { _logger.LogDebug("The DB does not contain the required table so we must be in an install state. We have no choice but to assume we can acquire."); _acquireWhenTablesNotAvailable = true; return true; } db.BeginTransaction(IsolationLevel.ReadCommitted); try { // wait to get a write lock _sqlServerSyntax.WriteLock(db, TimeSpan.FromMilliseconds(millisecondsTimeout), Cms.Core.Constants.Locks.MainDom); } catch(SqlException ex) { if (IsLockTimeoutException(ex)) { _logger.LogError(ex, "Sql timeout occurred, could not acquire MainDom."); _errorDuringAcquiring = true; return false; } // unexpected (will be caught below) throw; } var result = InsertLockRecord(tempId, db); //we change the row to a random Id to signal other MainDom to shutdown if (result == RecordPersistenceType.Insert) { // if we've inserted, then there was no MainDom so we can instantly acquire InsertLockRecord(_lockId, db); // so update with our appdomain id _logger.LogDebug("Acquired with ID {LockId}", _lockId); return true; } // if we've updated, this means there is an active MainDom, now we need to wait to // for the current MainDom to shutdown which also requires releasing our write lock } catch (Exception ex) { // unexpected _logger.LogError(ex, "Unexpected error, cannot acquire MainDom"); _errorDuringAcquiring = true; return false; } finally { db?.CompleteTransaction(); db?.Dispose(); } return await WaitForExistingAsync(tempId, millisecondsTimeout); } public Task ListenAsync() { if (_errorDuringAcquiring) { _logger.LogWarning("Could not acquire MainDom, listening is canceled."); return Task.CompletedTask; } // Create a long running task (dedicated thread) // to poll to check if we are still the MainDom registered in the DB return Task.Factory.StartNew( ListeningLoop, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, // Must explicitly specify this, see https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html TaskScheduler.Default); } /// <summary> /// Returns the keyvalue table key for the current server/app /// </summary> /// <remarks> /// The key is the the normal MainDomId which takes into account the AppDomainAppId and the physical file path of the app and this is /// combined with the current machine name. The machine name is required because the default semaphore lock is machine wide so it implicitly /// takes into account machine name whereas this needs to be explicitly per machine. /// </remarks> private string MainDomKey { get; } private void ListeningLoop() { while (true) { // poll every couple of seconds // local testing shows the actual query to be executed from client/server is approx 300ms but would change depending on environment/IO Thread.Sleep(2000); if (!_dbFactory.Configured) { // if we aren't configured, we just keep looping since we can't query the db continue; } lock (_locker) { // If cancellation has been requested we will just exit. Depending on timing of the shutdown, // we will have already flagged _mainDomChanging = true, or we're shutting down faster than // the other MainDom is taking to startup. In this case the db row will just be deleted and the // new MainDom will just take over. if (_cancellationTokenSource.IsCancellationRequested) { _logger.LogDebug("Task canceled, exiting loop"); return; } IUmbracoDatabase db = null; try { db = _dbFactory.CreateDatabase(); if (!_hasTable) { // re-check if its still false, we don't want to re-query once we know its there since this // loop needs to use minimal resources _hasTable = db.HasTable(Cms.Core.Constants.DatabaseSchema.Tables.KeyValue); if (!_hasTable) { // the Db does not contain the required table, we just keep looping since we can't query the db continue; } } // In case we acquired the main dom doing install when there was no database. We therefore have to insert our lockId now, but only handle this once. if (_acquireWhenTablesNotAvailable) { _acquireWhenTablesNotAvailable = false; InsertLockRecord(_lockId, db); } db.BeginTransaction(IsolationLevel.ReadCommitted); // get a read lock _sqlServerSyntax.ReadLock(db, Cms.Core.Constants.Locks.MainDom); if (!IsMainDomValue(_lockId, db)) { // we are no longer main dom, another one has come online, exit _mainDomChanging = true; _logger.LogDebug("Detected new booting application, releasing MainDom lock."); return; } } catch (Exception ex) { _logger.LogError(ex, "Unexpected error during listening."); // We need to keep on listening unless we've been notified by our own AppDomain to shutdown since // we don't want to shutdown resources controlled by MainDom inadvertently. We'll just keep listening otherwise. if (_cancellationTokenSource.IsCancellationRequested) { _logger.LogDebug("Task canceled, exiting loop"); return; } } finally { db?.CompleteTransaction(); db?.Dispose(); } } } } /// <summary> /// Wait for any existing MainDom to release so we can continue booting /// </summary> /// <param name="tempId"></param> /// <param name="millisecondsTimeout"></param> /// <returns></returns> private Task<bool> WaitForExistingAsync(string tempId, int millisecondsTimeout) { var updatedTempId = tempId + UpdatedSuffix; using (ExecutionContext.SuppressFlow()) { return Task.Run(() => { try { using var db = _dbFactory.CreateDatabase(); var watch = new Stopwatch(); watch.Start(); while (true) { // poll very often, we need to take over as fast as we can // local testing shows the actual query to be executed from client/server is approx 300ms but would change depending on environment/IO Thread.Sleep(1000); var acquired = TryAcquire(db, tempId, updatedTempId); if (acquired.HasValue) return acquired.Value; if (watch.ElapsedMilliseconds >= millisecondsTimeout) { return AcquireWhenMaxWaitTimeElapsed(db); } } } catch (Exception ex) { _logger.LogError(ex, "An error occurred trying to acquire and waiting for existing SqlMainDomLock to shutdown"); return false; } }, _cancellationTokenSource.Token); } } private bool? TryAcquire(IUmbracoDatabase db, string tempId, string updatedTempId) { // Creates a separate transaction to the DB instance so we aren't allocating tons of new DB instances for each transaction // since this is executed in a tight loop ITransaction transaction = null; try { transaction = db.GetTransaction(IsolationLevel.ReadCommitted); // get a read lock _sqlServerSyntax.ReadLock(db, Cms.Core.Constants.Locks.MainDom); // the row var mainDomRows = db.Fetch<KeyValueDto>("SELECT * FROM umbracoKeyValue WHERE [key] = @key", new { key = MainDomKey }); if (mainDomRows.Count == 0 || mainDomRows[0].Value == updatedTempId) { // the other main dom has updated our record // Or the other maindom shutdown super fast and just deleted the record // which indicates that we // can acquire it and it has shutdown. _sqlServerSyntax.WriteLock(db, Cms.Core.Constants.Locks.MainDom); // so now we update the row with our appdomain id InsertLockRecord(_lockId, db); _logger.LogDebug("Acquired with ID {LockId}", _lockId); return true; } else if (mainDomRows.Count == 1 && !mainDomRows[0].Value.StartsWith(tempId)) { // in this case, the prefixed ID is different which means // another new AppDomain has come online and is wanting to take over. In that case, we will not // acquire. _logger.LogDebug("Cannot acquire, another booting application detected."); return false; } } catch (Exception ex) { if (IsLockTimeoutException(ex as SqlException)) { _logger.LogError(ex, "Sql timeout occurred, waiting for existing MainDom is canceled."); _errorDuringAcquiring = true; return false; } // unexpected _logger.LogError(ex, "Unexpected error, waiting for existing MainDom is canceled."); _errorDuringAcquiring = true; return false; } finally { transaction?.Complete(); transaction?.Dispose(); } return null; // continue } private bool AcquireWhenMaxWaitTimeElapsed(IUmbracoDatabase db) { // Creates a separate transaction to the DB instance so we aren't allocating tons of new DB instances for each transaction // since this is executed in a tight loop // if the timeout has elapsed, it either means that the other main dom is taking too long to shutdown, // or it could mean that the previous appdomain was terminated and didn't clear out the main dom SQL row // and it's just been left as an orphan row. // There's really know way of knowing unless we are constantly updating the row for the current maindom // which isn't ideal. // So... we're going to 'just' take over, if the writelock works then we'll assume we're ok _logger.LogDebug("Timeout elapsed, assuming orphan row, acquiring MainDom."); ITransaction transaction = null; try { transaction = db.GetTransaction(IsolationLevel.ReadCommitted); _sqlServerSyntax.WriteLock(db, Cms.Core.Constants.Locks.MainDom); // so now we update the row with our appdomain id InsertLockRecord(_lockId, db); _logger.LogDebug("Acquired with ID {LockId}", _lockId); return true; } catch (Exception ex) { if (IsLockTimeoutException(ex as SqlException)) { // something is wrong, we cannot acquire, not much we can do _logger.LogError(ex, "Sql timeout occurred, could not forcibly acquire MainDom."); _errorDuringAcquiring = true; return false; } _logger.LogError(ex, "Unexpected error, could not forcibly acquire MainDom."); _errorDuringAcquiring = true; return false; } finally { transaction?.Complete(); transaction?.Dispose(); } } /// <summary> /// Inserts or updates the key/value row /// </summary> private RecordPersistenceType InsertLockRecord(string id, IUmbracoDatabase db) { return db.InsertOrUpdate(new KeyValueDto { Key = MainDomKey, Value = id, UpdateDate = DateTime.Now }); } /// <summary> /// Checks if the DB row value is equals the value /// </summary> /// <returns></returns> private bool IsMainDomValue(string val, IUmbracoDatabase db) { return db.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoKeyValue WHERE [key] = @key AND [value] = @val", new { key = MainDomKey, val = val }) == 1; } /// <summary> /// Checks if the exception is an SQL timeout /// </summary> /// <param name="exception"></param> /// <returns></returns> private bool IsLockTimeoutException(SqlException sqlException) => sqlException?.Number == 1222; #region IDisposable Support private bool _disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { lock (_locker) { _logger.LogDebug($"{nameof(SqlMainDomLock)} Disposing..."); // immediately cancel all sub-tasks, we don't want them to keep querying _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); if (_dbFactory.Configured && _hasTable) { IUmbracoDatabase db = null; try { db = _dbFactory.CreateDatabase(); db.BeginTransaction(IsolationLevel.ReadCommitted); // get a write lock _sqlServerSyntax.WriteLock(db, Cms.Core.Constants.Locks.MainDom); // When we are disposed, it means we have released the MainDom lock // and called all MainDom release callbacks, in this case // if another maindom is actually coming online we need // to signal to the MainDom coming online that we have shutdown. // To do that, we update the existing main dom DB record with a suffixed "_updated" string. // Otherwise, if we are just shutting down, we want to just delete the row. if (_mainDomChanging) { _logger.LogDebug("Releasing MainDom, updating row, new application is booting."); var count = db.Execute($"UPDATE umbracoKeyValue SET [value] = [value] + '{UpdatedSuffix}' WHERE [key] = @key", new { key = MainDomKey }); } else { _logger.LogDebug("Releasing MainDom, deleting row, application is shutting down."); var count = db.Execute("DELETE FROM umbracoKeyValue WHERE [key] = @key", new { key = MainDomKey }); } } catch (Exception ex) { _logger.LogError(ex, "Unexpected error during dipsose."); } finally { try { db?.CompleteTransaction(); db?.Dispose(); } catch (Exception ex) { _logger.LogError(ex, "Unexpected error during dispose when completing transaction."); } } } } } _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion } }
namespace OpenTK.Graphics { #pragma warning disable 1591 public enum GluVersion { Version11 = ((int)1), Version13 = ((int)1), Version12 = ((int)1), } public enum GluStringName { Version = ((int)100800), Extensions = ((int)100801), } public enum GluErrorCode { OutOfMemory = ((int)100902), InvalidEnum = ((int)100900), InvalidValue = ((int)100901), InvalidOperation = ((int)100904), } public enum Filter4TypeSGIS { MitchellNetravaliSgi = ((int)100301), LagrangianSgi = ((int)100300), } public enum NurbsDisplay { OutlinePolygon = ((int)100240), OutlinePatch = ((int)100241), Fill = ((int)QuadricDrawStyle.Fill), } public enum NurbsCallback { NurbsColorData = ((int)100173), NurbsVertexData = ((int)100171), NurbsNormal = ((int)100166), NurbsError = ((int)100103), NurbsTextureCoordExt = ((int)100168), Error = ((int)100103), NurbsEndDataExt = ((int)100175), NurbsEnd = ((int)100169), NurbsTextureCoord = ((int)100168), NurbsEndExt = ((int)100169), NurbsNormalDataExt = ((int)100172), NurbsColor = ((int)100167), NurbsColorExt = ((int)100167), NurbsVertexExt = ((int)100165), NurbsBeginExt = ((int)100164), NurbsTextureCoordData = ((int)100174), NurbsBeginData = ((int)100170), NurbsColorDataExt = ((int)100173), NurbsBeginDataExt = ((int)100170), NurbsVertex = ((int)100165), NurbsTextureCoordDataExt = ((int)100174), NurbsNormalExt = ((int)100166), NurbsVertexDataExt = ((int)100171), NurbsBegin = ((int)100164), NurbsEndData = ((int)100175), NurbsNormalData = ((int)100172), } public enum NurbsError { NurbsError37 = ((int)100287), NurbsError16 = ((int)100266), NurbsError26 = ((int)100276), NurbsError36 = ((int)100286), NurbsError19 = ((int)100269), NurbsError29 = ((int)100279), NurbsError8 = ((int)100258), NurbsError12 = ((int)100262), NurbsError9 = ((int)100259), NurbsError1 = ((int)100251), NurbsError18 = ((int)100268), NurbsError28 = ((int)100278), NurbsError4 = ((int)100254), NurbsError5 = ((int)100255), NurbsError6 = ((int)100256), NurbsError7 = ((int)100257), NurbsError3 = ((int)100253), NurbsError22 = ((int)100272), NurbsError32 = ((int)100282), NurbsError2 = ((int)100252), NurbsError11 = ((int)100261), NurbsError21 = ((int)100271), NurbsError31 = ((int)100281), NurbsError10 = ((int)100260), NurbsError20 = ((int)100270), NurbsError30 = ((int)100280), NurbsError15 = ((int)100265), NurbsError25 = ((int)100275), NurbsError35 = ((int)100285), NurbsError14 = ((int)100264), NurbsError24 = ((int)100274), NurbsError34 = ((int)100284), NurbsError13 = ((int)100263), NurbsError23 = ((int)100273), NurbsError33 = ((int)100283), NurbsError17 = ((int)100267), NurbsError27 = ((int)100277), } public enum NurbsProperty { DisplayMode = ((int)100204), ParametricTolerance = ((int)100202), NurbsRenderer = ((int)100162), NurbsTessellator = ((int)100161), NurbsTessellatorExt = ((int)100161), NurbsModeExt = ((int)100160), UStep = ((int)100206), SamplingMethod = ((int)100205), AutoLoadMatrix = ((int)100200), VStep = ((int)100207), Culling = ((int)100201), NurbsRendererExt = ((int)100162), NurbsMode = ((int)100160), SamplingTolerance = ((int)100203), } public enum NurbsSampling { ObjectParametricError = ((int)100208), ObjectPathLength = ((int)100209), PathLength = ((int)100215), DomainDistance = ((int)100217), ObjectPathLengthExt = ((int)100209), ObjectParametricErrorExt = ((int)100208), ParametricError = ((int)100216), } public enum NurbsTrim { Map1Trim3 = ((int)100211), Map1Trim2 = ((int)100210), } public enum QuadricDrawStyle { Line = ((int)100011), Silhouette = ((int)100013), Point = ((int)100010), Fill = ((int)100012), } public enum QuadricCallback { Error = ((int)NurbsCallback.Error), } public enum QuadricNormal { None = ((int)100002), Flat = ((int)100001), Smooth = ((int)100000), } public enum QuadricOrientation { Outside = ((int)100020), Inside = ((int)100021), } public enum TessCallback { TessEdgeFlagData = ((int)100110), Begin = ((int)100100), TessError = ((int)100103), EdgeFlag = ((int)100104), End = ((int)100102), TessCombine = ((int)100105), Error = ((int)100103), TessEndData = ((int)100108), TessBeginData = ((int)100106), TessErrorData = ((int)100109), Vertex = ((int)100101), TessVertexData = ((int)100107), TessVertex = ((int)100101), TessEdgeFlag = ((int)100104), TessEnd = ((int)100102), TessBegin = ((int)100100), TessCombineData = ((int)100111), } public enum TessContour { Exterior = ((int)100123), Ccw = ((int)100121), Interior = ((int)100122), Unknown = ((int)100124), Cw = ((int)100120), } public enum TessParameter { TessWindingRule = ((int)100140), TessBoundaryOnly = ((int)100141), TessTolerance = ((int)100142), } public enum TessError { TessMissingBeginPolygon = ((int)100151), TessMissingEndPolygon = ((int)100153), TessError1 = ((int)100151), TessMissingBeginContour = ((int)100152), TessCoordTooLarge = ((int)100155), TessError7 = ((int)100157), TessError2 = ((int)100152), TessError4 = ((int)100154), TessNeedCombineCallback = ((int)100156), TessError3 = ((int)100153), TessError6 = ((int)100156), TessError5 = ((int)100155), TessError8 = ((int)100158), TessMissingEndContour = ((int)100154), } public enum TessWinding { TessWindingNonzero = ((int)100131), TessWindingOdd = ((int)100130), TessWindingPositive = ((int)100132), TessWindingAbsGeqTwo = ((int)100134), TessWindingNegative = ((int)100133), } public enum AllGlu { None = ((int)100002), TessWindingRule = ((int)100140), TessWindingPositive = ((int)100132), ObjectPathLength = ((int)100209), NurbsTextureCoordExt = ((int)100168), Vertex = ((int)100101), TessCombine = ((int)100105), AutoLoadMatrix = ((int)100200), TessBoundaryOnly = ((int)100141), NurbsEndExt = ((int)100169), NurbsError17 = ((int)100267), NurbsError27 = ((int)100277), NurbsError37 = ((int)100287), Interior = ((int)100122), TessWindingOdd = ((int)100130), InvalidValue = ((int)100901), ParametricError = ((int)100216), TessError8 = ((int)100158), NurbsError14 = ((int)100264), NurbsError24 = ((int)100274), NurbsError34 = ((int)100284), NurbsTextureCoordDataExt = ((int)100174), TessMissingBeginContour = ((int)100152), Silhouette = ((int)100013), TessError7 = ((int)100157), NurbsNormalDataExt = ((int)100172), NurbsError21 = ((int)100271), NurbsError31 = ((int)100281), PathLength = ((int)100215), OutlinePolygon = ((int)100240), TessVertex = ((int)100101), TessWindingAbsGeqTwo = ((int)100134), Extensions = ((int)100801), TessEdgeFlagData = ((int)100110), EdgeFlag = ((int)100104), TessError1 = ((int)100151), Line = ((int)100011), NurbsBeginExt = ((int)100164), Point = ((int)100010), Begin = ((int)100100), Inside = ((int)100021), Flat = ((int)100001), TessBegin = ((int)100100), NurbsNormal = ((int)100166), NurbsColorData = ((int)100173), NurbsBeginDataExt = ((int)100170), NurbsRenderer = ((int)100162), NurbsBeginData = ((int)100170), Outside = ((int)100020), DisplayMode = ((int)100204), NurbsError15 = ((int)100265), NurbsError25 = ((int)100275), NurbsError35 = ((int)100285), NurbsVertexExt = ((int)100165), TessError5 = ((int)100155), Unknown = ((int)100124), NurbsEndDataExt = ((int)100175), NurbsError12 = ((int)100262), NurbsError22 = ((int)100272), NurbsError32 = ((int)100282), ObjectParametricErrorExt = ((int)100208), NurbsRendererExt = ((int)100162), TessError3 = ((int)100153), Fill = ((int)100012), TessError = ((int)100103), ObjectPathLengthExt = ((int)100209), TessWindingNegative = ((int)100133), NurbsTessellator = ((int)100161), NurbsColor = ((int)100167), NurbsModeExt = ((int)100160), SamplingTolerance = ((int)100203), NurbsColorDataExt = ((int)100173), Exterior = ((int)100123), Ccw = ((int)100121), Cw = ((int)100120), NurbsNormalExt = ((int)100166), NurbsError18 = ((int)100268), NurbsError28 = ((int)100278), LagrangianSgi = ((int)100300), TessEnd = ((int)100102), NurbsTessellatorExt = ((int)100161), NurbsEnd = ((int)100169), TessWindingNonzero = ((int)100131), OutOfMemory = ((int)100902), TessBeginData = ((int)100106), Error = ((int)100103), ObjectParametricError = ((int)100208), NurbsBegin = ((int)100164), TessCombineData = ((int)100111), TessMissingEndPolygon = ((int)100153), NurbsTextureCoord = ((int)100168), Smooth = ((int)100000), TessMissingBeginPolygon = ((int)100151), NurbsEndData = ((int)100175), NurbsVertexData = ((int)100171), TessEndData = ((int)100108), NurbsError11 = ((int)100261), NurbsVertex = ((int)100165), NurbsError30 = ((int)100280), Version11 = ((int)1), TessError6 = ((int)100156), Version13 = ((int)1), Version12 = ((int)1), TessErrorData = ((int)100109), NurbsError36 = ((int)100286), End = ((int)100102), SamplingMethod = ((int)100205), TessNeedCombineCallback = ((int)100156), UStep = ((int)100206), DomainDistance = ((int)100217), TessEdgeFlag = ((int)100104), NurbsColorExt = ((int)100167), NurbsError19 = ((int)100269), NurbsError29 = ((int)100279), InvalidOperation = ((int)100904), TessCoordTooLarge = ((int)100155), TessVertexData = ((int)100107), NurbsMode = ((int)100160), ParametricTolerance = ((int)100202), NurbsError2 = ((int)100252), VStep = ((int)100207), TessMissingEndContour = ((int)100154), Map1Trim2 = ((int)100210), Map1Trim3 = ((int)100211), Culling = ((int)100201), NurbsError16 = ((int)100266), NurbsError26 = ((int)100276), NurbsVertexDataExt = ((int)100171), NurbsNormalData = ((int)100172), TessError2 = ((int)100152), NurbsError13 = ((int)100263), NurbsError23 = ((int)100273), NurbsError33 = ((int)100283), NurbsError8 = ((int)100258), NurbsError9 = ((int)100259), TessError4 = ((int)100154), NurbsError10 = ((int)100260), NurbsError20 = ((int)100270), OutlinePatch = ((int)100241), NurbsError = ((int)100103), NurbsTextureCoordData = ((int)100174), NurbsError1 = ((int)100251), InvalidEnum = ((int)100900), NurbsError3 = ((int)100253), NurbsError4 = ((int)100254), NurbsError5 = ((int)100255), NurbsError6 = ((int)100256), NurbsError7 = ((int)100257), MitchellNetravaliSgi = ((int)100301), Version = ((int)100800), TessTolerance = ((int)100142), } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public enum _StartingState{ Default, Locked, Unlocked, } public enum _PerkTypeTB{ BonusHP, BonusAP, BonusHPRegen, BonusAPRegen, BonusMoveRange, BonusAttackRange, BonusDamage, BonusDamageMin, BonusDamageMax, BonusRangeDamage, BonusRangeDamageMin, BonusRangeDamageMax, BonusMeleeDamage, BonusMeleeDamageMin, BonusMeleeDamageMax, BonusCounterModifier, BonusHitRange, BonusHitMelee, BonusCritRange, BonusCritMelee, BonusMove, BonusAttack, BonusCounter, BonusDodge, BonusCritImmune, BonusDamageReduc, APAttackReduc, APMoveReduc, } [System.Serializable] public class EffectValue{ public float value=0; public float mod=0; } [System.Serializable] public class UnitStatModifier{ public UnitTB unit; public List<EffectValue> stats=new List<EffectValue>(); public UnitStatModifier(){ unit=null; int enumLength = Enum.GetValues(typeof(_PerkTypeTB)).Length; for(int i=0; i<enumLength; i++){ stats.Add(new EffectValue()); } } public UnitStatModifier(UnitTB unitTB){ unit=unitTB; int enumLength = Enum.GetValues(typeof(_PerkTypeTB)).Length; for(int i=0; i<enumLength; i++){ stats.Add(new EffectValue()); } } } [System.Serializable] public class PerkEffectTB{ //public public _PerkTypeTB type; public float value=1; public bool isModifier=false; public PerkEffectTB Clone(){ PerkEffectTB effect=new PerkEffectTB(); effect.type=type; effect.value=value; effect.isModifier=isModifier; return effect; } } [System.Serializable] public class PerkTB{ public int ID=-1; public string name=""; public string desp=""; public Texture icon; public Texture iconUnavailable; public Texture iconUnlocked; //[HideInInspector] public string iconName=""; public string iconUnavailableName=""; public string iconUnlockedName=""; public int cost=0; public int pointReq=0; public List<PerkEffectTB> effects=new List<PerkEffectTB>(); public List<int> prereq=new List<int>(); public List<int> reqby=new List<int>(); public bool applyToAllUnit=true; public List<UnitTB> unitPrefab=new List<UnitTB>(); public List<int> unitPrefabID=new List<int>(); public bool unlocked=false; public bool availableInScene=true; public _StartingState startingState=_StartingState.Default; public PerkTB Clone(){ PerkTB perk=new PerkTB(); perk.ID=ID; perk.name=name; perk.desp=desp; perk.icon=icon; perk.iconUnavailable=iconUnavailable; perk.iconUnlocked=iconUnlocked; //perk.type=type; perk.iconName=iconName; perk.iconUnavailableName=iconUnavailableName; perk.iconUnlockedName=iconUnlockedName; perk.cost=cost; //perk.effects=effects; for(int i=0; i<effects.Count; i++){ perk.effects.Add(effects[i].Clone()); } perk.prereq=prereq; perk.reqby=reqby; perk.applyToAllUnit=applyToAllUnit; perk.unitPrefab=unitPrefab; perk.unlocked=unlocked; perk.availableInScene=availableInScene; perk.startingState=startingState; return perk; } public int IsAvailable(){ if(!PerkManagerTB.UsePersistentData()){ if(PerkManagerTB.GetPoint()<cost){ return 1; //return "insufficient point to unlock perk"; //return false; } } else{ if(GlobalStatsTB.GetPlayerPoint()<cost){ return 1; //return "insufficient player point to unlock perk"; //return false; } } if(PerkManagerTB.GetPerkPoint()<pointReq){ return 2; //return "insufficient perk point to unlock perk"; //return false; } for(int i=0; i<prereq.Count; i++){ if(!PerkManagerTB.GetPerk(prereq[i]).unlocked){ return 3; //return "pre-req perk needed to unlock perk"; //return false; } } //return true; //return ""; return 0; } } public class PerkManagerTB : MonoBehaviour { public delegate void PerkUnlockHandler(PerkTB perk); public static event PerkUnlockHandler onPerkUnlockE; public List<PerkTB> localPerkList=new List<PerkTB>(); public static List<PerkTB> perkList=new List<PerkTB>(); public static UnitStatModifier globalUnitStats=new UnitStatModifier(); public static List<UnitStatModifier> unitStats=new List<UnitStatModifier>(); public static List<UnitTB> unitList=new List<UnitTB>(); //recording how many perk has been unlocked public static int perkPoint=0; public static int GetPerkPoint(){ return perkPoint; } //local point to unlock perk if persistant data is not used public int point=0; public static int GetPoint(){ if(instance==null) return 0; return instance.point; } public bool dontDestroyOnLoad=true; public bool usePersistentData=false; public static bool UsePersistentData(){ if(instance==null) return false; return instance.usePersistentData; } public static PerkManagerTB instance; void Awake(){ if(instance!=null) Destroy(gameObject); if(dontDestroyOnLoad){ GameObject.DontDestroyOnLoad(gameObject); } instance=this; LoadPerk(); LoadUnit(); //if(!GlobalStatsTB.loaded){ // perkPoint=startingPerkPoint; //} //ResetPerk(); } /* void OnGUI(){ int startX=10; int startY=10; GUI.Label(new Rect(startX, startY, 150, 25), "perk point: "+perkPoint); startY+=30; for(int i=0; i<perkList.Count; i++){ PerkTB perk=perkList[i]; if(perk.unlocked){ GUI.Label(new Rect(startX, startY, 100, 25), perk.name); } else{ if(perk.IsAvailable()){ if(GUI.Button(new Rect(startX, startY, 100, 25), perk.name)){ UnlockPerk(perk); } } else{ GUI.Box(new Rect(startX, startY, 100, 25), perk.name); } } startY+=30; } if(GUI.Button(new Rect(startX, startY+30, 100, 25), "reset all")){ ResetPerk(); } } */ public static void LoadPerk(){ GameObject obj=Resources.Load("PrefabList/PerkTBListPrefab", typeof(GameObject)) as GameObject; if(obj==null){ Debug.Log("load perk fail, make sure the resource file exists"); return; } PerkTBListPrefab prefab=obj.GetComponent<PerkTBListPrefab>(); perkList=prefab.perkTBList; if(!instance.usePersistentData){ for(int i=0; i<perkList.Count; i++){ perkList[i]=perkList[i].Clone(); } } //check local perk, synchronice the list, set the lock/unlock list for(int i=0; i<perkList.Count; i++){ PerkTB perk=perkList[i]; for(int j=0; j<instance.localPerkList.Count; j++){ PerkTB localPerk=instance.localPerkList[j]; if(perk.ID==localPerk.ID){ if(!localPerk.availableInScene){ perkList.RemoveAt(i); i-=1; } else{ if(localPerk.startingState==_StartingState.Locked){ perk.unlocked=false; } else if(localPerk.startingState==_StartingState.Unlocked){ perk.unlocked=true; } else if(localPerk.startingState==_StartingState.Default){ } } break; } } } //re-'unlocked' unlocked perk, to register the perk point and etc. for(int i=0; i<perkList.Count; i++){ if(perkList[i].unlocked) { UnlockPerk(perkList[i], false); } } } public static void LoadUnit(){ GameObject obj=Resources.Load("PrefabList/UnitListPrefab", typeof(GameObject)) as GameObject; if(obj==null){ Debug.Log("load unit fail, make sure the resource file exists"); return; } UnitListPrefab prefab=obj.GetComponent<UnitListPrefab>(); unitList=prefab.unitList; for(int i=0; i<unitList.Count; i++){ unitStats.Add(new UnitStatModifier(unitList[i])); } globalUnitStats=new UnitStatModifier(null); } public static void SavePerk(){ GameObject obj=Resources.Load("PrefabList/PerkTBListPrefab", typeof(GameObject)) as GameObject; if(obj==null){ Debug.Log("load perk fail, make sure the resource file exists"); return; } PerkTBListPrefab prefab=obj.GetComponent<PerkTBListPrefab>(); prefab.perkTBList=perkList; } public static void ResetPerk(){ for(int i=0; i<perkList.Count; i++){ perkList[i].unlocked=false; } } public static PerkTB GetPerk(int ID){ for (int i=0; i<perkList.Count; i++){ if(perkList[i].ID==ID){ return perkList[i].Clone(); } } return null; } public static List<PerkTB> GetAllPerks(){ return perkList; } public static bool UnlockPerk(int ID){ return UnlockPerk(perkList[ID], true); } public static bool UnlockPerk(int ID, bool flag){ return UnlockPerk(perkList[ID], flag); } public static bool UnlockPerk(PerkTB perk){ return UnlockPerk(perk, true); } public static bool UnlockPerk(PerkTB perk, bool flag){ if(perk.unlocked){ Debug.Log("attemp to unlock unlocked perk"); return false; } perk.unlocked=true; perkPoint+=1; if(flag){ if(!instance.usePersistentData) instance.point-=perk.cost; else GlobalStatsTB.GainPlayerPoint(-perk.cost); } if(perk.applyToAllUnit){ for(int i=0; i<perk.effects.Count; i++){ PerkEffectTB effect=perk.effects[i]; int effectID=(int)effect.type; if(effect.isModifier) globalUnitStats.stats[effectID].mod+=effect.value; else globalUnitStats.stats[effectID].value+=effect.value; } } else{ for(int i=0; i<unitStats.Count; i++){ if(perk.unitPrefab.Contains(unitStats[i].unit)){ perk.unitPrefabID.Add(unitStats[i].unit.prefabID); for(int j=0; j<perk.effects.Count; j++){ PerkEffectTB effect=perk.effects[j]; int effectID=(int)effect.type; if(effect.isModifier) unitStats[i].stats[effectID].mod+=effect.value; else unitStats[i].stats[effectID].value+=effect.value; } break; } } } if(onPerkUnlockE!=null) onPerkUnlockE(perk); return true; } public static UnitStatModifier GetSpecificUnitStat(int prefabID){ for(int i=0; i<unitStats.Count; i++){ if(unitStats[i].unit.prefabID==prefabID){ //Debug.Log(unitStats[i].unit.unitName+" "+prefabID); return unitStats[i]; } } Debug.Log("error, no unit prefab found"); return null; } //****************************************************************************************************************************** //get specific stats bonus public static int GetPerkHPBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusHP; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.HP*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.HP*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkAPBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusAP; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.AP*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.AP*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkHPRegenBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusHPRegen; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=(.5f*(uStats.unit.HPGainMin+uStats.unit.HPGainMax))*uStats.stats[statID].mod+uStats.stats[statID].value; total+=(.5f*(uStats.unit.HPGainMin+uStats.unit.HPGainMax))*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkAPRegenBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusAPRegen; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=(.5f*(uStats.unit.APGainMin+uStats.unit.APGainMax))*uStats.stats[statID].mod+uStats.stats[statID].value; total+=(.5f*(uStats.unit.APGainMin+uStats.unit.APGainMax))*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMoveRangeBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusMoveRange; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.movementRange*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.movementRange*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkAttackRangeBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusAttackRange; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.attackRangeMax*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.attackRangeMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkRangeDamageBonus(int prefabID, int dmg){ float total=0; int statID=(int)_PerkTypeTB.BonusDamage; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value; total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; statID=(int)_PerkTypeTB.BonusRangeDamage; uStats=GetSpecificUnitStat(prefabID); total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value; total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMeleeDamageBonus(int prefabID, int dmg){ float total=0; int statID=(int)_PerkTypeTB.BonusDamage; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value; total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; statID=(int)_PerkTypeTB.BonusMeleeDamage; uStats=GetSpecificUnitStat(prefabID); total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value; total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMinRangeDamageBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusDamageMin; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.rangeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.rangeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; statID=(int)_PerkTypeTB.BonusRangeDamageMin; uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.rangeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.rangeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMaxRangeDamageBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusDamageMax; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.rangeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.rangeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; statID=(int)_PerkTypeTB.BonusRangeDamageMax; uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.rangeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.rangeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMinMeleeDamageBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusDamageMin; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.meleeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.meleeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; statID=(int)_PerkTypeTB.BonusMeleeDamageMin; uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.meleeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.meleeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMaxMeleeDamageBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusDamageMax; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.meleeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.meleeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; statID=(int)_PerkTypeTB.BonusMeleeDamageMax; uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.meleeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.meleeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static float GetPerkCounterModifierBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusCounterModifier; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.counterDmgModifier*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.counterDmgModifier*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static float GetPerkRangeAttackBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusHitRange; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.attRange*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.attRange*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static float GetPerkMeleeAttackBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusHitMelee; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.attMelee*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.attMelee*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static float GetPerkRangeCriticalBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusCritRange; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.criticalRange*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.criticalRange*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static float GetPerkMeleeCriticalBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusCritMelee; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.criticalMelee*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.criticalMelee*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static int GetPerkMoveCountBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusMove; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.movePerTurn*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.movePerTurn*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkAttackCountBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusAttack; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.attackPerTurn*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.attackPerTurn*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkCounterCountBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusCounter; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.counterPerTurn*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.counterPerTurn*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static float GetPerkDefendBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusDodge; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.defend*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.defend*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static float GetPerkCritImmuneBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusCritImmune; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.critDef*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.critDef*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static float GetPerkDamageReductionBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.BonusDamageReduc; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total+=uStats.unit.damageReduc*uStats.stats[statID].mod+uStats.stats[statID].value; total+=uStats.unit.damageReduc*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return total; } public static int GetPerkAttackAPReductionBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.APAttackReduc; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total-=uStats.unit.APCostAttack*uStats.stats[statID].mod+uStats.stats[statID].value; total-=uStats.unit.APCostAttack*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } public static int GetPerkMoveAPReductionBonus(int prefabID){ float total=0; int statID=(int)_PerkTypeTB.APMoveReduc; UnitStatModifier uStats=GetSpecificUnitStat(prefabID); total-=uStats.unit.APCostMove*uStats.stats[statID].mod+uStats.stats[statID].value; total-=uStats.unit.APCostMove*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value; return (int)total; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { using System; using System.Globalization; using System.Text; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout public struct Guid : IFormattable, IComparable , IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid(byte[] b) { if (b==null) throw new ArgumentNullException("b"); if (b.Length != 16) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), "b"); Contract.EndContractBlock(); _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d==null) throw new ArgumentNullException("d"); // Check that array is not too big if(d.Length != 8) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), "d"); Contract.EndContractBlock(); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid parsedGuid; internal GuidParseThrowStyle throwStyle; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal object m_failureMessageFormatArgument; internal string m_failureArgumentName; internal Exception m_innerException; internal void Init(GuidParseThrowStyle canThrow) { parsedGuid = Guid.Empty; throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { m_failure = ParseFailureKind.NativeException; m_innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; m_failureArgumentName = failureArgumentName; m_innerException = innerException; if (throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.NativeException: return m_innerException; default: Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized")); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(String g) { if (g==null) { throw new ArgumentNullException("g"); } Contract.EndContractBlock(); this = Guid.Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(String input) { if (input == null) { throw new ArgumentNullException("input"); } Contract.EndContractBlock(); GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(String input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } public static Guid ParseExact(String input, String format) { if (input == null) throw new ArgumentNullException("input"); if (format == null) throw new ArgumentNullException("format"); if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(String input, String format, out Guid result) { if (format == null || format.Length != 1) { result = Guid.Empty; return false; } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { // invalid guid format specification result = Guid.Empty; return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result) { if (g == null) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } String guidString = g.Trim(); //Remove Whitespace if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } // Check for dashes bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0); if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch(IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Check for '0x' if(!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; // Check for '{' if(guidString.Length <= numStart+numLen+1 || guidString[numStart+numLen+1] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Prepare for loop numLen++; byte[] bytes = new byte[8]; for(int i = 0; i < 8; i++) { // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if(i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber"); return false; } } // Read in the number int signedNumber; if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) { return false; } uint number = (uint)signedNumber; // check for overflow if(number > 255) { result.SetFailure(ParseFailureKind.Format, "Overflow_Byte"); return false; } bytes[i] = (byte)number; } result.parsedGuid._d = bytes[0]; result.parsedGuid._e = bytes[1]; result.parsedGuid._f = bytes[2]; result.parsedGuid._g = bytes[3]; result.parsedGuid._h = bytes[4]; result.parsedGuid._i = bytes[5]; result.parsedGuid._j = bytes[6]; result.parsedGuid._k = bytes[7]; // Check for last '}' if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace"); return false; } // Check if we have extra characters at the end if( numStart+numLen+1 != guidString.Length -1) { result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd"); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; if(guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } for(int i= 0; i< guidString.Length; i++) { char ch = guidString[i]; if(ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture); if(upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos!=12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0]=='{') { if (guidString.Length!=38 || guidString[37]!='}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if (guidString[0]=='(') { if (guidString.Length!=38 || guidString[37]!=')') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if(guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } if (guidString[8+startPos] != '-' || guidString[13+startPos] != '-' || guidString[18+startPos] != '-' || guidString[23+startPos] != '-') { result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes"); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos=currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines; [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { return StringToShort(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { return StringToInt(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = (parsePos == null) ? 0 : (*parsePos); try { result = ParseNumbers.StringToInt(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } return true; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) { return StringToLong(str, null, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToLong(str, ppos, flags, out result, ref parseResult); } } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static String EatAllWhitespace(String str) { int newLength = 0; char[] chArr = new char[str.Length]; char curChar; // Now get each char from str and if it is not whitespace add it to chArr for(int i = 0; i < str.Length; i++) { curChar = str[i]; if(!Char.IsWhiteSpace(curChar)) { chArr[newLength++] = curChar; } } // Return a new string based on chArr return new String(chArr, 0, newLength); } private static bool IsHexPrefix(String str, int i) { if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x')) return true; else return false; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } // Returns the guid in "registry" format. public override String ToString() { return ToString("D",null); } public override int GetHashCode() { return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(Object o) { Guid g; // Check that o is a Guid first if(o == null || !(o is Guid)) return false; else g = (Guid) o; // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } public bool Equals(Guid g) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } private int GetResult(uint me, uint them) { if (me<them) { return -1; } return 1; } public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"), "value"); } Guid g = (Guid)value; if (g._a!=this._a) { return GetResult((uint)this._a, (uint)g._a); } if (g._b!=this._b) { return GetResult((uint)this._b, (uint)g._b); } if (g._c!=this._c) { return GetResult((uint)this._c, (uint)g._c); } if (g._d!=this._d) { return GetResult((uint)this._d, (uint)g._d); } if (g._e!=this._e) { return GetResult((uint)this._e, (uint)g._e); } if (g._f!=this._f) { return GetResult((uint)this._f, (uint)g._f); } if (g._g!=this._g) { return GetResult((uint)this._g, (uint)g._g); } if (g._h!=this._h) { return GetResult((uint)this._h, (uint)g._h); } if (g._i!=this._i) { return GetResult((uint)this._i, (uint)g._i); } if (g._j!=this._j) { return GetResult((uint)this._j, (uint)g._j); } if (g._k!=this._k) { return GetResult((uint)this._k, (uint)g._k); } return 0; } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=(Guid a, Guid b) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. [System.Security.SecuritySafeCritical] // auto-generated public static Guid NewGuid() { // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some // uniqueness guarantees. It should also never return a known GUID, but it's unclear // how extensively it checks for known values. Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid guid; Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1)); return guid; } public String ToString(String format) { return ToString(format, null); } private static char HexToChar(int a) { a = a & 0xf; return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b) { return HexsToChars(guidChars, offset, a, b, false); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(a>>4); guidChars[offset++] = HexToChar(a); if (hex) { guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(b>>4); guidChars[offset++] = HexToChar(b); return offset; } // IFormattable interface // We currently ignore provider [System.Security.SecuritySafeCritical] public String ToString(String format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; string guidString; int offset = 0; bool dash = true; bool hex = false; if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { guidString = string.FastAllocateString(36); } else if (formatCh == 'N' || formatCh == 'n') { guidString = string.FastAllocateString(32); dash = false; } else if (formatCh == 'B' || formatCh == 'b') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[37] = '}'; } } } else if (formatCh == 'P' || formatCh == 'p') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '('; guidChars[37] = ')'; } } } else if (formatCh == 'X' || formatCh == 'x') { guidString = string.FastAllocateString(68); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[67] = '}'; } } dash = false; hex = true; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } unsafe { fixed (char* guidChars = guidString) { if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); guidChars[offset++] = ','; guidChars[offset++] = '{'; offset = HexsToChars(guidChars, offset, _d, _e, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _f, _g, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _h, _i, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _j, _k, true); guidChars[offset++] = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _d, _e); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _f, _g); offset = HexsToChars(guidChars, offset, _h, _i); offset = HexsToChars(guidChars, offset, _j, _k); } } } return guidString; } } }
using System; using System.Collections; using System.Data; using System.Text; using System.Web; using System.Web.UI; using System.Xml; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Web.Routing; using umbraco.cms.businesslogic.property; using umbraco.cms.businesslogic.template; using umbraco.cms.businesslogic.web; using umbraco.interfaces; using Property = umbraco.cms.businesslogic.property.Property; namespace umbraco { /// <summary> /// Summary description for page. /// </summary> public class page { #region Private members and properties string _pageName; int _parentId; string _writerName; string _creatorName; string _path; int _nodeType; string _nodeTypeAlias; string[] _splitpath; DateTime _createDate; DateTime _updateDate; int _pageId; Guid _pageVersion; readonly int _template; readonly Hashtable _elements = new Hashtable(); readonly StringBuilder _pageContent = new StringBuilder(); Control _pageContentControl = new Control(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="page"/> class for a yet unpublished document, identified by its <c>id</c> and <c>version</c>. /// </summary> /// <param name="id">The identifier of the document.</param> /// <param name="version">The version to be displayed.</param> public page(int id, Guid version) : this(new Document(id, version)) { } /// <summary> /// Initializes a new instance of the <see cref="page"/> class for a yet unpublished document. /// </summary> /// <param name="document">The document.</param> public page(Document document) { var docParentId = -1; try { docParentId = document.Parent.Id; } catch (ArgumentException) { //ignore if no parent } populatePageData(document.Id, document.Text, document.ContentType.Id, document.ContentType.Alias, document.User.Name, document.Creator.Name, document.CreateDateTime, document.UpdateDate, document.Path, document.Version, docParentId); foreach (Property prop in document.GenericProperties) { string value = prop.Value != null ? prop.Value.ToString() : String.Empty; _elements.Add(prop.PropertyType.Alias, value); } _template = document.Template; } /// <summary> /// Initializes a new instance of the <see cref="page"/> class for a published document request. /// </summary> /// <param name="docreq">The <see cref="PublishedContentRequest"/> pointing to the document.</param> /// <remarks> /// The difference between creating the page with PublishedContentRequest vs an IPublishedContent item is /// that the PublishedContentRequest takes into account how a template is assigned during the routing process whereas /// with an IPublishedContent item, the template id is asssigned purely based on the default. /// </remarks> internal page(PublishedContentRequest docreq) { if (!docreq.HasPublishedContent) throw new ArgumentException("Document request has no node.", "docreq"); populatePageData(docreq.PublishedContent.Id, docreq.PublishedContent.Name, docreq.PublishedContent.DocumentTypeId, docreq.PublishedContent.DocumentTypeAlias, docreq.PublishedContent.WriterName, docreq.PublishedContent.CreatorName, docreq.PublishedContent.CreateDate, docreq.PublishedContent.UpdateDate, docreq.PublishedContent.Path, docreq.PublishedContent.Version, docreq.PublishedContent.Parent == null ? -1 : docreq.PublishedContent.Parent.Id); if (docreq.HasTemplate) { this._template = docreq.TemplateModel.Id; _elements["template"] = _template.ToString(); } PopulateElementData(docreq.PublishedContent); } /// <summary> /// Initializes a new instance of the page for a published document /// </summary> /// <param name="doc"></param> internal page(IPublishedContent doc) { if (doc == null) throw new ArgumentNullException("doc"); populatePageData(doc.Id, doc.Name, doc.DocumentTypeId, doc.DocumentTypeAlias, doc.WriterName, doc.CreatorName, doc.CreateDate, doc.UpdateDate, doc.Path, doc.Version, doc.Parent == null ? -1 : doc.Parent.Id); if (doc.TemplateId > 0) { //set the template to whatever is assigned to the doc _template = doc.TemplateId; _elements["template"] = _template.ToString(); } PopulateElementData(doc); } /// <summary> /// Initializes a new instance of the <see cref="page"/> class for a published document. /// </summary> /// <param name="node">The <c>XmlNode</c> representing the document.</param> public page(XmlNode node) { populatePageData(node); // Check for alternative template if (HttpContext.Current.Items[Constants.Conventions.Url.AltTemplate] != null && HttpContext.Current.Items[Constants.Conventions.Url.AltTemplate].ToString() != String.Empty) { _template = umbraco.cms.businesslogic.template.Template.GetTemplateIdFromAlias( HttpContext.Current.Items[Constants.Conventions.Url.AltTemplate].ToString()); _elements.Add("template", _template.ToString()); } else if (helper.Request(Constants.Conventions.Url.AltTemplate) != String.Empty) { _template = umbraco.cms.businesslogic.template.Template.GetTemplateIdFromAlias(helper.Request(Constants.Conventions.Url.AltTemplate).ToLower()); _elements.Add("template", _template.ToString()); } if (_template == 0) { try { _template = Convert.ToInt32(node.Attributes.GetNamedItem("template").Value); _elements.Add("template", node.Attributes.GetNamedItem("template").Value); } catch { HttpContext.Current.Trace.Warn("umbracoPage", "No template defined"); } } populateElementData(node); } #endregion #region Initialize void populatePageData(int pageID, string pageName, int nodeType, string nodeTypeAlias, string writerName, string creatorName, DateTime createDate, DateTime updateDate, string path, Guid pageVersion, int parentId) { this._pageId = pageID; this._pageName = pageName; this._nodeType = nodeType; this._nodeTypeAlias = nodeTypeAlias; this._writerName = writerName; this._creatorName = creatorName; this._createDate = createDate; this._updateDate = updateDate; this._parentId = parentId; this._path = path; this._splitpath = path.Split(','); this._pageVersion = pageVersion; // Update the elements hashtable _elements.Add("pageID", pageID); _elements.Add("parentID", parentId); _elements.Add("pageName", pageName); _elements.Add("nodeType", nodeType); _elements.Add("nodeTypeAlias", nodeTypeAlias); _elements.Add("writerName", writerName); _elements.Add("creatorName", creatorName); _elements.Add("createDate", createDate); _elements.Add("updateDate", updateDate); _elements.Add("path", path); _elements.Add("splitpath", _splitpath); _elements.Add("pageVersion", pageVersion); } void populatePageData(XmlNode node) { String s; DateTime dt; Guid guid; int i; if (int.TryParse(attrValue(node, "id"), out i)) _elements["pageID"] = this._pageId = i; if ((s = attrValue(node, "nodeName")) != null) _elements["pageName"] = this._pageName = s; if (int.TryParse(attrValue(node, "parentId"), out i)) _elements["parentId"] = this._parentId = i; if (int.TryParse(attrValue(node, "nodeType"), out i)) _elements["nodeType"] = this._nodeType = i; if ((s = attrValue(node, "nodeTypeAlias")) != null) _elements["nodeTypeAlias"] = this._nodeTypeAlias = s; if ((s = attrValue(node, "writerName")) != null) _elements["writerName"] = this._writerName = s; if ((s = attrValue(node, "creatorName")) != null) _elements["creatorName"] = this._creatorName = s; if (DateTime.TryParse(attrValue(node, "createDate"), out dt)) _elements["createDate"] = this._createDate = dt; if (DateTime.TryParse(attrValue(node, "updateDate"), out dt)) _elements["updateDate"] = this._updateDate = dt; if (Guid.TryParse(attrValue(node, "pageVersion"), out guid)) _elements["pageVersion"] = this._pageVersion = guid; if ((s = attrValue(node, "path")) != null) { _elements["path"] = this._path = s; _elements["splitpath"] = this._splitpath = _path.Split(','); } } string attrValue(XmlNode node, string attributeName) { var attr = node.Attributes.GetNamedItem(attributeName); var value = attr != null ? attr.Value : null; return value; } /// <summary> /// Puts the properties of the node into the elements table /// </summary> /// <param name="node"></param> void PopulateElementData(IPublishedContent node) { foreach(var p in node.Properties) { if (!_elements.ContainsKey(p.Alias)) { _elements[p.Alias] = p.Value; } } } void populateElementData(XmlNode node) { string xpath = "./* [not(@isDoc)]"; foreach (XmlNode data in node.SelectNodes(xpath)) { // ignore empty elements if (data.ChildNodes.Count == 0) continue; string alias = data.Name; string value = data.FirstChild.Value; // moved to PublishedContentRequest + UmbracoModule //if (alias == "umbracoRedirect") //{ // int i; // if (int.TryParse(value, out i)) // HttpContext.Current.Response.Redirect(library.NiceUrl(int.Parse(data.FirstChild.Value)), true); //} if (_elements.ContainsKey(alias)) { LogHelper.Debug<page>( string.Format("Aliases must be unique, an element with alias \"{0}\" has already been loaded!", alias), true); } else { _elements[alias] = value; LogHelper.Debug<page>( string.Format("Load element \"{0}\"", alias), true); } } } #endregion #region Wtf? public void RenderPage(int templateId) { if (templateId != 0) { template templateDesign = new template(templateId); _pageContentControl = templateDesign.ParseWithControls(this); _pageContent.Append(templateDesign.TemplateContent); } } #endregion #region Public properties public Control PageContentControl { get { return _pageContentControl; } } public string PageName { get { return _pageName; } } public int ParentId { get { return _parentId; } } public string NodeTypeAlias { get { return _nodeTypeAlias; } } public int NodeType { get { return _nodeType; } } public string WriterName { get { return _writerName; } } public string CreatorName { get { return _creatorName; } } public DateTime CreateDate { get { return _createDate; } } public DateTime UpdateDate { get { return _updateDate; } } public int PageID { get { return _pageId; } } public int Template { get { return _template; } } public Hashtable Elements { get { return _elements; } } public string PageContent { get { return _pageContent.ToString(); } } public string[] SplitPath { get { return this._splitpath; } } #endregion #region ToString public override string ToString() { return _pageName; } #endregion } }
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See license-pdn.txt for full licensing and attribution details. // // // // Ported to Pinta by: Jonathan Pobst <monkey@jpobst.com> // ///////////////////////////////////////////////////////////////////////////////// using Cairo; using Pinta.Core; namespace Pinta.Effects { public class GaussianBlurEffect { public static int[] CreateGaussianBlurRow (int amount) { int size = 1 + (amount * 2); int[] weights = new int[size]; for (int i = 0; i <= amount; ++i) { // 1 + aa - aa + 2ai - ii weights[i] = 16 * (i + 1); weights[weights.Length - i - 1] = weights[i]; } return weights; } unsafe public static void RenderBlurEffect (ImageSurface src, ImageSurface dest, Gdk.Rectangle[] rois, int radius) { int r = radius; int[] w = CreateGaussianBlurRow (r); int wlen = w.Length; int localStoreSize = wlen * 6 * sizeof (long); byte* localStore = stackalloc byte[localStoreSize]; byte* p = localStore; long* waSums = (long*)p; p += wlen * sizeof (long); long* wcSums = (long*)p; p += wlen * sizeof (long); long* aSums = (long*)p; p += wlen * sizeof (long); long* bSums = (long*)p; p += wlen * sizeof (long); long* gSums = (long*)p; p += wlen * sizeof (long); long* rSums = (long*)p; p += wlen * sizeof (long); // Cache these for a massive performance boost int src_width = src.Width; int src_height = src.Height; ColorBgra* src_data_ptr = (ColorBgra*)src.DataPtr; foreach (Gdk.Rectangle rect in rois) { if (rect.Height >= 1 && rect.Width >= 1) { for (int y = rect.Top; y < rect.Bottom; ++y) { //Memory.SetToZero (localStore, (ulong)localStoreSize); long waSum = 0; long wcSum = 0; long aSum = 0; long bSum = 0; long gSum = 0; long rSum = 0; ColorBgra* dstPtr = dest.GetPointAddressUnchecked (rect.Left, y); for (int wx = 0; wx < wlen; ++wx) { int srcX = rect.Left + wx - r; waSums[wx] = 0; wcSums[wx] = 0; aSums[wx] = 0; bSums[wx] = 0; gSums[wx] = 0; rSums[wx] = 0; if (srcX >= 0 && srcX < src_width) { for (int wy = 0; wy < wlen; ++wy) { int srcY = y + wy - r; if (srcY >= 0 && srcY < src_height) { ColorBgra c = src.GetPointUnchecked (src_data_ptr, src_width, srcX, srcY); int wp = w[wy]; waSums[wx] += wp; wp *= c.A + (c.A >> 7); wcSums[wx] += wp; wp >>= 8; aSums[wx] += wp * c.A; bSums[wx] += wp * c.B; gSums[wx] += wp * c.G; rSums[wx] += wp * c.R; } } int wwx = w[wx]; waSum += wwx * waSums[wx]; wcSum += wwx * wcSums[wx]; aSum += wwx * aSums[wx]; bSum += wwx * bSums[wx]; gSum += wwx * gSums[wx]; rSum += wwx * rSums[wx]; } } wcSum >>= 8; if (waSum == 0 || wcSum == 0) { dstPtr->Bgra = 0; } else { int alpha = (int)(aSum / waSum); int blue = (int)(bSum / wcSum); int green = (int)(gSum / wcSum); int red = (int)(rSum / wcSum); dstPtr->Bgra = ColorBgra.BgraToUInt32 (blue, green, red, alpha); } ++dstPtr; for (int x = rect.Left + 1; x < rect.Right; ++x) { for (int i = 0; i < wlen - 1; ++i) { waSums[i] = waSums[i + 1]; wcSums[i] = wcSums[i + 1]; aSums[i] = aSums[i + 1]; bSums[i] = bSums[i + 1]; gSums[i] = gSums[i + 1]; rSums[i] = rSums[i + 1]; } waSum = 0; wcSum = 0; aSum = 0; bSum = 0; gSum = 0; rSum = 0; int wx; for (wx = 0; wx < wlen - 1; ++wx) { long wwx = (long)w[wx]; waSum += wwx * waSums[wx]; wcSum += wwx * wcSums[wx]; aSum += wwx * aSums[wx]; bSum += wwx * bSums[wx]; gSum += wwx * gSums[wx]; rSum += wwx * rSums[wx]; } wx = wlen - 1; waSums[wx] = 0; wcSums[wx] = 0; aSums[wx] = 0; bSums[wx] = 0; gSums[wx] = 0; rSums[wx] = 0; int srcX = x + wx - r; if (srcX >= 0 && srcX < src_width) { for (int wy = 0; wy < wlen; ++wy) { int srcY = y + wy - r; if (srcY >= 0 && srcY < src_height) { ColorBgra c = src.GetPointUnchecked (src_data_ptr, src_width, srcX, srcY); int wp = w[wy]; waSums[wx] += wp; wp *= c.A + (c.A >> 7); wcSums[wx] += wp; wp >>= 8; aSums[wx] += wp * (long)c.A; bSums[wx] += wp * (long)c.B; gSums[wx] += wp * (long)c.G; rSums[wx] += wp * (long)c.R; } } int wr = w[wx]; waSum += (long)wr * waSums[wx]; wcSum += (long)wr * wcSums[wx]; aSum += (long)wr * aSums[wx]; bSum += (long)wr * bSums[wx]; gSum += (long)wr * gSums[wx]; rSum += (long)wr * rSums[wx]; } wcSum >>= 8; if (waSum == 0 || wcSum == 0) { dstPtr->Bgra = 0; } else { int alpha = (int)(aSum / waSum); int blue = (int)(bSum / wcSum); int green = (int)(gSum / wcSum); int red = (int)(rSum / wcSum); dstPtr->Bgra = ColorBgra.BgraToUInt32 (blue, green, red, alpha); } ++dstPtr; } } } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Web; using ServiceStack.Common.Utils; using ServiceStack.Common.Web; using ServiceStack.Logging; using ServiceStack.ServiceHost; namespace ServiceStack.WebHost.Endpoints.Extensions { /** * Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment Some HttpRequest path and URL properties: Request.ApplicationPath: /Cambia3 Request.CurrentExecutionFilePath: /Cambia3/Temp/Test.aspx Request.FilePath: /Cambia3/Temp/Test.aspx Request.Path: /Cambia3/Temp/Test.aspx/path/info Request.PathInfo: /path/info Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\Cambia3\ Request.QueryString: /Cambia3/Temp/Test.aspx/path/info?query=arg Request.Url.AbsolutePath: /Cambia3/Temp/Test.aspx/path/info Request.Url.AbsoluteUri: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg Request.Url.Fragment: Request.Url.Host: localhost Request.Url.LocalPath: /Cambia3/Temp/Test.aspx/path/info Request.Url.PathAndQuery: /Cambia3/Temp/Test.aspx/path/info?query=arg Request.Url.Port: 96 Request.Url.Query: ?query=arg Request.Url.Scheme: http Request.Url.Segments: / Cambia3/ Temp/ Test.aspx/ path/ info * */ public static class HttpRequestExtensions { private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions)); private static string WebHostDirectoryName = ""; static HttpRequestExtensions() { WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath()); } public static string GetOperationName(this HttpRequest request) { var pathInfo = request.GetLastPathInfo(); return GetOperationNameFromLastPathInfo(pathInfo); } public static string GetOperationNameFromLastPathInfo(string lastPathInfo) { if (string.IsNullOrEmpty(lastPathInfo)) return null; var operationName = lastPathInfo.Substring("/".Length); return operationName; } private static string GetLastPathInfoFromRawUrl(string rawUrl) { var pathInfo = rawUrl.IndexOf("?") != -1 ? rawUrl.Substring(0, rawUrl.IndexOf("?")) : rawUrl; pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/")); return pathInfo; } public static string GetLastPathInfo(this HttpRequest request) { var pathInfo = request.PathInfo; if (string.IsNullOrEmpty(pathInfo)) { pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl); } //Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}", // request.PathInfo, request.RawUrl, pathInfo); return pathInfo; } public static string GetUrlHostName(this HttpRequest request) { //TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host' try { return request.Url.Host; } catch (Exception ex) { Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex); return request.UserHostName; } } // http://localhost/ServiceStack.Examples.Host.Web/Public/Public/Soap12/Wsdl => // http://localhost/ServiceStack.Examples.Host.Web/Public/Soap12/ public static string GetParentBaseUrl(this HttpRequest request) { var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); // /Cambia3/Temp/Test.aspx/path return GetAuthority(request) + endpointsPath; } public static string GetBaseUrl(this HttpRequest request) { return GetAuthority(request) + request.RawUrl; } //=> http://localhost:96 ?? ex=> http://localhost private static string GetAuthority(HttpRequest request) { try { return request.Url.GetLeftPart(UriPartial.Authority); } catch (Exception ex) { Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex); return "http://" + request.UserHostName; } } public static string GetOperationName(this HttpListenerRequest request) { return request.Url.Segments[request.Url.Segments.Length - 1]; } public static string GetLastPathInfo(this HttpListenerRequest request) { return GetLastPathInfoFromRawUrl(request.RawUrl); } public static string GetPathInfo(this HttpRequest request) { return GetPathInfo(request.PathInfo, request.Path); } private static string GetPathInfo(string pathInfo, string fullPath) { if (!string.IsNullOrEmpty(pathInfo)) return pathInfo; var mappedPathRoot = EndpointHost.Config.ServiceStackHandlerFactoryPath; pathInfo = ResolvePathInfoFromMappedPath(fullPath, mappedPathRoot); if (!string.IsNullOrEmpty(pathInfo)) return pathInfo; pathInfo = ResolvePathInfoFromMappedPath(fullPath, WebHostDirectoryName); if (!string.IsNullOrEmpty(pathInfo)) return pathInfo; return fullPath; } private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot) { var sbPathInfo = new StringBuilder(); var fullPathParts = fullPath.Split('/'); var pathRootFound = false; foreach (var fullPathPart in fullPathParts) { if (pathRootFound) { sbPathInfo.Append("/" + fullPathPart); } else { pathRootFound = string.Equals(fullPathPart, mappedPathRoot, StringComparison.InvariantCultureIgnoreCase); } } return sbPathInfo.ToString(); } public static bool IsContentType(this IHttpRequest request, string contentType) { return request.ContentType.StartsWith(contentType, StringComparison.InvariantCultureIgnoreCase); } public static bool HasAnyOfContentTypes(this IHttpRequest request, params string[] contentTypes) { foreach (var contentType in contentTypes) { if (IsContentType(request, contentType)) return true; } return false; } public static IHttpRequest GetHttpRequest(this HttpRequest request) { return new HttpRequestWrapper(null, request); } public static IHttpRequest GetHttpRequest(this HttpListenerRequest request) { return new HttpListenerRequestWrapper(null, request); } public static Dictionary<string, string> GetRequestParams(this IHttpRequest request) { var map = new Dictionary<string, string>(); foreach (var name in request.QueryString.AllKeys) { map[name] = request.QueryString[name]; } if ((request.HttpMethod == HttpMethods.Post || request.HttpMethod == HttpMethods.Put) && request.FormData != null) { foreach (var name in request.FormData.AllKeys) { map[name] = request.FormData[name]; } } return map; } public static string GetQueryStringContentType(this IHttpRequest httpReq) { var callback = httpReq.QueryString["callback"]; if (!string.IsNullOrEmpty(callback)) return ContentType.Json; var format = httpReq.QueryString["format"]; if (format == null) return null; format = format.ToLower(); if (format.Contains("json")) return ContentType.Json; if (format.Contains("xml")) return ContentType.Xml; if (format.Contains("jsv")) return ContentType.Jsv; return null; } public static string[] PreferredContentTypes = new[] { ContentType.Json, ContentType.Xml, ContentType.Jsv }; public static string GetResponseContentType(this IHttpRequest httpReq) { var specifiedContentType = GetQueryStringContentType(httpReq); if (!string.IsNullOrEmpty(specifiedContentType)) return specifiedContentType; var acceptContentType = httpReq.AcceptTypes; var defaultContentType = httpReq.ContentType; if (httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData)) { defaultContentType = EndpointHost.Config.DefaultContentType; } var acceptsAnything = false; var hasDefaultContentType = !string.IsNullOrEmpty(defaultContentType); if (acceptContentType != null) { foreach (var contentType in acceptContentType) { acceptsAnything = acceptsAnything || contentType == "*/*"; if (acceptsAnything && hasDefaultContentType) return defaultContentType; foreach (var preferredContentType in PreferredContentTypes) { if (contentType.StartsWith(preferredContentType)) return preferredContentType; } } } //We could also send a '406 Not Acceptable', but this is allowed also return EndpointHost.Config.DefaultContentType; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityBase.EntityFramework.Entities; using IdentityBase.EntityFramework.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace IdentityBase.EntityFramework.Extensions { /// <summary> /// Extension methods to define the database schema for the configuration /// and operational data stores. /// </summary> public static class ModelBuilderExtensions { private static EntityTypeBuilder<TEntity> ToTable<TEntity>( this EntityTypeBuilder<TEntity> entityTypeBuilder, TableConfiguration configuration) where TEntity : class { return string.IsNullOrWhiteSpace(configuration.Schema) ? entityTypeBuilder.ToTable(configuration.Name) : entityTypeBuilder .ToTable(configuration.Name, configuration.Schema); } /// <summary> /// Configures the client context. /// </summary> /// <param name="modelBuilder">The model builder.</param> /// <param name="storeOptions">The store options.</param> public static void ConfigureClientContext( this ModelBuilder modelBuilder, EntityFrameworkOptions storeOptions) { if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema)) { modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema); } modelBuilder.Entity<Client>(client => { client.ToTable(storeOptions.Client); client.HasKey(x => x.Id); client.Property(x => x.ClientId) .HasMaxLength(200) .IsRequired(); client.Property(x => x.ProtocolType) .HasMaxLength(200) .IsRequired(); client.Property(x => x.ClientName) .HasMaxLength(200); client.Property(x => x.ClientUri) .HasMaxLength(2000); client.Property(x => x.LogoUri) .HasMaxLength(2000); client.Property(x => x.Description) .HasMaxLength(1000); client.Property(x => x.FrontChannelLogoutUri) .HasMaxLength(2000); client.Property(x => x.BackChannelLogoutUri) .HasMaxLength(2000); client.Property(x => x.ClientClaimsPrefix) .HasMaxLength(200); client.Property(x => x.PairWiseSubjectSalt) .HasMaxLength(200); client.HasIndex(x => x.ClientId).IsUnique(); client.HasMany(x => x.AllowedGrantTypes) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.RedirectUris) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.PostLogoutRedirectUris) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.AllowedScopes) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.ClientSecrets) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.Claims) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.IdentityProviderRestrictions) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.AllowedCorsOrigins) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); client.HasMany(x => x.Properties) .WithOne(x => x.Client) .IsRequired() .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity<ClientGrantType>(grantType => { grantType.ToTable(storeOptions.ClientGrantType); grantType.Property(x => x.GrantType) .HasMaxLength(250) .IsRequired(); }); modelBuilder.Entity<ClientRedirectUri>(redirectUri => { redirectUri.ToTable(storeOptions.ClientRedirectUri); redirectUri.Property(x => x.RedirectUri) .HasMaxLength(2000) .IsRequired(); }); modelBuilder .Entity<ClientPostLogoutRedirectUri>(postLogoutRedirectUri => { postLogoutRedirectUri .ToTable(storeOptions.ClientPostLogoutRedirectUri); postLogoutRedirectUri .Property(x => x.PostLogoutRedirectUri) .HasMaxLength(2000) .IsRequired(); }); modelBuilder.Entity<ClientScope>(scope => { scope.ToTable(storeOptions.ClientScopes); scope.Property(x => x.Scope) .HasMaxLength(200) .IsRequired(); }); modelBuilder.Entity<ClientSecret>(secret => { secret.ToTable(storeOptions.ClientSecret); secret.Property(x => x.Value) .HasMaxLength(2000).IsRequired(); secret.Property(x => x.Type) .HasMaxLength(250); secret.Property(x => x.Description) .HasMaxLength(2000); }); modelBuilder.Entity<ClientClaim>(claim => { claim.ToTable(storeOptions.ClientClaim); claim.Property(x => x.Type) .HasMaxLength(250).IsRequired(); claim.Property(x => x.Value) .HasMaxLength(250).IsRequired(); }); modelBuilder.Entity<ClientIdPRestriction>(idPRestriction => { idPRestriction.ToTable(storeOptions.ClientIdPRestriction); idPRestriction.Property(x => x.Provider) .HasMaxLength(200) .IsRequired(); }); modelBuilder.Entity<ClientCorsOrigin>(corsOrigin => { corsOrigin.ToTable(storeOptions.ClientCorsOrigin); corsOrigin.Property(x => x.Origin) .HasMaxLength(150) .IsRequired(); }); modelBuilder.Entity<ClientProperty>(property => { property.ToTable(storeOptions.ClientProperty); property.Property(x => x.Key) .HasMaxLength(250).IsRequired(); property.Property(x => x.Value) .HasMaxLength(2000).IsRequired(); }); } /// <summary> /// Configures the persisted grant context. /// </summary> /// <param name="modelBuilder">The model builder.</param> /// <param name="storeOptions">The store options.</param> public static void ConfigurePersistedGrantContext( this ModelBuilder modelBuilder, EntityFrameworkOptions storeOptions) { if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema)) { modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema); } modelBuilder.Entity<PersistedGrant>(grant => { grant.ToTable(storeOptions.PersistedGrants); grant.Property(x => x.Key) .HasMaxLength(200) .ValueGeneratedNever(); grant.Property(x => x.Type) .HasMaxLength(50) .IsRequired(); grant.Property(x => x.SubjectId) .HasMaxLength(200); grant.Property(x => x.ClientId) .HasMaxLength(200) .IsRequired(); grant.Property(x => x.CreationTime) .IsRequired(); // 50000 chosen to be explicit to allow enough size to avoid // truncation, yet stay beneath the MySql row size limit of // ~65K apparently anything over 4K converts to nvarchar(max) // on SqlServer grant.Property(x => x.Data) .HasMaxLength(50000) .IsRequired(); grant.HasKey(x => x.Key); grant.HasIndex(x => new { x.SubjectId, x.ClientId, x.Type }); }); } /// <summary> /// Configures the resources context. /// </summary> /// <param name="modelBuilder">The model builder.</param> /// <param name="storeOptions">The store options.</param> public static void ConfigureResourcesContext( this ModelBuilder modelBuilder, EntityFrameworkOptions storeOptions) { if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema)) { modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema); } modelBuilder.Entity<IdentityResource>(identityResource => { identityResource .ToTable(storeOptions.IdentityResource) .HasKey(x => x.Id); identityResource.Property(x => x.Name) .HasMaxLength(200) .IsRequired(); identityResource.Property(x => x.DisplayName) .HasMaxLength(200); identityResource.Property(x => x.Description) .HasMaxLength(1000); identityResource.HasIndex(x => x.Name) .IsUnique(); identityResource.HasMany(x => x.UserClaims) .WithOne(x => x.IdentityResource) .IsRequired() .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity<IdentityClaim>(claim => { claim .ToTable(storeOptions.IdentityClaim) .HasKey(x => x.Id); claim.Property(x => x.Type) .HasMaxLength(200) .IsRequired(); }); modelBuilder.Entity<ApiResource>(apiResource => { apiResource .ToTable(storeOptions.ApiResource) .HasKey(x => x.Id); apiResource.Property(x => x.Name) .HasMaxLength(200) .IsRequired(); apiResource.Property(x => x.DisplayName) .HasMaxLength(200); apiResource.Property(x => x.Description) .HasMaxLength(1000); apiResource.HasIndex(x => x.Name).IsUnique(); apiResource.HasMany(x => x.Secrets) .WithOne(x => x.ApiResource) .IsRequired() .OnDelete(DeleteBehavior.Cascade); apiResource.HasMany(x => x.Scopes) .WithOne(x => x.ApiResource) .IsRequired() .OnDelete(DeleteBehavior.Cascade); apiResource.HasMany(x => x.UserClaims) .WithOne(x => x.ApiResource) .IsRequired() .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity<ApiSecret>(apiSecret => { apiSecret .ToTable(storeOptions.ApiSecret) .HasKey(x => x.Id); apiSecret.Property(x => x.Description) .HasMaxLength(1000); apiSecret.Property(x => x.Value) .HasMaxLength(2000); apiSecret.Property(x => x.Type) .HasMaxLength(250); }); modelBuilder.Entity<ApiResourceClaim>(apiClaim => { apiClaim .ToTable(storeOptions.ApiClaim) .HasKey(x => x.Id); apiClaim.Property(x => x.Type) .HasMaxLength(200) .IsRequired(); }); modelBuilder.Entity<ApiScope>(apiScope => { apiScope .ToTable(storeOptions.ApiScope) .HasKey(x => x.Id); apiScope.Property(x => x.Name) .HasMaxLength(200) .IsRequired(); apiScope.Property(x => x.DisplayName) .HasMaxLength(200); apiScope.Property(x => x.Description) .HasMaxLength(1000); apiScope.HasIndex(x => x.Name) .IsUnique(); apiScope.HasMany(x => x.UserClaims) .WithOne(x => x.ApiScope) .IsRequired() .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity<ApiScopeClaim>(apiScopeClaim => { apiScopeClaim .ToTable(storeOptions.ApiScopeClaim) .HasKey(x => x.Id); apiScopeClaim.Property(x => x.Type) .HasMaxLength(200) .IsRequired(); }); } /// <summary> /// Configures the user account context. /// </summary> /// <param name="modelBuilder">The model builder.</param> /// <param name="storeOptions">The store options.</param> public static void ConfigureUserAccountContext( this ModelBuilder modelBuilder, EntityFrameworkOptions storeOptions) { if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema)) { modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema); } modelBuilder.Entity<UserAccount>(userAccount => { userAccount .ToTable(storeOptions.UserAccount); userAccount.HasKey(x => new { x.Id }); userAccount.Property(x => x.Email) .HasMaxLength(254) .IsRequired(); userAccount.Property(x => x.IsEmailVerified) .IsRequired(); userAccount.Property(x => x.EmailVerifiedAt); userAccount.Property(x => x.IsLoginAllowed) .IsRequired(); userAccount.Property(x => x.LastLoginAt); userAccount.Property(x => x.FailedLoginCount); userAccount.Property(x => x.PasswordHash) .HasMaxLength(200); userAccount.Property(x => x.PasswordChangedAt); userAccount.Property(x => x.VerificationKey) .HasMaxLength(100); userAccount.Property(x => x.VerificationPurpose); userAccount.Property(x => x.VerificationKeySentAt); userAccount.Property(x => x.VerificationStorage) .HasMaxLength(2000); userAccount.Property(x => x.CreatedAt); userAccount.Property(x => x.UpdatedAt); userAccount.Property(x => x.CreatedBy); userAccount.Property(x => x.CreationKind); userAccount.HasMany(x => x.Accounts) .WithOne(x => x.UserAccount) .HasForeignKey(x => x.UserAccountId) .IsRequired().OnDelete(DeleteBehavior.Cascade); userAccount.HasMany(x => x.Claims) .WithOne(x => x.UserAccount) .HasForeignKey(x => x.UserAccountId) .IsRequired().OnDelete(DeleteBehavior.Cascade); userAccount .HasIndex(x => x.Email) .IsUnique(); }); modelBuilder.Entity<ExternalAccount>(externalAccount => { externalAccount .ToTable(storeOptions.ExternalAccount); externalAccount.HasKey(x => new { x.UserAccountId, x.Provider, x.Subject }); externalAccount.Property(x => x.Provider) .IsRequired(); externalAccount.Property(x => x.Subject) .IsRequired(); externalAccount.Property(x => x.Email) .IsRequired().HasMaxLength(254); externalAccount.Property(x => x.IsLoginAllowed); externalAccount.Property(x => x.LastLoginAt); externalAccount.Property(x => x.CreatedAt) .IsRequired(); externalAccount.Property(x => x.UpdatedAt) .IsRequired(); externalAccount.Property(x => x.LastLoginAt); }); modelBuilder.Entity<UserAccountClaim>(claim => { claim .ToTable(storeOptions.UserAccountClaim); claim.HasKey(x => new { x.Id }); claim.Property(x => x.Type) .HasMaxLength(250).IsRequired(); claim.Property(x => x.Value) .HasMaxLength(250).IsRequired(); claim.Property(x => x.ValueType) .HasMaxLength(2000); }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using Azure.Core; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Producer; using Azure.Storage.Blobs; using Microsoft.Azure.WebJobs.EventHubs.Processor; using Microsoft.Azure.WebJobs.Extensions.Clients.Shared; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; namespace Microsoft.Azure.WebJobs.EventHubs { internal class EventHubClientFactory { private readonly IConfiguration _configuration; private readonly AzureComponentFactory _componentFactory; private readonly EventHubOptions _options; private readonly INameResolver _nameResolver; private readonly ConcurrentDictionary<string, EventHubProducerClient> _producerCache; private readonly ConcurrentDictionary<string, IEventHubConsumerClient> _consumerCache = new (); public EventHubClientFactory( IConfiguration configuration, AzureComponentFactory componentFactory, IOptions<EventHubOptions> options, INameResolver nameResolver) { _configuration = configuration; _componentFactory = componentFactory; _options = options.Value; _nameResolver = nameResolver; _producerCache = new ConcurrentDictionary<string, EventHubProducerClient>(_options.RegisteredProducers); } internal EventHubProducerClient GetEventHubProducerClient(string eventHubName, string connection) { eventHubName = _nameResolver.ResolveWholeString(eventHubName); return _producerCache.GetOrAdd(eventHubName, key => { if (!string.IsNullOrWhiteSpace(connection)) { var info = ResolveConnectionInformation(connection); if (info.FullyQualifiedEndpoint != null && info.TokenCredential != null) { return new EventHubProducerClient( info.FullyQualifiedEndpoint, eventHubName, info.TokenCredential, new EventHubProducerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } return new EventHubProducerClient( NormalizeConnectionString(info.ConnectionString, eventHubName), new EventHubProducerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } throw new InvalidOperationException("No event hub sender named " + eventHubName); }); } internal EventProcessorHost GetEventProcessorHost(string eventHubName, string connection, string consumerGroup) { eventHubName = _nameResolver.ResolveWholeString(eventHubName); consumerGroup ??= EventHubConsumerClient.DefaultConsumerGroupName; if (_options.RegisteredConsumerCredentials.TryGetValue(eventHubName, out var creds)) { return new EventProcessorHost(consumerGroup: consumerGroup, connectionString: creds.EventHubConnectionString, eventHubName: eventHubName, options: _options.EventProcessorOptions, eventBatchMaximumCount: _options.MaxBatchSize, invokeProcessorAfterReceiveTimeout: _options.InvokeFunctionAfterReceiveTimeout, exceptionHandler: _options.ExceptionHandler); } else if (!string.IsNullOrEmpty(connection)) { var info = ResolveConnectionInformation(connection); if (info.FullyQualifiedEndpoint != null && info.TokenCredential != null) { return new EventProcessorHost(consumerGroup: consumerGroup, fullyQualifiedNamespace: info.FullyQualifiedEndpoint, eventHubName: eventHubName, credential: info.TokenCredential, options: _options.EventProcessorOptions, eventBatchMaximumCount: _options.MaxBatchSize, invokeProcessorAfterReceiveTimeout: _options.InvokeFunctionAfterReceiveTimeout, exceptionHandler: _options.ExceptionHandler); } return new EventProcessorHost(consumerGroup: consumerGroup, connectionString: NormalizeConnectionString(info.ConnectionString, eventHubName), eventHubName: eventHubName, options: _options.EventProcessorOptions, eventBatchMaximumCount: _options.MaxBatchSize, invokeProcessorAfterReceiveTimeout: _options.InvokeFunctionAfterReceiveTimeout, exceptionHandler: _options.ExceptionHandler); } throw new InvalidOperationException("No event hub receiver named " + eventHubName); } internal IEventHubConsumerClient GetEventHubConsumerClient(string eventHubName, string connection, string consumerGroup) { eventHubName = _nameResolver.ResolveWholeString(eventHubName); consumerGroup ??= EventHubConsumerClient.DefaultConsumerGroupName; return _consumerCache.GetOrAdd(eventHubName, name => { EventHubConsumerClient client = null; if (_options.RegisteredConsumerCredentials.TryGetValue(eventHubName, out var creds)) { client = new EventHubConsumerClient(consumerGroup, creds.EventHubConnectionString, eventHubName); } else if (!string.IsNullOrEmpty(connection)) { var info = ResolveConnectionInformation(connection); if (info.FullyQualifiedEndpoint != null && info.TokenCredential != null) { client = new EventHubConsumerClient(consumerGroup, info.FullyQualifiedEndpoint, eventHubName, info.TokenCredential); } else { client = new EventHubConsumerClient(consumerGroup, NormalizeConnectionString(info.ConnectionString, eventHubName)); } } if (client != null) { return new EventHubConsumerClientImpl(client); } throw new InvalidOperationException("No event hub receiver named " + eventHubName); }); } internal BlobContainerClient GetCheckpointStoreClient(string eventHubName) { string storageConnectionString = null; if (_options.RegisteredConsumerCredentials.TryGetValue(eventHubName, out var creds)) { storageConnectionString = creds.StorageConnectionString; } // Fall back to default if not explicitly registered return new BlobContainerClient(storageConnectionString ?? _configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage), _options.CheckpointContainer); } internal static string NormalizeConnectionString(string originalConnectionString, string eventHubName) { var connectionString = ConnectionString.Parse(originalConnectionString); if (!connectionString.ContainsSegmentKey("EntityPath")) { connectionString.Add("EntityPath", eventHubName); } return connectionString.ToString(); } private EventHubsConnectionInformation ResolveConnectionInformation(string connection) { IConfigurationSection connectionSection = _configuration.GetWebJobsConnectionStringSection(connection); if (!connectionSection.Exists()) { // Not found throw new InvalidOperationException($"EventHub account connection string '{connection}' does not exist." + $"Make sure that it is a defined App Setting."); } if (!string.IsNullOrWhiteSpace(connectionSection.Value)) { return new EventHubsConnectionInformation(connectionSection.Value); } var fullyQualifiedNamespace = connectionSection["fullyQualifiedNamespace"]; if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace)) { // Not found throw new InvalidOperationException($"Connection should have an 'fullyQualifiedNamespace' property or be a string representing a connection string."); } var credential = _componentFactory.CreateTokenCredential(connectionSection); return new EventHubsConnectionInformation(fullyQualifiedNamespace, credential); } private record EventHubsConnectionInformation { public EventHubsConnectionInformation(string connectionString) { ConnectionString = connectionString; } public EventHubsConnectionInformation(string fullyQualifiedEndpoint, TokenCredential tokenCredential) { FullyQualifiedEndpoint = fullyQualifiedEndpoint; TokenCredential = tokenCredential; } public string ConnectionString { get; } public string FullyQualifiedEndpoint { get; } public TokenCredential TokenCredential { get; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ToolManifest; using Microsoft.DotNet.ToolPackage; using Microsoft.Extensions.EnvironmentAbstractions; using NuGet.Frameworks; using NuGet.Versioning; namespace Microsoft.DotNet.Tools.Tool.Restore { internal class ToolRestoreCommand : CommandBase { private readonly string _configFilePath; private readonly IReporter _errorReporter; private readonly ILocalToolsResolverCache _localToolsResolverCache; private readonly IToolManifestFinder _toolManifestFinder; private readonly AppliedOption _options; private readonly IFileSystem _fileSystem; private readonly IReporter _reporter; private readonly string[] _sources; private readonly IToolPackageInstaller _toolPackageInstaller; private readonly string _verbosity; public ToolRestoreCommand( AppliedOption appliedCommand, ParseResult result, IToolPackageInstaller toolPackageInstaller = null, IToolManifestFinder toolManifestFinder = null, ILocalToolsResolverCache localToolsResolverCache = null, IFileSystem fileSystem = null, IReporter reporter = null) : base(result) { _options = appliedCommand ?? throw new ArgumentNullException(nameof(appliedCommand)); if (toolPackageInstaller == null) { (IToolPackageStore, IToolPackageStoreQuery, IToolPackageInstaller installer) toolPackageStoresAndInstaller = ToolPackageFactory.CreateToolPackageStoresAndInstaller( additionalRestoreArguments: appliedCommand.OptionValuesToBeForwarded()); _toolPackageInstaller = toolPackageStoresAndInstaller.installer; } else { _toolPackageInstaller = toolPackageInstaller; } _toolManifestFinder = toolManifestFinder ?? new ToolManifestFinder(new DirectoryPath(Directory.GetCurrentDirectory())); _localToolsResolverCache = localToolsResolverCache ?? new LocalToolsResolverCache(); _fileSystem = fileSystem ?? new FileSystemWrapper(); _reporter = reporter ?? Reporter.Output; _errorReporter = reporter ?? Reporter.Error; _configFilePath = appliedCommand.ValueOrDefault<string>("configfile"); _sources = appliedCommand.ValueOrDefault<string[]>("add-source"); _verbosity = appliedCommand.SingleArgumentOrDefault("verbosity"); } public override int Execute() { FilePath? customManifestFileLocation = GetCustomManifestFileLocation(); FilePath? configFile = null; if (_configFilePath != null) { configFile = new FilePath(_configFilePath); } IReadOnlyCollection<ToolManifestPackage> packagesFromManifest; try { packagesFromManifest = _toolManifestFinder.Find(customManifestFileLocation); } catch (ToolManifestCannotBeFoundException e) { _reporter.WriteLine(e.Message.Yellow()); return 0; } ToolRestoreResult[] toolRestoreResults = packagesFromManifest .Select(package => InstallPackages(package, configFile)) .AsParallel().ToArray(); Dictionary<RestoredCommandIdentifier, RestoredCommand> downloaded = toolRestoreResults.SelectMany(result => result.SaveToCache) .ToDictionary(pair => pair.Item1, pair => pair.Item2); EnsureNoCommandNameCollision(downloaded); _localToolsResolverCache.Save(downloaded); return PrintConclusionAndReturn(toolRestoreResults); } private ToolRestoreResult InstallPackages( ToolManifestPackage package, FilePath? configFile) { string targetFramework = BundledTargetFramework.GetTargetFrameworkMoniker(); if (PackageHasBeenRestored(package, targetFramework)) { return ToolRestoreResult.Success( saveToCache: Array.Empty<(RestoredCommandIdentifier, RestoredCommand)>(), message: string.Format( LocalizableStrings.RestoreSuccessful, package.PackageId, package.Version.ToNormalizedString(), string.Join(", ", package.CommandNames))); } try { IToolPackage toolPackage = _toolPackageInstaller.InstallPackageToExternalManagedLocation( new PackageLocation( nugetConfig: configFile, additionalFeeds: _sources, rootConfigDirectory: package.FirstEffectDirectory), package.PackageId, ToVersionRangeWithOnlyOneVersion(package.Version), targetFramework, verbosity: _verbosity); if (!ManifestCommandMatchesActualInPackage(package.CommandNames, toolPackage.Commands)) { return ToolRestoreResult.Failure( string.Format(LocalizableStrings.CommandsMismatch, JoinBySpaceWithQuote(package.CommandNames.Select(c => c.Value.ToString())), package.PackageId, JoinBySpaceWithQuote(toolPackage.Commands.Select(c => c.Name.ToString())))); } return ToolRestoreResult.Success( saveToCache: toolPackage.Commands.Select(command => ( new RestoredCommandIdentifier( toolPackage.Id, toolPackage.Version, NuGetFramework.Parse(targetFramework), Constants.AnyRid, command.Name), command)).ToArray(), message: string.Format( LocalizableStrings.RestoreSuccessful, package.PackageId, package.Version.ToNormalizedString(), string.Join(" ", package.CommandNames))); } catch (ToolPackageException e) { return ToolRestoreResult.Failure(package.PackageId, e); } } private int PrintConclusionAndReturn(ToolRestoreResult[] toolRestoreResults) { if (toolRestoreResults.Any(r => !r.IsSuccess)) { _reporter.WriteLine(Environment.NewLine); _errorReporter.WriteLine(string.Join( Environment.NewLine, toolRestoreResults.Where(r => !r.IsSuccess).Select(r => r.Message)).Red()); var successMessage = toolRestoreResults.Where(r => r.IsSuccess).Select(r => r.Message); if (successMessage.Any()) { _reporter.WriteLine(Environment.NewLine); _reporter.WriteLine(string.Join(Environment.NewLine, successMessage)); } _errorReporter.WriteLine(Environment.NewLine + (toolRestoreResults.Any(r => r.IsSuccess) ? LocalizableStrings.RestorePartiallyFailed : LocalizableStrings.RestoreFailed).Red()); return 1; } else { _reporter.WriteLine(string.Join(Environment.NewLine, toolRestoreResults.Where(r => r.IsSuccess).Select(r => r.Message))); _reporter.WriteLine(Environment.NewLine); _reporter.WriteLine(LocalizableStrings.LocalToolsRestoreWasSuccessful.Green()); return 0; } } private static bool ManifestCommandMatchesActualInPackage( ToolCommandName[] commandsFromManifest, IReadOnlyList<RestoredCommand> toolPackageCommands) { ToolCommandName[] commandsFromPackage = toolPackageCommands.Select(t => t.Name).ToArray(); foreach (var command in commandsFromManifest) { if (!commandsFromPackage.Contains(command)) { return false; } } foreach (var command in commandsFromPackage) { if (!commandsFromManifest.Contains(command)) { return false; } } return true; } private bool PackageHasBeenRestored( ToolManifestPackage package, string targetFramework) { var sampleRestoredCommandIdentifierOfThePackage = new RestoredCommandIdentifier( package.PackageId, package.Version, NuGetFramework.Parse(targetFramework), Constants.AnyRid, package.CommandNames.First()); return _localToolsResolverCache.TryLoad( sampleRestoredCommandIdentifierOfThePackage, out var restoredCommand) && _fileSystem.File.Exists(restoredCommand.Executable.Value); } private FilePath? GetCustomManifestFileLocation() { string customFile = _options.ValueOrDefault<string>("tool-manifest"); FilePath? customManifestFileLocation; if (customFile != null) { customManifestFileLocation = new FilePath(customFile); } else { customManifestFileLocation = null; } return customManifestFileLocation; } private void EnsureNoCommandNameCollision(Dictionary<RestoredCommandIdentifier, RestoredCommand> dictionary) { string[] errors = dictionary .Select(pair => (PackageId: pair.Key.PackageId, CommandName: pair.Key.CommandName)) .GroupBy(packageIdAndCommandName => packageIdAndCommandName.CommandName) .Where(grouped => grouped.Count() > 1) .Select(nonUniquePackageIdAndCommandNames => string.Format(LocalizableStrings.PackagesCommandNameCollisionConclusion, string.Join(Environment.NewLine, nonUniquePackageIdAndCommandNames.Select( p => "\t" + string.Format( LocalizableStrings.PackagesCommandNameCollisionForOnePackage, p.CommandName.Value, p.PackageId.ToString()))))) .ToArray(); if (errors.Any()) { throw new ToolPackageException(string.Join(Environment.NewLine, errors)); } } private static string JoinBySpaceWithQuote(IEnumerable<object> objects) { return string.Join(" ", objects.Select(o => $"\"{o.ToString()}\"")); } private static VersionRange ToVersionRangeWithOnlyOneVersion(NuGetVersion version) { return new VersionRange( version, includeMinVersion: true, maxVersion: version, includeMaxVersion: true); } private struct ToolRestoreResult { public (RestoredCommandIdentifier, RestoredCommand)[] SaveToCache { get; } public bool IsSuccess { get; } public string Message { get; } private ToolRestoreResult( (RestoredCommandIdentifier, RestoredCommand)[] saveToCache, bool isSuccess, string message) { if (string.IsNullOrWhiteSpace(message)) { throw new ArgumentException("message", nameof(message)); } SaveToCache = saveToCache ?? Array.Empty<(RestoredCommandIdentifier, RestoredCommand)>(); IsSuccess = isSuccess; Message = message; } public static ToolRestoreResult Success( (RestoredCommandIdentifier, RestoredCommand)[] saveToCache, string message) { return new ToolRestoreResult(saveToCache, true, message); } public static ToolRestoreResult Failure(string message) { return new ToolRestoreResult(null, false, message); } public static ToolRestoreResult Failure( PackageId packageId, ToolPackageException toolPackageException) { return new ToolRestoreResult(null, false, string.Format(LocalizableStrings.PackageFailedToRestore, packageId.ToString(), toolPackageException.ToString())); } } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using DataAccess; // //reference: http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx // //This is our base master page, all other master pages will derive from this //master page. This page will handle db connection and cleanup etc... // //By defining the BaseMasterPage class as abstract, it can't be //created directly and can only serve as the base for another class. // //sequence of events for reference... //Master page controls Init event //Content controls Init event // //Master page Init event //Content page Init event // //Content page Load event //Master page Load event // //Content page PreRender event //Master page PreRender event // //Master page controls PreRender event //Content controls PreRender event // public abstract class BaseMaster : System.Web.UI.MasterPage { //04/16/2012 - Security Updates/////////////////////////// /// <summary> /// ASP .NET session id /// </summary> public string ASPSessionID { get { return Context.Session.SessionID; } } /// <summary> /// time out /// </summary> int m_nTimeOut = 15; public int Timeout { set { m_nTimeOut = value; } get { return m_nTimeOut; } } /// <summary> /// get/set session /// </summary> //DB session id member, this gets set when the user logs in public string DBSessionID { get { string strDBSessionID = ""; if (Session["DBSessionID"] == null) { return strDBSessionID; } strDBSessionID = Session["DBSessionID"].ToString(); return strDBSessionID; } set { Session["DBSessionID"] = value; } } ////////////////////////////////////////////////////////// //data connection member private CDataConnection m_DBConnection; //app specific controller not part of framework... public AppMaster APPMaster; /// <summary> /// get the database connection /// </summary> public CDataConnection DBConn { get { return m_DBConnection; } } public string Key { get; private set; } /// <summary> /// get/set status comment info, it will append... this allows us to keep /// a running list of errors if needed /// </summary> private string m_strStatusComment; public string StatusComment { get { return m_strStatusComment; } set { if (m_strStatusComment != "") { string strEnding = ""; if (m_strStatusComment.Length >= 6) { strEnding = m_strStatusComment.Substring(m_strStatusComment.Length - 6); } if (strEnding != "<br />") { Session["StatusComment"] += "<br />"; m_strStatusComment += "<br />"; } } Session["StatusComment"] += value; m_strStatusComment += value; //if the status contains an oracle error //then show a more user-friendly error instead //example: ORA-00942: table or view does not exist //search for "ORA-" if (m_strStatusComment.ToUpper().IndexOf("ORA-") != -1) { //todo: logg the current status in an error table m_strStatusComment = "An error occured while processing, please contact your system administrator."; m_strStatusComment += "<br />"; Session["StatusComment"] = m_strStatusComment; } } } /// <summary> /// clear the status, called by the masterpage after we display status info /// </summary> public void ClearStatus() { Session["StatusComment"] = ""; Session["StatusCode"] = 0; m_strStatusComment = ""; m_lStatusCode = 0; } /// <summary> /// get/set status code info /// </summary> private long m_lStatusCode; public long StatusCode { get { return m_lStatusCode; } set { //do not clear it if its already set to 1, this way //errors will overrule success for display if (m_lStatusCode < 1) //Changed because we have error status codes that are greater than 1. { Session["StatusCode"] = value; m_lStatusCode = value; } } } //use this check to see if the user clicked the //apps main "Save" button... public bool OnMasterSAVE() { //get the postback control string strPostBackControl = Request.Params["__EVENTTARGET"]; if (strPostBackControl != null) { //did we do a patient lookup? if (strPostBackControl.IndexOf("btnMasterSave") > -1) { return true; } } return false; } /// <summary> /// get/set user id /// </summary> //user id member - set when we login private long m_lFXUserID; public long FXUserID { get { return m_lFXUserID; } set { m_lFXUserID = value; } } //are we still logged in... public bool IsLoggedIn() { if (m_lFXUserID < 1) { return false; } return true; } /// <summary> /// get client ip, may be router but better than nothing /// </summary> public string ClientIP { get { return Context.Request.ServerVariables["REMOTE_ADDR"]; } } //sets a string viewstate value public void SetVSValue(string strKey, string strValue) { ViewState[strKey] = strValue; } //sets a bool viewstate value public void SetVSValue(string strKey, bool bValue) { ViewState[strKey] = bValue; } //sets a long viewstate value public void SetVSValue(string strKey, long lValue) { ViewState[strKey] = Convert.ToString(lValue); } //gets a string value from viewstate public string GetVSStringValue(string strKey) { string strValue = ""; if (ViewState[strKey] != null) { strValue = Convert.ToString(ViewState[strKey]); } return strValue; } //gets a bool value from view state public bool GetVSBoolValue(string strKey) { bool bValue = false; if (ViewState[strKey] != null) { bValue = Convert.ToBoolean(ViewState[strKey]); } return bValue; } //gets a long value from viewstate public long GetVSLongValue(string strKey) { long lValue = -1; if (ViewState[strKey] != null) { lValue = Convert.ToInt32(ViewState[strKey]); } return lValue; } //closes the patient public void ClosePatient() { this.SelectedPatientID = ""; this.SelectedTreatmentID = -1; this.LookupSearchCase = -1; this.SelectedEncounterID = ""; this.SelectedProblemID = -1; this.PatientTxStep = 0; this.NotificationTxStep = 0; this.PatientGender = ""; this.PatientAge = 0; this.PatientDOB = DateTime.Now; this.PatientHeight = 0; this.PatientWeight = 0; //remove session variables associated to the patient Session["PATIENTNAME"] = null; Session["PAT_DEMOGRAPHICS_DS"] = null; Session["PATIENT_STEP"] = null; Session["NOTIFICATION_STEP"] = null; } //this is the currently looked up patient id... public string SelectedPatientID { get { CSec sec = new CSec(); string strValue = ""; //more efficient to just use a session var //no db hit this way //GetSessionValue("SELECTED_PATIENT_ID", out strValue); if(Session["SELECTED_PATIENT_ID"] != null) { strValue = Session["SELECTED_PATIENT_ID"].ToString(); } return sec.dec(strValue, ""); } //set { SetSessionValue("SELECTED_PATIENT_ID", Convert.ToString(value)); } set { CSec sec = new CSec(); Session["SELECTED_PATIENT_ID"] = sec.Enc(Convert.ToString(value), ""); } } public bool IsPatientLocked { get { bool bLocked = false; if (Session["PATIENT_LOCKED_BM"] != null) { bLocked = Convert.ToBoolean(Session["PATIENT_LOCKED_BM"]); } return bLocked; } set { Session["PATIENT_LOCKED_BM"] = value; } } // 03/11/2011 - Selected treatment id public long SelectedTreatmentID { get { string strValue = "-1"; //GetSessionValue("SELECTED_TREATMENT_ID", out strValue); if (Session["SELECTED_TREATMENT_ID"] != null) { strValue = Session["SELECTED_TREATMENT_ID"].ToString(); } if (strValue.Length > 0) { return Convert.ToInt32(strValue); } else { return -1; } } // set { SetSessionValue("SELECTED_TREATMENT_ID", Convert.ToString(value)); } set { Session["SELECTED_TREATMENT_ID"] = Convert.ToString(value); } } // 2012-12-23 09:02PM ************************************************** public long PatientHeight { get { long value = 0; //more efficient to just use a session var //no db hit this way // if (Session["PATIENT_HEIGHT"] != null) { value = Convert.ToInt32(Session["PATIENT_HEIGHT"]); } return value; } set { Session["PATIENT_HEIGHT"] = value; } } public DateTime PatientDOB { get { DateTime dtDOB = DateTime.Now; //more efficient to just use a session var //no db hit this way // if (Session["PATIENT_DOB"] != null) { dtDOB = Convert.ToDateTime(Session["PATIENT_DOB"]); } return dtDOB; } set { Session["PATIENT_DOB"] = value; } } public long PatientAge { get { long value = 0; //more efficient to just use a session var //no db hit this way // if (Session["PATIENT_AGE"] != null) { value = Convert.ToInt32(Session["PATIENT_AGE"]); } return value; } set { Session["PATIENT_AGE"] = value; } } public string PatientGender { get { string value = ""; //more efficient to just use a session var //no db hit this way // if (Session["PATIENT_GENDER"] != null) { value = Session["PATIENT_GENDER"].ToString(); } return value; } set { Session["PATIENT_GENDER"] = value; } } public long PatientWeight { get { long value = 0; //more efficient to just use a session var //no db hit this way // if (Session["PATIENT_WEIGHT"] != null) { value = Convert.ToInt32(Session["PATIENT_WEIGHT"]); } return value; } set { Session["PATIENT_WEIGHT"] = value; } } // ********************************************************************* //this is the currently looked up patient id... public string SelectedEncounterID { get { string strValue = ""; //more efficient to just use a session var //no db hit this way //GetSessionValue("SELECTED_ENCOUNTER_ID", out strValue); // if(Session["SELECTED_ENCOUNTER_ID"] != null) { strValue = Session["SELECTED_ENCOUNTER_ID"].ToString(); } return strValue; } //set { SetSessionValue("SELECTED_ENCOUNTER_ID", Convert.ToString(value)); } set { Session["SELECTED_ENCOUNTER_ID"] = Convert.ToString(value); } } //this is the currently selected level of care public string SelectedLevelofCareID { get { string strValue = ""; if (Session["SELECTED_LEVELOFCARE_ID"] != null) { strValue = Session["SELECTED_LEVELOFCARE_ID"].ToString(); } return strValue; } set { Session["SELECTED_LEVELOFCARE_ID"] = Convert.ToString(value); } } //this is the currently looked up provider id... public string SelectedProviderID { get { string strValue = ""; //more efficient to just use a session var //no db hit this way //GetSessionValue("SELECTED_PROVIDER_ID", out strValue); if(Session["SELECTED_PROVIDER_ID"] != null) { strValue = Session["SELECTED_PROVIDER_ID"].ToString(); } return strValue; } //set { SetSessionValue("SELECTED_PROVIDER_ID", Convert.ToString(value)); } set { Session["SELECTED_PROVIDER_ID"] = Convert.ToString(value); } } //Patient Treatment Step public long PatientTxStep { get { long value = 0; //more efficient to just use a session var //no db hit this way if (Session["PATIENT_STEP"] != null) { value = Convert.ToInt32(Session["PATIENT_STEP"]); } return value; } set { Session["PATIENT_STEP"] = value; } } //Notification Treatment Step public long NotificationTxStep { get { long value = 0; //more efficient to just use a session var //no db hit this way if (Session["NOTIFICATION_STEP"] != null) { value = Convert.ToInt32(Session["NOTIFICATION_STEP"]); } return value; } set { Session["NOTIFICATION_STEP"] = value; } } /* ***************************************************************** * MODULE ID SUPPORT FOR PATIENT PORTAL * *************************************************************** */ /// get/set module id private int m_lModuleID; public int ModuleID { get { return m_lModuleID; } set { m_lModuleID = value; } } /// get/set page id private int m_lPageID; public int PageID { get { return m_lPageID; } set { m_lPageID = value; } } /// get/set random data segment private string m_strRDS; public string RDS { get { return m_strRDS; } set { m_strRDS = value; } } //------------------------------------------------------------------------------ private int m_nSessionLanguage; public int SessionLanguage { get { return m_nSessionLanguage; } set { Session["VS_ALTLANG"] = value; m_nSessionLanguage = value; } } //------------------------------------------------------------------------------ public string EncounterID { get { string strValue = ""; GetSessionValue("ENCOUNTER_ID", out strValue); return strValue; } set { SetSessionValue("ENCOUNTER_ID", Convert.ToString(value)); } } // 03/11/2011 - this is the type of lookup:: 1- all cases, 2- open cases, 3- closed cases public long LookupSearchCase { get { string strValue = "-1"; GetSessionValue("LOOKUP_SEARCH_CASE", out strValue); if (strValue.Length > 0) { return Convert.ToInt32(strValue); } else { return -1; } } set { SetSessionValue("LOOKUP_SEARCH_CASE", Convert.ToString(value)); } } // 11/17/2011 - Selected problem id public long SelectedProblemID { get { string strValue = "-1"; //GetSessionValue("SELECTED_PROBLEM_ID", out strValue); if (Session["SELECTED_PROBLEM_ID"] != null) { strValue = Session["SELECTED_PROBLEM_ID"].ToString(); } if (strValue.Length > 0) { return Convert.ToInt32(strValue); } else { return -1; } } // set { SetSessionValue("SELECTED_PROBLEM_ID", Convert.ToString(value)); } set { Session["SELECTED_PROBLEM_ID"] = Convert.ToString(value); } } //this is the currently selected Branch Of Service public long BranchOfService { get { string strValue = "-1"; GetSessionValue("BRANCH_OF_SERVICE", out strValue); if (strValue.Length > 0) { return Convert.ToInt32(strValue); } else { return -1; } } set { SetSessionValue("BRANCH_OF_SERVICE", Convert.ToString(value)); } } public bool HasMilitaryDetails { get { bool value = false; value = Convert.ToBoolean(Session["HAS_MILITARY_DETAILS"]); return value; } set { Session["HAS_MILITARY_DETAILS"] = value; } } public bool HasPatientSupervisorInput { get { bool value = false; value = Convert.ToBoolean(Session["HAS_PATIENT_SUPERVISOR_INPUT"]); return value; } set { Session["HAS_PATIENT_SUPERVISOR_INPUT"] = value; } } public bool HasPatientInsurance { get { bool value = false; value = Convert.ToBoolean(Session["HAS_PATIENT_INSURANCE"]); return value; } set { Session["HAS_PATIENT_INSURANCE"] = value; } } //this puts us into a developer mode so //that CAC stuff is bypassed //etc.... public bool DEV_MODE = false; /// <summary> /// constructor /// </summary> public BaseMaster() { //this puts us into a developer mode so //that CAC stuff is bypassed //etc.... //TODO: comment out before depoloying!!! DEV_MODE = true; //create a new dataconnection object m_DBConnection = new CDataConnection(); //clear status m_strStatusComment = ""; m_lStatusCode = -1; FXUserID = 0; m_lModuleID = 0; m_lPageID = 0; m_strRDS = ""; } /// <summary> /// this is the proper place to do initialization in a master page /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Init(object sender, EventArgs e) { //app specific stuff outside the base controller APPMaster = new AppMaster(); APPMaster.SetBaseMaster(this); //Returns a string that can be used in a client //event to cause postback to the server. Page.ClientScript.GetPostBackEventReference(this, String.Empty); //set the character set, since all pages derive from basemaster //this will set the encoding for all pages... Response.ContentEncoding = Encoding.UTF8; //init status info and objects m_strStatusComment = ""; m_lStatusCode = -1;//-1 = success no show //04/16/2012 - Security Updates //set the timeout if (Session.Timeout < 15) { Timeout = 15; } else { Timeout = Session.Timeout; } //connect to the data source if (!ConnectToDataSource()) { //redirect to an error page Response.Redirect("error_database.aspx"); Response.End(); } //sec helper CSec sec = new CSec(); //auto-login with CAC/cert NO! //from the inspection user must click banner //so no auto login here /*if (!IsPostBack) { string strPage = GetPageName(); if (strPage != "fx_logoff.aspx") { //don't try to login if we clicked the logoff option if (Request.QueryString["logoff"] == null) { //attempt a cac cert login if (Session["SessionID"] == null) { //auto login with the cert on the CAC... sec.CertLogin(this); } } } }*/ //get sessionid if set - set user id if session is ok //Session["SessionID"] gets set in the database when the user //logs in. this is used to cache values in the db and also //force timeouts etc.... /* if (Session["SessionID"] != null) { m_strSessionID = Session["SessionID"].ToString(); //get actual user id string strUID = ""; if (GetSessionValue("FX_USER_ID", out strUID)) { if (strUID != "") { m_lFXUserID = Convert.ToInt32(strUID); } //load the app specific user details //needed for the application APPMaster.LoadUserDetails(); } } else { //default to ASP.net session if we have not logged in m_strSessionID = Context.Session.SessionID; } */ //DBSessionID gets set in the database when the user //logs in. this is used to cache values in the db and to determine if the //user is logged in // //reset FXUserID, only gets set in the call below FXUserID = 0; if (!String.IsNullOrEmpty(DBSessionID)) { //get actual user id from the database session created when the //user logs in string strUID = ""; if (GetSessionValue("FX_USER_ID", out strUID)) { if (strUID != "") { FXUserID = Convert.ToInt32(strUID); } //load the app specific user details //needed for the application APPMaster.LoadUserDetails(); } else { //log off if we cannot retrieve a valid session, //user timed out LogOff(); } } //user does not have access to this page //so logoff. if (!sec.AuditPageAccess(this)) { LogOff(); } long lNewModuleID = -1; //keep the module id, page id and random data segment if (Request.QueryString["mid"] != null) { string strModuleID; GetSessionValue("CURR_MODULE_ID", out strModuleID); if (strModuleID != Request.QueryString["mid"].ToString()) { lNewModuleID = 1; } else { lNewModuleID = -1; } m_lModuleID = Convert.ToInt32(Request.QueryString["mid"].ToString()); SetSessionValue("CURR_MODULE_ID", Convert.ToString(m_lModuleID)); } if (Request.QueryString["pid"] != null) { if (lNewModuleID != -1) { m_lPageID = -1; } else { m_lPageID = Convert.ToInt32(Request.QueryString["pid"].ToString()); } SetSessionValue("CURR_PAGE_ID", Convert.ToString(m_lPageID)); } if (Request.QueryString["rds"] != null) { m_strRDS = Request.QueryString["rds"].ToString(); } if (m_lModuleID < 1) { string strModuleID = ""; if (m_lFXUserID > 0) { GetSessionValue("CURR_MODULE_ID", out strModuleID); if (strModuleID != "") { m_lModuleID = Convert.ToInt32(strModuleID); } } } if (m_lModuleID < 1) { string strModuleID = ""; if (m_lFXUserID > 0) { GetSessionValue("CURR_MODULE_ID", out strModuleID); if (strModuleID != "") { m_lModuleID = Convert.ToInt32(strModuleID); } } } if (m_lPageID < 1) { string strPageID = ""; if (m_lFXUserID > 0) { GetSessionValue("CURR_PAGE_ID", out strPageID); if (strPageID != "") { m_lPageID = Convert.ToInt32(strPageID); } } } } /// <summary> /// caches a session value in the database. /// stored encrypted and more secure then an asp.net session var /// </summary> /// <param name="strKey"></param> /// <param name="strKeyValue"></param> /// <returns></returns> public bool SetSessionValue( string strKey, string strKeyValue) { //status info long lStatusCode = -1; string strStatusComment = ""; if (!IsLoggedIn()) { return true; } //create a new parameter list CDataParameterList pList = new CDataParameterList(); //add params for the DB call // //in paramaters //these will always be passed in to all sp calls pList.AddParameter("pi_vSessionID", DBSessionID, ParameterDirection.Input); pList.AddParameter("pi_vSessionClientIP", ClientIP, ParameterDirection.Input); pList.AddParameter("pi_nUserID", FXUserID, ParameterDirection.Input); // pList.AddParameter("pi_vKey", strKey, ParameterDirection.Input); pList.AddParameter("pi_vKeyValue", strKeyValue, ParameterDirection.Input); // //execute the stored procedure DBConn.ExecuteOracleSP("PCK_FX_SEC.SetSessionValue", pList, out lStatusCode, out strStatusComment); // 0 = success if strStatus is populated it will show on the screen // 1 to n are errors and we always show errors if (lStatusCode == 0) { return true; } return false; } /// <summary> /// gets a cached session value from the database. /// stored encrypted and more secure then an asp.net session var /// </summary> /// <param name="strKey"></param> /// <param name="strKeyValue"></param> /// <returns></returns> public bool GetSessionValue(string strKey, out string strKeyValue) { strKeyValue = ""; //status info long lStatusCode = -1; string strStatusComment = ""; //create a new parameter list CDataParameterList pList = new CDataParameterList(); //in paramaters //these will always be passed in to all sp calls pList.AddParameter("pi_vDBSessionID", DBSessionID, ParameterDirection.Input); pList.AddParameter("pi_vWebSessionID", ASPSessionID, ParameterDirection.Input); pList.AddParameter("pi_vSessionClientIP", ClientIP, ParameterDirection.Input); pList.AddParameter("pi_nUserID", FXUserID, ParameterDirection.Input); // pList.AddParameter("pi_vKey", strKey, ParameterDirection.Input); pList.AddParameter("po_vKeyValue", strKeyValue, ParameterDirection.Output); // //execute the stored procedure DBConn.ExecuteOracleSP("PCK_FX_SEC.GetSessionValue", pList, out lStatusCode, out strStatusComment); // 0 = success if strStatus is populated it will show on the screen // 1 to n are errors and we always show errors if (lStatusCode == 0) { CDataParameter paramValue = pList.GetItemByName("po_vKeyValue"); strKeyValue = paramValue.StringParameterValue; return true; } strKeyValue = ""; return false; } /// <summary> /// deletes a cached session value in the database. /// </summary> /// <param name="strKey"></param> /// <returns></returns> public bool DeleteSessionValue(string strKey) { //status info long lStatusCode = -1; string strStatusComment = ""; //create a new parameter list CDataParameterList pList = new CDataParameterList(); //add params for the DB call // //in paramaters //these will always be passed in to all sp calls pList.AddParameter("pi_vSessionID", DBSessionID, ParameterDirection.Input); pList.AddParameter("pi_vSessionClientIP", ClientIP, ParameterDirection.Input); pList.AddParameter("pi_nUserID", FXUserID, ParameterDirection.Input); pList.AddParameter("pi_vKey", strKey, ParameterDirection.Input); // //execute the stored procedure DBConn.ExecuteOracleSP("PCK_FX_SEC.DeleteSessionValue", pList, out lStatusCode, out strStatusComment); // 0 = success if strStatus is populated it will show on the screen // 1 to n are errors and we always show errors if (lStatusCode == 0) { return true; } return false; } /// <summary> /// deletes all cached session values in the database. /// </summary> /// <returns></returns> public bool DeleteAllSessionValues() { //status info long lStatusCode = -1; string strStatusComment = ""; //create a new parameter list CDataParameterList pList = new CDataParameterList(); //add params for the DB call // //in paramaters //these will always be passed in to all sp calls pList.AddParameter("pi_vSessionID", DBSessionID, ParameterDirection.Input); pList.AddParameter("pi_vSessionClientIP", ClientIP, ParameterDirection.Input); pList.AddParameter("pi_nUserID", FXUserID, ParameterDirection.Input); //execute the stored procedure DBConn.ExecuteOracleSP("PCK_FX_SEC.DeleteAllSessionValues", pList, out lStatusCode, out strStatusComment); // 0 = success if strStatus is populated it will show on the screen // 1 to n are errors and we always show errors if (lStatusCode == 0) { return true; } return false; } /// <summary> /// helper to get the current page name /// </summary> /// <returns></returns> public string GetPageName() { string strPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; System.IO.FileInfo oInfo = new System.IO.FileInfo(strPath); return oInfo.Name.ToLower(); } /// <summary> /// good place to close connections etc... /// </summary> public override void Dispose() { //close the database connection if (m_DBConnection != null) { m_DBConnection.Close(); } base.Dispose(); } /// <summary> /// connect to datasource /// </summary> private bool ConnectToDataSource() { //get the connection string from the web.config file //connection string is encrypted in the file using MS recommended procedures // //cd\ //cd windows //cd microsoft.net //cd framework //cd v2.0.50727 //aspnet_regiis -pe "connectionStrings" -app "/PrimeCarePlus" -prov "RsaProtectedConfigurationProvider" // //look for connection strings in connection strings and app settings string strConnectionString = string.Empty; try { //try to get the connection string from the encrypted connectionstrings section strConnectionString = ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString; Key = ConfigurationManager.ConnectionStrings["Key"].ConnectionString; } catch (Exception e) { string strStatus = e.Message; } bool bAudit = (ConfigurationManager.AppSettings["AUDIT"] == "1") ? true : false; //Connect to the database, connection is housed in the master page //so that all pages that use the master have access to it. if (!m_DBConnection.Connect( strConnectionString, (int)DataConnectionType.Oracle, bAudit)) { Session["DB_ERROR_CODE"] = string.Empty; Session["DB_ERROR"] = string.Empty; m_strStatusComment = "Error Connecting to Data Source"; m_lStatusCode = 1; return false; } return true; } /// <summary> /// called to logoff the user /// </summary> public void LogOff() { //clear the patient this.ClosePatient(); //clear FX_USER session var Session["FX_USER"] = null; //clear account details session var Session["ACC_DETAILS"] = null; //do any clean up necessary to logoff CSec sec = new CSec(); sec.LogOff(this); //is an extra step for timeouts etc... if (!String.IsNullOrEmpty(DBSessionID)) { DeleteAllSessionValues(); } //clear the dbsessionid DBSessionID = String.Empty; //clear the session Session.Clear(); //abandon the session Session.Abandon(); //redirect; Response.Redirect("default.aspx"); } public void LogOff(bool bRedirect) { //clear the patient this.ClosePatient(); //clear FX_USER session var Session["FX_USER"] = null; //clear account details session var Session["ACC_DETAILS"] = null; //do any clean up necessary to logoff CSec sec = new CSec(); sec.LogOff(this); //is an extra step for timeouts etc... if (!String.IsNullOrEmpty(DBSessionID)) { DeleteAllSessionValues(); } //clear the dbsessionid DBSessionID = String.Empty; //clear the session Session.Clear(); //abandon the session Session.Abandon(); //redirect; if (bRedirect) { Response.Redirect("default.aspx"); } } /// <summary> /// Get a random number, good for forcing the browser to refresh a page /// also used to help generate our session id /// </summary> /// <returns></returns> public string GenerateRandomNumber() { string strRand = ""; Random r = new Random(); strRand = Convert.ToString(r.NextDouble()); strRand = strRand.Replace(".", ""); return strRand; } /// <summary> /// Get a random chars, good for forcing the browser to refresh a page /// also used to help generate our session id /// </summary> /// <returns></returns> public string GenerateRandomChars() { string strRand = ""; Random r = new Random(); strRand = Convert.ToString(r.NextDouble()); strRand = strRand.Replace(".", ""); string strRandChars = ""; for (int i = 0; i < strRand.Length; i++) { string strC = ""; strC = strRand.Substring(i, 1); if (strC == "0") { strRandChars += "a"; } else if (strC == "1") { strRandChars += "b"; } else if (strC == "2") { strRandChars += "c"; } else if (strC == "3") { strRandChars += "d"; } else if (strC == "4") { strRandChars += "e"; } else if (strC == "5") { strRandChars += "f"; } else if (strC == "6") { strRandChars += "g"; } else if (strC == "7") { strRandChars += "h"; } else if (strC == "8") { strRandChars += "i"; } else if (strC == "9") { strRandChars += "j"; } else { strRandChars += "z"; } } return strRandChars; } // 2011-07-21 D.S. // Get "Last Updated" info public bool getLastUpdated(DataSet ds) { if (ds != null) { DateTime dtLastUpdated; DateTime.TryParse("1900-01-01", out dtLastUpdated); long lLastUpdatedBy = -1; foreach (DataTable dt in ds.Tables) { foreach (DataRow dr in dt.Rows) { if (!dr.IsNull("last_updated") && !dr.IsNull("last_updated_by")) { DateTime dtRecUpdated = Convert.ToDateTime(dr["last_updated"]); if (dtRecUpdated > dtLastUpdated) { dtLastUpdated = dtRecUpdated; lLastUpdatedBy = Convert.ToInt32(dr["last_updated_by"]); } } } } if (lLastUpdatedBy > -1) { string strLastUpdatedBy = ""; string strLastUpdated = dtLastUpdated.ToString(); CUser user = new CUser(); DataSet dsUser = user.GetLoginUserDS(this, lLastUpdatedBy); if (dsUser != null) { CDataUtils utils = new CDataUtils(); strLastUpdatedBy = utils.GetStringValueFromDS(dsUser, "name"); string strUpdated = "Last updated on " + strLastUpdated + " by " + strLastUpdatedBy + "."; this.SetVSValue("LAST_UPDATED", strUpdated); return true; } } } return false; } //specify a different VS key public bool getLastUpdated(DataSet ds, string strVSKey) { if (ds != null) { DateTime dtLastUpdated; DateTime.TryParse("1900-01-01", out dtLastUpdated); long lLastUpdatedBy = -1; foreach (DataTable dt in ds.Tables) { foreach (DataRow dr in dt.Rows) { if (!dr.IsNull("last_updated") && !dr.IsNull("last_updated_by")) { DateTime dtRecUpdated = Convert.ToDateTime(dr["last_updated"]); if (dtRecUpdated > dtLastUpdated) { dtLastUpdated = dtRecUpdated; lLastUpdatedBy = Convert.ToInt32(dr["last_updated_by"]); } } } } if (lLastUpdatedBy > -1) { string strLastUpdatedBy = ""; string strLastUpdated = dtLastUpdated.ToString(); CUser user = new CUser(); DataSet dsUser = user.GetLoginUserDS(this, lLastUpdatedBy); if (dsUser != null) { CDataUtils utils = new CDataUtils(); strLastUpdatedBy = utils.GetStringValueFromDS(dsUser, "name"); string strUpdated = "Last updated on " + strLastUpdated + " by " + strLastUpdatedBy + "."; this.SetVSValue(strVSKey, strUpdated); return true; } } } return false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A lock-free, concurrent stack primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; namespace System.Collections.Concurrent { // A stack that uses CAS operations internally to maintain thread-safety in a lock-free // manner. Attempting to push or pop concurrently from the stack will not trigger waiting, // although some optimistic concurrency and retry is used, possibly leading to lack of // fairness and/or livelock. The stack uses spinning and backoff to add some randomization, // in hopes of statistically decreasing the possibility of livelock. // // Note that we currently allocate a new node on every push. This avoids having to worry // about potential ABA issues, since the CLR GC ensures that a memory address cannot be // reused before all references to it have died. /// <summary> /// Represents a thread-safe last-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the stack.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] [HostProtection(Synchronization = true, ExternalThreading = true)] #if !FEATURE_CORECLR [Serializable] #endif //!FEATURE_CORECLR public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { /// <summary> /// A simple (internal) node type used to store elements of concurrent stacks and queues. /// </summary> private class Node { internal readonly T m_value; // Value of the node. internal Node m_next; // Next pointer. /// <summary> /// Constructs a new node with the specified value and no next node. /// </summary> /// <param name="value">The value of the node.</param> internal Node(T value) { m_value = value; m_next = null; } } #if !FEATURE_CORECLR [NonSerialized] #endif //!FEATURE_CORECLR private volatile Node m_head; // The stack is a singly linked list, and only remembers the head. #if !FEATURE_CORECLR private T[] m_serializationArray; // Used for custom serialization. #endif //!FEATURE_CORECLR private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class. /// </summary> public ConcurrentStack() { } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class that contains elements copied from the specified collection /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentStack{T}"/>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is /// null.</exception> public ConcurrentStack(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } InitializeFromCollection(collection); } /// <summary> /// Initializes the contents of the stack from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { // We just copy the contents of the collection to our stack. Node lastNode = null; foreach (T element in collection) { Node newNode = new Node(element); newNode.m_next = lastNode; lastNode = newNode; } m_head = lastNode; } #if !FEATURE_CORECLR /// <summary> /// Get the data array to be serialized /// </summary> [OnSerializing] private void OnSerializing(StreamingContext context) { // save the data into the serialization array to be saved m_serializationArray = ToArray(); } /// <summary> /// Construct the stack from a previously seiralized one /// </summary> [OnDeserialized] private void OnDeserialized(StreamingContext context) { Contract.Assert(m_serializationArray != null); // Add the elements to our stack. We need to add them from head-to-tail, to // preserve the original ordering of the stack before serialization. Node prevNode = null; Node head = null; for (int i = 0; i < m_serializationArray.Length; i++) { Node currNode = new Node(m_serializationArray[i]); if (prevNode == null) { head = currNode; } else { prevNode.m_next = currNode; } prevNode = currNode; } m_head = head; m_serializationArray = null; } #endif //!FEATURE_CORECLR /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { // Checks whether the stack is empty. Clearly the answer may be out of date even prior to // the function returning (i.e. if another thread concurrently adds to the stack). It does // guarantee, however, that, if another thread does not mutate the stack, a subsequent call // to TryPop will return true -- i.e. it will also read the stack as non-empty. get { return m_head == null; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { // Counts the number of entries in the stack. This is an O(n) operation. The answer may be out // of date before returning, but guarantees to return a count that was once valid. Conceptually, // the implementation snaps a copy of the list and then counts the entries, though physically // this is not what actually happens. get { int count = 0; // Just whip through the list and tally up the number of nodes. We rely on the fact that // node next pointers are immutable after being enqueued for the first time, even as // they are being dequeued. If we ever changed this (e.g. to pool nodes somehow), // we'd need to revisit this implementation. for (Node curr = m_head; curr != null; curr = curr.m_next) { count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR } return count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported")); } } /// <summary> /// Removes all objects from the <see cref="ConcurrentStack{T}"/>. /// </summary> public void Clear() { // Clear the list by setting the head to null. We don't need to use an atomic // operation for this: anybody who is mutating the head by pushing or popping // will need to use an atomic operation to guarantee they serialize and don't // overwrite our setting of the head to null. m_head = null; } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must /// have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be /// a null reference (Nothing in Visual Basic) for reference types. /// </param> public void Push(T item) { // Pushes a node onto the front of the stack thread-safely. Internally, this simply // swaps the current head pointer using a (thread safe) CAS operation to accomplish // lock freedom. If the CAS fails, we add some back off to statistically decrease // contention at the head, and then go back around and retry. Node newNode = new Node(item); newNode.m_next = m_head; if (Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(newNode, newNode); } /// <summary> /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically. /// </summary> /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <remarks> /// When adding multiple items to the stack, using PushRange is a more efficient /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange /// guarantees that all of the elements will be added atomically, meaning that no other threads will /// be able to inject elements between the elements being pushed. Items at lower indices in /// the <paramref name="items"/> array will be pushed before items at higher indices. /// </remarks> public void PushRange(T[] items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } PushRange(items, 0, items.Length); } /// <summary> /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically. /// </summary> /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin /// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="count">The number of elements to be inserted onto the top of the <see /// cref="ConcurrentStack{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length /// of <paramref name="items"/>.</exception> /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is /// greater than the length of <paramref name="items"/>.</exception> /// <remarks> /// When adding multiple items to the stack, using PushRange is a more efficient /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange /// guarantees that all of the elements will be added atomically, meaning that no other threads will /// be able to inject elements between the elements being pushed. Items at lower indices in the /// <paramref name="items"/> array will be pushed before items at higher indices. /// </remarks> public void PushRange(T[] items, int startIndex, int count) { ValidatePushPopRangeInput(items, startIndex, count); // No op if the count is zero if (count == 0) return; Node head, tail; head = tail = new Node(items[startIndex]); for (int i = startIndex + 1; i < startIndex + count; i++) { Node node = new Node(items[i]); node.m_next = head; head = node; } tail.m_next = m_head; if (Interlocked.CompareExchange(ref m_head, head, tail.m_next) == tail.m_next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(head, tail); } /// <summary> /// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head /// and tail to the stack /// </summary> /// <param name="head">The head pointer to the new list</param> /// <param name="tail">The tail pointer to the new list</param> private void PushCore(Node head, Node tail) { SpinWait spin = new SpinWait(); // Keep trying to CAS the exising head with the new node until we succeed. do { spin.SpinOnce(); // Reread the head and link our new node. tail.m_next = m_head; } while (Interlocked.CompareExchange( ref m_head, head, tail.m_next) != tail.m_next); #if !FEATURE_CORECLR if (CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count); } #endif // !FEATURE_CORECLR } /// <summary> /// Local helper function to validate the Pop Push range methods input /// </summary> private void ValidatePushPopRangeInput(T[] items, int startIndex, int count) { if (items == null) { throw new ArgumentNullException(nameof(items)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ConcurrentStack_PushPopRange_CountOutOfRange")); } int length = items.Length; if (startIndex >= length || startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ConcurrentStack_PushPopRange_StartOutOfRange")); } if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow { throw new ArgumentException(Environment.GetResourceString("ConcurrentStack_PushPopRange_InvalidCount")); } } /// <summary> /// Attempts to add an object to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation /// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Push(item); return true; } /// <summary> /// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the top of the <see cref="T:System.Collections.Concurrent.ConccurrentStack{T}"/> or an /// unspecified value if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { Node head = m_head; // If the stack is empty, return false; else return the element and true. if (head == null) { result = default(T); return false; } else { result = head.m_value; return true; } } /// <summary> /// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the top of the <see /// cref="ConcurrentStack{T}"/> /// succesfully; otherwise, false.</returns> public bool TryPop(out T result) { Node head = m_head; //stack is empty if (head == null) { result = default(T); return false; } if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head) { result = head.m_value; return true; } // Fall through to the slow path. return TryPopCore(out result); } /// <summary> /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/> /// atomically. /// </summary> /// <param name="items"> /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see /// cref="ConcurrentStack{T}"/> will be added. /// </param> /// <returns>The number of objects successfully popped from the top of the <see /// cref="ConcurrentStack{T}"/> and inserted in /// <paramref name="items"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing /// in Visual Basic).</exception> /// <remarks> /// When popping multiple items, if there is little contention on the stack, using /// TryPopRange can be more efficient than using <see cref="TryPop"/> /// once per item to be removed. Nodes fill the <paramref name="items"/> /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// </remarks> public int TryPopRange(T[] items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } return TryPopRange(items, 0, items.Length); } /// <summary> /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/> /// atomically. /// </summary> /// <param name="items"> /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see /// cref="ConcurrentStack{T}"/> will be added. /// </param> /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin /// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="count">The number of elements to be popped from top of the <see /// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param> /// <returns>The number of objects successfully popped from the top of /// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length /// of <paramref name="items"/>.</exception> /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is /// greater than the length of <paramref name="items"/>.</exception> /// <remarks> /// When popping multiple items, if there is little contention on the stack, using /// TryPopRange can be more efficient than using <see cref="TryPop"/> /// once per item to be removed. Nodes fill the <paramref name="items"/> /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// </remarks> public int TryPopRange(T[] items, int startIndex, int count) { ValidatePushPopRangeInput(items, startIndex, count); // No op if the count is zero if (count == 0) return 0; Node poppedHead; int nodesCount = TryPopCore(count, out poppedHead); if (nodesCount > 0) { CopyRemovedItems(poppedHead, items, startIndex, nodesCount); } return nodesCount; } /// <summary> /// Local helper function to Pop an item from the stack, slow path /// </summary> /// <param name="result">The popped item</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryPopCore(out T result) { Node poppedNode; if (TryPopCore(1, out poppedNode) == 1) { result = poppedNode.m_value; return true; } result = default(T); return false; } /// <summary> /// Slow path helper for TryPop. This method assumes an initial attempt to pop an element /// has already occurred and failed, so it begins spinning right away. /// </summary> /// <param name="count">The number of items to pop.</param> /// <param name="poppedHead"> /// When this method returns, if the pop succeeded, contains the removed object. If no object was /// available to be removed, the value is unspecified. This parameter is passed uninitialized. /// </param> /// <returns>True if an element was removed and returned; otherwise, false.</returns> private int TryPopCore(int count, out Node poppedHead) { SpinWait spin = new SpinWait(); // Try to CAS the head with its current next. We stop when we succeed or // when we notice that the stack is empty, whichever comes first. Node head; Node next; int backoff = 1; Random r = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue while (true) { head = m_head; // Is the stack empty? if (head == null) { #if !FEATURE_CORECLR if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); } #endif //!FEATURE_CORECLR poppedHead = null; return 0; } next = head; int nodesCount = 1; for (; nodesCount < count && next.m_next != null; nodesCount++) { next = next.m_next; } // Try to swap the new head. If we succeed, break out of the loop. if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head) { #if !FEATURE_CORECLR if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); } #endif //!FEATURE_CORECLR // Return the popped Node. poppedHead = head; return nodesCount; } // We failed to CAS the new head. Spin briefly and retry. for (int i = 0; i < backoff; i++) { spin.SpinOnce(); } backoff = spin.NextSpinWillYield ? r.Next(1, BACKOFF_MAX_YIELDS) : backoff * 2; } } /// <summary> /// Local helper function to copy the poped elements into a given collection /// </summary> /// <param name="head">The head of the list to be copied</param> /// <param name="collection">The collection to place the popped items in</param> /// <param name="startIndex">the beginning of index of where to place the popped items</param> /// <param name="nodesCount">The number of nodes.</param> private void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount) { Node current = head; for (int i = startIndex; i < startIndex + nodesCount; i++) { collection[i] = current.m_value; current = current.m_next; } } /// <summary> /// Attempts to remove and return an object from the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at /// the top of the <see cref="ConcurrentStack{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryPop(out item); } /// <summary> /// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentStack{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Returns an array containing a snapshot of the list's contents, using /// the target list node as the head of a region in the list. /// </summary> /// <returns>An array of the list's contents.</returns> private List<T> ToList() { List<T> list = new List<T>(); Node curr = m_head; while (curr != null) { list.Add(curr.m_value); curr = curr.m_next; } return list; } /// <summary> /// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the stack. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the stack. /// </remarks> public IEnumerator<T> GetEnumerator() { // Returns an enumerator for the stack. This effectively takes a snapshot // of the stack's contents at the time of the call, i.e. subsequent modifications // (pushes or pops) will not be reflected in the enumerator's contents. //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of //the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called. //This is inconsistent with existing generic collections. In order to prevent it, we capture the //value of m_head in a buffer and call out to a helper method return GetEnumerator(m_head); } private IEnumerator<T> GetEnumerator(Node head) { Node current = head; while (current != null) { yield return current.m_value; current = current.m_next; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through /// the collection.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not /// reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use concurrently with reads /// from and writes to the stack. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\StaticMeshComponent.h:171 namespace UnrealEngine { public partial class UStaticMeshComponent : UMeshComponent { public UStaticMeshComponent(IntPtr adress) : base(adress) { } public UStaticMeshComponent(UObject Parent = null, string Name = "StaticMeshComponent") : base(IntPtr.Zero) { NativePointer = E_NewObject_UStaticMeshComponent(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bCastDistanceFieldIndirectShadow_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bCastDistanceFieldIndirectShadow_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bDisallowMeshPaintPerInstance_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bDisallowMeshPaintPerInstance_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfComplex_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfComplex_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfSimple_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfSimple_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bForceNavigationObstacle_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bForceNavigationObstacle_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bIgnoreInstanceForTextureStreaming_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bIgnoreInstanceForTextureStreaming_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bOverrideDistanceFieldSelfShadowBias_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bOverrideDistanceFieldSelfShadowBias_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bOverrideLightMapRes_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bOverrideLightMapRes_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bOverrideMinLOD_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bOverrideMinLOD_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bOverrideNavigationExport_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bOverrideNavigationExport_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bOverrideWireframeColor_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bOverrideWireframeColor_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bReverseCulling_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bReverseCulling_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bUseDefaultCollision_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bUseDefaultCollision_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_UStaticMeshComponent_bUseSubDivisions_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_bUseSubDivisions_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UStaticMeshComponent_DistanceFieldIndirectShadowMinVisibility_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_DistanceFieldIndirectShadowMinVisibility_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UStaticMeshComponent_DistanceFieldSelfShadowBias_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_DistanceFieldSelfShadowBias_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UStaticMeshComponent_ForcedLodModel_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_ForcedLodModel_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_UStaticMeshComponent_LightmassSettings_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_LightmassSettings_SET(IntPtr Ptr, IntPtr Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UStaticMeshComponent_MinLOD_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_MinLOD_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UStaticMeshComponent_OverriddenLightMapRes_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_OverriddenLightMapRes_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UStaticMeshComponent_PreviousLODLevel_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_PreviousLODLevel_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_UStaticMeshComponent_StreamingDistanceMultiplier_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_StreamingDistanceMultiplier_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_UStaticMeshComponent_SubDivisionStepSize_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_UStaticMeshComponent_SubDivisionStepSize_SET(IntPtr Ptr, int Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_UStaticMeshComponent(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_CachePaintedDataIfNecessary(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_CopyInstanceVertexColorsIfCompatible(IntPtr self, IntPtr sourceComponent); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_FixupOverrideColorsIfNecessary(IntPtr self, bool bRebuildingStaticMesh); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_UStaticMeshComponent_GetBlueprintCreatedComponentIndex(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_GetEstimatedLightAndShadowMapMemoryUsage(IntPtr self, int textureLightMapMemoryUsage, int textureShadowMapMemoryUsage, int vertexLightMapMemoryUsage, int vertexShadowMapMemoryUsage, int staticLightingResolution, bool bIsUsingTextureMapping, bool bHasLightmapTexCoords); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_GetEstimatedLightMapResolution(IntPtr self, int width, int height); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_GetLocalBounds(IntPtr self, IntPtr min, IntPtr max); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UStaticMeshComponent_GetMemberNameChecked_StaticMesh(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_GetTextureLightAndShadowMapMemoryUsage(IntPtr self, int inWidth, int inHeight, int outLightMapMemoryUsage, int outShadowMapMemoryUsage); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_UStaticMeshComponent_GetTextureStreamingTransformScale(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_HasLightmapTextureCoordinates(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_ReleaseResources(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_RemoveInstanceVertexColors(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_RemoveInstanceVertexColorsFromLOD(IntPtr self, int lODToRemoveColorsFrom); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_RequiresOverrideVertexColorsFixup(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_SetDistanceFieldSelfShadowBias(IntPtr self, float newValue); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_SetForcedLodModel(IntPtr self, int newForcedLodModel); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_SetMaterialPreview(IntPtr self, int inMaterialIndexPreview); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_SetReverseCulling(IntPtr self, bool reverseCulling); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_SetSectionPreview(IntPtr self, int inSectionIndexPreview); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_SetStaticLightingMapping(IntPtr self, bool bTextureMapping, int resolutionToUse); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_SupportsDefaultCollision(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UStaticMeshComponent_UpdateCollisionFromStaticMesh(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UStaticMeshComponent_UsesTextureLightmaps(IntPtr self, int inWidth, int inHeight); #endregion #region Property /// <summary> /// Whether to use the mesh distance field representation (when present) for shadowing indirect lighting (from lightmaps or skylight) on Movable components. /// <para>This works like capsule shadows on skeletal meshes, except using the mesh distance field so no physics asset is required. </para> /// The StaticMesh must have 'Generate Mesh Distance Field' enabled, or the project must have 'Generate Mesh Distance Fields' enabled for this feature to work. /// </summary> public byte DistanceFieldIndirectShadow { get => E_PROP_UStaticMeshComponent_bCastDistanceFieldIndirectShadow_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bCastDistanceFieldIndirectShadow_SET(NativePointer, value); } /// <summary> /// If true, mesh painting is disallowed on this instance. Set if vertex colors are overridden in a construction script. /// </summary> public byte bDisallowMeshPaintPerInstance { get => E_PROP_UStaticMeshComponent_bDisallowMeshPaintPerInstance_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bDisallowMeshPaintPerInstance_SET(NativePointer, value); } /// <summary> /// Draw mesh collision if used for complex collision /// </summary> public byte bDrawMeshCollisionIfComplex { get => E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfComplex_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfComplex_SET(NativePointer, value); } /// <summary> /// Draw mesh collision if used for simple collision /// </summary> public byte bDrawMeshCollisionIfSimple { get => E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfSimple_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bDrawMeshCollisionIfSimple_SET(NativePointer, value); } public byte bForceNavigationObstacle { get => E_PROP_UStaticMeshComponent_bForceNavigationObstacle_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bForceNavigationObstacle_SET(NativePointer, value); } /// <summary> /// Ignore this instance of this static mesh when calculating streaming information. /// <para>This can be useful when doing things like applying character textures to static geometry, </para> /// to avoid them using distance-based streaming. /// </summary> public byte bIgnoreInstanceForTextureStreaming { get => E_PROP_UStaticMeshComponent_bIgnoreInstanceForTextureStreaming_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bIgnoreInstanceForTextureStreaming_SET(NativePointer, value); } /// <summary> /// Whether to override the DistanceFieldSelfShadowBias setting of the static mesh asset with the DistanceFieldSelfShadowBias of this component. /// </summary> public byte bOverrideDistanceFieldSelfShadowBias { get => E_PROP_UStaticMeshComponent_bOverrideDistanceFieldSelfShadowBias_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bOverrideDistanceFieldSelfShadowBias_SET(NativePointer, value); } /// <summary> /// Whether to override the lightmap resolution defined in the static mesh. /// </summary> public byte bOverrideLightMapRes { get => E_PROP_UStaticMeshComponent_bOverrideLightMapRes_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bOverrideLightMapRes_SET(NativePointer, value); } /// <summary> /// Whether to override the MinLOD setting of the static mesh asset with the MinLOD of this component. /// </summary> public byte bOverrideMinLOD { get => E_PROP_UStaticMeshComponent_bOverrideMinLOD_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bOverrideMinLOD_SET(NativePointer, value); } public byte bOverrideNavigationExport { get => E_PROP_UStaticMeshComponent_bOverrideNavigationExport_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bOverrideNavigationExport_SET(NativePointer, value); } /// <summary> /// If true, WireframeColorOverride will be used. If false, color is determined based on mobility and physics simulation settings /// </summary> public byte bOverrideWireframeColor { get => E_PROP_UStaticMeshComponent_bOverrideWireframeColor_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bOverrideWireframeColor_SET(NativePointer, value); } /// <summary> /// Controls whether the static mesh component's backface culling should be reversed /// </summary> public byte bReverseCulling { get => E_PROP_UStaticMeshComponent_bReverseCulling_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bReverseCulling_SET(NativePointer, value); } /// <summary> /// Use the collision profile specified in the StaticMesh asset. /// </summary> public byte bUseDefaultCollision { get => E_PROP_UStaticMeshComponent_bUseDefaultCollision_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bUseDefaultCollision_SET(NativePointer, value); } public byte bUseSubDivisions { get => E_PROP_UStaticMeshComponent_bUseSubDivisions_GET(NativePointer); set => E_PROP_UStaticMeshComponent_bUseSubDivisions_SET(NativePointer, value); } /// <summary> /// Controls how dark the dynamic indirect shadow can be. /// </summary> public float DistanceFieldIndirectShadowMinVisibility { get => E_PROP_UStaticMeshComponent_DistanceFieldIndirectShadowMinVisibility_GET(NativePointer); set => E_PROP_UStaticMeshComponent_DistanceFieldIndirectShadowMinVisibility_SET(NativePointer, value); } /// <summary> /// Useful for reducing self shadowing from distance field methods when using world position offset to animate the mesh's vertices. /// </summary> public float DistanceFieldSelfShadowBias { get => E_PROP_UStaticMeshComponent_DistanceFieldSelfShadowBias_GET(NativePointer); set => E_PROP_UStaticMeshComponent_DistanceFieldSelfShadowBias_SET(NativePointer, value); } /// <summary> /// If 0, auto-select LOD level. if >0, force to (ForcedLodModel-1). /// </summary> public int ForcedLodModel { get => E_PROP_UStaticMeshComponent_ForcedLodModel_GET(NativePointer); set => E_PROP_UStaticMeshComponent_ForcedLodModel_SET(NativePointer, value); } /// <summary> /// The Lightmass settings for this object. /// </summary> public FLightmassPrimitiveSettings LightmassSettings { get => E_PROP_UStaticMeshComponent_LightmassSettings_GET(NativePointer); set => E_PROP_UStaticMeshComponent_LightmassSettings_SET(NativePointer, value); } /// <summary> /// Specifies the smallest LOD that will be used for this component. /// <para>This is ignored if ForcedLodModel is enabled. </para> /// </summary> public int MinLOD { get => E_PROP_UStaticMeshComponent_MinLOD_GET(NativePointer); set => E_PROP_UStaticMeshComponent_MinLOD_SET(NativePointer, value); } /// <summary> /// Light map resolution to use on this component, used if bOverrideLightMapRes is true and there is a valid StaticMesh. /// </summary> public int OverriddenLightMapRes { get => E_PROP_UStaticMeshComponent_OverriddenLightMapRes_GET(NativePointer); set => E_PROP_UStaticMeshComponent_OverriddenLightMapRes_SET(NativePointer, value); } public int PreviousLODLevel { get => E_PROP_UStaticMeshComponent_PreviousLODLevel_GET(NativePointer); set => E_PROP_UStaticMeshComponent_PreviousLODLevel_SET(NativePointer, value); } /// <summary> /// Allows adjusting the desired streaming distance of streaming textures that uses UV 0. /// <para>1.0 is the default, whereas a higher value makes the textures stream in sooner from far away. </para> /// A lower value (0.0-1.0) makes the textures stream in later (you have to be closer). /// <para>Value can be < 0 (from legcay content, or code changes) </para> /// </summary> public float StreamingDistanceMultiplier { get => E_PROP_UStaticMeshComponent_StreamingDistanceMultiplier_GET(NativePointer); set => E_PROP_UStaticMeshComponent_StreamingDistanceMultiplier_SET(NativePointer, value); } public int SubDivisionStepSize { get => E_PROP_UStaticMeshComponent_SubDivisionStepSize_GET(NativePointer); set => E_PROP_UStaticMeshComponent_SubDivisionStepSize_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Save off the data painted on to this mesh per LOD if necessary /// </summary> public void CachePaintedDataIfNecessary() => E_UStaticMeshComponent_CachePaintedDataIfNecessary(this); /// <summary> /// Copies instance vertex colors from the SourceComponent into this component /// </summary> /// <param name="sourceComponent">The component to copy vertex colors from</param> public void CopyInstanceVertexColorsIfCompatible(UStaticMeshComponent sourceComponent) => E_UStaticMeshComponent_CopyInstanceVertexColorsIfCompatible(this, sourceComponent); /// <summary> /// Update the vertex override colors if necessary (i.e. vertices from source mesh have changed from override colors) /// <para>@returns true if any fixup was performed. </para> /// </summary> /// <param name="bRebuildingStaticMesh">true if we are rebuilding the static mesh used by this component</param> public bool FixupOverrideColorsIfNecessary(bool bRebuildingStaticMesh = false) => E_UStaticMeshComponent_FixupOverrideColorsIfNecessary(this, bRebuildingStaticMesh); /// <summary> /// Get this components index in its parents blueprint created components array (used for matching instance data) /// </summary> public int GetBlueprintCreatedComponentIndex() => E_UStaticMeshComponent_GetBlueprintCreatedComponentIndex(this); /// <summary> /// Returns the light and shadow map memory for this primite in its out variables. /// <para>Shadow map memory usage is per light whereof lightmap data is independent of number of lights, assuming at least one. </para> /// </summary> /// <param name="@out">TextureLightMapMemoryUsage Estimated memory usage in bytes for light map texel data</param> /// <param name="@out">TextureShadowMapMemoryUsage Estimated memory usage in bytes for shadow map texel data</param> /// <param name="@out">VertexLightMapMemoryUsage Estimated memory usage in bytes for light map vertex data</param> /// <param name="@out">VertexShadowMapMemoryUsage Estimated memory usage in bytes for shadow map vertex data</param> /// <param name="@out">StaticLightingResolution The StaticLightingResolution used for Texture estimates</param> /// <param name="@out">bIsUsingTextureMapping Set to true if the mesh is using texture mapping currently; false if vertex</param> /// <param name="@out">bHasLightmapTexCoords Set to true if the mesh has the proper UV channels</param> /// <return>bool</return> public virtual bool GetEstimatedLightAndShadowMapMemoryUsage(int textureLightMapMemoryUsage, int textureShadowMapMemoryUsage, int vertexLightMapMemoryUsage, int vertexShadowMapMemoryUsage, int staticLightingResolution, bool bIsUsingTextureMapping, bool bHasLightmapTexCoords) => E_UStaticMeshComponent_GetEstimatedLightAndShadowMapMemoryUsage(this, textureLightMapMemoryUsage, textureShadowMapMemoryUsage, vertexLightMapMemoryUsage, vertexShadowMapMemoryUsage, staticLightingResolution, bIsUsingTextureMapping, bHasLightmapTexCoords); /// <summary> /// Returns the lightmap resolution used for this primitive instance in the case of it supporting texture light/ shadow maps. /// <para>This will return the value assuming the primitive will be automatically switched to use texture mapping. </para> /// </summary> /// <param name="width">out] Width of light/shadow map</param> /// <param name="height">out] Height of light/shadow map</param> public virtual void GetEstimatedLightMapResolution(int width, int height) => E_UStaticMeshComponent_GetEstimatedLightMapResolution(this, width, height); /// <summary> /// Get Local bounds /// </summary> public void GetLocalBounds(FVector min, FVector max) => E_UStaticMeshComponent_GetLocalBounds(this, min, max); /// <summary> /// Helper function to get the FName of the private static mesh member /// </summary> public string GetMemberNameChecked_StaticMesh() => E_UStaticMeshComponent_GetMemberNameChecked_StaticMesh(this); /// <summary> /// Get the memory used for texture-based light and shadow maps of the given width and height /// </summary> /// <param name="inWidth">The desired width of the light/shadow map</param> /// <param name="inHeight">The desired height of the light/shadow map</param> /// <param name="outLightMapMemoryUsage">The resulting lightmap memory used</param> /// <param name="outShadowMapMemoryUsage">The resulting shadowmap memory used</param> public virtual void GetTextureLightAndShadowMapMemoryUsage(int inWidth, int inHeight, int outLightMapMemoryUsage, int outShadowMapMemoryUsage) => E_UStaticMeshComponent_GetTextureLightAndShadowMapMemoryUsage(this, inWidth, inHeight, outLightMapMemoryUsage, outShadowMapMemoryUsage); /// <summary> /// Get the scale comming form the component, when computing StreamingTexture data. Used to support instanced meshes. /// </summary> public virtual float GetTextureStreamingTransformScale() => E_UStaticMeshComponent_GetTextureStreamingTransformScale(this); /// <summary> /// Returns true if the static mesh the component uses has valid lightmap texture coordinates /// </summary> public virtual bool HasLightmapTextureCoordinates() => E_UStaticMeshComponent_HasLightmapTextureCoordinates(this); public void ReleaseResources() => E_UStaticMeshComponent_ReleaseResources(this); /// <summary> /// Removes instance vertex colors from all LODs /// </summary> public void RemoveInstanceVertexColors() => E_UStaticMeshComponent_RemoveInstanceVertexColors(this); /// <summary> /// Removes instance vertex colors from the specified LOD /// </summary> /// <param name="lODToRemoveColorsFrom">Index of the LOD to remove instance colors from</param> public void RemoveInstanceVertexColorsFromLOD(int lODToRemoveColorsFrom) => E_UStaticMeshComponent_RemoveInstanceVertexColorsFromLOD(this, lODToRemoveColorsFrom); /// <summary> /// Determines whether any of the component's LODs require override vertex color fixups /// </summary> /// <return>true</return> public bool RequiresOverrideVertexColorsFixup() => E_UStaticMeshComponent_RequiresOverrideVertexColorsFixup(this); /// <summary> /// Sets the component's DistanceFieldSelfShadowBias. bOverrideDistanceFieldSelfShadowBias must be enabled for this to have an effect. /// </summary> public void SetDistanceFieldSelfShadowBias(float newValue) => E_UStaticMeshComponent_SetDistanceFieldSelfShadowBias(this, newValue); public void SetForcedLodModel(int newForcedLodModel) => E_UStaticMeshComponent_SetForcedLodModel(this, newForcedLodModel); /// <summary> /// Sets the value of the MaterialIndexPreview flag and reattaches the component as necessary. /// </summary> /// <param name="inMaterialIndexPreview">New value of MaterialIndexPreview.</param> public void SetMaterialPreview(int inMaterialIndexPreview) => E_UStaticMeshComponent_SetMaterialPreview(this, inMaterialIndexPreview); /// <summary> /// Set forced reverse culling /// </summary> public void SetReverseCulling(bool reverseCulling) => E_UStaticMeshComponent_SetReverseCulling(this, reverseCulling); /// <summary> /// Sets the value of the SectionIndexPreview flag and reattaches the component as necessary. /// </summary> /// <param name="inSectionIndexPreview">New value of SectionIndexPreview.</param> public void SetSectionPreview(int inSectionIndexPreview) => E_UStaticMeshComponent_SetSectionPreview(this, inSectionIndexPreview); /// <summary> /// Switches the static mesh component to use either Texture or Vertex static lighting. /// <para>If false, set it to use vertex light mapping. </para> /// If false, set it to use vertex light mapping. /// </summary> /// <param name="bTextureMapping">If true, set the component to use texture light mapping.</param> /// <param name="resolutionToUse">If != 0, set the resolution to the given value.</param> /// <return>bool</return> public virtual bool SetStaticLightingMapping(bool bTextureMapping, int resolutionToUse) => E_UStaticMeshComponent_SetStaticLightingMapping(this, bTextureMapping, resolutionToUse); /// <summary> /// Whether or not the component supports default collision from its static mesh asset /// </summary> public virtual bool SupportsDefaultCollision() => E_UStaticMeshComponent_SupportsDefaultCollision(this); /// <summary> /// Sets the BodyInstance to use the mesh's body setup for external collision information /// </summary> public void UpdateCollisionFromStaticMesh() => E_UStaticMeshComponent_UpdateCollisionFromStaticMesh(this); /// <summary> /// Returns true if the component uses texture lightmaps /// </summary> /// <param name="inWidth">in] The width of the light/shadow map</param> /// <param name="inHeight">in] The width of the light/shadow map</param> /// <return>bool</return> public virtual bool UsesTextureLightmaps(int inWidth, int inHeight) => E_UStaticMeshComponent_UsesTextureLightmaps(this, inWidth, inHeight); #endregion public static implicit operator IntPtr(UStaticMeshComponent self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator UStaticMeshComponent(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<UStaticMeshComponent>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Linq; using Marten.Schema; using Marten.Schema.Identity; using Marten.Services; using Marten.Services.Includes; using Marten.Storage; using Marten.Util; using Npgsql; using NpgsqlTypes; using Remotion.Linq; namespace Marten.Events { public abstract class EventMapping : IDocumentMapping, IQueryableDocument { private readonly StoreOptions _options; private readonly EventGraph _parent; protected readonly DocumentMapping _inner; protected EventMapping(EventGraph parent, Type eventType) { _options = parent.Options; _parent = parent; DocumentType = eventType; EventTypeName = Alias = DocumentType.Name.ToTableAlias(); IdMember = DocumentType.GetProperty(nameof(IEvent.Id)); _inner = new DocumentMapping(eventType, parent.Options); } public Type DocumentType { get; } public string EventTypeName { get; set; } public string Alias { get; } public MemberInfo IdMember { get; } public NpgsqlDbType IdType { get; } = NpgsqlDbType.Uuid; Type IDocumentMapping.IdType => typeof(Guid); public DbObjectName Table => new DbObjectName(_options.Events.DatabaseSchemaName, "mt_events"); public DuplicatedField[] DuplicatedFields { get; } public DeleteStyle DeleteStyle { get; } public string DatabaseSchemaName { get { return _options.Events.DatabaseSchemaName; } set { throw new NotSupportedException("The DatabaseSchemaName of Event can't be set."); } } public PropertySearching PropertySearching { get; } = PropertySearching.JSON_Locator_Only; public string[] SelectFields() { return new[] {"id", "data"}; } public IField FieldFor(IEnumerable<MemberInfo> members) { return _inner.FieldFor(members); } public IWhereFragment FilterDocuments(QueryModel model, IWhereFragment query) { return new CompoundWhereFragment("and", DefaultWhereFragment(), query); } public IWhereFragment DefaultWhereFragment() { return new WhereFragment($"d.type = '{EventTypeName}'"); } public abstract IDocumentStorage BuildStorage(StoreOptions options); public void DeleteAllDocuments(ITenant factory) { factory.RunSql($"delete from mt_events where type = '{Alias}'"); } public IdAssignment<T> ToIdAssignment<T>(ITenant tenant) { throw new NotSupportedException(); } public IQueryableDocument ToQueryableDocument() { return this; } public IncludeJoin<TOther> JoinToInclude<TOther>(JoinType joinType, IQueryableDocument other, MemberInfo[] members, Action<TOther> callback) { return _inner.JoinToInclude<TOther>(joinType, other, members, callback); } } public class EventMapping<T> : EventMapping, IDocumentStorage<T> where T : class { private readonly string _tableName; public EventMapping(EventGraph parent) : base(parent, typeof(T)) { var schemaName = parent.DatabaseSchemaName; _tableName = schemaName == StoreOptions.DefaultDatabaseSchemaName ? "mt_events" : $"{schemaName}.mt_events"; } public override IDocumentStorage BuildStorage(StoreOptions options) { return this; } public NpgsqlCommand LoaderCommand(object id) { return new NpgsqlCommand($"select d.data, d.id from {_tableName} as d where id = :id and type = '{Alias}'").With("id", id); } public NpgsqlCommand LoadByArrayCommand<TKey>(TenancyStyle tenancyStyle, TKey[] ids) { return new NpgsqlCommand($"select d.data, d.id from {_tableName} as d where id = ANY(:ids) and type = '{Alias}'").With("ids", ids); } public object Identity(object document) { return document.As<IEvent>().Id; } public void RegisterUpdate(UpdateBatch batch, object entity) { // Do nothing } public void RegisterUpdate(UpdateBatch batch, object entity, string json) { // Do nothing } public void Remove(IIdentityMap map, object entity) { throw new InvalidOperationException("Use IDocumentSession.Events for all persistence of IEvent objects"); } public void Delete(IIdentityMap map, object id) { throw new InvalidOperationException("Use IDocumentSession.Events for all persistence of IEvent objects"); } public void Store(IIdentityMap map, object id, object entity) { throw new InvalidOperationException("Use IDocumentSession.Events for all persistence of IEvent objects"); } public IStorageOperation DeletionForId(TenancyStyle tenancyStyle, object id) { throw new NotSupportedException("You cannot delete events at this time"); } public IStorageOperation DeletionForEntity(TenancyStyle tenancyStyle, object entity) { throw new NotSupportedException("You cannot delete events at this time"); } public IStorageOperation DeletionForWhere(IWhereFragment @where, TenancyStyle tenancyStyle) { throw new NotSupportedException("You cannot delete events at this time"); } public T Resolve(int startingIndex, DbDataReader reader, IIdentityMap map) { var id = reader.GetGuid(startingIndex); var json = reader.GetTextReader(startingIndex + 1); return map.Get<T>(id, json, null); } public async Task<T> ResolveAsync(int startingIndex, DbDataReader reader, IIdentityMap map, CancellationToken token) { var id = await reader.GetFieldValueAsync<Guid>(startingIndex, token).ConfigureAwait(false); // TODO -- DO NOT LIKE THIS. Ask the Npgsql guys if this is okay var json = reader.GetTextReader(startingIndex + 1); //var json = await reader.GetFieldValueAsync<string>(1, token).ConfigureAwait(false); return map.Get<T>(id, json, null); } public FetchResult<T> Fetch(DbDataReader reader, ISerializer serializer) { if (!reader.Read()) return null; var json = reader.GetTextReader(0); var doc = serializer.FromJson<T>(json); return new FetchResult<T>(doc, json, null); } public async Task<FetchResult<T>> FetchAsync(DbDataReader reader, ISerializer serializer, CancellationToken token) { var found = await reader.ReadAsync(token).ConfigureAwait(false); if (!found) return null; var json = reader.GetTextReader(0); //var json = await reader.GetFieldValueAsync<string>(0, token).ConfigureAwait(false); var doc = serializer.FromJson<T>(json); return new FetchResult<T>(doc, json, null); } public T Resolve(IIdentityMap map, ILoader loader, object id) { return map.Get(id, () => loader.LoadDocument<T>(id)); } public Task<T> ResolveAsync(IIdentityMap map, ILoader loader, CancellationToken token, object id) { return map.GetAsync(id, tkn => loader.LoadDocumentAsync<T>(id, tkn), token); } } }
// Shared source file using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace NuGetMirror { internal class TaskUtils { /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), token: CancellationToken.None); } /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks, CancellationToken token) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), useTaskRun: false, token: token); } /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks, bool useTaskRun, CancellationToken token) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), useTaskRun: false, token: token); } /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks, bool useTaskRun, int maxThreads, CancellationToken token) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), useTaskRun: false, maxThreads: maxThreads, token: token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks) { return RunAsync(tasks, CancellationToken.None); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks, CancellationToken token) { return RunAsync(tasks, useTaskRun: false, token: token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks, bool useTaskRun, CancellationToken token) { var maxThreads = Environment.ProcessorCount * 2; return RunAsync(tasks, useTaskRun, maxThreads, token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks, bool useTaskRun, int maxThreads, CancellationToken token) { return RunAsync(tasks, useTaskRun, maxThreads, DefaultProcess, token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public async static Task<R[]> RunAsync<T, R>(IEnumerable<Func<Task<T>>> tasks, bool useTaskRun, int maxThreads, Func<Task<T>, Task<R>> process, CancellationToken token) { var toRun = new ConcurrentQueue<WorkItem<T>>(); var index = 0; foreach (var task in tasks) { // Create work items, save the original position. toRun.Enqueue(new WorkItem<T>(task, index)); index++; } var totalCount = index; // Create an array for the results, at this point index is the count. var results = new R[totalCount]; List<Task> threads = null; var taskCount = GetAdditionalThreadCount(maxThreads, totalCount); if (taskCount > 0) { threads = new List<Task>(taskCount); // Create long running tasks to run work on. for (var i = 0; i < taskCount; i++) { Task task = null; if (useTaskRun) { // Start a new task task = Task.Run(() => RunTaskAsync(toRun, results, process, token)); } else { // Run directly task = RunTaskAsync(toRun, results, process, token); } threads.Add(task); } } // Run tasks on the current thread // This is used both for parallel and non-parallel. await RunTaskAsync(toRun, results, process, token); // After all work completes on this thread, wait for the rest. if (threads != null) { await Task.WhenAll(threads); } return results; } private static int GetAdditionalThreadCount(int maxThreads, int index) { // Number of threads total var x = Math.Min(index, maxThreads); // Remove one for the current thread x--; // Avoid -1 x = Math.Max(0, x); return x; } /// <summary> /// Run tasks on a single thread. /// </summary> private static async Task RunTaskAsync<T, R>(ConcurrentQueue<WorkItem<T>> toRun, R[] results, Func<Task<T>, Task<R>> process, CancellationToken token) { // Run until cancelled or we are out of work. while (!token.IsCancellationRequested && toRun.TryDequeue(out var item)) { var result = await process(item.Item()); results[item.Index] = result; } } private static Task<T> DefaultProcess<T>(Task<T> result) { return result; } private static Func<Task<bool>> GetFuncWithReturnValue(Func<Task> task) { return new Func<Task<bool>>(() => { return RunWithReturnValue(task); }); } private static async Task<bool> RunWithReturnValue(Func<Task> task) { await task(); return true; } /// <summary> /// Contains a Func to run and the original position in the queue. /// </summary> private sealed class WorkItem<T> { internal Func<Task<T>> Item { get; } internal int Index { get; } public WorkItem(Func<Task<T>> item, int index) { Item = item; Index = index; } } } }
// 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! namespace Google.Cloud.Talent.V4Beta1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedTenantServiceClientSnippets { /// <summary>Snippet for CreateTenant</summary> public void CreateTenantRequestObject() { // Snippet: CreateTenant(CreateTenantRequest, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; // Make the request Tenant response = tenantServiceClient.CreateTenant(request); // End snippet } /// <summary>Snippet for CreateTenantAsync</summary> public async Task CreateTenantRequestObjectAsync() { // Snippet: CreateTenantAsync(CreateTenantRequest, CallSettings) // Additional: CreateTenantAsync(CreateTenantRequest, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; // Make the request Tenant response = await tenantServiceClient.CreateTenantAsync(request); // End snippet } /// <summary>Snippet for CreateTenant</summary> public void CreateTenant() { // Snippet: CreateTenant(string, Tenant, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Tenant tenant = new Tenant(); // Make the request Tenant response = tenantServiceClient.CreateTenant(parent, tenant); // End snippet } /// <summary>Snippet for CreateTenantAsync</summary> public async Task CreateTenantAsync() { // Snippet: CreateTenantAsync(string, Tenant, CallSettings) // Additional: CreateTenantAsync(string, Tenant, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Tenant tenant = new Tenant(); // Make the request Tenant response = await tenantServiceClient.CreateTenantAsync(parent, tenant); // End snippet } /// <summary>Snippet for CreateTenant</summary> public void CreateTenantResourceNames() { // Snippet: CreateTenant(ProjectName, Tenant, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Tenant tenant = new Tenant(); // Make the request Tenant response = tenantServiceClient.CreateTenant(parent, tenant); // End snippet } /// <summary>Snippet for CreateTenantAsync</summary> public async Task CreateTenantResourceNamesAsync() { // Snippet: CreateTenantAsync(ProjectName, Tenant, CallSettings) // Additional: CreateTenantAsync(ProjectName, Tenant, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Tenant tenant = new Tenant(); // Make the request Tenant response = await tenantServiceClient.CreateTenantAsync(parent, tenant); // End snippet } /// <summary>Snippet for GetTenant</summary> public void GetTenantRequestObject() { // Snippet: GetTenant(GetTenantRequest, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; // Make the request Tenant response = tenantServiceClient.GetTenant(request); // End snippet } /// <summary>Snippet for GetTenantAsync</summary> public async Task GetTenantRequestObjectAsync() { // Snippet: GetTenantAsync(GetTenantRequest, CallSettings) // Additional: GetTenantAsync(GetTenantRequest, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; // Make the request Tenant response = await tenantServiceClient.GetTenantAsync(request); // End snippet } /// <summary>Snippet for GetTenant</summary> public void GetTenant() { // Snippet: GetTenant(string, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]"; // Make the request Tenant response = tenantServiceClient.GetTenant(name); // End snippet } /// <summary>Snippet for GetTenantAsync</summary> public async Task GetTenantAsync() { // Snippet: GetTenantAsync(string, CallSettings) // Additional: GetTenantAsync(string, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]"; // Make the request Tenant response = await tenantServiceClient.GetTenantAsync(name); // End snippet } /// <summary>Snippet for GetTenant</summary> public void GetTenantResourceNames() { // Snippet: GetTenant(TenantName, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); // Make the request Tenant response = tenantServiceClient.GetTenant(name); // End snippet } /// <summary>Snippet for GetTenantAsync</summary> public async Task GetTenantResourceNamesAsync() { // Snippet: GetTenantAsync(TenantName, CallSettings) // Additional: GetTenantAsync(TenantName, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); // Make the request Tenant response = await tenantServiceClient.GetTenantAsync(name); // End snippet } /// <summary>Snippet for UpdateTenant</summary> public void UpdateTenantRequestObject() { // Snippet: UpdateTenant(UpdateTenantRequest, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new FieldMask(), }; // Make the request Tenant response = tenantServiceClient.UpdateTenant(request); // End snippet } /// <summary>Snippet for UpdateTenantAsync</summary> public async Task UpdateTenantRequestObjectAsync() { // Snippet: UpdateTenantAsync(UpdateTenantRequest, CallSettings) // Additional: UpdateTenantAsync(UpdateTenantRequest, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new FieldMask(), }; // Make the request Tenant response = await tenantServiceClient.UpdateTenantAsync(request); // End snippet } /// <summary>Snippet for UpdateTenant</summary> public void UpdateTenant() { // Snippet: UpdateTenant(Tenant, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) Tenant tenant = new Tenant(); // Make the request Tenant response = tenantServiceClient.UpdateTenant(tenant); // End snippet } /// <summary>Snippet for UpdateTenantAsync</summary> public async Task UpdateTenantAsync() { // Snippet: UpdateTenantAsync(Tenant, CallSettings) // Additional: UpdateTenantAsync(Tenant, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) Tenant tenant = new Tenant(); // Make the request Tenant response = await tenantServiceClient.UpdateTenantAsync(tenant); // End snippet } /// <summary>Snippet for DeleteTenant</summary> public void DeleteTenantRequestObject() { // Snippet: DeleteTenant(DeleteTenantRequest, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; // Make the request tenantServiceClient.DeleteTenant(request); // End snippet } /// <summary>Snippet for DeleteTenantAsync</summary> public async Task DeleteTenantRequestObjectAsync() { // Snippet: DeleteTenantAsync(DeleteTenantRequest, CallSettings) // Additional: DeleteTenantAsync(DeleteTenantRequest, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; // Make the request await tenantServiceClient.DeleteTenantAsync(request); // End snippet } /// <summary>Snippet for DeleteTenant</summary> public void DeleteTenant() { // Snippet: DeleteTenant(string, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]"; // Make the request tenantServiceClient.DeleteTenant(name); // End snippet } /// <summary>Snippet for DeleteTenantAsync</summary> public async Task DeleteTenantAsync() { // Snippet: DeleteTenantAsync(string, CallSettings) // Additional: DeleteTenantAsync(string, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]"; // Make the request await tenantServiceClient.DeleteTenantAsync(name); // End snippet } /// <summary>Snippet for DeleteTenant</summary> public void DeleteTenantResourceNames() { // Snippet: DeleteTenant(TenantName, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); // Make the request tenantServiceClient.DeleteTenant(name); // End snippet } /// <summary>Snippet for DeleteTenantAsync</summary> public async Task DeleteTenantResourceNamesAsync() { // Snippet: DeleteTenantAsync(TenantName, CallSettings) // Additional: DeleteTenantAsync(TenantName, CancellationToken) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) TenantName name = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); // Make the request await tenantServiceClient.DeleteTenantAsync(name); // End snippet } /// <summary>Snippet for ListTenants</summary> public void ListTenantsRequestObject() { // Snippet: ListTenants(ListTenantsRequest, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) ListTenantsRequest request = new ListTenantsRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenants(request); // Iterate over all response items, lazily performing RPCs as required foreach (Tenant 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 (ListTenantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Tenant 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<Tenant> 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 (Tenant 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 ListTenantsAsync</summary> public async Task ListTenantsRequestObjectAsync() { // Snippet: ListTenantsAsync(ListTenantsRequest, CallSettings) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) ListTenantsRequest request = new ListTenantsRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenantsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Tenant 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((ListTenantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Tenant 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<Tenant> 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 (Tenant 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 ListTenants</summary> public void ListTenants() { // Snippet: ListTenants(string, string, int?, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenants(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Tenant 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 (ListTenantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Tenant 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<Tenant> 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 (Tenant 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 ListTenantsAsync</summary> public async Task ListTenantsAsync() { // Snippet: ListTenantsAsync(string, string, int?, CallSettings) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedAsyncEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenantsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Tenant 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((ListTenantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Tenant 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<Tenant> 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 (Tenant 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 ListTenants</summary> public void ListTenantsResourceNames() { // Snippet: ListTenants(ProjectName, string, int?, CallSettings) // Create client TenantServiceClient tenantServiceClient = TenantServiceClient.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenants(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Tenant 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 (ListTenantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Tenant 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<Tenant> 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 (Tenant 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 ListTenantsAsync</summary> public async Task ListTenantsResourceNamesAsync() { // Snippet: ListTenantsAsync(ProjectName, string, int?, CallSettings) // Create client TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListTenantsResponse, Tenant> response = tenantServiceClient.ListTenantsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Tenant 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((ListTenantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Tenant 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<Tenant> 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 (Tenant 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 } } }