示例#1
0
        public Simulator.Admin.Models.Simulator CreateSimulator(DeploymentInstance instance, EntityHeader org, EntityHeader user, DateTime creationTimeStamp)
        {
            var simulator = new Simulator.Admin.Models.Simulator()
            {
                Id               = "Simulator for Sample App",
                Key              = "sampleappsimulator",
                DefaultEndPoint  = instance.DnsHostName,
                TLSSSL           = false,
                DefaultTransport = EntityHeader <Simulator.Admin.Models.TransportTypes> .Create(Simulator.Admin.Models.TransportTypes.RestHttp),
                MessageTemplates = new List <Simulator.Admin.Models.MessageTemplate>()
                {
                    new Simulator.Admin.Models.MessageTemplate()
                    {
                        Name               = "Motion Message",
                        Key                = "motionmsg",
                        Id                 = Guid.NewGuid().ToId(),
                        TextPayload        = "{'motion':'~motionvalue~','level':~motionlevel~}",
                        PathAndQueryString = "/smplmot001/~deviceid~",
                        DynamicAttributes  = new List <Simulator.Admin.Models.MessageDynamicAttribute>()
                        {
                            new Simulator.Admin.Models.MessageDynamicAttribute()
                            {
                                Id            = Guid.NewGuid().ToId(),
                                Key           = "motionvalue",
                                DefaultValue  = "on",
                                Name          = "Motion On/Off",
                                ParameterType = EntityHeader <ParameterTypes> .Create(ParameterTypes.String),
                                Description   = "Provide a value of 'on' or 'off' to simulate motion detected"
                            },
                            new Simulator.Admin.Models.MessageDynamicAttribute()
                            {
                                Id            = Guid.NewGuid().ToId(),
                                Key           = "motionlevel",
                                DefaultValue  = "100",
                                Name          = "Motion Level",
                                ParameterType = EntityHeader <ParameterTypes> .Create(ParameterTypes.Integer),
                                Description   = "Provide a value between 0 and 100 as to the level of motion detected"
                            }
                        }
                    },
                    new Simulator.Admin.Models.MessageTemplate()
                    {
                        Name           = "Temperature Message",
                        Key            = "tempmsg",
                        Id             = Guid.NewGuid().ToId(),
                        TextPayload    = "~temperaturevalue~,~humidityvalue~",
                        PayloadType    = EntityHeader <Simulator.Admin.Models.PaylodTypes> .Create(Simulator.Admin.Models.PaylodTypes.String),
                        ContentType    = "text/csv",
                        HttpVerb       = "POST",
                        MessageHeaders = new List <Simulator.Admin.Models.MessageHeader>()
                        {
                            new Simulator.Admin.Models.MessageHeader()
                            {
                                HeaderName = "x-messageid", Value = "smpltmp001", Id = Guid.NewGuid().ToId(), Key = "xmessageid", Name = "x-messageid"
                            },
                            new Simulator.Admin.Models.MessageHeader()
                            {
                                HeaderName = "x-deviceid", Value = "~deviceid~", Id = Guid.NewGuid().ToId(), Key = "xdeviceid", Name = "x-deviceid"
                            },
                        },
                        DynamicAttributes = new List <Simulator.Admin.Models.MessageDynamicAttribute>()
                        {
                            new Simulator.Admin.Models.MessageDynamicAttribute()
                            {
                                Id            = Guid.NewGuid().ToId(),
                                Key           = "temperaturevalue",
                                DefaultValue  = "98.6",
                                Name          = "Temperature",
                                ParameterType = EntityHeader <ParameterTypes> .Create(ParameterTypes.Decimal),
                                Description   = "Provide a value of 'on' or 'off' to simulate motion detected"
                            },
                            new Simulator.Admin.Models.MessageDynamicAttribute()
                            {
                                Id            = Guid.NewGuid().ToId(),
                                Key           = "humidityvalue",
                                DefaultValue  = "65",
                                Name          = "Humidity",
                                ParameterType = EntityHeader <ParameterTypes> .Create(ParameterTypes.Decimal),
                                Description   = "Provide a value between 0 and 100 as to the level of motion detected"
                            }
                        }
                    },
                }
            };

            AddId(simulator);
            AddOwnedProperties(simulator, org);
            AddAuditProperties(simulator, creationTimeStamp, org, user);

            return(simulator);
        }
        public async Task <ServiceTicket> GetServiceTicketAsync(string id, EntityHeader org, EntityHeader user)
        {
            Console.WriteLine("Starting getting ticket");
            Console.WriteLine("=====================================");

            var sw     = Stopwatch.StartNew();
            var ticket = await _repo.GetServiceTicketAsync(id);

            Console.WriteLine("Loaded service ticket: " + sw.Elapsed.TotalMilliseconds);

            await AuthorizeAsync(ticket, AuthorizeResult.AuthorizeActions.Read, user, org);

            Console.WriteLine("Authorized: " + sw.Elapsed.TotalMilliseconds);
            var sw2 = Stopwatch.StartNew();

            if (!EntityHeader.IsNullOrEmpty(ticket.DeviceRepo))
            {
                var repo = await _repoManager.GetDeviceRepositoryWithSecretsAsync(ticket.DeviceRepo.Id, org, user);

                Console.WriteLine("Loaded device repo: " + sw2.Elapsed.TotalMilliseconds);
                sw2 = Stopwatch.StartNew();
                if (!EntityHeader.IsNullOrEmpty(ticket.Device))
                {
                    ticket.Device.Value = await _deviceManager.GetDeviceByIdAsync(repo, ticket.Device.Id, org, user, true);
                }

                Console.WriteLine("Device load time: " + sw2.Elapsed.TotalMilliseconds);
            }

            var statusType = await _ticketStatusRepo.GetTicketStatusDefinitionAsync(ticket.StatusType.Id);

            ticket.StatusType = EntityHeader <TicketStatusDefinition> .Create(statusType);

            if (!EntityHeader.IsNullOrEmpty(ticket.ServiceBoard))
            {
                ticket.ServiceBoard.Value = await _serviceBoardRepo.GetServiceBoardAsync(ticket.ServiceBoard.Id);
            }

            Console.WriteLine("Loaded board: " + sw.Elapsed.TotalMilliseconds);

            if (!EntityHeader.IsNullOrEmpty(ticket.Template))
            {
                ticket.Template.Value = await _templateRepo.GetServiceTicketTemplateAsync(ticket.Template.Id);

                if (!EntityHeader.IsNullOrEmpty(ticket.Template.Value.TemplateCategory))
                {
                    ticket.Template.Value.TemplateCategory.Value = await _templateCategoryRepo.GetTemplateCategoryAsync(ticket.Template.Value.TemplateCategory.Id);
                }
            }

            Console.WriteLine("Total load time: " + sw.Elapsed.TotalMilliseconds);

            if (!ticket.IsViewed && !EntityHeader.IsNullOrEmpty(ticket.AssignedTo) && ticket.AssignedTo.Id == user.Id)
            {
                ticket.IsViewed   = true;
                ticket.ViewedBy   = user;
                ticket.ViewedDate = DateTime.UtcNow.ToJSONString();
                var history = new ServiceTicketStatusHistory()
                {
                    AddedBy   = user,
                    DateStamp = ticket.ViewedDate,
                    Status    = ticket.Status.Text,
                    Note      = $"Viewed by [{user.Text}]"
                };

                ticket.History.Insert(0, history);
                await _repo.UpdateServiceTicketAsync(ticket);
            }

            return(ticket);
        }
 public InputTranslatorConfiguration()
 {
     InputTranslatorType = EntityHeader <InputTranslatorTypes> .Create(InputTranslatorTypes.MessageBased);
 }
示例#4
0
 public MessageValue(ParameterTypes value)
 {
     Type = EntityHeader <ParameterTypes> .Create(value);
 }
示例#5
0
 public EntityHeader GetOrgEntityHeader()
 {
     return(EntityHeader.Create(OrganizationId, OrganizationName));
 }
示例#6
0
 public OutputTranslatorConfiguration()
 {
     OutputTranslatorType = EntityHeader <OutputTranslatorTypes> .Create(OutputTranslatorTypes.MessageBased);
 }
示例#7
0
        /// <summary>
        /// This comes in when validating a device id and message id parser.
        /// </summary>
        /// <returns></returns>
        public ValidationResult Validate()
        {
            /* Will always use strings for device and message ids */
            StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.String);

            var result = Validator.Validate(this);

            /* If base validation doesn't work, don't bother getting into the details */
            if (result.Successful)
            {
                if (EntityHeader.IsNullOrEmpty(ContentType) && SearchLocation.Value == SearchLocations.Body)
                {
                    result.Errors.Add(Resources.DeviceMessagingAdminErrorCodes.CouldNotDetermineDeviceId.ToErrorMessage());
                }
                else
                {
                    switch (SearchLocation.Value)
                    {
                    case SearchLocations.Body:
                        foreach (var property in typeof(DeviceMessageDefinitionField).GetTypeInfo().DeclaredProperties)
                        {
                            var name     = GetDisplayName(property);
                            var hasValue = HasValue(property);
                            AddWarningForUnsedProperties(result, ContentType, property, name, hasValue, true);
                            AddErrorsForMissingProperties(result, ContentType, property, name, hasValue, true);
                        }

                        break;

                    case SearchLocations.Header:
                        if (String.IsNullOrEmpty(HeaderName))
                        {
                            result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_HeaderNameMissing));
                        }
                        break;

                    case SearchLocations.Path:
                        if (String.IsNullOrEmpty(PathLocator))
                        {
                            result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_PathNameMissing));
                        }
                        break;

                    case SearchLocations.QueryString:
                        if (String.IsNullOrEmpty(QueryStringField))
                        {
                            result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_QueryStringNameMissing));
                        }
                        break;

                    case SearchLocations.Topic:
                        if (String.IsNullOrEmpty(TopicLocator))
                        {
                            result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_TopicRegEx));
                        }
                        if (String.IsNullOrEmpty(RegExGroupName))
                        {
                            result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_TopicGroupNameMissing));
                        }
                        break;
                    }
                }

                if (StorageType.Value == ParameterTypes.ValueWithUnit && EntityHeader.IsNullOrEmpty(UnitSet))
                {
                    result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_FieldDefinitionMissing_UnitSet));
                }
                if (StorageType.Value == ParameterTypes.State && EntityHeader.IsNullOrEmpty(StateSet))
                {
                    result.Errors.Add(new ErrorMessage(DeviceMessagingAdminResources.Err_FieldDefinitionMissing_StateSet));
                }
            }

            return(result);
        }
        public void InputCommand_DuplicateKeysOnParamters_Invalid()
        {
            var workflow     = GetDeviceWorkflow();
            var inputCommand = GetInputCommand();

            inputCommand.Parameters.Add(new Models.Parameter()
            {
                ParameterType = EntityHeader <ParameterTypes> .Create(ParameterTypes.String), ParameterLocation = EntityHeader <PayloadTypes> .Create(PayloadTypes.QueryString), Key = inputCommand.Parameters[0].Key, Name = inputCommand.Parameters[0].Name
            });
            workflow.InputCommands.Add(inputCommand);
            AssertIsInValid(workflow);
        }
