private static object GetValue(Crate crate, string fieldKey)
        {
            if (crate.IsOfType <StandardTableDataCM>())
            {
                var tableCrate = crate.Get <StandardTableDataCM>();
                if (tableCrate.FirstRowHeaders && tableCrate.Table.Count > 1)
                {
                    return(tableCrate.Table[1].Row.FirstOrDefault(a => a.Cell.Key == fieldKey)?.Cell?.Value);
                }
            }

            if (crate.IsKnownManifest)
            {
                var    data  = crate.Get();
                object value = null;

                Fr8ReflectionHelper.VisitPropertiesRecursive(data, (instance, member) =>
                {
                    if (!member.CanRead)
                    {
                        return(Fr8ReflectionHelper.PropertiesVisitorOp.Continue);
                    }

                    var manifestAttr = member.GetCustomAttribute <ManifestFieldAttribute>();

                    if (manifestAttr != null && manifestAttr.IsHidden)
                    {
                        return(Fr8ReflectionHelper.PropertiesVisitorOp.Continue);
                    }

                    var tempValue = member.GetValue(instance);

                    if (member.Name == fieldKey)
                    {
                        value = tempValue;
                        return(Fr8ReflectionHelper.PropertiesVisitorOp.Terminate);
                    }

                    var keyValuePair = tempValue as KeyValueDTO;
                    if (keyValuePair != null)
                    {
                        if (keyValuePair.Key == fieldKey)
                        {
                            value = keyValuePair.Value;
                            return(Fr8ReflectionHelper.PropertiesVisitorOp.Terminate);
                        }

                        return(Fr8ReflectionHelper.PropertiesVisitorOp.SkipBranch);
                    }

                    return(Fr8ReflectionHelper.PropertiesVisitorOp.Continue);
                });

                return(value);
            }

            // do nothing for uknown manifests
            return(null);
        }
Esempio n. 2
0
        private static object GetDataListItem(Crate crate, int index)
        {
            var tableData = crate.ManifestType.Id == (int)MT.StandardTableData ? crate.Get <StandardTableDataCM>() : null;

            if (tableData != null)
            {
                //why?? why just skip header and return first row?
                return(tableData.FirstRowHeaders ? tableData.Table[index + 1] : tableData.Table[index]);
            }
            return(Fr8ReflectionHelper.FindFirstArray(crate.Get())[index]);
        }
Esempio n. 3
0
        public StandardTableDataCM GetExcelFile(byte[] fileAsByteArray, string selectedFilePath, bool isFirstRowAsColumnNames = true, string sheetName = null)
        {
            var ext = Path.GetExtension(selectedFilePath);
            // Read file from repository
            // Fetch column headers in Excel file
            var headersArray = GetColumnHeaders(fileAsByteArray, ext, sheetName);

            // Fetch rows in Excel file
            var rowsDictionary = GetTabularData(fileAsByteArray, ext, isFirstRowAsColumnNames, sheetName);

            Crate curExcelPayloadRowsCrateDTO = null;

            if (rowsDictionary != null && rowsDictionary.Count > 0)
            {
                var rows = CreateTableCellPayloadObjects(rowsDictionary, headersArray, isFirstRowAsColumnNames);
                if (rows != null && rows.Count > 0)
                {
                    curExcelPayloadRowsCrateDTO = Crate.FromContent("Excel Payload Rows", new StandardTableDataCM(isFirstRowAsColumnNames, rows.ToArray()));
                }
            }

            var curStandardTableDataMS = (curExcelPayloadRowsCrateDTO != null) ?
                                         curExcelPayloadRowsCrateDTO.Get <StandardTableDataCM>()
                : new StandardTableDataCM();

            return(curStandardTableDataMS);
        }
