public static HttpConfiguration GetConfig()
            {
                var config = new HttpConfiguration();

                config.MapHttpAttributeRoutes();

                var cors = new EnableCorsAttribute("*", "*", "*");

                config.EnableCors(cors);

                config.EnableSwagger(x => x.SingleApiVersion("v1", "MyDiaryStorageApi"))
                .EnableSwaggerUi();

                ////var pathHandler = new DefaultODataPathHandler();
                ////var routingConventions = ODataRoutingConventions.CreateDefault();
                ////var batchHandler = new DefaultODataBatchHandler(new HttpServer(config));

                config.MapODataServiceRoute(
                    routeName: "MyDiaryStorage",
                    routePrefix: "v1",
                    model: OData.GetEdmModel());


                config.EnsureInitialized();

                return(config);
            }
Beispiel #2
0
        public void Test_ToString()
        {
            var odata = "$count=false&$filter=&$orderby=&$top=10&$skip=0";
            var parts = new OData <TestModel>(odata);

            parts.ToString().Should().Be(odata);
        }
Beispiel #3
0
        private void VerifySequence(string value, params TokenType[] types)
        {
            var tokens = OData.Tokenize(value).ToArray();
            var actual = tokens.Select(t => t.Type).ToArray();

            CollectionAssert.AreEqual(types, actual);
        }
Beispiel #4
0
        public void Tokens_FilterQuery_DataTypes()
        {
            var urls = new Dictionary <string, TokenType>()
            {
                { "?$filter=NullValue eq null", TokenType.Null },
                { "?$filter=TrueValue eq true", TokenType.True },
                { "?$filter=FalseValue eq false", TokenType.False },
                { "?$filter=BinaryValue eq binary'T0RhdGE'", TokenType.Base64 },
                { "?$filter=BinaryValue eq X'ffa3cd'", TokenType.Binary },
                { "?$filter=IntegerValue lt -128", TokenType.Integer },
                { "?$filter=IntegerValue lt -128L", TokenType.Long },
                { "?$filter=DoubleValue ge 0.31415926535897931e1", TokenType.Double },
                { "?$filter=DoubleValue ge 0.31415926535897931M", TokenType.Decimal },
                { "?$filter=DoubleValue ge 0.31415926535897931d", TokenType.Double },
                { "?$filter=DoubleValue ge 0.314f", TokenType.Single },
                { "?$filter=SingleValue eq INF", TokenType.PosInfinity },
                { "?$filter=DecimalValue eq 34.95", TokenType.Double },
                { "?$filter=StringValue eq 'Say Hello,then go'", TokenType.String },
                { "?$filter=DateValue eq 2012-12-03", TokenType.Date },
                { "?$filter=DateValue eq datetime'2012-12-03'", TokenType.Date },
                { "?$filter=DateTimeOffsetValue eq 2012-12-03T07:16:23Z", TokenType.Date },
                { "?$filter=DateTimeOffsetValue eq datetimeoffset'2012-12-03T07:16:23Z'", TokenType.Date },
                { "?$filter=DurationValue eq duration'P12DT23H59M59.999999999999S'", TokenType.Duration },
                { "?$filter=DurationValue eq time'P12DT23H59M59.999999999999S'", TokenType.Duration },
                { "?$filter=TimeOfDayValue eq 07:59:59.999", TokenType.TimeOfDay },
                { "?$filter=GuidValue eq 01234567-89ab-cdef-0123-456789abcdef", TokenType.Guid },
                { "?$filter=GuidValue eq guid'01234567-89ab-cdef-0123-456789abcdef'", TokenType.Guid },
                { "?$filter=Int64Value eq 0", TokenType.Integer },
            };

            foreach (var url in urls)
            {
                Assert.AreEqual(url.Value, OData.Tokenize(url.Key).Last().Type);
            }
        }
        private async void RunAction( object sender, RoutedEventArgs e ) {

            try {
                //this.tab_Table.DataContext = ViewModel;
                this.OutputView.Text = "";
                this.StatusText.Text = "Waiting for response ...";

                if ( this.chbx_useController.IsChecked == true ) {
                    this.requestUrl = string.Format( "{0}/{1}", this.Url.Text, this.combo_Controller.SelectedValue.ToString() );
                } else {
                    requestUrl = this.Url.Text;
                }

                HttpResponseMessage response = await httpClient.GetAsync( requestUrl );
                response.EnsureSuccessStatusCode();
                this.StatusText.Text = string.Format( "{0}", response.StatusCode );
                string oDataResponse = await response.Content.ReadAsStringAsync();
                OutputView.Text = oDataResponse;
                Log.Debug( oDataResponse );
                this.odata = JsonConvert.DeserializeObject<OData<ViewUser>>( oDataResponse );
                this.contentDataGrid.ItemsSource = this.odata.Value;
                this.contentDataGrid.Columns[ 0 ].Visibility = Visibility.Hidden;
                this.contentDataGrid.Columns[ 1 ].Visibility = Visibility.Hidden;

            } catch ( HttpRequestException hre ) {
                Log.Error( e );
                StatusText.Text = hre.Message;
                OutPut( string.Format( "{0}\n{1}", hre.Message, hre.StackTrace ), "error" );
            } catch ( Exception ex ) {
                Log.Error( e );
                StatusText.Text = ex.Message;
                OutPut( string.Format( "{0}\n{1}", ex.Message, ex.StackTrace ), "error" );
            }

        }
