public IHttpActionResult Put(int id, string sessionId, [FromBody] Event value)
        {
            var repository       = EventRepositoryCache.Instance.Get(sessionId.ToGuidWithAccessDenied());
            var validationResult = EventValidator.ValidateV3Update(value, true);

            if (!string.IsNullOrWhiteSpace(validationResult))
            {
                return(InternalServerError(new ArgumentException(validationResult)));
            }
            var item = repository.GetById(id);

            if (item == null || !repository.IsInteraction(item))
            {
                return(NotFound());
            }
            item.Date              = value.Date;
            item.AddressType       = value.AddressType;
            item.Broker            = value.Broker;
            item.BrokerAttendees   = value.BrokerAttendees;
            item.Companies         = value.Companies;
            item.Duration          = value.Duration;
            item.InteractionType   = value.InteractionType;
            item.InvestorAttendees = value.InvestorAttendees;
            item.Location          = value.Location;
            item.MeetingTypes      = value.MeetingTypes;
            item.Sectors           = value.Sectors;
            item.Title             = value.Title;
            repository.SetUpdated(item);
            return(Ok());
        }
示例#2
0
 public IActionResult SubmitForm(EventValidator data)
 {
     if (ModelState.IsValid)
     {
         if (data.Date < DateTime.Now)
         {
             ViewBag.Error = "Date has to be in future";
             return(View("EventForm"));
         }
         else
         {
             int?     x             = HttpContext.Session.GetInt32("ID");
             string   totalDuration = data.Duration + "" + data.Duration2;
             DateTime thisDate      = data.Date;
             DateTime g             = thisDate.Add(data.Time);
             Event    newEvent      = new Event {
                 Title       = data.Title,
                 Description = data.Description,
                 Datetime    = g,
                 Duration    = totalDuration,
                 UserId      = (int)x
             };
             _context.events.Add(newEvent);
             _context.SaveChanges();
             return(RedirectToAction("Main"));
         }
     }
     else
     {
         return(View("EventForm"));
     }
 }
