示例#1
0
 /// <inheritdoc/>
 public void DeepCopy(Queue <T> input, Queue <T> output, CopyContext context)
 {
     foreach (var item in input)
     {
         output.Enqueue(_copier.DeepCopy(item, context));
     }
 }
示例#2
0
        public ReadOnlyMemory <T> DeepCopy(ReadOnlyMemory <T> input, CopyContext context)
        {
            if (input.IsEmpty)
            {
                return(input);
            }

            var inputSpan = input.Span;
            var result    = new T[inputSpan.Length];

            // Note that there is a possibility for unbounded recursion if the underlying object in the input is
            // able to take part in a cyclic reference. If we could get that object then we could prevent that cycle.
            // It is also possible that an IMemoryOwner<T> is the backing object, in which case this will not work.
            if (MemoryMarshal.TryGetArray(input, out var segment))
            {
                context.RecordCopy(segment.Array, result);
            }

            for (var i = 0; i < inputSpan.Length; i++)
            {
                result[i] = _elementCopier.DeepCopy(inputSpan[i], context);
            }

            return(result);
        }
示例#3
0
        /// <summary>
        /// This is a higher level function which uses InsertCopy function alongside with the knowledge of IFC schema to copy over
        /// products with their types and other related information (classification, aggregation, documents, properties) and optionally
        /// geometry. It will also bring in spatial hierarchy relevant to selected products. However, resulting model is not guaranteed
        /// to be compliant with any Model View Definition unless you explicitly check the compliance. Context of a single product tend to
        /// consist from hundreds of objects which need to be identified and copied over so this operation might be potentially expensive.
        /// You should never call this function more than once between two models. It not only selects objects to be copied over but also
        /// excludes other objects from being copied over so that it doesn't bring the entire model in a chain dependencies. This means
        /// that some objects are modified (like spatial relations) and won't get updated which would lead to an inconsistent copy.
        /// </summary>
        /// <param name="model">The target model</param>
        /// <param name="products">Products from other model to be inserted into this model</param>
        /// <param name="includeGeometry">If TRUE, geometry of the products will be copied over.</param>
        /// <param name="keepLabels">If TRUE, entity labels from original model will be used. Always set this to FALSE
        /// if you are going to insert products from multiple source models or if you are going to insert products to a non-empty model</param>
        /// <param name="mappings">Mappings to avoid multiple insertion of objects. Keep a single instance for insertion between two models.
        /// If you also use InsertCopy() function for some other insertions, use the same instance of mappings.</param>
        public static void InsertCopy(this IModel model, IEnumerable <IIfcProduct> products, bool includeGeometry, bool keepLabels,
                                      XbimInstanceHandleMap mappings)
        {
            var context = new CopyContext
            {
                IncludeGeometry = includeGeometry
            };

            var roots = products.Cast <IPersistEntity>().ToList();

            //return if there is nothing to insert
            if (!roots.Any())
            {
                return;
            }

            var source = roots.First().Model;

            if (source == model)
            {
                //don't do anything if the source and target are the same
                return;
            }

            var toInsert = GetEntitiesToInsert(context, source, roots);
            //create new cache is none is defined
            var cache = mappings ?? new XbimInstanceHandleMap(source, model);

            foreach (var entity in toInsert)
            {
                model.InsertCopy(entity, cache,
                                 (property, obj) => Filter(context, property, obj),
                                 true, keepLabels);
            }
        }
示例#4
0
        private static T Copy <T>(T source, CopyContext context)
        {
            if (context.TryGetCopy(source, out var existingCopy))
            {
                return((T)existingCopy);
            }

            if (!(source is Array sourceAsArray))
            {
                throw new InvalidCastException($"Cannot cast non-array type {source?.GetType()} to Array.");
            }

            var elementType = source.GetType().GetElementType();

            var rank    = sourceAsArray.Rank;
            var lengths = new int[rank];

            for (var i = 0; i < rank; i++)
            {
                lengths[i] = sourceAsArray.GetLength(i);
            }

            var target = Array.CreateInstance(elementType, lengths);

            context.RecordCopy(sourceAsArray, target);
            Array.Copy(sourceAsArray, target, sourceAsArray.Length);

            return((T)(object)target);
        }