Beispiel #6
0
        /// <summary>
        /// Executes a select returning one or more items.
        /// </summary>
        /// <typeparam name="T">The entity <see cref="Type"/>.</typeparam>
        /// <param name="queryModel">The <see cref="QueryModel"/>.</param>
        /// <param name="pagingTakeOverride">The optional paging take override value.</param>
        /// <returns>The resultant items.</returns>
        public IEnumerable <T> ExecuteCollection <T>(QueryModel queryModel, int?pagingTakeOverride)
        {
            var coll = new List <T>();

            Task.Run(async() => await OData.Query(QueryArgs, GetQueryAggregator(queryModel, pagingTakeOverride), coll)).Wait();
            return(coll);
        }
Beispiel #7
0
        public void Parse_Function()
        {
            var tree        = OData.Parse(@"?$filter=day(Date) eq 2");
            var initialNode = tree.QueryOption["$filter"].Children.First().Children.First();

            Assert.AreEqual(true, initialNode is CallNode);
            Assert.AreEqual(2, initialNode.Children.Count);
        }
Beispiel #8
0
        public void Parse_NavigationProperty()
        {
            var tree    = OData.Parse(@"?$orderby=Concrete/Complete,Title");
            var orderBy = tree.QueryOption["$orderby"];

            Assert.IsInstanceOfType(orderBy.Children[0], typeof(AscNode));
            Assert.AreEqual(2, orderBy.Children[0].Children[0].Children.Count);
            Assert.IsInstanceOfType(orderBy.Children[1], typeof(AscNode));
        }
Beispiel #9
0
        public void Parse_Query()
        {
            var tree = OData.Parse("?$format=json&$filter=Name eq 'Apple'");

            Assert.AreEqual(2, tree.QueryOption.Count);
            Assert.AreEqual("eq", tree.QueryOption["$filter"].Children.First().Text);

            tree = OData.Parse("$format=json&$filter=Name eq 'Apple'&$top=3");
            Assert.AreEqual(3, tree.QueryOption.Count);
        }
        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>                     
        public async Task<HttpResponseMessage> GetAllData()
        {
            List<Event> dataList = DataEventRepository.GetAll();
            OData<Event> data = new OData<Event>(dataList, dataList.Count);

            return await Task<HttpResponseMessage>.Factory.StartNew(() =>
            {
                return Request.CreateResponse(HttpStatusCode.OK, data);
            });
        }
Beispiel #11
0
        public static IList <dynamic> GetTitlesByDirector(string directorName)
        {
            var people = OData.Get("http://odata.netflix.com/Catalog/People", "$filter=Name eq '" + directorName + "'");

            if (people.Count() > 0)
            {
                return(OData.Get("http://odata.netflix.com/Catalog/People(" + people.First().Id + ")/TitlesDirected"));
            }

            return(new List <dynamic>());
        }
Beispiel #12
0
        public void Tokens_EscapeString04()
        {
            var url = "http://host/service/Categories('Smartphone%2FTablet')";

            VerifySequence(url
                           , TokenType.Scheme, TokenType.PathSeparator, TokenType.Authority
                           , TokenType.PathSeparator, TokenType.Identifier, TokenType.PathSeparator, TokenType.Identifier
                           , TokenType.OpenParen, TokenType.String, TokenType.CloseParen);
            var parts = OData.Tokenize(url).ToArray();

            Assert.AreEqual("Smartphone/Tablet", parts[8].AsPrimitive());
        }