Esempio n. 4
0
        private void PopulateRowData(CrateDescriptionDTO crateDescriptionToProcess, OperationalStateCM.LoopStatus loopData, Crate crateToProcess)
        {
            string label = GetCrateName(crateDescriptionToProcess);

            Payload.RemoveUsingPredicate(a => a.Label == label && a.ManifestType == crateToProcess.ManifestType);

            if (crateDescriptionToProcess.ManifestId == (int)MT.StandardTableData)
            {
                var table          = crateToProcess.Get <StandardTableDataCM>();
                var rowOfData      = table.DataRows.ElementAt(loopData.Index);
                var extractedCrate = new StandardTableDataCM(false, new List <TableRowDTO>()
                {
                    rowOfData
                });
                Payload.Add(Crate.FromContent(label, extractedCrate));
            }
            else
            {
                var cloned_crate = CloneCrateAndReplaceArrayWithASingleValue(crateToProcess, "", loopData.Index, GetCrateName(crateDescriptionToProcess));
                Payload.Add(cloned_crate);
            }
        }
Esempio n. 5
0
        public static StandardTableDataCM ExtractPayloadCrateDataToStandardTableData(Crate crate)
        {
            if (crate.ManifestType.Id == (int)MT.StandardTableData)
            {
                return(crate.Get <StandardTableDataCM>());
            }
            if (crate.ManifestType.Id == (int)MT.FieldDescription)
            {
                var fields = crate.Get <FieldDescriptionsCM>();
                return(new StandardTableDataCM
                {
                    FirstRowHeaders = true,
                    Table = new List <TableRowDTO>
                    {
                        //Keys of fields will become column headers
                        new TableRowDTO {
                            Row = fields.Fields.Select(x => new TableCellDTO {
                                Cell = new FieldDTO(x.Key, x.Key)
                            }).ToList()
                        },
                        new TableRowDTO {
                            Row = fields.Fields.Select(x => new TableCellDTO {
                                Cell = x
                            }).ToList()
                        }
                    }
                });
            }
            var tableData = new StandardTableDataCM
            {
                FirstRowHeaders = true,
                Table           = new List <TableRowDTO>()
            };
            var headerIsAdded = false;


            var item = CrateStorageSerializer.Default.ConvertToDto(crate);

            var token = JToken.Parse(item.Contents.ToString());

            var jObject = token as JObject;

            if (jObject != null)
            {
                //check if jObject has some JArray properties
                var arrayProperty = jObject.Properties().FirstOrDefault(x => x.Value is JArray);

                //check how StandardPayloadDataCM is structured
                if (arrayProperty != null)
                {
                    foreach (var arrayItem in arrayProperty.Value)
                    {
                        //arrayItem is PayloadObjectDTO which on has an List<FieldDTO>
                        var innerArrayProperty = ((JObject)arrayItem).Properties().FirstOrDefault(x => x.Value is JArray);
                        if (innerArrayProperty != null)
                        {
                            var headerRow = new TableRowDTO();
                            var dataRow   = new TableRowDTO();

                            foreach (var innerArrayItem in innerArrayProperty.Value)
                            {
                                //try to parse the property as FieldDTO
                                if (innerArrayItem is JObject)
                                {
                                    var fieldObj = (JObject)innerArrayItem;
                                    if (fieldObj.Property("key") != null && fieldObj.Property("value") != null)
                                    {
                                        headerRow.Row.Add(new TableCellDTO
                                        {
                                            Cell = new FieldDTO(fieldObj["key"].ToString(), fieldObj["key"].ToString())
                                        });
                                        dataRow.Row.Add(new TableCellDTO
                                        {
                                            Cell =
                                                new FieldDTO(fieldObj["key"].ToString(), fieldObj["value"].ToString())
                                        });
                                    }
                                }
                            }

                            if (!headerIsAdded)
                            {
                                tableData.Table.Add(headerRow);
                                headerIsAdded = true;
                            }
                            tableData.Table.Add(dataRow);
                        }

                        // StandardFileListCM manifest has structure like this.
                        else
                        {
                            var headerRow = new TableRowDTO();
                            var dataRow   = new TableRowDTO();

                            foreach (var property in ((JObject)arrayItem).Properties())
                            {
                                //try to parse the property as FieldDTO
                                if (property.Name != null && property.Value != null)
                                {
                                    headerRow.Row.Add(new TableCellDTO
                                    {
                                        Cell = new FieldDTO(property.Name, property.Name)
                                    });
                                    dataRow.Row.Add(new TableCellDTO
                                    {
                                        Cell =
                                            new FieldDTO(property.Name, property.Value.ToString())
                                    });
                                }
                            }
                            if (!headerIsAdded)
                            {
                                tableData.Table.Add(headerRow);
                                headerIsAdded = true;
                            }
                            tableData.Table.Add(dataRow);
                        }
                    }
                }
                else
                {
                    var headerRow = new TableRowDTO();
                    var dataRow   = new TableRowDTO();

                    foreach (JProperty property in jObject.Properties())
                    {
                        //try to parse the property as FieldDTO
                        if (property.Value is JObject)
                        {
                            var fieldObj = (JObject)property.Value;
                            if (fieldObj.Property("key") != null && fieldObj.Property("value") != null)
                            {
                                headerRow.Row.Add(new TableCellDTO {
                                    Cell = new FieldDTO(fieldObj["key"].ToString(), fieldObj["key"].ToString())
                                });
                                dataRow.Row.Add(new TableCellDTO {
                                    Cell = new FieldDTO(fieldObj["key"].ToString(), fieldObj["value"].ToString())
                                });
                            }
                        }
                        else
                        {
                            headerRow.Row.Add(new TableCellDTO {
                                Cell = new FieldDTO(property.Name, property.Name)
                            });
                            dataRow.Row.Add(new TableCellDTO {
                                Cell = new FieldDTO(property.Name, property.Value.ToString())
                            });
                        }
                    }
                    if (!headerIsAdded)
                    {
                        tableData.Table.Add(headerRow);
                        headerIsAdded = true;
                    }
                    tableData.Table.Add(dataRow);
                }
            }
            return(tableData);
        }