示例#9
0
        public async Task Simple_Clone()
        {
            var original = new ParentModel();

            original.OwnerOrganization = EntityHeader.Create(Guid.NewGuid().ToId(), "owner org");
            original.LastUpdatedBy     = EntityHeader.Create(Guid.NewGuid().ToId(), "owner org");
            original.CreatedBy         = original.LastUpdatedBy;
            original.CreationDate      = DateTime.UtcNow.AddDays(-5).ToJSONString();
            original.LastUpdatedDate   = original.CreationDate;
            original.IsPublic          = false;
            original.Name = "orig name";
            original.Key  = "key";

            original.Child2 = new ChildModel2()
            {
                OwnerOrganization = original.OwnerOrganization,
                LastUpdatedBy     = original.LastUpdatedBy,
                CreatedBy         = original.CreatedBy,
                Name            = "Some Name",
                Key             = "somekey",
                IsPublic        = true,
                CreationDate    = original.CreationDate,
                Id              = Guid.NewGuid().ToId(),
                LastUpdatedDate = original.LastUpdatedDate,
                GrandChild      = new ChildModel2()
                {
                    OwnerOrganization = original.OwnerOrganization,
                    LastUpdatedBy     = original.LastUpdatedBy,
                    CreatedBy         = original.CreatedBy,
                    Name            = "Some Name",
                    Key             = "somekey",
                    IsPublic        = true,
                    CreationDate    = original.CreationDate,
                    Id              = Guid.NewGuid().ToId(),
                    LastUpdatedDate = original.LastUpdatedDate,
                }
            };

            var originalGrandChildId = original.Child2.GrandChild.Id;

            var user2 = EntityHeader.Create(Guid.NewGuid().ToId(), "new user");
            var org2  = EntityHeader.Create(Guid.NewGuid().ToId(), "other user");

            original.Child1 = new ChildModel1()
            {
                Prop1 = "p1",
                Prop2 = "p2",
                Prop3 = "p3",
            };

            original.Children1 = new List <ChildModel1>();
            original.Children1.Add(new ChildModel1()
            {
                Prop1 = "a", Prop2 = "b", Prop3 = "c"
            });
            original.Children1.Add(new ChildModel1()
            {
                Prop1 = "d", Prop2 = "e", Prop3 = "f"
            });

            var clone = await original.CloneAsync(user2, org2, "DiffObject", "DIffKey");

            Assert.AreEqual("p1", clone.Child1.Prop1);
            Assert.AreEqual("p2", clone.Child1.Prop2);
            Assert.AreEqual("p3", clone.Child1.Prop3);

            Assert.AreEqual(org2.Id, clone.Child2.OwnerOrganization.Id);
            Assert.AreEqual(user2.Id, clone.Child2.CreatedBy.Id);
            Assert.AreEqual(user2.Id, clone.Child2.LastUpdatedBy.Id);

            Assert.AreEqual(2, clone.Children1.Count);
            Assert.IsNotNull(clone.Child2.GrandChild);

            Assert.AreEqual(org2.Id, clone.Child2.GrandChild.OwnerOrganization.Id);
            Assert.AreEqual(user2.Id, clone.Child2.GrandChild.CreatedBy.Id);
            Assert.AreEqual(user2.Id, clone.Child2.GrandChild.LastUpdatedBy.Id);

            Assert.AreNotEqual(original.Child2.Id, clone.Child2.LastUpdatedBy.Id);
            Assert.AreNotEqual(originalGrandChildId, clone.Child2.GrandChild.Id);
        }
示例#10
0
        public async Task <SimulatorNetwork> ValidateRequest()
        {
            var request = HttpContext.Request;

            foreach (var header in request.Headers.Keys)
            {
                Console.WriteLine($"{header}={request.Headers[header.ToLower()]} - {request.Headers.ContainsKey(header)} - {request.Headers.ContainsKey(header.ToLower())}");
            }

            CheckHeader(request, REQUEST_ID);
            CheckHeader(request, ORG_ID);
            CheckHeader(request, ORG);
            CheckHeader(request, NETWORK_ID);
            CheckHeader(request, DATE);
            CheckHeader(request, VERSION);

            var authheader = GetHeaderValue(request, "authorization");

            var requestId = GetHeaderValue(request, REQUEST_ID);
            var dateStamp = GetHeaderValue(request, DATE);
            var orgId     = GetHeaderValue(request, ORG_ID);
            var org       = GetHeaderValue(request, ORG);
            var networkId = GetHeaderValue(request, NETWORK_ID);
            var userId    = GetHeaderValue(request, USER_ID);
            var userName  = GetHeaderValue(request, USER);

            var version = GetHeaderValue(request, VERSION);

            var bldr = new StringBuilder();

            //Adding the \r\n manualy ensures that the we don't have any
            //platform specific code messing with our signature.
            bldr.Append($"{requestId}\r\n");
            bldr.Append($"{dateStamp}\r\n");
            bldr.Append($"{version}\r\n");
            bldr.Append($"{orgId}\r\n");
            bldr.Append($"{userId}\r\n");
            bldr.Append($"{networkId}\r\n");

            OrgEntityHeader  = EntityHeader.Create(orgId, org);
            UserEntityHeader = EntityHeader.Create(userId, userName);

            var network = await _simNetworkManager.GetSimulatorNetworkAsync(networkId, OrgEntityHeader, UserEntityHeader);

            if (network == null)
            {
                throw new Exception("Could not find simulator for network id [networkId]");
            }

            Console.WriteLine($"Found network {network.Name} - {network.SharedAccessKey1SecretId},{network.SharedAccessKey2SecretId}");
            Console.WriteLine($"Calc {network.Name} - {network.SharedAccessKey1SecretId},{network.SharedAccessKey2SecretId}");

            var key1 = await _secureStorage.GetSecretAsync(OrgEntityHeader, network.SharedAccessKey1SecretId, UserEntityHeader);

            if (!key1.Successful)
            {
                throw new Exception(key1.Errors.First().Message);
            }

            var calculatedFromFirst = GetSignature(requestId, key1.Result, bldr.ToString());

            Console.WriteLine($"Calc {calculatedFromFirst} - {authheader}");

            if (calculatedFromFirst != authheader)
            {
                var key2 = await _secureStorage.GetSecretAsync(OrgEntityHeader, network.SharedAccessKey2SecretId, UserEntityHeader);

                if (!key2.Successful)
                {
                    throw new Exception(key2.Errors.First().Message);
                }

                var calculatedFromSecond = GetSignature(requestId, key2.Result, bldr.ToString());
                if (calculatedFromSecond != authheader)
                {
                    throw new UnauthorizedAccessException("Invalid signature.");
                }
            }

            foreach (var simulator in network.Simulators)
            {
                simulator.Simulator.Value = await _simManager.GetSimulatorAsync(simulator.Simulator.Id, OrgEntityHeader, UserEntityHeader, true);
            }

            return(network);
        }