示例#5
0
        private static List <T> Copy <T>(List <T> source, CopyContext context)
        {
            if (context.TryGetCopy(source, out var existingCopy))
            {
                return((List <T>)existingCopy);
            }

            var length = source.Count;
            var target = new List <T>(length);

            context.RecordCopy(source, target);

            for (var i = 0; i < length; i++)
            {
                T sourceItem = source[i];

                if (sourceItem != null)
                {
                    target.Add(Cloner <T> .Get(sourceItem, context));
                }
                else
                {
                    target.Add(sourceItem);
                }
            }

            return(target);
        }
示例#6
0
 /// <inheritdoc/>
 public void DeepCopy(List <T> input, List <T> output, CopyContext context)
 {
     foreach (var item in input)
     {
         output.Add(_copier.DeepCopy(item, context));
     }
 }
示例#7
0
    /// <inheritdoc/>
    object IDeepCopier <object> .DeepCopy(object input, CopyContext context)
    {
        if (input is null)
        {
            return(null);
        }

        var bufferWriter = new BufferWriterBox <PooledArrayBufferWriter>(new PooledArrayBufferWriter());

        using var jsonWriter = new Utf8JsonWriter(bufferWriter);
        JsonSerializer.Serialize(jsonWriter, input, _options.SerializerOptions);
        var sequence = bufferWriter.Value.RentReadOnlySequence();

        try
        {
            var jsonReader = new Utf8JsonReader(sequence, _options.ReaderOptions);
            var result     = JsonSerializer.Deserialize(ref jsonReader, input.GetType(), _options.SerializerOptions);
            context.RecordCopy(input, result);
            return(result);
        }
        finally
        {
            bufferWriter.Value.ReturnReadOnlySequence(sequence);
        }
    }
示例#8
0
        public void Clone <T>(CloneArguments <T> args)
        {
            args.Context = new Dictionary <object, object>(16, ReferenceEqualsComparer.Instance);
            CopyContext c = new CopyContext(args.Context);

            args.Target = Cloner <T> .Get(args.Source, c);
        }
示例#9
0
    /// <inheritdoc/>
    object IDeepCopier <object> .DeepCopy(object input, CopyContext context)
    {
        if (input is null)
        {
            return(null);
        }

        var stream = PooledBufferStream.Rent();

        try
        {
            var type = input.GetType();
            using var streamWriter = new StreamWriter(stream);
            using var textWriter   = new JsonTextWriter(streamWriter);
            _serializer.Serialize(textWriter, input, type);
            textWriter.Flush();

            stream.Position = 0;

            using var streamReader = new StreamReader(stream);
            using var jsonReader   = new JsonTextReader(streamReader);
            var result = _serializer.Deserialize(jsonReader, type);

            context.RecordCopy(input, result);
            return(result);
        }
        finally
        {
            PooledBufferStream.Return(stream);
        }
    }
示例#10
0
 private void CopyDirectory(string directoryPath, CopyContext context)
 {
     foreach (string filePath in TexoDirectory.GetFiles(directoryPath))
     {
         CopyFile(filePath, context);
     }
 }
示例#11
0
        private static string BuildOutput(CopyContext context)
        {
            MarkdownBuilder builder = new MarkdownBuilder();

            builder.Header("Copy");
            builder.Link(context.Destination, ActionBuilder.PathOpenUri(context.Destination));
            bool empty = true;

            if (context.CopiedFiles.Count > 0)
            {
                builder.Header("Copied", 2);
                builder.WritePathList(context.CopiedFiles, context.Destination);
                empty = false;
            }

            if (context.OverwritenFiles.Count > 0)
            {
                builder.Header("Overwriten");
                builder.WritePathList(context.OverwritenFiles, context.Destination);
                empty = false;
            }

            if (empty)
            {
                builder.WriteLine();
                builder.WriteLine();
                builder.Italic("Nothing copied.");
            }

            return(builder.ToString());
        }
示例#12
0
        private static T[,] Copy <T>(T[,] source, CopyContext context)
        {
            if (context.TryGetCopy(source, out var existingCopy))
            {
                return((T[, ])existingCopy);
            }

            var lenI   = source.GetLength(0);
            var lenJ   = source.GetLength(1);
            var target = new T[lenI, lenJ];

            context.RecordCopy(source, target);

            for (var i = 0; i < lenI; i++)
            {
                for (var j = 0; j < lenJ; j++)
                {
                    T sourceItem = source[i, j];

                    if (sourceItem != null)
                    {
                        target[i, j] = Cloner <T> .Get(sourceItem, context);
                    }
                }
            }

            return(target);
        }
