Modular Application Creator Use Case Based Documentation
Loading...
Searching...
No Matches
HardwareGenerationExcelBased.cs
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Runtime.InteropServices;
5using Siemens.Automation.ModularApplicationCreator.Core;
6using Siemens.Automation.ModularApplicationCreatorBasics.Logging;
7using Siemens.Engineering;
8using Excel = Microsoft.Office.Interop.Excel;
9
11
18{
34 private static List<DeviceInfo> ReadExcelFile(string filePath)
35 {
36 var devices = new List<DeviceInfo>();
37 Excel.Application xlApp = null;
38 Excel.Workbook xlWorkbook = null;
39 Excel.Worksheet xlWorksheet = null;
40 Excel.Range xlRange = null;
41
42 try
43 {
44 xlApp = new Excel.Application();
45 xlWorkbook = xlApp.Workbooks.Open(filePath);
46 xlWorksheet = xlWorkbook.Sheets[1];
47 xlRange = xlWorksheet.UsedRange;
48
49 var rowCount = xlRange.Rows.Count;
50 var colCount = xlRange.Columns.Count;
51
52 // Create a mapping of column indices to ensure flexibility in column order
53 var columnMap = new Dictionary<string, int>();
54 for (var j = 1; j <= colCount; j++)
55 {
56 if (xlRange.Cells[1, j].Value2 != null)
57 {
58 columnMap[xlRange.Cells[1, j].Value2.ToString()] = j;
59 }
60 }
61
62 // Validate required columns exist (excluding Type as it's optional)
63 string[] requiredColumns = { "OrderNumber", "Version", "Name", "DeviceName" };
64 foreach (var column in requiredColumns)
65 {
66 if (!columnMap.ContainsKey(column))
67 {
68 throw new Exception($"Required column '{column}' not found in Excel file");
69 }
70 }
71
72 // Read data rows
73 for (var i = 2; i <= rowCount; i++) // Start from row 2 to skip headers
74 {
75 if (xlRange.Cells[i, columnMap["OrderNumber"]].Value2 == null)
76 {
77 continue;
78 }
79
80 var device = new DeviceInfo
81 {
82 OrderNumber = GetCellValueAsString(xlRange.Cells[i, columnMap["OrderNumber"]]),
83 Version = GetCellValueAsString(xlRange.Cells[i, columnMap["Version"]]),
84 Name = GetCellValueAsString(xlRange.Cells[i, columnMap["Name"]]),
85 DeviceName = GetCellValueAsString(xlRange.Cells[i, columnMap["DeviceName"]])
86 };
87
88 // Handle Type column separately as it's optional
89 if (columnMap.TryGetValue("Type", out var value))
90 {
91 device.Type = GetCellValueAsString(xlRange.Cells[i, value]);
92 }
93
94 // Only add device if required fields are not empty
95 if (!string.IsNullOrWhiteSpace(device.OrderNumber) &&
96 !string.IsNullOrWhiteSpace(device.Version) &&
97 !string.IsNullOrWhiteSpace(device.Name) &&
98 !string.IsNullOrWhiteSpace(device.DeviceName))
99 {
100 devices.Add(device);
101 }
102 }
103 }
104 finally
105 {
106 // Clean up COM objects
107 if (xlRange != null)
108 {
109 Marshal.ReleaseComObject(xlRange);
110 }
111
112 if (xlWorksheet != null)
113 {
114 Marshal.ReleaseComObject(xlWorksheet);
115 }
116
117 if (xlWorkbook != null)
118 {
119 xlWorkbook.Close(false);
120 Marshal.ReleaseComObject(xlWorkbook);
121 }
122
123 if (xlApp != null)
124 {
125 xlApp.Quit();
126 Marshal.ReleaseComObject(xlApp);
127 }
128 }
129
130 return devices;
131 }
132
138 private static string GetCellValueAsString(Excel.Range cell)
139 {
140 return cell?.Value2 == null ? string.Empty : (string)cell.Value2.ToString().Trim();
141 }
142
159 public static void CreateNewDevicesFromExcelSheet(MAC_use_casesEM module, Project tiaProject, string excelFilePath)
160 {
161 try
162 {
163 if (!File.Exists(excelFilePath))
164 {
165 throw new FileNotFoundException("Excel file not found", excelFilePath);
166 }
167
168 var deviceInfos = ReadExcelFile(excelFilePath);
169
170 foreach (var deviceInfo in deviceInfos)
171 {
172 try
173 {
174 MacManagement.LoggingService.LogMessage(LogTypes.GenerationInfo,
175 $"Processing device: {deviceInfo}", module.Name);
176
177 var typeIdentifier = string.IsNullOrWhiteSpace(deviceInfo.Type)
178 ? $"OrderNumber:{deviceInfo.OrderNumber}/{deviceInfo.Version}"
179 : $"OrderNumber:{deviceInfo.OrderNumber}/{deviceInfo.Version}/{deviceInfo.Type}";
180
181 MacManagement.LoggingService.LogMessage(LogTypes.GenerationInfo,
182 $"Creating device with identifier: {typeIdentifier}", module.Name);
183
184 HardwareGeneration.GetOrCreateDevice(tiaProject, typeIdentifier, deviceInfo.Name,
185 deviceInfo.DeviceName);
186
187 MacManagement.LoggingService.LogMessage(LogTypes.GenerationInfo,
188 $"Successfully added device: {deviceInfo.DeviceName}", module.Name);
189 }
190 catch (Exception ex)
191 {
192 MacManagement.LoggingService.LogMessage(LogTypes.GenerationError,
193 $"Failed to process device {deviceInfo}. Error: {ex.Message}", module.Name);
194 }
195 }
196 }
197 catch (Exception ex)
198 {
199 throw new Exception($"Error creating devices from Excel file: {ex.Message}", ex);
200 }
201 }
202
206 private class DeviceInfo
207 {
208 public string OrderNumber { get; set; }
209 public string Version { get; set; }
210 public string Type { get; set; }
211 public string Name { get; set; }
212 public string DeviceName { get; set; }
213
214 public override string ToString()
215 {
216 return $"Device Information:\n" +
217 $" Name: {Name}\n" +
218 $" Type: {Type}\n" +
219 $" Order Number: {OrderNumber}\n" +
220 $" Version: {Version}\n" +
221 $" Device Name: {DeviceName}";
222 }
223 }
224}
This is the main class in which the workflow starts. Here are all sections for creating or generating...
Handles the generation of hardware configurations based on Excel file inputs. This class provides fun...
static List< DeviceInfo > ReadExcelFile(string filePath)
Reads device information from a specified Excel file.
static void CreateNewDevicesFromExcelSheet(MAC_use_casesEM module, Project tiaProject, string excelFilePath)
Creates new devices in the TIA Portal project based on information from an Excel sheet.
static string GetCellValueAsString(Excel.Range cell)
Converts an Excel cell value to a string, handling null values.
All the functions to configure and generate Hardware are defined here.
static Device GetOrCreateDevice(Project project, string typeIdentifier, string name, string deviceName)
Creates or retrieves a device in the TIA Portal project based on the specified parameters.