示例#11
0
        public async Task <InvokeResult <AppUser> > AddDeviceUser([FromBody] DeviceUserRegistrationRequest newuser)
        {
            String userId = Guid.NewGuid().ToId();

            newuser.Device.OwnerUser = EntityHeader.Create(userId, newuser.Email);

            var repo = await GetDeviceRepositoryWithSecretsAsync();

            var addDeviceResult = await _deviceManager.AddDeviceAsync(repo, newuser.Device, OrgEntityHeader, UserEntityHeader);

            if (!addDeviceResult.Successful)
            {
                return(InvokeResult <AppUser> .FromInvokeResult(addDeviceResult));
            }

            var appUser = new AppUser()
            {
                Id                   = userId,
                FirstName            = newuser.FirstName,
                LastName             = newuser.LastName,
                CurrentOrganization  = OrgEntityHeader,
                Email                = $"{repo.Id}-{newuser.Email}",
                PhoneNumber          = newuser.PhoneNumber,
                UserName             = $"{repo.Id}-{newuser.Email}",
                EmailConfirmed       = true,
                PhoneNumberConfirmed = true,
                IsAppBuilder         = false,
                IsOrgAdmin           = false,
                IsUserDevice         = true,
                PrimaryDevice        = EntityHeader.Create(newuser.Device.Id, newuser.Device.DeviceId),
                DeviceConfiguration  = EntityHeader.Create(newuser.Device.DeviceConfiguration.Id, newuser.Device.DeviceConfiguration.Text),
                DeviceRepo           = EntityHeader.Create(newuser.Device.DeviceRepository.Id, newuser.Device.DeviceRepository.Text),
                ProfileImageUrl      = new ImageDetails()
                {
                    Width    = 128,
                    Height   = 128,
                    ImageUrl = "https://bytemaster.blob.core.windows.net/userprofileimages/watermark.png",
                    Id       = "b78ca749a1e64ce59df4aa100050dcc7"
                }
            };


            SetAuditProperties(appUser);
            SetOwnedProperties(appUser);

            Console.WriteLine("Device Created  - " + newuser.Device.DeviceId);

            try
            {
                var result = await _userManager.CreateAsync(appUser, newuser.Password);

                if (result.Succeeded)
                {
                    var addToOrgResult = await _orgManager.AddUserToOrgAsync(OrgEntityHeader.Id, appUser.Id, OrgEntityHeader, UserEntityHeader);

                    if (addToOrgResult.Successful)
                    {
                        return(InvokeResult <AppUser> .Create(appUser));
                    }
                    else
                    {
                        await _userManager.DeleteAsync(appUser);

                        return(InvokeResult <AppUser> .FromInvokeResult(addToOrgResult));
                    }
                }
                else
                {
                    Console.WriteLine("Error creating user - removing device - " + newuser.Device.DeviceId);
                    var device = await _deviceManager.GetDeviceByDeviceIdAsync(repo, newuser.Device.DeviceId, OrgEntityHeader, UserEntityHeader);

                    await _deviceManager.DeleteDeviceAsync(repo, device.Id, OrgEntityHeader, UserEntityHeader);

                    return(InvokeResult <AppUser> .FromError(result.Errors.First().Description));
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Exception - removing device - " + newuser.Device.DeviceId);
                var device = await _deviceManager.GetDeviceByDeviceIdAsync(repo, newuser.Device.DeviceId, OrgEntityHeader, UserEntityHeader);

                await _deviceManager.DeleteDeviceAsync(repo, device.Id, OrgEntityHeader, UserEntityHeader);

                throw;
            }
        }
示例#12
0
        private async Task <InvokeResult> HandleSystemMessageAsync(string path, string payload)
        {
            PEMBus.InstanceLogger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Message, "ListenerMOdule_HandleSystemMessageAsync", "Received System Message", path.ToKVP("topic"), payload.ToKVP("body"));

            var parts = path.Split('/');

            if (parts.Length < 5)
            {
                var errMsg = $"NuvIoT service messages must be at least 5 segments {path} is {parts.Length} segments";
                PEMBus.InstanceLogger.AddError("ListenerModule__HandleSystemMessage", errMsg);
                return(InvokeResult.FromError(errMsg));
            }

            var deviceId = parts[3];

            var device = await PEMBus.DeviceStorage.GetDeviceByDeviceIdAsync(deviceId);

            if (device == null)
            {
                var errMsg = $"Could not find device with device id {deviceId}.";
                PEMBus.InstanceLogger.AddError("ListenerModule__HandleSystemMessage", errMsg);
                return(InvokeResult.FromError(errMsg));
            }


            device.LastContact = DateTime.UtcNow.ToJSONString();

            if (parts[4] == "state")
            {
                device.DeviceTwinDetails.Insert(0, new DeviceManagement.Models.DeviceTwinDetails()
                {
                    Timestamp = DateTime.UtcNow.ToJSONString(),
                    Details   = payload
                });
            }

            await PEMBus.DeviceStorage.UpdateDeviceAsync(device);

            var json         = JsonConvert.SerializeObject(Models.DeviceForNotification.FromDevice(device), _camelCaseSettings);
            var notification = new Notification()
            {
                Payload     = json,
                Channel     = EntityHeader <Channels> .Create(Channels.Device),
                ChannelId   = device.Id,
                PayloadType = "Device",
                DateStamp   = DateTime.UtcNow.ToJSONString(),
                MessageId   = Guid.NewGuid().ToId(),
                Text        = "Device Updated",
                Title       = "Device Updated"
            };

            await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification);

            notification = new Notification()
            {
                Payload     = json,
                Channel     = EntityHeader <Channels> .Create(Channels.DeviceRepository),
                ChannelId   = device.DeviceRepository.Id,
                PayloadType = "Device",
                DateStamp   = DateTime.UtcNow.ToJSONString(),
                MessageId   = Guid.NewGuid().ToId(),
                Text        = "Device Updated",
                Title       = "Device Updated"
            };

            await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification);

            foreach (var group in device.DeviceGroups)
            {
                notification = new Notification()
                {
                    Payload     = json,
                    Channel     = EntityHeader <Channels> .Create(Channels.DeviceGroup),
                    ChannelId   = group.Id,
                    PayloadType = "Device",
                    DateStamp   = DateTime.UtcNow.ToJSONString(),
                    MessageId   = Guid.NewGuid().ToId(),
                    Text        = "Device Updated",
                    Title       = "Device Updated"
                };

                await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification);
            }

            return(InvokeResult.Success);
        }