示例#13
0
 /// <inheritdoc />
 public void DeepCopy(SortedSet <T> input, SortedSet <T> output, CopyContext context)
 {
     foreach (var element in input)
     {
         output.Add(_elementCopier.DeepCopy(element, context));
     }
 }
示例#14
0
        protected override T GetClone <T>(T source, int expectedCount)
        {
            CopyContext c      = new CopyContext();
            T           target = Cloner <T> .Get(source, c);

            Assert.Equal(expectedCount, c.GetCount());
            return(target);
        }
    /// <inheritdoc/>
    public TField DeepCopy(TField input, CopyContext context)
    {
        var surrogate = _converter.ConvertToSurrogate(in input);
        var copy      = _surrogateCopier.DeepCopy(surrogate, context);
        var result    = _converter.ConvertFromSurrogate(in copy);

        return(result);
    }
示例#16
0
 //#####################################################################################
 /// <summary>
 /// 构造函数,从已有对象创建
 /// </summary>
 /// <param name="existingInstance"></param>
 /// <param name="context"></param>
 private J2Evaluator(J2Evaluator existingInstance, CopyContext context)
     : base(existingInstance, context)
 {
     this.m_position  = existingInstance.m_position;
     this.m_gravity   = existingInstance.m_gravity;
     this.m_definedIn = context.UpdateReference <Axes>(existingInstance.m_definedIn);
     this.UpdateEvaluatorReferences(context);
 }
示例#17
0
        /// <inheritdoc/>
        public T?DeepCopy(T?input, CopyContext context)
        {
            if (!input.HasValue)
            {
                return(input);
            }

            return(new T?(_copier.DeepCopy(input.Value, context)));
        }
示例#18
0
        //#########################################################################################

        #region 构造函数
        /// <summary>
        /// 构造函数,缺省使用中心天体:地球(J2项系数为0)
        /// </summary>
        //public J2Gravity()
        //    : base(RoleOfForce.Principal, KindOfForce.NewtonianSpecificForce)
        //{
        //    CentralBodiesFacet fromContext = CentralBodiesFacet.GetFromContext();
        //    this.m_centralBody = fromContext.Earth;
        //    this.m_gravitationalParameter = WorldGeodeticSystem1984.GravitationalParameter;
        //    this.J2ZonalHarmonicCoefficient = 0.0;
        //    this.m_referenceDistance = m_centralBody.Shape.SemimajorAxisLength;
        //}

        /// <summary>
        /// 构造函数,缺省使用中心天体:地球(J2项系数为0)
        /// </summary>
        /// <param name="targetPoint">计算引力的瞬时点(位置、速度)</param>
        //public J2Gravity(Point targetPoint)
        //    : this()
        //{
        //    this.m_targetPoint = targetPoint;
        //}

        /// <summary>
        /// 构造函数,从已有对象复制
        /// </summary>
        /// <param name="existingInstance">已有对象</param>
        /// <param name="context">A CopyContext that controls the depth of the copy.</param>
        protected J2Gravity(J2Gravity existingInstance, CopyContext context)
            : base(existingInstance, context)
        {
            this.m_centralBody                = context.UpdateReference <CentralBody>(existingInstance.m_centralBody);
            this.m_gravitationalParameter     = existingInstance.m_gravitationalParameter;
            this.m_ignorePartials             = existingInstance.m_ignorePartials;
            this.m_targetPoint                = context.UpdateReference <Point>(existingInstance.m_targetPoint);
            this.m_j2ZonalHarmonicCoefficient = existingInstance.m_j2ZonalHarmonicCoefficient;
            this.m_referenceDistance          = existingInstance.m_referenceDistance;
        }
示例#19
0
        public object DeepCopy(object input, CopyContext context)
        {
            if (context.TryGetCopy <object>(input, out var result))
            {
                return(result);
            }

            ThrowNotNullException(input);
            return(null);
        }
