Example #1
0
        public HttpResponseMessage <JsonQueryResult> Get(
            [FromUri(Name = "designmode")] bool isInDesignMode = false,
            string id    = null,
            string ns    = null,
            string alias = null
            )
        {
            using (Profiler.Measure("FormController.Get"))
            {
                // Get the entityRef
                EntityRef formRef = WebApiHelpers.MakeEntityRef(id, ns, alias);

                long formId;

                try
                {
                    formId = formRef.Id;
                } catch (ArgumentException)
                {
                    throw new FormNotFoundException();
                }

                EntityData formEntityData = _formControllerRequestHandler.GetFormAsEntityData(formId, isInDesignMode);

                var context = new EntityPackage();
                context.AddEntityData(formEntityData, "formEntity");
                return(new HttpResponseMessage <JsonQueryResult>(context.GetQueryResult()));
            }
        }
Example #2
0
        public List <TypeAccessReason> Get(string subjectAliasOrId, [FromUri] string advanced = null)
        {
            EntityRef subjectRef = WebApiHelpers.GetId(subjectAliasOrId);

            // Demand read access to the admin role, as a proxy for determining who can use this service
            EntityRepository.Get("core:administratorRole");

            // Ensure that the requested ID is a role or user.
            Subject subject = EntityRepository.Get <Subject>(subjectRef.Id);

            if (subject == null)
            {
                throw new WebArgumentNotFoundException("subject");
            }

            using (new SecurityBypassContext( ))
            {
                var settings = new TypeAccessReasonSettings(advanced == "true");

                // Get list of reasons
                IReadOnlyList <AccessReason> reasons = TypeAccessReasonService.GetTypeAccessReasons(subjectRef.Id, settings);

                // Format result
                List <TypeAccessReason> result = new List <TypeAccessReason>( );
                foreach (AccessReason reason in reasons)
                {
                    TypeAccessReason formattedReason = FormatAccessReason(reason);
                    result.Add(formattedReason);
                }

                return(result);
            }
        }
        private IHttpActionResult AssignTeamToPlayer(Player playerToUpdate, Uri link)
        {
            int teamId;

            try
            {
                teamId = WebApiHelpers.GetKeyFromUri <int>(Request, link);
                _teamService.Get(teamId);
                playerToUpdate.TeamId = teamId;
                _playerService.Edit(playerToUpdate);
            }
            catch (MissingEntityException ex)
            {
                ModelState.AddModelError(string.Format("{0}.{1}", CONTROLLER_NAME, ex.Source), ex.Message);
                return(BadRequest(ModelState));
            }
            catch (InvalidOperationException ex)
            {
                ModelState.AddModelError(string.Format("{0}.{1}", CONTROLLER_NAME, ex.Source), ex.Message);
                return(BadRequest(ModelState));
            }

            var player = PlayerViewModel.Map(playerToUpdate);

            return(Ok(player));
        }
        /// <summary>
        ///     Related entities.
        /// </summary>
        /// <param name="related">The related.</param>
        /// <param name="nodeIds">The node ids.</param>
        /// <returns></returns>
        private IEnumerable <RelatedResource> RelatedEntities(IEnumerable <JsonRelatedEntityInQuery> related, Dictionary <string, Guid> nodeIds)
        {
            var relatedEntities = new List <RelatedResource>( );

            if (related != null)
            {
                foreach (JsonRelatedEntityInQuery r in related)
                {
                    string asId = r.Related.As ?? "";

                    if (nodeIds.ContainsKey(asId))
                    {
                        continue;
                    }

                    nodeIds.Add(asId, Guid.NewGuid( ));

                    var re = new RelatedResource
                    {
                        NodeId                = nodeIds[asId],
                        RelationshipTypeId    = WebApiHelpers.GetId(r.Related.Id),
                        RelationshipDirection = r.Forward ? RelationshipDirection.Forward : RelationshipDirection.Reverse,
                        ResourceMustExist     = r.MustExist
                    };
                    re.RelatedEntities.AddRange(RelatedEntities(r.Related.Related, nodeIds));
                    relatedEntities.Add(re);
                }
            }

            return(relatedEntities);
        }