示例#13
0
        private async Task <InvokeResult> CreatePointArrayStorageAsync(DataStream stream, EntityHeader org, EntityHeader user)
        {
            var orgNamespace = (await _orgUtils.GetOrgNamespaceAsync(org.Id)).Result;

            stream.DeviceIdFieldName  = "device_id";
            stream.TimestampFieldName = "time_stamp";
            stream.DbSchema           = "public";
            stream.DbURL       = _defaultConnectionSettings.PointArrayConnectionSettings.Uri;
            stream.DbTableName = $"point_array_{stream.Key}";

            stream.CreateTableDDL = GetPointArrayDataStorageSQL_DDL(stream.DbTableName);

            stream.DatabaseName = orgNamespace;
            stream.DbName       = orgNamespace;
            stream.DbUserName   = orgNamespace;

            stream.AutoCreateSQLTable = false;

            // we will create it here as part of our setup.
            stream.DBPasswordSecureId = $"ps_db_uid_{org.Id}";

            var existingPassword = await _secureStorage.GetSecretAsync(org, stream.DBPasswordSecureId, user);

            if (existingPassword.Successful)
            {
                stream.DbPassword = existingPassword.Result;
            }
            else
            {
                stream.DbPassword = Guid.NewGuid().ToId();

                var addSecretResult = await _secureStorage.AddSecretAsync(org, stream.DBPasswordSecureId, stream.DbPassword);

                if (!addSecretResult.Successful)
                {
                    return(addSecretResult.ToInvokeResult());
                }
            }

            stream.Fields.Clear();

            stream.Fields.Add(new DataStreamField()
            {
                Name        = "Start Time Stamp",
                Key         = "starttimestamp",
                FieldName   = "starttimestamp",
                Description = "Time in seconds from UTC epoch (1/1/1970).",
                FieldType   = EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Integer),
                IsRequired  = true,
            });

            stream.Fields.Add(new DataStreamField()
            {
                Name        = "Sensor Index",
                Key         = "sensorindex",
                FieldName   = "sensorindex",
                Description = "Sensor Index on Board for this point array.",
                FieldType   = EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Integer),
                IsRequired  = true,
            });

            stream.Fields.Add(new DataStreamField()
            {
                Name        = "Point Count",
                Key         = "pointcount",
                FieldName   = "pointcount",
                Description = "Number of points that make up this point array.",
                FieldType   = EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Integer),
                IsRequired  = true
            });

            stream.Fields.Add(new DataStreamField()
            {
                Name        = "Interval",
                Key         = "interval",
                FieldName   = "interval",
                Description = "Interval between sample collection points.",
                FieldType   = EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Decimal),
                IsRequired  = true,
            });

            stream.Fields.Add(new DataStreamField()
            {
                Name        = "Point Array",
                Key         = "pointarray",
                FieldName   = "pointarray",
                Description = "Collection of points that make up the data collected from the device.",
                FieldType   = EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.DecimalArray),
                IsRequired  = true,
            });

            this.ValidationCheck(stream, Actions.Create);

            await CreatePostgresStorage(stream, stream.DbPassword);

            stream.DbPassword = null;

            return(InvokeResult.Success);
        }
        public async Task <InvokeResult <string> > CreateServiceTicketAsync(CreateServiceTicketRequest createServiceTicketRequest, EntityHeader org, EntityHeader user)
        {
            if (createServiceTicketRequest == null)
            {
                throw new ArgumentNullException(nameof(createServiceTicketRequest));
            }
            if (String.IsNullOrEmpty(createServiceTicketRequest.RepoId))
            {
                throw new ArgumentNullException(createServiceTicketRequest.RepoId);
            }
            if (String.IsNullOrEmpty(createServiceTicketRequest.DeviceId) &&
                String.IsNullOrEmpty(createServiceTicketRequest.DeviceUniqueId))
            {
                throw new ArgumentNullException(nameof(createServiceTicketRequest.DeviceId) + " and " + nameof(createServiceTicketRequest.DeviceUniqueId));
            }
            if (String.IsNullOrEmpty(createServiceTicketRequest.TemplateId) &&
                String.IsNullOrEmpty(createServiceTicketRequest.TemplateKey))
            {
                throw new ArgumentNullException(nameof(createServiceTicketRequest.TemplateId) + " and " + nameof(createServiceTicketRequest.TemplateKey));
            }

            ServiceTicketTemplate template;

            if (String.IsNullOrEmpty(createServiceTicketRequest.TemplateKey))
            {
                template = await _templateRepo.GetServiceTicketTemplateAsync(createServiceTicketRequest.TemplateId);

                if (template == null)
                {
                    throw new NullReferenceException($"Could not load ticket template for {createServiceTicketRequest.TemplateId}");
                }
            }
            else
            {
                template = await _templateRepo.GetServiceTicketTemplateByKeyAsync(org.Id, createServiceTicketRequest.TemplateKey);

                if (template == null)
                {
                    throw new NullReferenceException($"Could not load ticket template for {createServiceTicketRequest.TemplateKey}");
                }
            }

            org ??= template.OwnerOrganization;
            user ??= template.DefaultContact ?? template.CreatedBy;

            if (org == null)
            {
                throw new NullReferenceException(nameof(org));
            }
            if (user == null)
            {
                throw new NullReferenceException(nameof(user));
            }

            var repo = await _repoManager.GetDeviceRepositoryWithSecretsAsync(createServiceTicketRequest.RepoId, org, user);

            if (repo == null)
            {
                throw new InvalidOperationException($"Could not find repository for id {createServiceTicketRequest.RepoId}");
            }
            if (org != null && template.OwnerOrganization != org)
            {
                throw new InvalidOperationException("Template, org mismatch.");
            }

            Console.WriteLine("+++1");

            Device device = null;

            if (!String.IsNullOrEmpty(createServiceTicketRequest.DeviceId))
            {
                device = await _deviceManager.GetDeviceByDeviceIdAsync(repo, createServiceTicketRequest.DeviceId, template.OwnerOrganization, user ?? template.DefaultContact);

                if (device == null)
                {
                    device = await _deviceManager.GetDeviceByIdAsync(repo, createServiceTicketRequest.DeviceId, template.OwnerOrganization, user ?? template.DefaultContact);

                    if (device == null) // still null
                    {
                        throw new ArgumentNullException($"Could not find device with device id {createServiceTicketRequest.DeviceId}.");
                    }
                }
            }
            else if (!String.IsNullOrEmpty(createServiceTicketRequest.DeviceUniqueId))
            {
                device = await _deviceManager.GetDeviceByIdAsync(repo, createServiceTicketRequest.DeviceUniqueId, template.OwnerOrganization, user ?? template.DefaultContact);

                if (device == null)
                {
                    throw new ArgumentNullException($"Could not find device with device id {createServiceTicketRequest.DeviceUniqueId}.");
                }
            }
            else
            {
                throw new ArgumentNullException("Must supply either DeviceId or DeviceUniqueId to create a service ticket.");
            }

            if (org != null && device.OwnerOrganization != org)
            {
                throw new InvalidOperationException("Device, org mismatch.");
            }

            Console.WriteLine("+++2");

            var stateSet = await _ticketStatusRepo.GetTicketStatusDefinitionAsync(template.StatusType.Id);

            var defaultState = stateSet.Items.Where(st => st.IsDefault).First();

            var assignedToUser = device.AssignedUser;

            if (assignedToUser == null)
            {
                assignedToUser = repo.AssignedUser;
            }

            if (assignedToUser == null)
            {
                assignedToUser = template.DefaultContact;
            }

            var currentTimeStamp = DateTime.UtcNow.ToJSONString();

            EntityHeader <ServiceBoard> boardEH = null;

            Console.WriteLine("+++3");

            var ticketId = Guid.NewGuid().ToString();

            if (!String.IsNullOrEmpty(createServiceTicketRequest.BoardId))
            {
                var board = await _serviceBoardRepo.GetServiceBoardAsync(createServiceTicketRequest.BoardId);

                boardEH = new EntityHeader <ServiceBoard>()
                {
                    Id = board.Id, Text = board.Name
                };
                var ticketNumber = await _serviceBoardRepo.GetNextTicketNumber(createServiceTicketRequest.BoardId);

                ticketId = $"{board.BoardAbbreviation}-{ticketNumber}";

                if (assignedToUser == null && !EntityHeader.IsNullOrEmpty(board.PrimaryContact))
                {
                    assignedToUser = board.PrimaryContact;
                }
            }
            else if (!EntityHeader.IsNullOrEmpty(repo.ServiceBoard))
            {
                boardEH = new EntityHeader <ServiceBoard>()
                {
                    Id = repo.ServiceBoard.Id, Text = repo.ServiceBoard.Text
                };

                var board = await _serviceBoardRepo.GetServiceBoardAsync(repo.ServiceBoard.Id);

                var ticketNumber = await _serviceBoardRepo.GetNextTicketNumber(repo.ServiceBoard.Id);

                ticketId = $"{board.BoardAbbreviation}-{ticketNumber}";
            }

            Console.WriteLine("+++4");

            string dueDate = null;

            if (!EntityHeader.IsNullOrEmpty(template.TimeToCompleteTimeSpan) &&
                template.TimeToCompleteTimeSpan.Value != TimeSpanIntervals.NotApplicable &&
                template.TimeToCompleteQuantity.HasValue)
            {
                TimeSpan ts = TimeSpan.Zero;
                switch (template.TimeToCompleteTimeSpan.Value)
                {
                case TimeSpanIntervals.Minutes: ts = TimeSpan.FromMinutes(template.TimeToCompleteQuantity.Value); break;

                case TimeSpanIntervals.Hours: ts = TimeSpan.FromHours(template.TimeToCompleteQuantity.Value); break;

                case TimeSpanIntervals.Days: ts = TimeSpan.FromDays(template.TimeToCompleteQuantity.Value); break;
                }

                dueDate = DateTime.UtcNow.Add(ts).ToJSONString();
            }

            string statusDueDate = null;

            if (EntityHeader.IsNullOrEmpty(defaultState.TimeAllowedInStatusTimeSpan) &&
                defaultState.TimeAllowedInStatusTimeSpan.Value != TimeSpanIntervals.NotApplicable &&
                defaultState.TimeAllowedInStatusQuantity.HasValue)
            {
                TimeSpan ts = TimeSpan.Zero;
                switch (defaultState.TimeAllowedInStatusTimeSpan.Value)
                {
                case TimeSpanIntervals.Minutes: ts = TimeSpan.FromMinutes(defaultState.TimeAllowedInStatusQuantity.Value); break;

                case TimeSpanIntervals.Hours: ts = TimeSpan.FromHours(defaultState.TimeAllowedInStatusQuantity.Value); break;

                case TimeSpanIntervals.Days: ts = TimeSpan.FromDays(defaultState.TimeAllowedInStatusQuantity.Value); break;
                }

                statusDueDate = DateTime.UtcNow.Add(ts).ToJSONString();
            }

            Console.WriteLine("+++5");

            var ticket = new ServiceTicket()
            {
                Key             = template.Key,
                TicketId        = ticketId,
                DeviceRepo      = EntityHeader.Create(repo.Id, repo.Name),
                CreationDate    = currentTimeStamp,
                LastUpdatedDate = currentTimeStamp,
                DueDate         = dueDate,
                Name            = $"{template.Name} ({device.DeviceId})",
                Address         = device.Address,
                IsClosed        = false,
                Description     = template.Description,
                Subject         = String.IsNullOrEmpty(createServiceTicketRequest.Subject) ? $"{template.Name} ({device.DeviceId})" : createServiceTicketRequest.Subject,
                AssignedTo      = assignedToUser,
                Template        = new EntityHeader <ServiceTicketTemplate>()
                {
                    Id = template.Id, Text = template.Name
                },
                ServiceBoard = boardEH,
                Device       = new EntityHeader <IoT.DeviceManagement.Core.Models.Device>()
                {
                    Id = device.Id, Text = device.Name
                },
                Status               = EntityHeader.Create(defaultState.Key, defaultState.Name),
                StatusDate           = DateTime.UtcNow.ToJSONString(),
                OwnerOrganization    = template.OwnerOrganization,
                HoursEstimate        = template.HoursEstimate,
                CostEstimate         = template.CostEstimate,
                SkillLevel           = template.SkillLevel,
                Urgency              = template.Urgency,
                Tools                = template.Tools,
                PartsKits            = template.PartsKits,
                ServiceParts         = template.ServiceParts,
                Instructions         = template.Instructions,
                StatusType           = template.StatusType,
                StatusDueDate        = statusDueDate,
                Resources            = template.Resources,
                TroubleshootingSteps = template.TroubleshootingSteps,
                CreatedBy            = user,
                LastUpdatedBy        = user
            };

            ticket.StatusType.Value = stateSet;

            ticket.History.Add(new ServiceTicketStatusHistory()
            {
                AddedBy   = user,
                DateStamp = DateTime.UtcNow.ToJSONString(),
                Status    = ticket.Status.Text,
                Note      = $"Created service ticket with {defaultState.Name} status."
            });

            Console.WriteLine("+++6");

            ticket.Notes.Add(new ServiceTicketNote()
            {
                AddedBy   = user,
                DateStamp = currentTimeStamp,
                Note      = assignedToUser != null ? $"Service ticket created and assigned to {assignedToUser.Text}." : "Service ticket created and not assigned to technician."
            });

            if (!String.IsNullOrEmpty(createServiceTicketRequest.Details))
            {
                ticket.Notes.Add(new ServiceTicketNote()
                {
                    Id        = Guid.NewGuid().ToString(),
                    Note      = createServiceTicketRequest.Details,
                    AddedBy   = ticket.CreatedBy,
                    DateStamp = DateTime.UtcNow.ToJSONString()
                });
            }

            Console.WriteLine("+++7");


            await _repo.AddServiceTicketAsync(ticket);

            Console.WriteLine("+++8");

            await SendTicketNotificationAsync(ticket);

            Console.WriteLine("+++9");

            return(InvokeResult <string> .Create(ticket.TicketId));
        }