示例#3
0
        public void Tree_Lazy_Child_ResolvesOnlyOnce()
        {
            var client = BaseTest.Initialize_Client(new TreeRequestResponse(TreeRequestScenario.MultiLevelContainer));

            var validator = new EventValidator(client, new[]
            {
                //Get Object
                UnitRequest.Objects("filter_objid=1001"),

                //Get Probe
                UnitRequest.Probes("filter_objid=1001&filter_parentid=0"),

                //Probe -> Devices/Groups
                UnitRequest.Devices("filter_parentid=1001"),
                UnitRequest.Groups("filter_parentid=1001"),

                //Probe -> Device -> Sensors
                UnitRequest.Sensors("filter_parentid=3001")
            });

            validator.MoveNext(2);
            var tree = client.GetTreeLazy(1001);

            validator.MoveNext(2);
            var child      = tree.Children[0];
            var childAgain = tree.Children[0];

            validator.MoveNext();
            var grandChild      = child.Children[0];
            var grandChildAgain = child.Children[0];
        }
        public ServiceSlotServiceInterceptor(EventValidator eventValidator, ServiceSlotValidator serviceSlotValidator)
        {
            _eventValidator       = eventValidator;
            _serviceSlotValidator = serviceSlotValidator;
            var mappings = new Dictionary <string, Action <IInvocation> >
            {
                {
                    nameof(AddServiceSlotAsync),
                    x => AddServiceSlotAsync((ServiceSlot)x.Arguments[0])
                },
                {
                    nameof(DeleteServiceSlotAsync),
                    x => DeleteServiceSlotAsync((int)x.Arguments[0], (int)x.Arguments[1])
                },
                {
                    nameof(GetAllServiceSlotsForEventAsync),
                    x => GetAllServiceSlotsForEventAsync((int)x.Arguments[0])
                },
                {
                    nameof(GetServiceSlotAsync),
                    x => GetServiceSlotAsync((int)x.Arguments[0], (int)x.Arguments[1])
                },
                {
                    nameof(UpdateServiceSlotAsync),
                    x => UpdateServiceSlotAsync((ServiceSlot)x.Arguments[0])
                }
            };

            BuildUp(mappings);
        }
        public void Execute(string[] parameters)
        {
            if (LogedUser.User == null)
            {
                throw new InvalidOperationException(ConsoleMessages.LogInFirst);
            }
            if (parameters.Length != 5)
            {
                throw new InvalidOperationException(ConsoleMessages.InvalidArgumentCount);
            }

            string   name        = parameters[1];
            string   description = parameters[2];
            DateTime?startDate   = parameters[3].CanConvertTo(typeof(DateTime)) ? (DateTime?)DateTime.Parse(parameters[3]) : null;
            DateTime?endDate     = parameters[4].CanConvertTo(typeof(DateTime)) ? (DateTime?)DateTime.Parse(parameters[4]) : null;

            var inputEvent = new InputEvent()
            {
                Name        = parameters[1],
                Description = parameters[2],
                StartDate   = parameters[3],
                EndDate     = parameters[4]
            };

            using (var ctx = new TeamBuilderContext())
            {
                var validator = new EventValidator();
                CommandUtils.ValidateAndThrowErrorCode(validator, inputEvent);
                var e = new Event();
                Mapper.Map(inputEvent, e);
                CreateEvent(ctx, e);
            }

            this.SucessMessage = $"Event {name} was created successfully!";
        }
        public async Task <CoapMessage> PutAsync(CoapMessage message)
        {
            CoapUri             uri = new CoapUri(message.ResourceUri.ToString());
            ResponseMessageType rmt = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;

            //EventValidator.Validate(false, resourceUriString, Channel, graphManager, context).Validated
            //if (!await adapter.CanSubscribeAsync(uri.Resource, channel.IsEncrypted))
            if (EventValidator.Validate(false, uri.Resource, channel, graphManager).Validated)
            {
                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
            }

            if (coapObserved.ContainsKey(uri.Resource) || coapUnobserved.Contains(uri.Resource))
            {
                //resource previously subscribed
                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.NotAcceptable, message.Token));
            }

            //this point the resource is not being observed, so we can
            // #1 subscribe to it
            // #2 add to unobserved resources (means not coap observed)

            SubscriptionMetadata metadata = new SubscriptionMetadata()
            {
                IsEphemeral = true,
                Identity    = session.Identity,
                Indexes     = session.Indexes
            };

            string subscriptionUriString = await adapter.SubscribeAsync(uri.Resource, metadata);

            coapUnobserved.Add(uri.Resource);

            return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Created, message.Token));
        }