Example #5
0
        public HttpResponseMessage Get(
            [FromUri] string tenant,                // Our stuff
            [FromUri] string notifierId,
            [FromUri] TwilioSms sms)
        {
            // Run service
            using (Profiler.Measure("TwilioController.Get"))
            {
                try
                {
                    long notifierIdNum;

                    try
                    {
                        notifierIdNum = Int64.Parse(notifierId);
                    }
                    catch
                    {
                        throw new UnmatchedNotifierException();
                    }

                    using (WebApiHelpers.GetTenantContext(tenant))
                    {
                        _receiver.HandleRequest(notifierIdNum, sms);
                    }

                    return(new HttpResponseMessage(HttpStatusCode.Accepted));
                }
                catch (TwilioValidationException)
                {
                    EventLog.Application.WriteError($"Request failed validation. URL:{System.Web.HttpContext.Current.Request.Url}");
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }
            }
        }
Example #6
0
        public HttpResponseMessage GetDownloadImage(string imageId)
        {
            using (Profiler.Measure("ImageController.GetDownloadImage"))
            {
                EntityRef imageIdRef = WebApiHelpers.GetIdWithDashedAlias(imageId);

                var imageInterface = new ImageInterface();
                imageInterface.PreloadImage(imageIdRef);

                var imageFileType = ReadiNow.Model.Entity.Get <ImageFileType>(imageIdRef);

                if (imageFileType == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                string fileName      = imageFileType.Name;
                string fileExtension = imageFileType.FileExtension;

                string extension = Path.GetExtension(fileName);
                if (string.IsNullOrEmpty(extension))
                {
                    fileName = string.Format("{0}{1}", fileName, fileExtension);
                }

                Stream stream = imageInterface.GetImageDataStream(imageIdRef);
                if (stream == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                };

                response.Content.Headers.ContentType = new MediaTypeHeaderValue(GetImageMediaType(fileExtension));

                // Note: We are not setting the content length because the CompressionHandler will compress
                // the stream . Specifying the length here will cause the browser to hang as the actual data it
                // receives (as it is compressed) will be less than the specified content length.
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName,
                };

                return(response);
            }
        }
Example #7
0
        public HttpResponseMessage <JsonQueryResult> GetDefaultForm(
            string id    = null,
            string ns    = null,
            string alias = null,
            [FromUri(Name = "designmode")] bool isInDesignMode   = false,
            [FromUri(Name = "forcegenerate")] bool forceGenerate = false
            )
        {
            // Get the entityRef
            EntityRef typeRef = WebApiHelpers.MakeEntityRef(id, ns, alias);

            var entityType = ReadiNow.Model.Entity.Get <EntityType>(typeRef);

            return(Helper.GetDefaultFormForType(entityType, isInDesignMode, forceGenerate));
        }
Example #8
0
        public HttpResponseMessage <JsonQueryResult> GetGenerateForm(
            string id    = null,
            string ns    = null,
            string alias = null,
            [FromUri(Name = "designmode")] bool isInDesignMode = false
            )
        {
            using (Profiler.Measure("TypeController.GetGenerateForm"))
            {
                // Get the entityRef
                EntityRef entityRef = WebApiHelpers.MakeEntityRef(id, ns, alias);

                return(Helper.GetGeneratedFormForType(entityRef, isInDesignMode));
            }
        }
Example #9
0
        public HttpResponseMessage <JsonQueryResult> Get(
            string id    = null,
            string ns    = null,
            string alias = null,
            [FromUri(Name = "designmode")] bool isInDesignMode   = false,
            [FromUri(Name = "forcegenerate")] bool forceGenerate = false
            )
        {
            using (Profiler.Measure("InstanceController.Get"))
            {
                // Get the entityRef
                EntityRef entityRef = WebApiHelpers.MakeEntityRef(id, ns, alias);

                var entityType = ReadiNow.Model.Entity.Get(entityRef).EntityTypes.First().Cast <EntityType>();

                return(Helper.GetDefaultFormForType(entityType, isInDesignMode, forceGenerate));
            }
        }
Example #10
0
        public HttpResponseMessage Get(
            [FromUri] string tenant,
            [FromUri] string token,
            [FromUri] string select = null
            )
        {
            if (!Factory.FeatureSwitch.Get("enableWfUserActionNotify"))
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.NotFound));
            }

            using (Profiler.Measure("ApproveController.Approve"))
            {
                using (WebApiHelpers.GetTenantContext(tenant))
                {
                    string responseHtml = null;

                    var task = UserTaskHelper.GetTaskFromLinkToken(token);

                    if (task == null)
                    {
                        responseHtml = _htmlGenerator.GenerateRejectionPage();
                    }
                    else
                    {
                        if (select == null)
                        {
                            responseHtml = _htmlGenerator.GenerateSelectionPage(task);
                        }
                        else
                        {
                            // TODO: make the selection]
                            UserTaskHelper.ProcessApproval(task.Id, select);
                            responseHtml = _htmlGenerator.GenerateCompletedPage(task);
                        }
                    }

                    var response = new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
                    response.Content = new StringContent(responseHtml, Encoding.UTF8, "text/html");

                    return(response);
                }
            }
        }