示例#15
0
        public async void Connect()
        {
            try
            {
                IsBusy = true;
                switch (Model.DefaultTransport.Value)
                {
                /*                    case TransportTypes.AMQP:
                 *                      {
                 *                          var connectionString = $"Endpoint=sb://{Model.DefaultEndPoint}.servicebus.windows.net/;SharedAccessKeyName={Model.AccessKeyName};SharedAccessKey={Model.AccessKey}";
                 *                          var bldr = new EventHubsConnectionStringBuilder(connectionString)
                 *                          {
                 *                              EntityPath = Model.HubName
                 *                          };
                 *
                 *                          _isConnected = true;
                 *                      }
                 *
                 *                      break;*/

                case TransportTypes.AzureIoTHub:
                {
                    if (String.IsNullOrEmpty(Model.AccessKey))
                    {
                        if (!await PromptForAccessKey())
                        {
                            return;
                        }
                    }

                    var connectionString = $"HostName={Model.DefaultEndPoint};DeviceId={Model.DeviceId};SharedAccessKey={Model.AccessKey}";
                    _azureIoTHubClient = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Amqp_Tcp_Only);
                    await _azureIoTHubClient.OpenAsync();

                    ReceivingTask = Task.Run(ReceiveDataFromAzure);
                    SetConnectedState();
                }
                break;

                case TransportTypes.MQTT:
                    if (!Model.Anonymous && String.IsNullOrEmpty(Model.Password))
                    {
                        if (!await PromptForPassword())
                        {
                            return;
                        }
                    }

                    _mqttClient = SLWIOC.Create <IMQTTDeviceClient>();
                    _mqttClient.ShowDiagnostics = true;
                    _mqttClient.BrokerHostName  = Model.DefaultEndPoint;
                    _mqttClient.BrokerPort      = Model.DefaultPort;
                    _mqttClient.DeviceId        = Model.UserName;
                    _mqttClient.Password        = Model.Password;
                    var result = await _mqttClient.ConnectAsync();

                    if (result.Result == ConnAck.Accepted)
                    {
                        _isConnected = true;
                        if (!String.IsNullOrEmpty(Model.Subscription))
                        {
                            var subscription = new MQTTSubscription()
                            {
                                Topic = Model.Subscription.Replace("~deviceid~", Model.DeviceId),
                                QOS   = EntityHeader <QOS> .Create(QOS.QOS2)
                            };
                            await _mqttClient.SubscribeAsync(subscription);

                            _mqttClient.MessageReceived += _mqttClient_CommandReceived;
                        }

                        SetConnectedState();
                    }
                    else
                    {
                        await Popups.ShowAsync($"{Resources.SimulatorCoreResources.Simulator_ErrorConnecting}: {result.Message}");
                    }

                    break;

                case TransportTypes.TCP:
                    _tcpClient = SLWIOC.Create <ITCPClient>();
                    await _tcpClient.ConnectAsync(Model.DefaultEndPoint, Model.DefaultPort);

                    StartReceiveThread();
                    SetConnectedState();
                    break;

                case TransportTypes.UDP:
                    _udpClient = SLWIOC.Create <IUDPClient>();
                    await _udpClient.ConnectAsync(Model.DefaultEndPoint, Model.DefaultPort);

                    StartReceiveThread();
                    SetConnectedState();
                    break;
                }

                RightMenuIcon = Client.Core.ViewModels.RightMenuIcon.None;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                await Popups.ShowAsync(ex.Message);

                if (_mqttClient != null)
                {
                    _mqttClient.Dispose();
                    _mqttClient = null;
                }

                if (_azureIoTHubClient != null)
                {
                    await _azureIoTHubClient.CloseAsync();

                    _azureIoTHubClient.Dispose();
                    _azureIoTHubClient = null;
                }

                if (_tcpClient != null)
                {
                    await _tcpClient.DisconnectAsync();

                    _tcpClient.Dispose();
                    _tcpClient = null;
                }

                if (_udpClient != null)
                {
                    await _udpClient.DisconnectAsync();

                    _udpClient.Dispose();
                    _udpClient = null;
                }

                SetDisconnectedState();
            }
            finally
            {
                IsBusy = false;
            }
        }
        protected async Task ValidateRequest(HttpRequest request)
        {
            CheckHeader(request, DATE);
            CheckHeader(request, VERSION);
            CheckHeader(request, REQUEST_ID);
            CheckHeader(request, ORG_ID);
            CheckHeader(request, ORG);
            CheckHeader(request, USER_ID);
            CheckHeader(request, USER);
            CheckHeader(request, INSTANCE_ID);
            CheckHeader(request, INSTANCE);

            var authheader = request.Headers["Authorization"];

            var requestId    = GetHeader(request, REQUEST_ID);
            var dateStamp    = GetHeader(request, DATE);
            var orgId        = GetHeader(request, ORG_ID);
            var org          = GetHeader(request, ORG);
            var userId       = GetHeader(request, USER_ID);
            var user         = GetHeader(request, USER);
            var instanceId   = GetHeader(request, INSTANCE_ID);
            var instanceName = GetHeader(request, INSTANCE);
            var version      = GetHeader(request, VERSION);

            var bldr = new StringBuilder();

            //Adding the \r\n manualy ensures that the we don't have any
            //platform specific code messing with our signature.
            bldr.Append($"{requestId}\r\n");
            bldr.Append($"{dateStamp}\r\n");
            bldr.Append($"{version}\r\n");
            bldr.Append($"{orgId}\r\n");
            bldr.Append($"{userId}\r\n");
            bldr.Append($"{instanceId}\r\n");

            OrgEntityHeader      = EntityHeader.Create(orgId, org);
            UserEntityHeader     = EntityHeader.Create(userId, user);
            InstanceEntityHeader = EntityHeader.Create(instanceId, instanceName);

            var instance = await _instanceManager.GetInstanceAsync(instanceId, OrgEntityHeader, UserEntityHeader);

            var key1 = await _secureStorage.GetSecretAsync(OrgEntityHeader, instance.SharedAccessKeySecureId1, UserEntityHeader);

            if (!key1.Successful)
            {
                throw new Exception(key1.Errors.First().Message);
            }

            var calculatedFromFirst = GetSignature(requestId, key1.Result, bldr.ToString());

            if (calculatedFromFirst != authheader)
            {
                var key2 = await _secureStorage.GetSecretAsync(OrgEntityHeader, instance.SharedAccessKeySecureId2, UserEntityHeader);

                if (!key2.Successful)
                {
                    throw new Exception(key2.Errors.First().Message);
                }

                var calculatedFromSecond = GetSignature(requestId, key2.Result, bldr.ToString());
                if (calculatedFromSecond != authheader)
                {
                    throw new UnauthorizedAccessException("Invalid signature.");
                }
            }
        }
示例#17
0
 public override void MapToOrganizationLocation(OrgLocation location)
 {
     base.MapToOrganizationLocation(location);
     location.AdminContact     = EntityHeader.Create(AdminContactId, AdminContact);
     location.TechnicalContact = EntityHeader.Create(AdminContactId, TechnicalContact);
 }
示例#18
0
 public EntityHeader GetInvitedByEntityHeader()
 {
     return(EntityHeader.Create(InvitedById, InvitedByName));
 }
示例#19
0
 public EntityHeader ToEntityHeader()
 {
     return(EntityHeader.Create(Id, Name));
 }
示例#20
0
        private DataStream GetValidStream()
        {
            if (_stream != null)
            {
                return(_stream);
            }

            _stream = new Pipeline.Admin.Models.DataStream()
            {
                Id = "06A0754DB67945E7BAD5614B097C61F5",
                DbValidateSchema = true,
                Key                = "mykey",
                Name               = "My Name",
                StreamType         = Core.Models.EntityHeader <DataStreamTypes> .Create(DataStreamTypes.SQLServer),
                DbUserName         = System.Environment.GetEnvironmentVariable("SQLSERVERUID"),
                DbName             = System.Environment.GetEnvironmentVariable("SQLSERVERDB"),
                DbURL              = System.Environment.GetEnvironmentVariable("SQLSERVERURL"),
                DbPassword         = System.Environment.GetEnvironmentVariable("SQLSERVERPWD"),
                AzureAccessKey     = System.Environment.GetEnvironmentVariable("AZUREACCESSKEY"),
                CreationDate       = DateTime.Now.ToJSONString(),
                LastUpdatedDate    = DateTime.Now.ToJSONString(),
                CreatedBy          = EntityHeader.Create("A8A087E53D2043538F32FB18C2CA67F7", "user"),
                LastUpdatedBy      = EntityHeader.Create("A8A087E53D2043538F32FB18C2CA67F7", "user"),
                DbTableName        = "unittest",
                DeviceIdFieldName  = "deviceId",
                TimestampFieldName = "timeStamp",
            };


            Assert.IsNotNull(_stream.DbURL);
            Assert.IsNotNull(_stream.DbUserName);
            Assert.IsNotNull(_stream.DbPassword);
            Assert.IsNotNull(_stream.DbName);

            _stream.Fields.Add(new DataStreamField()
            {
                FieldName  = "value1",
                IsRequired = true,
                FieldType  = Core.Models.EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Integer),
                Name       = "name1",
                Key        = "key1"
            });

            _stream.Fields.Add(new DataStreamField()
            {
                FieldName = "value2",
                FieldType = Core.Models.EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Integer),
                Name      = "name2",
                Key       = "key2"
            });

            _stream.Fields.Add(new DataStreamField()
            {
                FieldName = "value3",
                FieldType = Core.Models.EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Decimal),
                Name      = "name3",
                Key       = "key3"
            });

            _stream.Fields.Add(new DataStreamField()
            {
                FieldName  = "customid",
                IsRequired = true,
                FieldType  = Core.Models.EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.String),
                Name       = "name4",
                Key        = "key4"
            });

            _stream.Fields.Add(new DataStreamField()
            {
                FieldName = "location",
                FieldType = Core.Models.EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.GeoLocation),
                Name      = "name5",
                Key       = "key5"
            });

            _stream.Fields.Add(new DataStreamField()
            {
                FieldName  = "pointIndex",
                FieldType  = Core.Models.EntityHeader <DeviceAdmin.Models.ParameterTypes> .Create(DeviceAdmin.Models.ParameterTypes.Integer),
                Name       = "name6",
                IsRequired = true,
                Key        = "key6"
            });

            return(_stream);
        }
        public void InstanceValidation_ListenerUniquePorts_Valid()
        {
            var instance = new DeploymentInstance()
            {
                Id                  = Guid.NewGuid().ToId(),
                CreationDate        = DateTime.UtcNow.ToJSONString(),
                LastUpdatedDate     = DateTime.UtcNow.ToJSONString(),
                LastUpdatedBy       = EntityHeader.Create("6DA61E6EA91448618F2248C97C354F1C", "USER"),
                CreatedBy           = EntityHeader.Create("6DA61E6EA91448618F2248C97C354F1C", "CREATED"),
                OwnerOrganization   = EntityHeader.Create("1112403B28644ED180465C0393F0CA14", "USER"),
                Key                 = "instancekey",
                Name                = "MyInstance",
                NuvIoTEdition       = EntityHeader <NuvIoTEditions> .Create(NuvIoTEditions.App),
                ContainerRepository = new EntityHeader()
                {
                    Id = "2212403B28644ED180465C0393F0CA14", Text = "Container"
                },
                ContainerTag = new EntityHeader()
                {
                    Id = "3312403B28644ED180465C0393F0CA14", Text = "ContainerTag"
                },
                CloudProvider = new EntityHeader()
                {
                    Id = "4412403B28644ED180465C0393F0CA14", Text = "CloudProvider"
                },
                Subscription = new EntityHeader()
                {
                    Id = "7712403B28644ED180465C0393F0CA14", Text = "MySubscription"
                },
                Size = new EntityHeader()
                {
                    Id = "9912403B28644ED180465C0393F0CA14", Text = "MySubscription"
                },
                DeviceRepository = new EntityHeader <DeviceManagement.Core.Models.DeviceRepository>()
                {
                    Id    = "AA12403B28644ED180465C0393F0CA14",
                    Text  = "DeviceRepo",
                    Value = new DeviceManagement.Core.Models.DeviceRepository()
                    {
                    }
                },
                Solution = new EntityHeader <Solution>()
                {
                    Id    = "BB12403B28644ED180465C0393F0CA14",
                    Text  = "MySolution",
                    Value = new Solution()
                    {
                        Id                = "BB12403B28644ED180465C0393F0CA14",
                        CreationDate      = DateTime.UtcNow.ToJSONString(),
                        LastUpdatedDate   = DateTime.UtcNow.ToJSONString(),
                        LastUpdatedBy     = EntityHeader.Create("6DA61E6EA91448618F2248C97C354F1C", "USER"),
                        CreatedBy         = EntityHeader.Create("6DA61E6EA91448618F2248C97C354F1C", "CREATED"),
                        OwnerOrganization = EntityHeader.Create("1112403B28644ED180465C0393F0CA14", "USER"),
                        Key               = "solutionkey",
                        Name              = "MySolution",
                        Planner           = new EntityHeader <Pipeline.Admin.Models.PlannerConfiguration>()
                        {
                            Id    = "07F5FD0D4D734AC48110-184DCB20F285",
                            Text  = "MyPlanner",
                            Value = new Pipeline.Admin.Models.PlannerConfiguration()
                            {
                                Id                = "07F5FD0D4D734AC48110184DCB20F285",
                                Name              = "MyPlanner",
                                CreationDate      = DateTime.UtcNow.ToJSONString(),
                                LastUpdatedDate   = DateTime.UtcNow.ToJSONString(),
                                LastUpdatedBy     = EntityHeader.Create("6DA61E6EA91448618F2248C97C354F1C", "USER"),
                                CreatedBy         = EntityHeader.Create("6DA61E6EA91448618F2248C97C354F1C", "CREATED"),
                                OwnerOrganization = EntityHeader.Create("1112403B28644ED180465C0393F0CA14", "USER"),
                                Key               = "plannerkey",
                            }
                        }
                    }
                }
            };

            var result = Validator.Validate(instance, Actions.Any);

            //AssertIsValid(result);
        }