示例#7
0
        public AttendeeServiceInterceptor(AttendeeValidator attendeeValidator, EventValidator eventValidator, PersonValidator personValidator)
        {
            _attendeeValidator = attendeeValidator;
            _eventValidator    = eventValidator;
            _personValidator   = personValidator;
            var mappings = new Dictionary <string, Action <IInvocation> >
            {
                {
                    nameof(CreateAttendeeRelationshipAsync),
                    x => CreateAttendeeRelationshipAsync((AttendeeRelationship)x.Arguments[0])
                },
                {
                    nameof(DeleteAttendeeRelationshipAsync),
                    x => DeleteAttendeeRelationshipAsync((int)x.Arguments[0], (int)x.Arguments[1])
                },
                {
                    nameof(GetAllRelationshipsForEventAsync),
                    x => GetAllRelationshipsForEventAsync((int)x.Arguments[0])
                },
                {
                    nameof(GetSingleRelationshipAsync),
                    x => GetSingleRelationshipAsync((int)x.Arguments[0], (int)x.Arguments[1])
                },
                {
                    nameof(UpdateAttendeeRelationshipAsync),
                    x => UpdateAttendeeRelationshipAsync((AttendeeRelationship)x.Arguments[0])
                }
            };

            BuildUp(mappings);
        }
        public async Task <CoapMessage> ObserveAsync(CoapMessage message)
        {
            if (!message.Observe.HasValue)
            {
                //RST because GET needs to be observe/unobserve
                await logger?.LogWarningAsync($"CoAP observe received without Observe flag and will return RST for {session.Identity}");

                await logger?.LogDebugAsync($"Returning RST because GET needs to be observe/unobserve for {session.Identity}");

                return(new CoapResponse(message.MessageId, ResponseMessageType.Reset, ResponseCodeType.EmptyMessage));
            }

            CoapUri             uri = new CoapUri(message.ResourceUri.ToString());
            ResponseMessageType rmt = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;

            ValidatorResult result = EventValidator.Validate(false, uri.Resource, channel, graphManager);

            if (!result.Validated)
            {
                await logger?.LogErrorAsync($"{result.ErrorMessage} for {session.Identity}");

                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
            }

            if (!message.Observe.Value)
            {
                //unsubscribe
                await logger?.LogInformationAsync($"CoAP unobserve '{message.ResourceUri.ToString()}' for {session.Identity}.");

                await adapter.UnsubscribeAsync(uri.Resource);

                await logger?.LogDebugAsync($"CoAP unsubscribed '{message.ResourceUri.ToString()} for {session.Identity}'.");

                coapObserved.Remove(uri.Resource);
            }
            else
            {
                //subscribe
                SubscriptionMetadata metadata = new SubscriptionMetadata()
                {
                    IsEphemeral = true,
                    Identity    = session.Identity,
                    Indexes     = session.Indexes
                };

                await logger?.LogInformationAsync($"CoAP subscribed '{message.ResourceUri.ToString()}' for {session.Identity}");

                string subscriptionUriString = await adapter.SubscribeAsync(uri.Resource, metadata);


                if (!coapObserved.ContainsKey(uri.Resource)) //add resource to observed list
                {
                    coapObserved.Add(uri.Resource, message.Token);
                    await logger?.LogDebugAsync("Key added to observable resource.");
                }
            }

            return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Valid, message.Token));
        }
示例#9
0
 public EventController(
     IEventService eventService,
     IImageProfileManager imageProfileManager)
 {
     _eventService        = eventService;
     _imageProfileManager = imageProfileManager;
     _validator           = new EventValidator(T);
 }
示例#10
0
 public EventTest()
 {
     _Name        = "Event name Test";
     _Description = "Event description";
     _StartDate   = "2019/03/07";
     _FinishDate  = "2019/03/07";
     validator    = new EventValidator();
 }