Esempio n. 6
0
        public async Task ProcessInboundEvents(Crate curCrateStandardEventReport)
        {
            var inboundEvent = curCrateStandardEventReport.Get <EventReportCM>();

            if (string.IsNullOrWhiteSpace(inboundEvent.ExternalDomainId) && string.IsNullOrWhiteSpace(inboundEvent.ExternalAccountId))
            {
                Logger.GetLogger().Error($"External event has no information about external account or external domain. Processing is cancelled. Event names - {inboundEvent.EventNames}, " +
                                         $"manufacturer - {inboundEvent.Manufacturer} ");
                return;
            }

            var systemUser = _fr8Account.GetSystemUser();

            if (systemUser == null)
            {
                throw new ApplicationException("System User Account is Missing");
            }
            string systemUserEmail = systemUser.UserName;

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                Logger.GetLogger().Info($"Received external event for account '{inboundEvent.ExternalAccountId}'");
                if (inboundEvent.ExternalAccountId == systemUserEmail)
                {
                    try
                    {
                        var eventCm = curCrateStandardEventReport.Get <EventReportCM>();

                        EventRouter currentRouter = GetEventRouter(eventCm);

                        var errorMsgList = new List <string>();
                        foreach (var crate in eventCm.EventPayload)
                        {
                            if (crate.ManifestType.Id != (int)Fr8.Infrastructure.Data.Constants.MT.LoggingData)
                            {
                                errorMsgList.Add("Don't know how to process an EventReport with the Contents: " + _crateManager.ToDto(crate));
                                continue;
                            }

                            var loggingData = crate.Get <LoggingDataCM>();
                            currentRouter(loggingData);
                        }

                        if (errorMsgList.Count > 0)
                        {
                            throw new InvalidOperationException(String.Join(";;;", errorMsgList));
                        }
                    }
                    catch (Exception ex)
                    {
                        EventManager.UnexpectedError(ex);
                    }
                }
                else
                {
                    //Find the corresponding Fr8 accounts
                    var authTokens = uow.AuthorizationTokenRepository.GetPublicDataQuery();
                    if (!string.IsNullOrWhiteSpace(inboundEvent.ExternalDomainId))
                    {
                        authTokens = authTokens.Where(x => x.ExternalDomainId == inboundEvent.ExternalDomainId);
                    }
                    //If external account Id doesn't exist it means that event is domain-wide i.e. it relates to all accounts that belong to specified domain
                    if (!string.IsNullOrWhiteSpace(inboundEvent.ExternalAccountId))
                    {
                        authTokens = authTokens.Where(x => x.ExternalAccountId == inboundEvent.ExternalAccountId);
                    }
                    //Checking both domain and account is additional way to protect from running plans not related to the event as account Id is often an email and can be the same across
                    //multiple terminals
                    var planOwnerIds = authTokens.Select(x => x.UserID).Distinct().ToArray();
                    Logger.GetLogger().Info($"External event for domain '{inboundEvent.ExternalDomainId}' and account '{inboundEvent.ExternalAccountId}' relates to {planOwnerIds.Length} user(s)");
                    if (string.IsNullOrEmpty(inboundEvent.ExternalDomainId) && planOwnerIds.Length > 1)
                    {
                        Logger.GetLogger().Warn($"Multiple users are identified as owners of plans related to external domain '{inboundEvent.ExternalDomainId}' and account '{inboundEvent.ExternalAccountId}'");
                    }
                    foreach (var planOwnerId in planOwnerIds)
                    {
                        try
                        {
                            FindAndExecuteAccountPlans(uow, inboundEvent, curCrateStandardEventReport, planOwnerId);
                        }
                        catch (Exception ex)
                        {
                            EventManager.UnexpectedError(ex);
                        }
                    }
                }
            }
        }