示例#22
0
 public Verifier()
 {
     Headers         = new ObservableCollection <Header>();
     ExpectedOutputs = new ObservableCollection <ExpectedValue>();
     VerifierType    = EntityHeader <VerifierTypes> .Create(VerifierTypes.NotSpecified);
 }
示例#23
0
 public EntityHeader ToUserEntityHeader()
 {
     return(EntityHeader.Create(RequestedByUserId, RequestedByUserName));
 }
示例#24
0
        private async Task <InvokeResult> HandleSystemMessageAsync(string path, string payload)
        {
            Metrics.MessagesProcessed++;

            PEMBus.InstanceLogger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Message, "ListenerMOdule_HandleSystemMessageAsync", "Received System Message", path.ToKVP("topic"), payload.ToKVP("body"));

            var parts = path.Split('/');

            if (parts.Length < 5)
            {
                var errMsg = $"NuvIoT service messages must be at least 5 segments {path} is {parts.Length} segments";
                PEMBus.InstanceLogger.AddError("ListenerModule__HandleSystemMessage", errMsg);
                return(InvokeResult.FromError(errMsg));
            }

            var deviceId = parts[3];

            var device = await PEMBus.DeviceStorage.GetDeviceByDeviceIdAsync(deviceId);

            if (device == null)
            {
                var errMsg = $"Could not find device with device id {deviceId}.";
                PEMBus.InstanceLogger.AddError("ListenerModule__HandleSystemMessage", errMsg);
                return(InvokeResult.FromError(errMsg));
            }

            device.LastContact = DateTime.UtcNow.ToJSONString();

            if (parts[4] == "state")
            {
                device.DeviceTwinDetails.Insert(0, new DeviceManagement.Models.DeviceTwinDetails()
                {
                    Timestamp = DateTime.UtcNow.ToJSONString(),
                    Details   = payload
                });

                var payloadSegements = payload.Split(',');
                foreach (var segement in payloadSegements)
                {
                    var fieldParts = segement.Split('=');
                    if (fieldParts.Length == 2)
                    {
                        var nameParts = fieldParts[0].Split('-');
                        if (nameParts.Length == 2)
                        {
                            var typeName = nameParts[0];
                            var key      = nameParts[1];
                            var value    = fieldParts[1];
                            if (typeName != "readonly")
                            {
                                var prop = device.Properties.FirstOrDefault(prp => prp.Key == key);
                                if (prop != null)
                                {
                                    if (prop.Value != value)
                                    {
                                        prop.Value         = value;
                                        prop.LastUpdated   = DateTime.UtcNow.ToJSONString();
                                        prop.LastUpdatedBy = "Device Twin";
                                    }
                                }
                            }
                            else
                            {
                                if (key == "firmwareSku")
                                {
                                    device.ActualFirmware     = value;
                                    device.ActualFirmwareDate = DateTime.Now.ToJSONString();
                                }
                                if (key == "firmwareVersion")
                                {
                                    device.ActualFirmwareRevision = value;
                                    device.ActualFirmwareDate     = DateTime.Now.ToJSONString();
                                }
                            }
                        }
                    }
                }
            }
            else if (parts[4] == "err")
            {
                var err       = parts[5];
                var action    = parts[6];
                var exception = new DeviceException()
                {
                    ErrorCode          = err,
                    DeviceId           = device.DeviceId,
                    DeviceUniqueId     = device.Id,
                    DeviceRepositoryId = device.DeviceRepository.Id,
                    Timestamp          = DateTime.UtcNow.ToString(),
                };

                exception.AdditionalDetails.Add(payload);

                if (action == "raise")
                {
                    await PEMBus.InstanceConnector.HandleDeviceExceptionAsync(exception);
                }
                else if (action == "clear")
                {
                    await PEMBus.InstanceConnector.ClearDeviceExceptionAsync(exception);
                }
            }
            else if (parts[4] == "iovalues")
            {
                var values = payload.Split(',');
                if (values.Length != 16)
                {
                    throw new InvalidDataException($"IO Configuration from device should consist of 16 comma delimited values, message consists of ${values.Length} items.");
                }

                for (int idx = 0; idx < 8; ++idx)
                {
                    if (!String.IsNullOrEmpty(values[idx + 8]))
                    {
                        var sensor = device.SensorCollection.Where(sns => sns.Technology != null && sns.Technology.Value == DeviceManagement.Models.SensorTechnology.ADC && sns.PortIndex == idx).FirstOrDefault();
                        if (sensor != null)
                        {
                            sensor.Value       = values[idx + 8];
                            sensor.LastUpdated = DateTime.UtcNow.ToJSONString();
                        }
                    }
                }

                for (int idx = 0; idx < 8; ++idx)
                {
                    if (!String.IsNullOrEmpty(values[idx]))
                    {
                        var sensor = device.SensorCollection.Where(sns => sns.Technology != null && sns.Technology.Value == DeviceManagement.Models.SensorTechnology.IO && sns.PortIndex == idx).FirstOrDefault();
                        if (sensor != null)
                        {
                            sensor.Value       = values[idx];
                            sensor.LastUpdated = DateTime.UtcNow.ToJSONString();
                        }
                    }
                }

                await PEMBus.SensorEvaluator.EvaluateAsync(device);
            }
            else if (parts[4] == "geo")
            {
                var values = payload.Split(',');
                if (values.Length < 2)
                {
                    throw new InvalidDataException($"Geo Location Data type must contain a minimum of 2 fields for latitude and longitude, message consists of ${values.Length} items.");
                }

                if (!double.TryParse(values[0], out double lat))
                {
                    throw new InvalidDataException($"Invalid Latitude value [{values[0]}].");
                }

                if (lat > 90 || lat < -90)
                {
                    throw new InvalidDataException($"Invalid Latitude value [{values[0]}], must be between -90 and 90.");
                }

                if (!double.TryParse(values[1], out double lon))
                {
                    throw new InvalidDataException($"Invalid Longitude value [{values[1]}].");
                }

                if (lon > 180 || lon < -180)
                {
                    throw new InvalidDataException($"Invalid Latitude value [{values[1]}], must be between -180 and 180.");
                }

                device.GeoLocation = new LagoVista.Core.Models.Geo.GeoLocation()
                {
                    LastUpdated = DateTime.UtcNow.ToJSONString(),
                    Latitude    = lat,
                    Longitude   = lon,
                };
            }
            else if (parts[4] == "online")
            {
                device.ConnectionTimeStamp = DateTime.UtcNow.ToJSONString();
                var rssi      = -1.0;
                var reconnect = false;

                var payloadSegements = payload.Split(',');
                foreach (var segement in payloadSegements)
                {
                    var fieldParts = segement.Split('=');
                    if (fieldParts.Length == 2)
                    {
                        var nameParts = fieldParts[0].Split('-');
                        if (nameParts.Length == 2)
                        {
                            var typeName = nameParts[0];
                            var key      = nameParts[1];
                            var value    = fieldParts[1];
                            if (typeName != "readonly")
                            {
                                var prop = device.Properties.FirstOrDefault(prp => prp.Key == key);
                                if (prop != null)
                                {
                                    if (prop.Value != value)
                                    {
                                        if (prop.AttributeType.Value == DeviceAdmin.Models.ParameterTypes.TrueFalse)
                                        {
                                            if (value == "1")
                                            {
                                                value = "true";
                                            }
                                            else if (value == "0")
                                            {
                                                value = "false";
                                            }
                                            else
                                            {
                                                value = value.ToLower();
                                            }
                                        }
                                        prop.Value         = value;
                                        prop.LastUpdated   = DateTime.UtcNow.ToJSONString();
                                        prop.LastUpdatedBy = "Device Twin";
                                    }
                                }
                            }
                            else
                            {
                                if (key == "firmwareSku")
                                {
                                    device.ActualFirmware     = value;
                                    device.ActualFirmwareDate = DateTime.Now.ToJSONString();
                                }
                                if (key == "firmwareVersion")
                                {
                                    device.ActualFirmwareRevision = value;
                                    device.ActualFirmwareDate     = DateTime.Now.ToJSONString();
                                }
                                if (key == "rssi")
                                {
                                    double.TryParse(value, out rssi);
                                }
                                if (key == "reconnect")
                                {
                                    reconnect = value != "0";
                                }
                            }
                        }
                    }
                }

                var connectionEvent = new DeviceConnectionEvent()
                {
                    DeviceId         = device.Id,
                    FirmwareRevision = device.ActualFirmwareRevision,
                    FirmwareSKU      = device.ActualFirmware,
                    TimeStamp        = DateTime.UtcNow.ToJSONString(),
                    RSSI             = rssi,
                    Reconnect        = reconnect
                };

                await PEMBus.DeviceConnectionEvent.AddDeviceEventConnectionEvent(connectionEvent);
            }

            await PEMBus.DeviceStorage.UpdateDeviceAsync(device);

            var json         = JsonConvert.SerializeObject(Models.DeviceForNotification.FromDevice(device), _camelCaseSettings);
            var notification = new Notification()
            {
                Payload     = json,
                Channel     = EntityHeader <Channels> .Create(Channels.Device),
                ChannelId   = device.Id,
                PayloadType = "Device",
                DateStamp   = DateTime.UtcNow.ToJSONString(),
                MessageId   = Guid.NewGuid().ToId(),
                Text        = "Device Updated",
                Title       = "Device Updated"
            };

            await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification);

            notification = new Notification()
            {
                Payload     = json,
                Channel     = EntityHeader <Channels> .Create(Channels.DeviceRepository),
                ChannelId   = device.DeviceRepository.Id,
                PayloadType = "Device",
                DateStamp   = DateTime.UtcNow.ToJSONString(),
                MessageId   = Guid.NewGuid().ToId(),
                Text        = "Device Updated",
                Title       = "Device Updated"
            };

            await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification);

            foreach (var group in device.DeviceGroups)
            {
                notification = new Notification()
                {
                    Payload     = json,
                    Channel     = EntityHeader <Channels> .Create(Channels.DeviceGroup),
                    ChannelId   = group.Id,
                    PayloadType = "Device",
                    DateStamp   = DateTime.UtcNow.ToJSONString(),
                    MessageId   = Guid.NewGuid().ToId(),
                    Text        = "Device Updated",
                    Title       = "Device Updated"
                };

                await PEMBus.NotificationPublisher.PublishAsync(Targets.WebSocket, notification);
            }

            return(InvokeResult.Success);
        }