示例#11
0
        private async Task PublishAsync(PublishMessage message)
        {
            MessageAuditRecord record   = null;
            EventMetadata      metadata = null;

            try
            {
                MqttUri mqttUri = new MqttUri(message.Topic);
                metadata = await graphManager.GetPiSystemMetadataAsync(mqttUri.Resource);

                if (EventValidator.Validate(true, metadata, Channel, graphManager, context).Validated)
                {
                    EventMessage msg = new EventMessage(mqttUri.ContentType, mqttUri.Resource, ProtocolType.MQTT,
                                                        message.Encode(), DateTime.UtcNow, metadata.Audit);
                    if (!string.IsNullOrEmpty(mqttUri.CacheKey))
                    {
                        msg.CacheKey = mqttUri.CacheKey;
                    }

                    if (mqttUri.Indexes != null)
                    {
                        List <KeyValuePair <string, string> > list = GetIndexes(mqttUri);
                        await adapter.PublishAsync(msg, list);
                    }
                    else
                    {
                        await adapter.PublishAsync(msg);
                    }
                }
                else
                {
                    if (metadata.Audit)
                    {
                        record = new MessageAuditRecord("XXXXXXXXXXXX", session.Identity, Channel.TypeId, "MQTT",
                                                        message.Payload.Length, MessageDirectionType.In, false, DateTime.UtcNow,
                                                        "Not authorized, missing resource metadata, or channel encryption requirements");
                    }

                    throw new SecurityException(string.Format("'{0}' not authorized to publish to '{1}'",
                                                              session.Identity, metadata.ResourceUriString));
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex, $"MQTT adapter PublishAsync error on channel '{Channel.Id}'.");

                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
            finally
            {
                if (metadata != null && metadata.Audit && record != null)
                {
                    await messageAuditor?.WriteAuditRecordAsync(record);
                }
            }
        }
示例#12
0
        public void Tree_Lazy_Object_NoAPIRequests()
        {
            var client = BaseTest.Initialize_Client(new TreeRequestResponse(TreeRequestScenario.ContainerWithGrandChild));

            var validator = new EventValidator(client, new string[] {});

            var tree = client.GetTreeLazy(new Group {
                Id = 0
            });
        }
示例#13
0
        private static void TestSbSingle()
        {
            var bus     = ServiceBusFactory.GetServiceBus();
            var eventId = new Guid("cf0a200c-e6d3-472e-8c2c-286b2032ba6e");

            const string EventType = "ITOperations.Mating.HeatEvent";

            var          validationResult   = new EventValidator("Animal", "animalIdentity").GetValidationResult(eventId);
            const string ValidatorQueueName = "EventProcessing.ValidationAggregator.service.input";

            using (var ts = new TransactionScope())
            {
                bus.Send(ValidatorQueueName,
                         new ValidationResult
                {
                    EventID = eventId,
                    EventServiceBoundary = AIWebAPI.ResourceLocator.ServiceName,
                    EventSource          = AnimalIdentityServiceEventSources.MindaPro,
                    ValidationOutcome    = ValidationResultFlag.Valid,
                    EventType            = EventType
                });

                bus.Send(ValidatorQueueName,
                         new ValidationResult
                {
                    EventID = eventId,
                    EventServiceBoundary = AIWebAPI.ResourceLocator.ServiceName,
                    EventSource          = AnimalIdentityServiceEventSources.MindaPro,
                    ValidationOutcome    = ValidationResultFlag.Valid,
                    EventType            = EventType
                });
                bus.Send(ValidatorQueueName,
                         new ValidationResult
                {
                    EventID = eventId,
                    EventServiceBoundary = "ITOperations.AnimalCharacteristic",
                    EventSource          = AnimalIdentityServiceEventSources.MindaPro,
                    ValidationOutcome    = ValidationResultFlag.Valid,
                    EventType            = EventType
                });

                bus.Send(ValidatorQueueName,
                         new ValidationResult
                {
                    EventID = eventId,
                    EventServiceBoundary = AIWebAPI.ResourceLocator.ServiceName,
                    EventSource          = AnimalIdentityServiceEventSources.MindaPro,
                    ValidationOutcome    = ValidationResultFlag.Valid,
                    EventType            = EventType
                });

                ts.Complete();
            }
        }
示例#14
0
        public IHttpActionResult Post(string sessionId, FileFormat fileFormat)
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                var repository = EventRepositoryCache.Instance.Get(sessionId.ToGuidWithAccessDenied());

                var httpPostedFile = HttpContext.Current.Request.Files["Data"];
                if (httpPostedFile != null)
                {
                    string       result = StreamToString(httpPostedFile.InputStream);
                    List <Event> events;
                    try
                    {
                        switch (fileFormat)
                        {
                        case FileFormat.Csv:
                            events = DeserializeCsv(result);
                            break;

                        case FileFormat.Xml:
                            events = DeserializeXml(result);
                            break;

                        case FileFormat.Json:
                            events = DeserializeJson(result);
                            break;

                        default:
                            return(InternalServerError(new ArgumentException("FileFormat")));
                        }
                    }
                    catch (Exception e)
                    {
                        return(InternalServerError(new IOException("Parsing error", e)));
                    }
                    foreach (Event e in events)
                    {
                        var validationResult = EventValidator.ValidateCorrect(e, null);
                        if (!string.IsNullOrWhiteSpace(validationResult))
                        {
                            return(InternalServerError(new ArgumentException(validationResult)));
                        }
                        repository.Create(e);
                    }

                    return(Ok());
                }

                return(BadRequest("File is not provided"));
            }

            return(BadRequest("File is not provided"));
        }