Esempio n. 7
0
        private static FieldDTO FindField(OperationalStateCM operationalState, Crate crate, string fieldKey)
        {
            object searchArea;
            //let's check if we are in a loop
            //and this is a loop data?
            //check if this crate is loop related
            var loopState = operationalState.CallStack.FirstOrDefault(x =>
            {
                if (x.LocalData?.Type == "Loop")
                {
                    var loopStatus = x.LocalData.ReadAs <OperationalStateCM.LoopStatus>();

                    if (loopStatus != null && loopStatus.CrateManifest.CrateDescriptions[0].Label == crate.Label && loopStatus.CrateManifest.CrateDescriptions[0].ManifestType == crate.ManifestType.Type)
                    {
                        return(true);
                    }
                }

                return(false);
            });

            if (loopState != null) //this is a loop related data request
            {
                searchArea = GetDataListItem(crate, loopState.LocalData.ReadAs <OperationalStateCM.LoopStatus>().Index);
            }
            else
            {
                //hmmm this is a regular data request
                //lets search in complete crate
                searchArea = crate;
                //if we have a StandardTableDataCM and we are not in the loop and crate has Headers - we should search next row
                if (crate.IsOfType <StandardTableDataCM>())
                {
                    var tableCrate = crate.Get <StandardTableDataCM>();
                    if (tableCrate.FirstRowHeaders && tableCrate.Table.Count > 1)
                    {
                        //TODO it is weird to get just first row of table data while searching for a field
                        //note: GetDataListItem function skips header
                        TableRowDTO row = GetDataListItem(crate, 0) as TableRowDTO;
                        if (row != null)
                        {
                            return(row.Row.FirstOrDefault(a => a.Cell.Key == fieldKey)?.Cell);
                        }
                    }
                }
            }

            if (searchArea is Crate)
            {
                if (((Crate)searchArea).IsKnownManifest)
                {
                    searchArea = ((Crate)searchArea).Get();
                }
                else
                {
                    return(null);
                }
            }

            //we should find first related field and return
            var fields     = Fr8ReflectionHelper.FindFieldsRecursive(searchArea);
            var fieldMatch = fields.FirstOrDefault(f => f.Key == fieldKey);

            //let's return first match
            return(fieldMatch);
        }
Esempio n. 8
0
        internal static int?GetDataListSize(Crate crateToProcess)
        {
            var tableData = crateToProcess.ManifestType.Id == (int)MT.StandardTableData ? crateToProcess.Get <StandardTableDataCM>() : null;

            if (tableData != null)
            {
                return(tableData.FirstRowHeaders ? Math.Max(0, tableData.Table.Count - 1) : tableData.Table.Count);
            }
            var array = crateToProcess.IsKnownManifest ? Fr8ReflectionHelper.FindFirstArray(crateToProcess.Get()) : Fr8ReflectionHelper.FindFirstArray(crateToProcess.GetRaw());

            return(array?.Length);
        }