blob: 398ff171cdf94a4c3d188cab3cdc30bb15cb977c [file] [log] [blame]
Constantin Ziesche857c7ab2020-02-25 11:24:51 +01001/*******************************************************************************
2* Copyright (c) 2020 Robert Bosch GmbH
3* Author: Constantin Ziesche (constantin.ziesche@bosch.com)
4*
5* This program and the accompanying materials are made available under the
6* terms of the Eclipse Public License 2.0 which is available at
7* http://www.eclipse.org/legal/epl-2.0
8*
9* SPDX-License-Identifier: EPL-2.0
10*******************************************************************************/
Constantin Ziesche7ab66d12020-07-15 15:01:16 +020011using BaSyx.Models.Core.AssetAdministrationShell.Generics;
12using BaSyx.Models.Core.AssetAdministrationShell.Generics.SubmodelElementTypes;
Constantin Ziesche857c7ab2020-02-25 11:24:51 +010013using BaSyx.Models.Core.AssetAdministrationShell.Identification;
Constantin Ziesche7ab66d12020-07-15 15:01:16 +020014using BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes;
15using BaSyx.Models.Core.Common;
16using System;
17using System.Collections.Generic;
18using System.Reflection;
Constantin Ziesche857c7ab2020-02-25 11:24:51 +010019
20namespace BaSyx.Models.Extensions
21{
22 public static class SubmodelElementExtensions
23 {
24 public static T ToModelElement<T>(this IReferable referable) where T : class, IReferable
25 {
26 return referable as T;
27 }
Constantin Ziesche7ab66d12020-07-15 15:01:16 +020028
29 public static ISubmodelElementCollection CreateSubmodelElementCollection<T>(this IEnumerable<T> enumerable, string idShort)
30 {
31 SubmodelElementCollection smCollection = new SubmodelElementCollection()
32 {
33 IdShort = idShort
34 };
35 Type type = typeof(T);
36 foreach (var item in enumerable)
37 {
38 foreach (var property in type.GetProperties())
39 {
40 ISubmodelElement smElement = CreateSubmodelElement(property, item);
41 smCollection.Value.Add(smElement);
42 }
43 }
44 return smCollection;
45 }
46
47 public static ISubmodelElement CreateSubmodelElement(this PropertyInfo property, object target)
48 {
49 if (DataType.IsSimpleType(property.PropertyType))
50 {
51 DataType dataType = DataType.GetDataTypeFromSystemType(property.PropertyType);
52 Property smProp = new Property(dataType)
53 {
54 IdShort = property.Name,
55 Value = property.GetValue(target)
56 };
57 return smProp;
58 }
59 else
60 {
61 SubmodelElementCollection smCollection = new SubmodelElementCollection()
62 {
63 IdShort = property.Name
64 };
65 object value = property.GetValue(target);
66 Type valueType = value.GetType();
67 foreach (var subProperty in valueType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
68 {
69 ISubmodelElement smElement = CreateSubmodelElement(subProperty, value);
70 smCollection.Value.Add(smElement);
71 }
72 return smCollection;
73 }
74 }
Constantin Ziesche857c7ab2020-02-25 11:24:51 +010075 }
76}