示例#15
0
        public IHttpActionResult Post(string sessionId, [FromBody] Event value)
        {
            var repository       = EventRepositoryCache.Instance.Get(sessionId.ToGuidWithAccessDenied());
            var validationResult = EventValidator.ValidateCorrect(value, false);

            if (!string.IsNullOrWhiteSpace(validationResult))
            {
                return(InternalServerError(new ArgumentException(validationResult)));
            }
            var result = repository.Create(value);

            return(Ok(result));
        }
示例#16
0
        public void Tree_Lazy_Id_OneAPIRequest()
        {
            var client = BaseTest.Initialize_Client(new TreeRequestResponse(TreeRequestScenario.ContainerWithGrandChild));

            var validator = new EventValidator(client, new[]
            {
                UnitRequest.Objects("filter_objid=1001"),
                UnitRequest.Probes("filter_objid=1001&filter_parentid=0")
            });

            validator.MoveNext(2);

            var tree = client.GetTreeLazy(1001);
        }
        public async Task <CoapMessage> PostAsync(CoapMessage message)
        {
            try
            {
                CoapUri             uri      = new CoapUri(message.ResourceUri.ToString());
                ResponseMessageType rmt      = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;
                EventMetadata       metadata = await graphManager.GetPiSystemMetadataAsync(uri.Resource);

                ValidatorResult result = EventValidator.Validate(true, metadata, null, graphManager);

                if (!result.Validated)
                {
                    if (metadata.Audit)
                    {
                        await auditor?.WriteAuditRecordAsync(new MessageAuditRecord("XXXXXXXXXXXX", session.Identity, this.channel.TypeId, "COAP", message.Payload.Length, MessageDirectionType.In, false, DateTime.UtcNow, "Not authorized, missing resource metadata, or channel encryption requirements")).LogExceptions(logger);
                    }

                    logger?.LogErrorAsync(result.ErrorMessage);
                    return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
                }

                string contentType = message.ContentType.HasValue ? message.ContentType.Value.ConvertToContentType() : "application/octet-stream";

                EventMessage msg = new EventMessage(contentType, uri.Resource, ProtocolType.COAP, message.Encode(), DateTime.UtcNow, metadata.Audit);

                if (!string.IsNullOrEmpty(uri.CacheKey))
                {
                    msg.CacheKey = uri.CacheKey;
                }

                if (uri.Indexes == null)
                {
                    await adapter.PublishAsync(msg);
                }
                else
                {
                    List <KeyValuePair <string, string> > indexes = GetIndexes(uri);
                    await adapter.PublishAsync(msg, indexes);
                }

                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Created, message.Token));
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"CoAP POST fault for {session.Identity}.");
                throw ex;
            }
        }