示例#20
0
        /// <summary>
        /// Creates a deep copy of the provided input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="context">The context.</param>
        /// <returns>A copy of <paramref name="input" />.</returns>
        public static byte[] DeepCopy(byte[] input, CopyContext context)
        {
            if (context.TryGetCopy <byte[]>(input, out var result))
            {
                return(result);
            }

            result = new byte[input.Length];
            context.RecordCopy(input, result);
            input.CopyTo(result.AsSpan());
            return(result);
        }
示例#21
0
        public void SetUp()
        {
            _instance = Builder <PlanReceiptOrder> .CreateNew()
                        .WithConstructor(() => new PlanReceiptOrder(100))
                        .With(x => x.PlanCertificates, Builder <PlanCertificate> .CreateListOfSize(1).Build())
                        .Build();

            _instance.PlanCertificates[0].PlanReceiptOrder = _instance;

            _copyContext = new CopyContext <PlanReceiptOrder>();
            _copyContext.SetSourceValue(_instance);
        }
        private async Task<CopyContext> RequireContext(RootName root, string apiKey = null)
        {
            if (root == null)
                throw new ArgumentNullException(nameof(root));

            var result = default(CopyContext);
            if (!contextCache.TryGetValue(root, out result)) {
                var client = await OAuthAuthenticator.Login(root.UserName, apiKey);
                contextCache.Add(root, result = new CopyContext(client));
            }
            return result;
        }
示例#23
0
        public void Test2()
        {
            var cq  = new CertificateQuality(100);
            var doc = new AttachedDocument(100);

            doc.Content = ImagesConverter.ToByteArray(new Bitmap(@"D:\Repositories\HalfbloodApp\Halfblood.UnitTests\Halfblood.UnitTests\36.jpg"));
            cq.Documents.Add(doc);

            var context = new CopyContext <CertificateQuality>(cq);

            context.Commit();
        }
示例#24
0
        private static T[,] Copy <T>(T[,] source, CopyContext context)
        {
            if (context.TryGetCopy(source, out var existingCopy))
            {
                return((T[, ])existingCopy);
            }

            var result = new T[source.GetLength(0), source.GetLength(1)];

            context.RecordCopy(source, result);
            Array.Copy(source, result, source.Length);
            return(result);
        }
示例#25
0
        private static IEnumerable <IPersistEntity> GetEntitiesToInsert(CopyContext context, IModel model, List <IPersistEntity> roots)
        {
            context.PrimaryElements = roots.OfType <IIfcProduct>().ToList();

            //add any aggregated elements. For example IfcRoof is typically aggregation of one or more slabs so we need to bring
            //them along to have all the information both for geometry and for properties and materials.
            //This has to happen before we add spatial hierarchy or it would bring in full hierarchy which is not an intention
            var decompositionRels = GetAggregations(context, context.PrimaryElements.ToList(), model).ToList();

            context.PrimaryElements.AddRange(context.Decomposition);
            roots.AddRange(decompositionRels);

            //we should add spatial hierarchy right here so it brings its attributes as well
            var spatialRels = model.Instances.Where <IIfcRelContainedInSpatialStructure>(
                r => context.PrimaryElements.Any(e => r.RelatedElements.Contains(e))).ToList();
            var spatialRefs =
                model.Instances.Where <IIfcRelReferencedInSpatialStructure>(
                    r => context.PrimaryElements.Any(e => r.RelatedElements.Contains(e))).ToList();
            var bottomSpatialHierarchy =
                spatialRels.Select(r => r.RelatingStructure).Union(spatialRefs.Select(r => r.RelatingStructure)).ToList();
            var spatialAggregations = GetUpstreamHierarchy(bottomSpatialHierarchy, model).ToList();

            //add all spatial elements from bottom and from upstream hierarchy
            context.PrimaryElements.AddRange(bottomSpatialHierarchy);
            context.PrimaryElements.AddRange(spatialAggregations.Select(r => r.RelatingObject).OfType <IIfcProduct>());
            roots.AddRange(spatialAggregations);
            roots.AddRange(spatialRels);
            roots.AddRange(spatialRefs);

            //we should add any feature elements used to subtract mass from a product
            var featureRels = GetFeatureRelations(context.PrimaryElements).ToList();
            var openings    = featureRels.Select(r => r.RelatedOpeningElement);

            context.PrimaryElements.AddRange(openings);
            roots.AddRange(featureRels);

            //object types and properties for all primary products (elements and spatial elements)
            roots.AddRange(context.PrimaryElements.SelectMany(p => p.IsDefinedBy));
            roots.AddRange(context.PrimaryElements.SelectMany(p => p.IsTypedBy));



            //assignmnet to groups will bring in all system aggregarions if defined in the file
            roots.AddRange(context.PrimaryElements.SelectMany(p => p.HasAssignments));

            //associations with classification, material and documents
            roots.AddRange(context.PrimaryElements.SelectMany(p => p.HasAssociations));

            return(roots);
        }