Beispiel #13
0
        public void Tokens_EscapeString03()
        {
            var url = "http://host/service/People%28%27O%27%27Neil%27%29";

            VerifySequence(url
                           , TokenType.Scheme, TokenType.PathSeparator, TokenType.Authority
                           , TokenType.PathSeparator, TokenType.Identifier, TokenType.PathSeparator, TokenType.Identifier
                           , TokenType.OpenParen, TokenType.String, TokenType.CloseParen);
            var parts = OData.Tokenize(url).ToArray();

            Assert.AreEqual("O'Neil", parts[8].AsPrimitive());
        }
Beispiel #14
0
        public void Parse_FunctionMultiParam()
        {
            var tree        = OData.Parse(@"?$filter=day(Date, 2) eq 2");
            var initialNode = tree.QueryOption["$filter"].Children.First().Children.First();

            Assert.AreEqual(true, initialNode is CallNode);
            Assert.AreEqual(3, initialNode.Children.Count);

            tree        = OData.Parse(@"?$filter=day(Date, 2, 'string') eq 2");
            initialNode = tree.QueryOption["$filter"].Children.First().Children.First();
            Assert.AreEqual(true, initialNode is CallNode);
            Assert.AreEqual(4, initialNode.Children.Count);
        }
Beispiel #15
0
        public void Parse_Url()
        {
            var tree     = OData.Parse("http://host/service/ProductsByColor(color=@color)?@color='red'&callback=2func&random=3*stuff");
            var segments = tree.PathSegments.ToArray();

            Assert.AreEqual(2, segments.Length);
            Assert.AreEqual("service", segments[0].Text);
            Assert.AreEqual("ProductsByColor", segments[1].Text);
            Assert.AreEqual(TokenType.Call, segments[1].Type);
            var call = (CallNode)segments[1];

            Assert.AreEqual("'red'", call.Arguments["color"].Text);
        }
Beispiel #16
0
        /// <summary>
        /// Configurations the specified application builder.
        /// </summary>
        /// <param name="appBuilder">The application builder.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        public void Configuration(IAppBuilder appBuilder)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException(nameof(appBuilder));
            }

            appBuilder.UseCors(CorsOptions.AllowAll);
            appBuilder.UseNinjectMiddleware(() => Ninject.ConfiguredKernel);
            appBuilder.UseNinjectWebApi(WebApi.GetConfig(OData.CreateModel()));

            appBuilder.Use <NotFoundMiddleware>();
        }
Beispiel #17
0
        public async Task <IActionResult> OnGetAsync()
        {
            Stream response = await _crmClient.GetStreamAsync(Product.List());

            if (response == null)
            {
                return(NotFound("Strangely no product is available."));
            }
            OData <Product> wrapper = CRMClient.DeserializeObject <OData <Product> >(response);

            Products = wrapper.Value;
            return(Page());
        }
Beispiel #18
0
 // TODO test that this works with a dependency that specified a version like "greater than 1.0 but less than 2.0"
 public override IPackage Get(PackageDependency dependency)
 {
     if (dependency.Versions.Count == 1 && dependency.Versions.First().Operator == PackageDependency.Operators.EqualTo)
     {
         return(EntityToPackage(OData.Get(new {
             Id = dependency.PackageId,
             Version = dependency.Versions.First().VersionText
         })));
     }
     else
     {
         return(GetPackagesWithId(dependency.PackageId).Where(pkg => dependency.Matches(pkg)).ToList().Latest());
     }
 }