Example #11
0
        public IHttpActionResult GetFormCalculationDependencies(string id = null, string ns = null, string alias = null)
        {
            using (Profiler.Measure("FormController.GetFormCalculationDependencies"))
            {
                try
                {
                    // Get the entityRef
                    EntityRef formRef = WebApiHelpers.MakeEntityRef(id, ns, alias);

                    var response = _formControllerRequestHandler.GetFormCalculationDependencies(formRef);

                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    EventLog.Application.WriteError(ex.ToString());
                    return(InternalServerError());
                }
            }
        }
Example #12
0
        public HttpResponseMessage GetImage(string imageId)
        {
            using (Profiler.Measure("ImageController.GetImage"))
            {
                EntityRef imageIdRef = WebApiHelpers.GetIdWithDashedAlias(imageId);

                var imageInterface = new ImageInterface( );
                imageInterface.PreloadImage(imageIdRef);

                using (CacheManager.ExpectCacheHits( ))
                {
                    HttpResponseMessage response = FileController.GetFileForRequest(Request, imageIdRef, GetImageEtag);

                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.OK:
                    {
                        var imageFileType = ReadiNow.Model.Entity.Get <ImageFileType>(imageIdRef);

                        response.Headers.CacheControl = new CacheControlHeaderValue
                        {
                            MustRevalidate = true,
                            MaxAge         = GetCacheMaxAge( )
                        };
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue(GetImageMediaType(imageFileType.FileExtension));
                    }
                    break;

                    case HttpStatusCode.NotModified:
                        response.Headers.CacheControl = new CacheControlHeaderValue
                        {
                            MustRevalidate = true,
                            MaxAge         = GetCacheMaxAge( )
                        };
                        break;
                    }

                    return(response);
                }
            }
        }
Example #13
0
        public HttpResponseMessage <JsonQueryResult> ClearFormsCache([FromBody] string[] formIds)
        {
            if (formIds != null)
            {
                foreach (var formRef in formIds.Select(id => WebApiHelpers.MakeEntityRef(id, "", "")))
                {
                    long formId;
                    try
                    {
                        formId = formRef.Id;
                    }
                    catch (ArgumentException)
                    {
                        throw new FormNotFoundException();
                    }

                    _formsCache.Remove(formId);
                }
            }
            return(new HttpResponseMessage <JsonQueryResult>(HttpStatusCode.OK));
        }
        public HttpResponseMessage <ExportDataInfo> ExportData(long rid, string format, [FromBody] ReportParameters reportParameters)
        {
            WebApiHelpers.CheckEntityId <ReadiNow.Model.Report>("rid", rid);

            var queryString = Request.RequestUri.ParseQueryString();
            var settings    = ReportController.SettingsFromQuery(queryString, reportParameters);

            settings.RequireFullMetadata = true;

            ExportFormat exportFormat;

            if (!Enum.TryParse(format, true, out exportFormat))
            {
                throw new WebArgumentException("Unknown format", "format");
            }

            var        exportInterface = new ExportDataInterface();
            ExportInfo exportInfo      = exportInterface.ExportData(rid, settings, exportFormat);

            return(new HttpResponseMessage <ExportDataInfo>(PackResult(exportInfo), HttpStatusCode.OK));
        }
Example #15
0
        public HttpResponseMessage UpdateStatus([FromUri] string tenant, [FromUri] string notifierId, SmsStatus request)
        {
            string messageSid    = request.SmsSid;
            string messageStatus = request.MessageStatus;
            string errorCode     = request.ErrorCode;

            // Run service
            using (Profiler.Measure("TwilioController.UpdateStatus"))
            {
                try
                {
                    long notifierIdNum;

                    try
                    {
                        notifierIdNum = Int64.Parse(notifierId);
                    }
                    catch
                    {
                        throw new UnmatchedNotifierException();
                    }

                    bool handled = false;

                    using (WebApiHelpers.GetTenantContext(tenant))
                    {
                        handled = _receiver.HandleStatusUpdate(notifierIdNum, messageSid, messageStatus, errorCode);
                    }

                    return(new HttpResponseMessage(handled ? HttpStatusCode.Accepted : HttpStatusCode.NotFound));
                }
                catch (TwilioValidationException)
                {
                    EventLog.Application.WriteError($"Request failed validation. URL:{System.Web.HttpContext.Current.Request.Url}");
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }
            }
        }