示例#18
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
        {
            var newEvent = JsonConvert.DeserializeObject <Event>(await req.ReadAsStringAsync());

            var validator        = new EventValidator();
            var validatorResults = validator.Validate(newEvent);

            if (!validatorResults.IsValid)
            {
                return(new BadRequestObjectResult(validatorResults.Errors));
            }

            await newEvent.SaveAsync(Repository);

            return(new JsonResult(newEvent));
        }
        public EventLocationServiceInterceptor(EventValidator eventValidator)
        {
            _eventValidator = eventValidator;
            var mappings = new Dictionary <string, Action <IInvocation> >
            {
                {
                    nameof(GetLocationForEventAsync),
                    x => GetLocationForEventAsync((int)x.Arguments[0])
                },
                {
                    nameof(UpdateLocationForEventAsync),
                    x => UpdateLocationForEventAsync((int)x.Arguments[0], (Location)x.Arguments[1])
                }
            };

            BuildUp(mappings);
        }
    /// <summary>
    /// Used when an event is raised and the event needs to be published to the analytics server instantly
    /// </summary>
    /// <param name="package">Event package we are sending</param>
    public static void PublishEvent(EventPackage package)
    {
        var result = UnityEngine.Analytics.AnalyticsEvent.Custom(ApplicationVersion + ":" + package.EventName, package.Data);

        if (result != UnityEngine.Analytics.AnalyticsResult.Ok)
        {
            UnityEngine.Debug.LogError(package.EventName + " Failed: " + result.ToString());
            Log.Write(package.EventName + " Failed: " + result.ToString());
        }
#if (UNITY_EDITOR || UNITY_EDITOR_OSX)
        if (Application.isEditor)
        {
            //var sendName = ApplicationVersion + ":" + package.EventName + "(" + result.ToString() + ")";
            //package.EventName = sendName;
            EventValidator.RecieveEvent(package, result);
            //ConvertToJSON(package);
        }
#endif
    }
 public AgreementServiceInterceptor(AgreementValidator agreementValidator, EventValidator eventValidator, ServiceSlotValidator serviceSlotValidator, EventServiceModelValidator eventServiceModelValidator)
 {
     _agreementValidator         = agreementValidator;
     _eventValidator             = eventValidator;
     _serviceSlotValidator       = serviceSlotValidator;
     _eventServiceModelValidator = eventServiceModelValidator;
     BuildUp(new Dictionary <string, Action <IInvocation> >
     {
         {
             nameof(GetSingleServiceAgreementByEventSlot),
             x => GetSingleServiceAgreementByEventSlot((int)x.Arguments[0], (int)x.Arguments[1])
         },
         {
             nameof(GetAllServiceAgreementsByEvent),
             x => GetAllServiceAgreementsByEvent((int)x.Arguments[0])
         },
         {
             nameof(CreateServiceAgreement),
             x => CreateServiceAgreement((int)x.Arguments[0], (int)x.Arguments[1], (int)x.Arguments[2])
         },
         {
             nameof(UpdateServiceAgreement),
             x => UpdateServiceAgreement((ServiceAgreement)x.Arguments[0])
         },
         {
             nameof(DeleteAgreement),
             x => DeleteAgreement((int)x.Arguments[0], (int)x.Arguments[1])
         },
         {
             nameof(ProposeAgreement),
             x => ProposeAgreement((int)x.Arguments[0], (int)x.Arguments[1])
         },
         {
             nameof(AcceptAgreement),
             x => AcceptAgreement((int)x.Arguments[0], (int)x.Arguments[1])
         },
         {
             nameof(DeclineAgreement),
             x => DeclineAgreement((int)x.Arguments[0], (int)x.Arguments[1])
         }
     });
 }
示例#22
0
        static void Main()
        {
            log4net.Config.XmlConfigurator.Configure();
            logger.Info("Program Started");

            UserDbRepo        urepo      = new UserDbRepo();
            ChildDbRepo       crepo      = new ChildDbRepo();
            EventDbRepository erepo      = new EventDbRepository();
            ChildValidator    cvalidator = new ChildValidator();
            EventValidator    evalidator = new EventValidator();
            UserService       userv      = new UserService(urepo);
            ChildService      cserv      = new ChildService(crepo, cvalidator);
            EventService      eserv      = new EventService(erepo, evalidator);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Login(userv, cserv, eserv));
            //ChildDbRepo repo = new ChildDbRepo();
            //Child  c = repo.save(new Child("Adrian", "Ionel", 9));
            logger.Info("Program ended.");
        }
        public Notification <bool> CreateEvent(Event ev)
        {
            ev.SetId(GetMaxId() + 1);
            EventValidator      validator = new EventValidator(ev);
            bool                valid     = validator.Validate();
            Notification <bool> notifier  = new Notification <bool>();

            if (!valid)
            {
                foreach (var error in validator.GetErrors())
                {
                    notifier.AddError(error);
                }
                notifier.SetResult(false);
            }
            else
            {
                notifier.SetResult(eventRepo.Create(ev));
            }
            return(notifier);
        }
示例#24
0
        public IActionResult Post([FromBody] EventItem item)
        {
            if (item == null)
            {
                _logger.LogDebug("Item is null");
                return(BadRequest());
            }

            var validator = new EventValidator();

            if (!validator.isValid(item))
            {
                _logger.LogDebug("Item is not valid");
                return(BadRequest("One or more properties is not valid"));
            }

            _context.EventItems.Add(item);
            _context.SaveChanges();
            _logger.LogDebug(string.Format("Created item with id {0}", item.Id.ToString()));

            return(CreatedAtRoute("GetEvent", new { id = item.Id }, item));
        }