示例#25
0
 public EntityHeader ToOrgEntityHeader()
 {
     return(EntityHeader.Create(RequestedByOrganizationId, RequestedByOrganizationName));
 }
示例#26
0
 public EntityHeader ToEntityHeader()
 {
     return(EntityHeader.Create(Id, $"{FirstName} ${LastName}"));
 }
示例#27
0
        public async Task <InvokeResult <Solution> > CreateSimpleSolutionAsync(EntityHeader org, EntityHeader user, DateTime createTimeStamp)
        {
            /* Create unit/state sets */
            var stateSet = new StateSet()
            {
                Key         = "onoff",
                Name        = "On/Off",
                Description = "Provides two simple states, On and Off",
                States      = new List <State> {
                    new State()
                    {
                        Key = "on", Name = "On", IsInitialState = true
                    },
                    new State()
                    {
                        Key = "off", Name = "Off"
                    }
                }
            };

            AddId(stateSet);
            AddOwnedProperties(stateSet, org);
            AddAuditProperties(stateSet, createTimeStamp, org, user);
            await _deviceAdminMgr.AddStateSetAsync(stateSet, org, user);

            var unitSet = new UnitSet()
            {
                Key   = "Temperature",
                Name  = "temperature",
                Units = new List <Unit>()
                {
                    new Unit()
                    {
                        Key = "fahrenheit", Name = "Fahrenheit", IsDefault = true
                    },
                    new Unit()
                    {
                        Key = "celsius", Name = "Celsius", IsDefault = false
                    },
                }
            };

            AddId(unitSet);
            AddOwnedProperties(unitSet, org);
            AddAuditProperties(unitSet, createTimeStamp, org, user);
            await _deviceAdminMgr.AddUnitSetAsync(unitSet, org, user);

            /* Create Pipeline Modules */
            var restListener = new ListenerConfiguration()
            {
                Name           = "Sample Rest",
                Key            = "samplereset",
                ListenerType   = EntityHeader <ListenerTypes> .Create(ListenerTypes.Rest),
                RestServerType = EntityHeader <RESTServerTypes> .Create(RESTServerTypes.HTTP),
                ListenOnPort   = 80,
                ContentType    = EntityHeader <DeviceMessaging.Admin.Models.MessageContentTypes> .Create(DeviceMessaging.Admin.Models.MessageContentTypes.JSON),
                UserName       = "******",
                Password       = "******"
            };

            AddId(restListener);
            AddOwnedProperties(restListener, org);
            AddAuditProperties(restListener, createTimeStamp, org, user);
            await _pipelineMgr.AddListenerConfigurationAsync(restListener, org, user);

            var msgTempDefinition = new DeviceMessaging.Admin.Models.DeviceMessageDefinition()
            {
                Name           = "Sample Temperature Message",
                Key            = "sampletempmsg",
                SampleMessages = new List <DeviceMessaging.Admin.Models.SampleMessage>()
                {
                    new DeviceMessaging.Admin.Models.SampleMessage()
                    {
                        Id      = Guid.NewGuid().ToId(),
                        Name    = "Example Temperature Message",
                        Key     = "exmpl001",
                        Payload = "98.5,38",
                        Headers = new System.Collections.ObjectModel.ObservableCollection <DeviceMessaging.Admin.Models.Header>()
                        {
                            new DeviceMessaging.Admin.Models.Header()
                            {
                                Name = "x-deviceid", Value = "device001"
                            },
                            new DeviceMessaging.Admin.Models.Header()
                            {
                                Name = "x-messageid", Value = "tmpmsg001"
                            }
                        }
                    }
                },
                MessageId   = "smpltmp001",
                ContentType = EntityHeader <DeviceMessaging.Admin.Models.MessageContentTypes> .Create(DeviceMessaging.Admin.Models.MessageContentTypes.Delimited),
                Fields      = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id             = Guid.NewGuid().ToId(),
                        Name           = "Temperature",
                        Key            = "temp",
                        DelimitedIndex = 0,
                        UnitSet        = new EntityHeader <UnitSet>()
                        {
                            Id = unitSet.Id, Text = unitSet.Name, Value = unitSet
                        },
                        StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.State),
                    },
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id             = Guid.NewGuid().ToId(),
                        Name           = "Humidity",
                        Key            = "humidity",
                        DelimitedIndex = 1,
                        StorageType    = EntityHeader <ParameterTypes> .Create(ParameterTypes.Integer),
                    }
                }
            };

            AddId(msgTempDefinition);
            AddOwnedProperties(msgTempDefinition, org);
            AddAuditProperties(msgTempDefinition, createTimeStamp, org, user);
            await _deviceMsgMgr.AddDeviceMessageDefinitionAsync(msgTempDefinition, org, user);

            var motionMsgDefinition = new DeviceMessaging.Admin.Models.DeviceMessageDefinition()
            {
                Name           = "Sample Motion Message",
                Key            = "samplemptionmsg",
                SampleMessages = new List <DeviceMessaging.Admin.Models.SampleMessage>()
                {
                    new DeviceMessaging.Admin.Models.SampleMessage()
                    {
                        Id                 = Guid.NewGuid().ToId(),
                        Name               = "Example Motion Message",
                        Key                = "exmpl001",
                        Payload            = "{'motion':'on','level':80}",
                        PathAndQueryString = "/motion/device001"
                    }
                },
                MessageId   = "smplmot001",
                ContentType = EntityHeader <DeviceMessaging.Admin.Models.MessageContentTypes> .Create(DeviceMessaging.Admin.Models.MessageContentTypes.JSON),
                Fields      = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id       = Guid.NewGuid().ToId(),
                        Name     = "Motion",
                        Key      = "motion",
                        JsonPath = "motion",
                        StateSet = new EntityHeader <StateSet>()
                        {
                            Id = stateSet.Id, Text = stateSet.Name, Value = stateSet
                        },
                        StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.State),
                    },
                    new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
                    {
                        Id          = Guid.NewGuid().ToId(),
                        Name        = "Level",
                        Key         = "level",
                        JsonPath    = "level",
                        StorageType = EntityHeader <ParameterTypes> .Create(ParameterTypes.Integer),
                    }
                }
            };

            AddId(motionMsgDefinition);
            AddOwnedProperties(motionMsgDefinition, org);
            AddAuditProperties(motionMsgDefinition, createTimeStamp, org, user);
            await _deviceMsgMgr.AddDeviceMessageDefinitionAsync(motionMsgDefinition, org, user);


            var deviceIdParser1 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Header),
                HeaderName     = "x-deviceid",
                Name           = "Device Id in Header",
                Key            = "xdeviceid"
            };

            var deviceIdParser2 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Path),
                PathLocator    = "/*/{deviceid}",
                Name           = "Device Id in Path",
                Key            = "pathdeviceid"
            };

            var messageIdParser1 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Header),
                HeaderName     = "x-messageid",
                Name           = "Message Id in Header",
                Key            = "xmessageid",
            };
            var messageIdParser2 = new DeviceMessaging.Admin.Models.DeviceMessageDefinitionField()
            {
                SearchLocation = EntityHeader <DeviceMessaging.Admin.Models.SearchLocations> .Create(DeviceMessaging.Admin.Models.SearchLocations.Path),
                PathLocator    = "/{messageid}/*",
                Name           = "Message Id in Path",
                Key            = "pathmessageid"
            };

            var verifier = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = motionMsgDefinition.Id,
                    Text = motionMsgDefinition.Name
                },
                ExpectedOutputs = new System.Collections.ObjectModel.ObservableCollection <ExpectedValue>()
                {
                    new ExpectedValue()
                    {
                        Key = "motion", Value = "on"
                    },
                    new ExpectedValue()
                    {
                        Key = "level", Value = "80"
                    }
                },
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Simple Message Verifier",
                Key                = "smplmsgver",
                Description        = "Validates that a Sample Motion Message has the proper field parsers",
                Input              = "{'motion':'on','level':80}",
                PathAndQueryString = "/smplmot001/device001",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageParser)
            };

            AddId(verifier);
            AddOwnedProperties(verifier, org);
            AddAuditProperties(verifier, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(verifier, org, user);

            var deviceIdParserVerifier1 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = deviceIdParser1.Id,
                    Text = deviceIdParser1.Name
                },
                ExpectedOutput = "device001",
                InputType      = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name           = "Find Device Id in Header",
                Key            = "msgidheader",
                Description    = "Validates that the Device Id can be extracted from the header",
                Headers        = new System.Collections.ObjectModel.ObservableCollection <DeviceMessaging.Admin.Models.Header>()
                {
                    new DeviceMessaging.Admin.Models.Header()
                    {
                        Name = "x-messageid", Value = "device001"
                    }
                },
                ShouldSucceed = true,
                VerifierType  = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(deviceIdParserVerifier1);
            AddOwnedProperties(deviceIdParserVerifier1, org);
            AddAuditProperties(deviceIdParserVerifier1, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(deviceIdParserVerifier1, org, user);

            var deviceIdParserVerifier2 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = deviceIdParser2.Id,
                    Text = deviceIdParser2.Name
                },
                ExpectedOutput     = "device002",
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Finds Device Id in Path",
                Key                = "msgidpath",
                Description        = "Validats the the device id can be extracted from thepath",
                PathAndQueryString = "/smplmot001/device002",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(deviceIdParserVerifier2);
            AddOwnedProperties(deviceIdParserVerifier2, org);
            AddAuditProperties(deviceIdParserVerifier2, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(deviceIdParserVerifier2, org, user);

            var messageIdParserVerifier1 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = messageIdParser1.Id,
                    Text = messageIdParser1.Name
                },
                ExpectedOutput = "smplmsg001",
                InputType      = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name           = "Finds Message id in Header",
                Key            = "msgidheader",
                Description    = "Validates that the message id can be extracted from the header",
                Headers        = new System.Collections.ObjectModel.ObservableCollection <DeviceMessaging.Admin.Models.Header>()
                {
                    new DeviceMessaging.Admin.Models.Header()
                    {
                        Name = "x-messageid", Value = "smplmsg001"
                    }
                },
                ShouldSucceed = true,
                VerifierType  = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(messageIdParserVerifier1);
            AddOwnedProperties(messageIdParserVerifier1, org);
            AddAuditProperties(messageIdParserVerifier1, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(messageIdParserVerifier1, org, user);

            var messageIdParserVerifier2 = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = messageIdParser2.Id,
                    Text = messageIdParser2.Name
                },
                ExpectedOutput     = "smplmot002",
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Finds Message id in Path",
                Key                = "msgidpath",
                Description        = "Validates that the message id can be extracted from path.",
                PathAndQueryString = "/smplmot002/device001",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser)
            };

            AddId(messageIdParserVerifier2);
            AddOwnedProperties(messageIdParserVerifier2, org);
            AddAuditProperties(messageIdParserVerifier2, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(messageIdParserVerifier2, org, user);

            var planner = new PlannerConfiguration()
            {
                Name = "Sample Planner",
                Key  = "sampleplanner",
                MessageTypeIdParsers = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    messageIdParser1, messageIdParser2
                },
                DeviceIdParsers = new List <DeviceMessaging.Admin.Models.DeviceMessageDefinitionField>()
                {
                    deviceIdParser1, deviceIdParser2
                }
            };

            AddId(planner);
            AddOwnedProperties(planner, org);
            AddAuditProperties(planner, createTimeStamp, org, user);
            await _pipelineMgr.AddPlannerConfigurationAsync(planner, org, user);


            /* Create Pipeline Modules */
            var sentinelConfiguration = new SentinelConfiguration()
            {
                Name = "Sample Sentinel",
                Key  = "samplereset",
            };

            AddId(sentinelConfiguration);
            AddOwnedProperties(sentinelConfiguration, org);
            AddAuditProperties(sentinelConfiguration, createTimeStamp, org, user);
            await _pipelineMgr.AddSentinelConfigurationAsync(sentinelConfiguration, org, user);

            var inputTranslator = new InputTranslatorConfiguration()
            {
                Name = "Sample Input Translator",
                Key  = "sampleinputtranslator",
                InputTranslatorType = EntityHeader <InputTranslatorConfiguration.InputTranslatorTypes> .Create(InputTranslatorConfiguration.InputTranslatorTypes.MessageBased),
            };

            AddId(inputTranslator);
            AddOwnedProperties(inputTranslator, org);
            AddAuditProperties(inputTranslator, createTimeStamp, org, user);
            await _pipelineMgr.AddInputTranslatorConfigurationAsync(inputTranslator, org, user);

            var wf = new DeviceWorkflow()
            {
                Key         = "sampleworkflow",
                Name        = "Sample Workflow",
                Description = "Sample Workflow",
                Attributes  = new List <DeviceAdmin.Models.Attribute>()
                {
                },
                Inputs = new List <WorkflowInput>()
                {
                },
                InputCommands = new List <InputCommand>()
                {
                },
                StateMachines = new List <StateMachine>()
                {
                },
                OutputCommands = new List <OutputCommand>()
                {
                }
            };

            AddId(wf);
            AddOwnedProperties(wf, org);
            AddAuditProperties(wf, createTimeStamp, org, user);
            await _deviceAdminMgr.AddDeviceWorkflowAsync(wf, org, user);

            var outTranslator = new OutputTranslatorConfiguration()
            {
                Name = "Sample Output Translator",
                Key  = "sampleinputtranslator",
                OutputTranslatorType = EntityHeader <OutputTranslatorConfiguration.OutputTranslatorTypes> .Create(OutputTranslatorConfiguration.OutputTranslatorTypes.MessageBased),
            };

            AddId(outTranslator);
            AddOwnedProperties(outTranslator, org);
            AddAuditProperties(outTranslator, createTimeStamp, org, user);
            await _pipelineMgr.AddOutputTranslatorConfigurationAsync(outTranslator, org, user);

            var tmpOutTrn = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = outTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = outTranslator.Id, Text = outTranslator.Name, Value = outTranslator
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.OutputTranslator)
            };
            var tmpWf = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = wf.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = wf.Id, Text = wf.Name, Value = wf
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = tmpOutTrn.Id, Name = outTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Workflow)
            };
            var tmpInputTrn = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = inputTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = inputTranslator.Id, Text = inputTranslator.Name, Value = inputTranslator
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = tmpWf.Id, Name = wf.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.InputTranslator)
            };
            var tmpSent = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = sentinelConfiguration.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = sentinelConfiguration.Id, Text = sentinelConfiguration.Name, Value = sentinelConfiguration
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = tmpInputTrn.Id, Name = inputTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Sentinel)
            };


            /* Create Route */
            var temperatureRoute = new Route()
            {
                Name = "Sample Temperature Route",
                Key  = "sampletemproute",
                MessageDefinition = new EntityHeader <DeviceMessaging.Admin.Models.DeviceMessageDefinition>()
                {
                    Id = msgTempDefinition.Id, Text = msgTempDefinition.Name, Value = msgTempDefinition
                },
                PipelineModules = new List <RouteModuleConfig>()
            };

            var motOutTran = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = outTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = outTranslator.Id, Text = outTranslator.Name, Value = outTranslator
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.OutputTranslator)
            };
            var motWf = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = wf.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = wf.Id, Text = wf.Name, Value = wf
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = motOutTran.Id, Name = outTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Workflow)
            };
            var motInputTrn = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = inputTranslator.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = inputTranslator.Id, Text = inputTranslator.Name, Value = inputTranslator
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = motWf.Id, Name = wf.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.InputTranslator)
            };

            var motSent = new RouteModuleConfig()
            {
                Id     = Guid.NewGuid().ToId(),
                Name   = sentinelConfiguration.Name,
                Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
                {
                    Id = sentinelConfiguration.Id, Text = sentinelConfiguration.Name, Value = sentinelConfiguration
                },
                PrimaryOutput = new RouteConnection()
                {
                    Id = motInputTrn.Id, Name = inputTranslator.Name, Mappings = new List <KeyValuePair <string, object> >()
                },
                ModuleType = EntityHeader <PipelineModuleType> .Create(PipelineModuleType.Sentinel)
            };

            /* Create Route */
            var motionRoute = new Route()
            {
                Name = "Sample Motion Route",
                Key  = "sampletemproute",
                MessageDefinition = new EntityHeader <DeviceMessaging.Admin.Models.DeviceMessageDefinition>()
                {
                    Id = motionMsgDefinition.Id, Text = motionMsgDefinition.Name, Value = motionMsgDefinition
                },
                PipelineModules = new List <RouteModuleConfig>()
                {
                    motSent, motInputTrn, motWf, motOutTran
                }
            };

            var deviceConfig = new DeviceConfiguration()
            {
                ConfigurationVersion = 1.0,
                Name       = "Sample Device Config",
                Key        = "sampledeviceconfig",
                Properties = new List <CustomField>()
                {
                    new CustomField()
                    {
                        Id           = Guid.NewGuid().ToId(),
                        DefaultValue = "90",
                        FieldType    = EntityHeader <ParameterTypes> .Create(ParameterTypes.Decimal),
                        Key          = "setpoint",
                        Name         = "Setpoint",
                        Label        = "Setpoint",
                        HelpText     = "Setpoint where temperature will trigger warning",
                        IsRequired   = true,
                        Order        = 1
                    }
                },
                Routes = new List <Route>()
                {
                    temperatureRoute,
                    motionRoute
                }
            };

            AddId(deviceConfig);
            AddOwnedProperties(deviceConfig, org);
            AddAuditProperties(deviceConfig, createTimeStamp, org, user);
            await _deviceCfgMgr.AddDeviceConfigurationAsync(deviceConfig, org, user);

            var deviceType = new DeviceType()
            {
                Name = "Sample Device Type",
                Key  = "sampledevicetype",
                DefaultDeviceConfiguration = new EntityHeader()
                {
                    Id = deviceConfig.Id, Text = deviceConfig.Name
                }
            };

            AddId(deviceType);
            AddOwnedProperties(deviceType, org);
            AddAuditProperties(deviceType, createTimeStamp, org, user);
            await _deviceTypeMgr.AddDeviceTypeAsync(deviceType, org, user);


            /* Create Solution */
            var solution = new Solution()
            {
                Id        = "Sample App",
                Name      = "sampleapp",
                Listeners = new List <EntityHeader <ListenerConfiguration> >()
                {
                    new EntityHeader <ListenerConfiguration>()
                    {
                        Id = restListener.Id, Text = restListener.Name, Value = restListener
                    }
                },
                Planner = new EntityHeader <PlannerConfiguration>()
                {
                    Id = planner.Id, Text = planner.Name, Value = planner
                },
                DeviceConfigurations = new List <EntityHeader <DeviceConfiguration> >()
                {
                    new EntityHeader <DeviceConfiguration>()
                    {
                        Id = deviceConfig.Id, Text = deviceConfig.Name, Value = deviceConfig
                    }
                },
            };

            AddId(solution);
            AddOwnedProperties(solution, org);
            AddAuditProperties(solution, createTimeStamp, org, user);

            return(InvokeResult <Solution> .Create(solution));
        }