示例#26
0
文件: Cloner.cs 项目: deipax/Deipax
        public static T Get(T source, CopyContext context)
        {
            if (source == null)
            {
                return(source);
            }
            var runtimeType = source.GetType();

            CloneDel <T> del = runtimeType == _type
                ? _del
                : _cache.GetOrAdd(runtimeType, _create);

            return(del(source, context));
        }
示例#27
0
    /// <inheritdoc/>
    public TField DeepCopy(TField input, CopyContext context)
    {
        if (context.TryGetCopy <TField>(input, out var result))
        {
            return(result);
        }

        var surrogate = _converter.ConvertToSurrogate(in input);
        var copy      = _surrogateCopier.DeepCopy(surrogate, context);

        result = _converter.ConvertFromSurrogate(in copy);

        context.RecordCopy(input, result);
        return(result);
    }
示例#28
0
        public Tuple <T> DeepCopy(Tuple <T> input, CopyContext context)
        {
            if (context.TryGetCopy(input, out Tuple <T> result))
            {
                return(result);
            }

            if (input.GetType() != typeof(Tuple <T>))
            {
                return(context.Copy(input));
            }

            result = new Tuple <T>(_copier.DeepCopy(input.Item1, context));
            context.RecordCopy(input, result);
            return(result);
        }
示例#29
0
 private static void DoCopy(CopyContext context, object source, object destination)
 {
     try
     {
         var get_set = context.Getters.Zip(context.Setters, (a, b) => new { get = a, set = b });
         foreach (var gs in get_set)
         {
             var val = gs.get.Invoke(source, null);
             gs.set.Invoke(destination, new[] { val });
         }
     }
     catch (Exception ex)
     {
         throw new InterfaceCopyException("An Exception occured during copying, please see inner exception", ex);
     }
 }
示例#30
0
        public T[] DeepCopy(T[] input, CopyContext context)
        {
            if (context.TryGetCopy <T[]>(input, out var result))
            {
                return(result);
            }

            result = new T[input.Length];
            context.RecordCopy(input, result);
            for (var i = 0; i < input.Length; i++)
            {
                result[i] = _elementCopier.DeepCopy(input[i], context);
            }

            return(result);
        }
示例#31
0
        private async Task <CopyContext> RequireContextAsync(RootName root, string apiKey = null)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var result = default(CopyContext);

            if (!contextCache.TryGetValue(root, out result))
            {
                var client = await OAuthAuthenticator.LoginAsync(root.UserName, apiKey, settingsPassPhrase);

                contextCache.Add(root, result = new CopyContext(client));
            }
            return(result);
        }
示例#32
0
        public object DeepCopy(object input, CopyContext context)
        {
            if (context.TryGetCopy <object>(input, out var result))
            {
                return(result);
            }

            var type = input.GetType();

            if (type != typeof(object))
            {
                return(context.Copy(input));
            }

            result = new object();
            context.RecordCopy(input, result);
            return(result);
        }
示例#33
0
        private static CopyContext CreateContext(CopyContext.CKey key)
        {
            try
            {
                var getters = new List<MethodInfo>();
                var setters = new List<MethodInfo>();

                var props = key.TCopy.Flatten(t => t.GetTypeInfo().GetInterfaces()).Distinct().SelectMany(i => i.GetRuntimeProperties()).Distinct((a, b) => a.Name == b.Name && a.PropertyType == b.PropertyType);
                foreach (var p in props)
                {
                    var getter = key.TSource.GetRuntimeProperty(p.Name).GetGetMethod();
                    var setter = key.TDestination.GetRuntimeProperty(p.Name).GetSetMethod();
                    getters.Add(getter);
                    setters.Add(setter);
                }

                return new CopyContext(key, getters, setters);
            }
            catch (Exception ex)
            {
                throw new InterfaceCopyException("Some error occured getting getters and setters, see inner exception", ex);
            }
        }