Beispiel #19
0
        public void Tokens_Escape()
        {
            var url = "?$callback=jQuery112304312923812233427_1494592722830&%24inlinecount=allpages&%24format=json&%24filter=startswith(tolower(name)%2C%27c+b%27)";

            VerifySequence(url
                           , TokenType.Question, TokenType.QueryName, TokenType.QueryAssign, TokenType.Identifier
                           , TokenType.Amperstand, TokenType.QueryName, TokenType.QueryAssign, TokenType.Identifier
                           , TokenType.Amperstand, TokenType.QueryName, TokenType.QueryAssign, TokenType.Identifier
                           , TokenType.Amperstand, TokenType.QueryName, TokenType.QueryAssign, TokenType.Identifier
                           , TokenType.OpenParen, TokenType.Identifier, TokenType.OpenParen, TokenType.Identifier, TokenType.CloseParen
                           , TokenType.Comma, TokenType.String, TokenType.CloseParen);
            var parts = OData.Tokenize(url).ToArray();

            Assert.AreEqual("c b", parts[parts.Length - 2].AsPrimitive());
        }
        public async Task <ApiResponse <List <TimeAgreement> > > Get(OData odata)
        {
            if (odata == null)
            {
                throw new ArgumentNullException("odata", "odata cannot be null");
            }
            if (string.IsNullOrEmpty(odata.Select))
            {
                throw new ArgumentNullException("odata", "odata.select must be informed for this method");
            }

            var result = await _client.Get <List <TimeAgreement> >(odata.ToString());

            return(result);
        }
Beispiel #21
0
        public void Parse_OrderBy()
        {
            var tree    = OData.Parse(@"?$orderby=ReleaseDate asc, Rating desc, Another desc");
            var orderBy = tree.QueryOption["$orderby"];

            Assert.IsInstanceOfType(orderBy.Children[0], typeof(AscNode));
            Assert.IsInstanceOfType(orderBy.Children[1], typeof(DescNode));
            Assert.IsInstanceOfType(orderBy.Children[2], typeof(DescNode));

            tree    = OData.Parse(@"?$orderby=ReleaseDate, Rating, Another desc");
            orderBy = tree.QueryOption["$orderby"];
            Assert.IsInstanceOfType(orderBy.Children[0], typeof(AscNode));
            Assert.IsInstanceOfType(orderBy.Children[1], typeof(AscNode));
            Assert.IsInstanceOfType(orderBy.Children[2], typeof(DescNode));
        }
        protected byte[] Data()
        {
            var entity = new OData <JObject>();

            entity.Metadata = $"{mRequest.Scheme}://{mRequest.Authority}{mRequest.AbsolutePath}";
            // we should change the mresponse.Entity.Data to a JObject since the query result will return a JObject
            if (mResponse.Entity.Data != null)
            {
                foreach (JObject obj in mResponse.Entity.Data)
                {
                    entity.Value.Add(obj);
                }
            }
            else
            {
                var tempJObject = new JObject();
                tempJObject.Add("Message", "No Entities Returned");
                entity.Value.Add(tempJObject);
            }
            return(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(entity)));
        }
Beispiel #23
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            var model              = OData.CreateModel();
            var pathHandler        = new DefaultODataPathHandler();
            var routingConventions = ODataRoutingConventions.CreateDefault();

            routingConventions.Insert(0, new MediaEntityStreamRoutingConvention());
            var batchHandler = new DefaultODataBatchHandler(new HttpServer(config));

            config.MapODataServiceRoute(
                routeName: "ODataService",
                routePrefix: "",
                model: model,
                pathHandler: pathHandler,
                routingConventions: routingConventions,
                batchHandler: batchHandler);

            app.UseNinjectMiddleware(Ninject.GetConfiguredKernel);
            app.UseNinjectWebApi(config);
        }
Beispiel #24
0
        public async Task <ApiResponse <List <Ticket> > > Get(OData odata, bool includeDeletedItems = false)
        {
            var result = await _apiClient.Get <List <Ticket> >($"&includeDeletedItems={includeDeletedItems}{odata.ToString()}");

            return(result);
        }
