private async Task<bool> IsAppEnabled(IApiContext apiContext) { var applicationResource = new ApplicationResource(apiContext); var application = await applicationResource.ThirdPartyGetApplicationAsync(); return application.Enabled.GetValueOrDefault(false); }
private void ApiPost(IApiContext apiContext) { var sequence = apiContext.Request["sequence"].ToObject<JArray>(); if (sequence.Count == 0) { return; } var codeSequence = new LPD433MHzCodeSequence(); foreach (var item in sequence) { var code = item.ToObject<JObject>(); var value = (uint)code["value"]; var length = (byte)code["length"]; var repeats = (byte)code["repeats"]; if (value == 0 || length == 0) { throw new InvalidOperationException("Value or length is null."); } codeSequence.WithCode(new LPD433MHzCode(value, length, repeats)); } Send(codeSequence); }
public override void HandleApiCall(IApiContext apiContext) { var request = apiContext.Request.ToObject<ApiCallRequest>(); if (!string.IsNullOrEmpty(request.Action)) { if (request.Action == "nextState") { SetState(GetNextState(GetState())); } return; } if (!string.IsNullOrEmpty(request.State)) { var stateId = new ComponentState(request.State); if (!SupportsState(stateId)) { apiContext.ResultCode = ApiResultCode.InvalidBody; apiContext.Response["Message"] = "State ID not supported."; } SetState(stateId); } }
public async Task ProcessEventAsync(IApiContext apiContext, Event eventPayLoad) { try { Trace.CorrelationManager.ActivityId = !String.IsNullOrEmpty(apiContext.CorrelationId) ? Guid.Parse(apiContext.CorrelationId) : Guid.NewGuid(); _logger.Info(String.Format("Got Event {0} for tenant {1}", eventPayLoad.Topic, apiContext.TenantId)); var eventType = eventPayLoad.Topic.Split('.'); var topic = eventType[0]; if (String.IsNullOrEmpty(topic)) throw new ArgumentException("Topic cannot be null or empty"); var eventCategory = (EventCategory) (Enum.Parse(typeof (EventCategory), topic, true)); var eventProcessor = _container.ResolveKeyed<IEventProcessor>(eventCategory); await eventProcessor.ProcessAsync(_container, apiContext, eventPayLoad); } catch (Exception exc) { _emailHandler.SendErrorEmail(new ErrorInfo{Message = "Error Processing Event : "+ JsonConvert.SerializeObject(eventPayLoad), Context = apiContext, Exception = exc}); throw exc; } }
public void HandleApiCall(IApiContext apiContext) { lock (_syncRoot) { apiContext.Response = JObject.FromObject(_schedules); } }
public PipelineContinuation Execute(IApiContext context) { ValidateContext(context); _log.InfoFormat("Creating a web request for {0}", context.Request.Uri); var request = WebRequest.Create(context.Request.Uri); request.Timeout = context.Request.Timeout; request.Method = context.Request.HttpMethod; if (context.Request.Headers != null) foreach (var header in context.Request.Headers) request.Headers[header.Key] = header.Value; if (context.UseFiddler) { _log.InfoFormat("Setting proxy to enable Fiddle"); request.Proxy = new WebProxy("127.0.0.1", 8888); } context.Request.Request = request; return PipelineContinuation.Continue; }
public async Task<GeneralSettings> GetGeneralSettings(IApiContext apiContext, string responseFields = null) { if (apiContext.SiteId.GetValueOrDefault(0) == 0) throw new Exception("Site ID is missing in api context"); var settingResource = new GeneralSettingsResource(apiContext); return await settingResource.GetGeneralSettingsAsync(responseFields); }
public async Task<TimeZone> GetTimezone(IApiContext apiContext, GeneralSettings generalSettings = null) { if (generalSettings == null) generalSettings = await GetGeneralSettings(apiContext,"siteTimeZone"); var referenceApi = new ReferenceDataResource(); var timeZones = await referenceApi.GetTimeZonesAsync(); return timeZones.Items.SingleOrDefault(x => x.Id.Equals(generalSettings.SiteTimeZone)); }
public void History(IApiContext apiContext) { if (apiContext == null) throw new ArgumentNullException(nameof(apiContext)); lock (_syncRoot) { apiContext.Response = JObject.FromObject(_history); } }
public void Init() { _container = new Bootstrapper().Bootstrap().Container; var appSetting = _container.Resolve<IAppSetting>(); var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString()); var siteId = int.Parse(appSetting.Settings["SiteId"].ToString()); _apiContext = new ApiContext(tenantId, siteId); }
public void RestoreBackup(IApiContext apiContext) { if (apiContext.Request.Type != JTokenType.Object) { throw new NotSupportedException(); } var eventArgs = new BackupEventArgs(apiContext.Request); RestoringBackup?.Invoke(this, eventArgs); }
public PipelineContinuation Execute(IApiContext context) { if(context.Request.Data != null && context.Request.Data.GetType() != typeof(string)) { var metadata = _resourceSpaceConfig.Get(context.Request.Data.GetType()); var codec = _pipeline.GetCodec(metadata.ContentType); context.Request.Data = codec.Encode(context.Request.Data); } return PipelineContinuation.Continue; }
public override void HandleApiCall(IApiContext apiContext) { var action = (string)apiContext.Request["Duration"]; if (!string.IsNullOrEmpty(action) && action.Equals(ButtonPressedDuration.Long.ToString(), StringComparison.OrdinalIgnoreCase)) { OnPressedLong(); } else { OnPressedShortlyShort(); } }
public override void HandleApiCall(IApiContext apiContext) { var action = (string)apiContext.Request["Action"]; if (action.Equals("detected", StringComparison.OrdinalIgnoreCase)) { UpdateState(MotionDetectorStateId.MotionDetected); } else if (action.Equals("detectionCompleted", StringComparison.OrdinalIgnoreCase)) { UpdateState(MotionDetectorStateId.Idle); } }
public async Task ProcessEventAsync(IApiContext apiContext, Event eventPayLoad) { try { var eventProcessor = _container.Resolve<IGenericEventProcessor>(); await eventProcessor.ProcessEvent(apiContext, eventPayLoad); } catch (Exception exc) { _emailHandler.SendErrorEmail(new ErrorInfo { Message = "Error Processing Event : " + JsonConvert.SerializeObject(eventPayLoad), Context = apiContext, Exception = exc }); throw; } }
public void CreateBackup(IApiContext apiContext) { var backup = new JObject { ["Type"] = "HA4IoT.Backup", ["Timestamp"] = DateTime.Now.ToString("O"), ["Version"] = 1 }; var eventArgs = new BackupEventArgs(backup); CreatingBackup?.Invoke(this, eventArgs); apiContext.Response = backup; }
public void Ask(IApiContext apiContext) { var message = (string)apiContext.Request["Message"]; if (string.IsNullOrEmpty(message)) { apiContext.ResultCode = ApiResultCode.InvalidBody; return; } var inboundMessage = new ApiInboundMessage(DateTime.Now, message); var answer = ProcessMessage(inboundMessage); apiContext.Response["Answer"] = answer; }
public void Execute(IApiContext context) { foreach (var contributor in Contributors) { try { if(contributor.Execute(context) == PipelineContinuation.Abort) break; } catch (Exception ex) { context.PipelineException = ex; break; } } }
public async Task<Site> GetSite(IApiContext apiContext) { if (apiContext.SiteId.GetValueOrDefault(0) == 0) throw new Exception("Site ID is missing in api context"); var tenant = apiContext.Tenant; if (tenant == null) { var tenantResource = new TenantResource(); tenant = await tenantResource.GetTenantAsync(apiContext.TenantId); } var site = tenant.Sites.SingleOrDefault(x => x.Id == apiContext.SiteId); if (site == null) throw new Exception("Site " + apiContext.SiteId + " not found for tenant " + tenant.Name); return site; }
public PipelineContinuation Execute(IApiContext context) { WriteDataToStream(context.Request); var webRequest = context.Request.Request; try { context.Response.Response = (HttpWebResponse)webRequest.GetResponse(); } catch (WebException ex) { context.Response.Response = (HttpWebResponse)ex.Response; } return PipelineContinuation.Continue; }
public async Task<EntityList> GetEntityListAsync(IApiContext apiContext, String name, string nameSpace) { var entityListResource = new EntityListResource(apiContext); String listFQN = GetListFQN(name, nameSpace); EntityList entityList = null; try { entityList = await entityListResource.GetEntityListAsync(listFQN); } catch (AggregateException ae) { if (ae.InnerException.GetType() == typeof (ApiException)) throw; var aex = (ApiException)ae.InnerException; _logger.Error(aex.Message, aex); throw aex; } return entityList; }
public async Task<EntityList> InstallSchemaAsync(IApiContext apiContext, EntityList entityList, EntityScope scope, IndexedProperty idProperty,List<IndexedProperty> indexedProperties) { if (indexedProperties != null && indexedProperties.Count > 4) throw new Exception("Only 4 indexed properties are supported"); if (string.IsNullOrEmpty(entityList.Name)) throw new Exception("Entity name is missing"); entityList.TenantId = apiContext.TenantId; entityList.ContextLevel = scope.ToString(); if (indexedProperties != null) { entityList.IndexA = indexedProperties.Count >= 1 ? indexedProperties[0] : null; entityList.IndexB = indexedProperties.Count >= 2 ? indexedProperties[1] : null; entityList.IndexC = indexedProperties.Count >= 3 ? indexedProperties[2] : null; entityList.IndexD = indexedProperties.Count >= 4 ? indexedProperties[3] : null; } if (idProperty == null) entityList.UseSystemAssignedId = true; else entityList.IdProperty = idProperty; if (string.IsNullOrEmpty(entityList.NameSpace)) entityList.NameSpace = _appSetting.Namespace; var entityListResource = new EntityListResource(apiContext); var listFQN = GetListFQN(entityList.Name, entityList.NameSpace); var existing = await GetEntityListAsync(apiContext, entityList.Name); try { existing = existing != null ? await entityListResource.UpdateEntityListAsync(entityList, listFQN) : await entityListResource.CreateEntityListAsync(entityList); } catch (AggregateException ae) { if (ae.InnerException.GetType() == typeof(ApiException)) throw; var aex = (ApiException)ae.InnerException; _logger.Error(aex.Message, aex); throw aex; } return entityList; }
public void ProcessEvent(IApiContext apiContext, Event eventPayLoad) { var eventConfigSection = ConfigurationManager.GetSection("eventSection") as EventSection; if (eventConfigSection == null) throw new Exception("Events are not configured"); var eventType = eventPayLoad.Topic.Split('.'); var topic = eventType[0]; var action = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(eventType[1]); var entityConfigElement = eventConfigSection.Events[topic]; if (entityConfigElement == null) throw new Exception("CorrelationId:{0},No Registered module found for "+topic); var type = entityConfigElement.Type; InvokeMethod(type, action, apiContext, eventPayLoad); }
private void InvokeMethod(string type, string action, IApiContext apiContext, Event mzEvent) { var assemblyType = Type.GetType(type); if (assemblyType == null) throw new Exception("Method : " + type + " could not be loaded"); var typeConstructor = assemblyType.GetConstructor(Type.EmptyTypes); if (typeConstructor == null) throw new Exception("Method : Default constructor not be found for type "+ type); var typeObject = typeConstructor.Invoke(new Object[] { }); var methodInfo = assemblyType.GetMethod(action, BindingFlags.IgnoreCase | BindingFlags.Public); if (methodInfo == null) throw new Exception("Method : " + action + " not found in " + type); methodInfo.Invoke(typeObject, new Object[] { apiContext, mzEvent }); }
private static void ValidateContext(IApiContext context) { if (string.IsNullOrEmpty(context.Request.HttpMethod)) { throw new InvalidContextException("The http method was not set in the context", context); } if (string.IsNullOrEmpty(context.Request.Uri)) { throw new InvalidContextException("The uri was not set in the context", context); } try { new Uri(context.Request.Uri); } catch (UriFormatException ex) { throw new InvalidContextException("Invalid uri in the context", context, ex); } }
public static async Task EnsureSuccessAsync(HttpResponseMessage response, IApiContext apiContext) { if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); ApiException exception; var htmlMediaType = new MediaTypeHeaderValue("text/html"); if (response.Content.Headers.ContentType != null && response.Content.Headers.ContentType.MediaType == htmlMediaType.MediaType) { var message = String.Format("Status Code {0}, Uri - {1}", response.StatusCode, response.RequestMessage.RequestUri.AbsoluteUri); exception = new ApiException(message, new Exception(content)); } else exception = JsonConvert.DeserializeObject<ApiException>(content); exception.HttpStatusCode = response.StatusCode; exception.CorrelationId = HttpHelper.GetHeaderValue(Headers.X_VOL_CORRELATION, response.Headers); exception.ApiContext = apiContext; throw exception; } }
public async Task ProcessEventAsync(IApiContext apiContext, Event eventPayLoad) { Trace.CorrelationManager.ActivityId = !String.IsNullOrEmpty(apiContext.CorrelationId) ? Guid.Parse(apiContext.CorrelationId) : Guid.NewGuid(); _logger.Info(String.Format("Got Event {0} for tenant {1}", eventPayLoad.Topic, apiContext.TenantId)); var eventType = eventPayLoad.Topic.Split('.'); var topic = eventType[0]; if (topic != "application" && !IsAppEnabled(apiContext).Result) { _logger.Info("App is not enabled, skipping processing of event"); return; } if (String.IsNullOrEmpty(topic)) throw new ArgumentException("Topic cannot be null or empty"); var eventCategory = (EventCategory)(Enum.Parse(typeof(EventCategory), topic, true)); var eventProcessor = _container.ResolveKeyed<IEventProcessor>(eventCategory); await eventProcessor.ProcessAsync(_container, apiContext, eventPayLoad); }
public Task ClosedAsync(IApiContext apiContext, Event eventPayLoad) { throw new NotImplementedException(); }
public AuthTicketResource(IApiContext apiContext) { _apiContext = apiContext; }
public InStockNotificationSubscriptionResource(IApiContext apiContext) { _apiContext = apiContext; }
public void HandleApiRequest(IApiContext apiContext) { }
public OrderReturnableItemResource(IApiContext apiContext) { _apiContext = apiContext; }
public AttributeResource(IApiContext apiContext) { _apiContext = apiContext; }
public ProductExtraResource(IApiContext apiContext) { _apiContext = apiContext; _dataViewMode = DataViewMode.Live; }
public ReturnResource(IApiContext apiContext) { _apiContext = apiContext; }
public ServiceClientMessageHandler(IApiContext context) { _ctx = context; }
public TaxableTerritoryResource(IApiContext apiContext) { _apiContext = apiContext; }
public CategoryResource(IApiContext apiContext, DataViewMode dataViewMode) { _apiContext = apiContext; _dataViewMode = dataViewMode; }
public CategoryResource(IApiContext apiContext) { _apiContext = apiContext; _dataViewMode = DataViewMode.Live; }
public SoftAllocationResource(IApiContext apiContext) { _apiContext = apiContext; }
public ExtendedPropertyResource(IApiContext apiContext) { _apiContext = apiContext; }
public CustomerNoteResource(IApiContext apiContext) { _apiContext = apiContext; }
public void HandleApiCommand(IApiContext apiContext) { }
public CustomerRepository(IApiContext context) { _context = context; }
public ChannelGroupResource(IApiContext apiContext) { _apiContext = apiContext; }
public FacetResource(IApiContext apiContext) { _apiContext = apiContext; }
public TransactionResource(IApiContext apiContext) { _apiContext = apiContext; }
public TenantResource() { _apiContext = null; }
public AuthTicketResource() { _apiContext = null; }
public TenantResource(IApiContext apiContext) { _apiContext = apiContext; }
public PackageResource(IApiContext apiContext) { _apiContext = apiContext; }
public ListViewResource(IApiContext apiContext) { _apiContext = apiContext; }
public void Fulfilled(IApiContext apiContext, Event eventPayLoad) { throw new NotImplementedException(); }
public AdjustmentResource(IApiContext apiContext) { _apiContext = apiContext; }
public ServiceController(IApiContext apiContext) { _apiContext = apiContext; }
/// <summary> /// Gets an entity framework query pointing to all of the models available for the current request context /// </summary> /// <param name="context">The current API context</param> /// <returns>An <see cref="IQueryable{T}" /> of all of the models available</returns> public async Task <IQueryable <TModel> > GetModelsAsync(IApiContext <TModel, object> context) { TContext DatabaseContext = context.Services.GetRequiredService <TContext>(); return(DatabaseContext.Set <TModel>()); }
public UserDataResource(IApiContext apiContext) { _apiContext = apiContext; }
public ReturnResource(IApiContext apiContext) { _apiContext = apiContext; }
public ProductExtraResource(IApiContext apiContext, DataViewMode dataViewMode) { _apiContext = apiContext; _dataViewMode = dataViewMode; }
/// <summary> /// Validate HttpResponse message, throws an Api Exception with context /// </summary> /// <param name="response"></param> /// <param name="request"></param> /// <param name="apiContext"></param> /// <exception cref="ApiException"></exception> public static void EnsureSuccess(HttpResponseMessage response, HttpRequestMessage request=null, IApiContext apiContext=null) { if (response.IsSuccessStatusCode) return; if (response.StatusCode == HttpStatusCode.NotModified) return; var content = response.Content.ReadAsStringAsync().Result; ApiException exception ; var htmlMediaType = new MediaTypeHeaderValue("text/html"); if (response.Content.Headers.ContentType != null && response.Content.Headers.ContentType.MediaType == htmlMediaType.MediaType) { var message = String.Format("Status Code {0}, Uri - {1}", response.StatusCode, response.RequestMessage.RequestUri.AbsoluteUri); exception = new ApiException(message, new Exception(content)); } else if (!String.IsNullOrEmpty(content)) exception = JsonConvert.DeserializeObject<ApiException>(content); else if (HttpStatusCode.NotFound == response.StatusCode && string.IsNullOrEmpty(content) && request != null) exception = new ApiException("Uri "+request.RequestUri.AbsoluteUri + " does not exist"); else exception = new ApiException("Unknow Exception"); exception.HttpStatusCode = response.StatusCode; exception.CorrelationId = HttpHelper.GetHeaderValue(Headers.X_VOL_CORRELATION, response.Headers); exception.ApiContext = apiContext; if (!MozuConfig.ThrowExceptionOn404 && string.Equals(exception.ErrorCode, "ITEM_NOT_FOUND", StringComparison.OrdinalIgnoreCase) && response.RequestMessage.Method.Method == "GET") return; throw exception; }