示例#25
0
        private void Session_OnUnsubscribe(object sender, MqttMessageEventArgs args)
        {
            try
            {
                UnsubscribeMessage msg = (UnsubscribeMessage)args.Message;
                foreach (var item in msg.Topics)
                {
                    MqttUri uri = new MqttUri(item.ToLowerInvariant());

                    if (EventValidator.Validate(false, uri.Resource, Channel, graphManager, context).Validated)
                    {
                        adapter.UnsubscribeAsync(uri.Resource).GetAwaiter();
                        logger?.LogInformationAsync($"MQTT adapter unsubscribed {uri.ToString()}");
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Session_OnUnsubscribe error on channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
        }
示例#26
0
        public async Task PrtgClient_ParsesInvalidXml_RetainsDirtyAsync()
        {
            var xml = "<property><value>\01</value></property>";

            var client = BaseTest.Initialize_Client(new BasicResponse(xml.ToString()));

            var validator = new EventValidator <string>(new[]
            {
                //First - retry a dirty response
                "https://prtg.example.com/api/table.xml?content=objects&columns=objid,name,tags,type,active,basetype&count=*&username=username&passhash=12345678",
                "XmlSerializer encountered exception ''.', hexadecimal value 0x00, is an invalid character. Line 1, position 18.' while processing request. Retrying request and flagging engine as dirty.",
                "https://prtg.example.com/api/table.xml?content=objects&columns=objid,name,tags,type,active,basetype&count=*&username=username&passhash=12345678",

                //Second - engine should be already marked as dirty
                "https://prtg.example.com/api/table.xml?content=objects&columns=objid,name,tags,type,active,basetype&count=*&username=username&passhash=12345678"
            });

            client.LogVerbose += (s, e) =>
            {
                var message = e.Message;

                if (message.StartsWith("Synchronously") || message.StartsWith("Asynchronously"))
                {
                    message = Regex.Replace(e.Message, "(.+ request )(.+)", "$2");
                }

                Assert.AreEqual(validator.Get(message), message);
            };

            validator.MoveNext(3);
            var result = await client.ObjectEngine.GetObjectAsync <DummyElementRoot>(new PrtgObjectParameters());

            validator.MoveNext();
            result = await client.ObjectEngine.GetObjectAsync <DummyElementRoot>(new PrtgObjectParameters());

            Assert.IsTrue(validator.Finished, "Did not process all requests");
        }
示例#27
0
        private List <string> Session_OnSubscribe(object sender, MqttMessageEventArgs args)
        {
            List <string> list = new List <string>();

            try
            {
                SubscribeMessage message = args.Message as SubscribeMessage;

                SubscriptionMetadata metadata = new SubscriptionMetadata
                {
                    Identity    = session.Identity,
                    Indexes     = session.Indexes,
                    IsEphemeral = true
                };

                foreach (var item in message.Topics)
                {
                    MqttUri uri = new MqttUri(item.Key);
                    string  resourceUriString = uri.Resource;

                    if (EventValidator.Validate(false, resourceUriString, Channel, graphManager, context).Validated)
                    {
                        Task <string> subTask = Subscribe(resourceUriString, metadata);
                        string        subscriptionUriString = subTask.Result;
                        list.Add(resourceUriString);
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Session_OnSubscribe error on channel '{Channel.Id}'.")
                .GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            return(list);
        }
示例#28
0
 public EventValidatorTests()
 {
     _validator = new EventValidator();
 }
示例#29
0
 public void Setup()
 {
     _dateConverter  = new Mock <IDateConverter>();
     _eventValidator = new EventValidator(_dateConverter.Object);
 }
 public AgreementValidator(DataContext dataContext, IPersonService personService, EventValidator eventValidator)
 {
     _dataContext    = dataContext;
     _personService  = personService;
     _eventValidator = eventValidator;
 }
 public EventValidatorTests() {
     _validator = new EventValidator();
 }