Beispiel #25
0
        public static QueryResults ExecuteNonCached(ParsedQuery query, Site site, User user, AsyncQueryRunner.AsyncResult result)
        {
            var remoteIP     = OData.GetRemoteIP();
            var key          = "total-" + remoteIP;
            var currentCount = (int?)Current.GetCachedObject(key) ?? 0;

            currentCount++;
            Current.SetCachedObjectSliding(key, currentCount, 60 * 60);

            if (currentCount > 130)
            {
                // clearly a robot, auto black list
                Current.DB.BlackList.Insert(new { CreationDate = DateTime.UtcNow, IPAddress = remoteIP });
            }

            if (currentCount > 100)
            {
                throw new Exception("You can not run any new queries for another hour, you have exceeded your limit!");
            }

            if (Current.DB.Query <int>("select count(*) from BlackList where IPAddress = @remoteIP", new { remoteIP }).First() > 0)
            {
                System.Threading.Thread.Sleep(2000);
                throw new Exception("You have been blacklisted due to abuse!");
            }

            var results = new QueryResults();

            using (SqlConnection cnn = site.GetOpenConnection())
            {
                // well we do not want to risk blocking, if somebody needs to change this we will need to add a setting
                cnn.Execute("set transaction isolation level read uncommitted");

                var timer = new Stopwatch();
                timer.Start();

                var messages = new StringBuilder();

                var infoHandler = new SqlInfoMessageEventHandler((sender, args) =>
                {
                    // todo handle errors as well
                    messages.AppendLine(args.Message);
                });
                try
                {
                    cnn.InfoMessage += infoHandler;

                    if (query.IncludeExecutionPlan)
                    {
                        using (var command = new SqlCommand("SET STATISTICS XML ON", cnn))
                        {
                            command.ExecuteNonQuery();
                        }
                    }

                    var plan = new QueryPlan();

                    foreach (string batch in query.ExecutionSqlBatches)
                    {
                        using (var command = new SqlCommand(batch, cnn))
                        {
                            if (result != null)
                            {
                                result.Command = command;
                                if (result.Cancelled)
                                {
                                    continue;
                                }
                            }
                            command.CommandTimeout = AppSettings.QueryTimeout;

                            try
                            {
                                PopulateResults(results, command, result, messages, query.IncludeExecutionPlan);
                            }
                            catch (Exception ex)
                            {
                                // Ugh. So, if we cancel the query in-process, we get an exception...
                                // But we have no good way of knowing that the exception here is actually
                                // *that* exception...so we'll just assume it was if the state is Cancelled
                                if (result == null || result.State != AsyncQueryRunner.AsyncState.Cancelled)
                                {
                                    throw ex;
                                }
                            }
                        }

                        if (query.IncludeExecutionPlan)
                        {
                            plan.AppendBatchPlan(results.ExecutionPlan);
                            results.ExecutionPlan = null;
                        }
                    }

                    results.ExecutionPlan = plan.PlanXml;
                }
                finally
                {
                    cnn.InfoMessage -= infoHandler;
                    results.Messages = messages.ToString();
                }

                timer.Stop();
                results.ExecutionTime = timer.ElapsedMilliseconds;

                ProcessMagicColumns(results, cnn);
            }

            return(results);
        }
Beispiel #26
0
 public static IList <dynamic> GetMoviesContainingWord(string word)
 {
     return(OData.Get("http://odata.netflix.com/Catalog/Titles", "$filter=Type eq 'Movie' and (substringof('" + word + "', Name) or substringof('" + word + "', Synopsis))"));
 }
Beispiel #27
0
 public static IList <dynamic> GetMatchingTitles(string title)
 {
     return(OData.Get("http://odata.netflix.com/Catalog/Titles?$filter=Name eq '" + title + "'"));
 }
Beispiel #28
0
 public static IList <dynamic> GetTopMoviesByGenre(string genreId, int count = 10, int skip = 0)
 {
     return(OData.Get("http://odata.netflix.com/Catalog/Genres('" + genreId + "')/Titles", "$filter=Type eq 'Movie'&$orderby=AverageRating desc" + "&$top=" + count + "&skip=" + skip));
 }
Beispiel #29
0
 public override List <IPackage> GetPackagesWithId(string id)
 {
     return(EntitiesToPackages(OData.Where("Id"._Equals(id))));
 }
Beispiel #30
0
 public override List <IPackage> GetPackagesWithIdStartingWith(string query)
 {
     return(EntitiesToPackages(OData.Where("Id"._StartsWith(query))));
 }
        public async Task <ApiResponse <List <Person> > > Get(OData odata = null)
        {
            var result = await _apiClient.Get <List <Person> >(odata?.ToString());

            return(result);
        }
 /// <summary>
 /// Get api function for models
 /// </summary>
 /// <param name="oData">Query string based on OData protocol</param>
 /// <returns></returns>
 protected Func <Task <ApiResult <TModel> > > GetModels(OData oData = null) =>
 () => _ploomesApiClient.GetAsync <TModel>(_token, ResourceName, oData?.ToString());