Example #16
0
        public HttpResponseMessage GetImageThumbnail(string imageId, string sizeId, string scaleId)
        {
            using (Profiler.Measure("ImageController.GetImageThumbnail"))
            {
                EntityRef imageIdRef = WebApiHelpers.GetIdWithDashedAlias(imageId);
                EntityRef sizeIdRef  = WebApiHelpers.GetIdWithDashedAlias(sizeId);
                EntityRef scaleIdRef = WebApiHelpers.GetIdWithDashedAlias(scaleId);

                var imageInterface = new ImageInterface();
                imageInterface.PreloadImageThumbnail(imageIdRef);

                ImageFileType thumbnailImage = imageInterface.GetImageThumbnail(imageIdRef, sizeIdRef, scaleIdRef);

                if (thumbnailImage == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                string dataHash = thumbnailImage.FileDataHash;
                // Get the entity tag, which is the hash of the image data + dimensions + scaling
                string etag = string.Format("\"{0}\"", imageInterface.GetImageThumbnailETag(dataHash, sizeIdRef, scaleIdRef));

                // If the request contains the same e-tag then return a not modified
                if (Request.Headers.IfNoneMatch != null &&
                    Request.Headers.IfNoneMatch.Any(et => et.Tag == etag))
                {
                    var notModifiedResponse = new HttpResponseMessage(HttpStatusCode.NotModified);
                    notModifiedResponse.Headers.ETag         = new EntityTagHeaderValue(etag, false);
                    notModifiedResponse.Headers.CacheControl = new CacheControlHeaderValue
                    {
                        MustRevalidate = true,
                        MaxAge         = GetCacheMaxAge( )
                    };
                    return(notModifiedResponse);
                }

                Stream imageDataStream;

                try
                {
                    imageDataStream = imageInterface.GetImageDataStream(dataHash);
                }
                catch (FileNotFoundException)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                if (imageDataStream == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                // Return the image
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(imageDataStream)
                };
                response.Headers.ETag         = new EntityTagHeaderValue(etag, false);
                response.Headers.CacheControl = new CacheControlHeaderValue
                {
                    MustRevalidate = true,
                    MaxAge         = GetCacheMaxAge( )
                };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(GetImageMediaType(thumbnailImage.FileExtension));

                return(response);
            }
        }
Example #17
0
        public HttpResponseMessage <ReportDataDefinition> Query([FromBody] JsonStructuredQuery jsonQuery)
        {
            if (jsonQuery == null)
            {
                throw new WebArgumentNullException("jsonQuery");
            }
            if (jsonQuery.Root == null)
            {
                throw new WebArgumentNullException("jsonQuery.Root");
            }

            try
            {
                var    query   = new StructuredQuery( );
                var    nodeIds = new Dictionary <string, Guid>( );
                string rootAs  = jsonQuery.Root.As ?? "";

                nodeIds.Add(rootAs, Guid.NewGuid( ));
                query.RootEntity = new ResourceEntity
                {
                    EntityTypeId = WebApiHelpers.GetId(jsonQuery.Root.Id),
                    NodeId       = nodeIds[rootAs]
                };

                query.RootEntity.RelatedEntities.AddRange(RelatedEntities(jsonQuery.Root.Related, nodeIds));

                query.SelectColumns.Add(new SelectColumn
                {
                    ColumnId   = Guid.NewGuid( ),
                    ColumnName = "_Id",
                    IsHidden   = true,
                    Expression = new IdExpression
                    {
                        NodeId = query.RootEntity.NodeId
                    }
                });
                if (jsonQuery.Selects != null)
                {
                    foreach (JsonSelectInQuery f in jsonQuery.Selects)
                    {
                        if (!string.IsNullOrEmpty(f.Field) && f.Field.ToLower( ) == "_id" && f.On != null)
                        {
                            if (f.On != null)
                            {
                                query.SelectColumns.Add(new SelectColumn
                                {
                                    ColumnId   = Guid.NewGuid( ),
                                    ColumnName = f.DisplayAs ?? f.On + "_Id",
                                    IsHidden   = true,
                                    Expression = new IdExpression
                                    {
                                        NodeId = nodeIds[f.On]
                                    }
                                });
                            }
                        }
                        else
                        {
                            var field = new ResourceDataColumn
                            {
                                FieldId = WebApiHelpers.GetId(f.Field),
                                NodeId  = nodeIds[f.On ?? rootAs]
                            };
                            string name = field.FieldId.Entity.Cast <Resource>( ).Name;
                            var    sc   = new SelectColumn
                            {
                                ColumnId    = Guid.NewGuid( ),
                                DisplayName = f.DisplayAs ?? name,
                                ColumnName  = name,
                                Expression  = field
                            };
                            query.SelectColumns.Add(sc);
                        }
                    }
                }
                if (jsonQuery.Conds != null)
                {
                    foreach (JsonCondition c in jsonQuery.Conds)
                    {
                        var qc = new QueryCondition
                        {
                            Operator = GetConditionOperator(c.Operation),
                            Argument = new TypedValue(c.Value)
                        };
                        if (!string.IsNullOrEmpty(c.Expression.Field) && c.Expression.Field.ToLower( ) == "_id")
                        {
                            qc.Expression = new IdExpression
                            {
                                NodeId = nodeIds[c.Expression.On ?? rootAs]
                            };
                        }
                        else
                        {
                            qc.Expression = new ResourceDataColumn
                            {
                                FieldId = WebApiHelpers.GetId(c.Expression.Field),
                                NodeId  = nodeIds[c.Expression.On ?? rootAs]
                            };
                        }
                        query.Conditions.Add(qc);
                    }
                }

                QueryResult result = Factory.QueryRunner.ExecuteQuery(query, new QuerySettings
                {
                    SecureQuery = true
                });

                // debug
                LogResult(result);

                return(new HttpResponseMessage <ReportDataDefinition>(PackReportResponse(result)));
            }
            catch (HttpResponseException)
            {
                throw;
            }
            catch (PlatformSecurityException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (e is ArgumentException)                   // would be better if there was a more specific exception for 'not found'
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                throw;
            }
        }
Example #18
0
        /// <summary>
        ///     Inners the compile.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        private static CompileResult InnerCompile(EvalRequest request)
        {
            try
            {
                var settings = new BuilderSettings( );

                if (!string.IsNullOrEmpty(request.Context))
                {
                    EntityRef contextType = WebApiHelpers.GetId(request.Context);
                    settings.RootContextType = ExprTypeHelper.EntityOfType(contextType);
                }
                if (!string.IsNullOrEmpty(request.Host))
                {
                    settings.ScriptHost = ( ScriptHostType )Enum.Parse(typeof(ScriptHostType), request.Host);
                }

                if (request.ExpectedResultType != null)
                {
                    settings.ExpectedResultType = request.ExpectedResultType.ToExprType();
                }

                var paramTypes = new Dictionary <string, ExprType>( );

                if (request.Parameters != null)
                {
                    foreach (ExpressionParameter p in request.Parameters)
                    {
                        if (p.Name == null)
                        {
                            throw new WebArgumentException("Param 'name' was not specified");
                        }
                        if (p.TypeName == null)
                        {
                            throw new WebArgumentException("Param 'type' was not specified");
                        }

                        var type = ( DataType )Enum.Parse(typeof(DataType), p.TypeName);
                        if (type == DataType.Entity)
                        {
                            if (p.EntityTypeId == null)
                            {
                                throw new WebArgumentException("Param 'entityTypeId' was not specified");
                            }

                            long typeId;
                            paramTypes[p.Name] = long.TryParse(p.EntityTypeId, out typeId)
                                                                ? ExprTypeHelper.EntityOfType(new EntityRef(typeId))
                                                                : ExprTypeHelper.EntityOfType(new EntityRef(p.EntityTypeId));
                        }
                        else
                        {
                            paramTypes[p.Name] = new ExprType(type);
                        }
                        paramTypes[p.Name].IsList = p.IsList;
                    }
                    settings.ParameterNames          = paramTypes.Keys.ToList( );
                    settings.StaticParameterResolver = paramName =>
                    {
                        ExprType result2;
                        return(paramTypes.TryGetValue(paramName, out result2) ? result2 : null);
                    };
                }

                // Compile
                IExpression expression = Factory.ExpressionCompiler.Compile(request.Expression, settings);

                // Return success result
                return(new CompileResult
                {
                    ResultType = expression.ResultType.Type,
                    IsList = expression.ResultType.IsList,
                    EntityTypeId = expression.ResultType.EntityTypeId
                });
            }
            catch (ParseException ex)
            {
                // Return script error result
                return(new CompileResult
                {
                    ErrorMessage = ex.Message
                });
            }
        }