private static IRestContext CreateRestContext()
        {
            IHttpFacade  httpFacade = new TestDataHttpFacade();
            IRestContext context    = new RestContext("http://base_address", "app_name", "app_api_key", null, httpFacade, new JsonContentSerializer(), RestApiVersion.V1);

            return(context);
        }
Exemplo n.º 2
0
        protected override void Delete(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return;
            }

            var video = (Video)synchronizer.CreateEntity(operation.Item);

            var inactivatedVideo = new Video
            {
                Id        = video.Id,
                ItemState = ItemState.INACTIVE
            };

            var authenticator = new BrightcoveAthenticator(operation.AccountItem);

            var context = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var updateData = new PostData("update_video", authenticator, "video", inactivatedVideo);

            var data = context.Update <PostData, ResultData <Video> >("update_data", updateData).Data;
        }
 public AccountController(ApplicationUserManager userManager,
                          ISecureDataFormat <AuthenticationTicket> accessTokenFormat, RestContext context)
 {
     UserManager       = userManager;
     AccessTokenFormat = accessTokenFormat;
     _context          = context;
 }
        public TriggersViewModel(RestContext restContext)
        {
            _restContext = restContext;
            //_restContext.ConnectionChanged += ;

            InitializeTriggers();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Update a label.
        /// </summary>
        /// <param name="operation">
        /// The operation.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        protected override object Update(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return(null);
            }

            var authenticator = new OoyalaAthenticator(operation.AccountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var lab = (Label)synchronizer.CreateEntity(operation.Item);

            return(context.Update <Label, Label>(
                       "update_label",
                       new Label {
                Name = lab.Name, ParentId = !string.IsNullOrEmpty(lab.ParentId) ? lab.ParentId : "root"
            },
                       new List <Parameter>
            {
                new Parameter
                {
                    Type = ParameterType.UrlSegment,
                    Name = "id",
                    Value = lab.Id
                }
            }).Data);
        }
Exemplo n.º 6
0
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var c = challenge as CreativeCookingChallenge;

            if (data.IngredientsId == null)
            {
                throw new NullReferenceException("Ingredients are required.");
            }

            if (data.RecipeId == -1)
            {
                throw new ArgumentException("Well then please just give a recipe.");
            }

            var recipe = context.Recipes.FirstOrDefault(r => r.RecipeId == data.RecipeId);

            if (recipe == null)
            {
                throw new NullReferenceException($"No recipe was found with id {data.RecipeId}.");
            }
            c.Recipe = recipe;

            foreach (int ingredientId in data.IngredientsId)
            {
                var ingredient = context.Ingredients.FirstOrDefault(i => i.IngredientId == ingredientId);
                if (ingredient != null)
                {
                    c.Ingredients.Add(ingredient);
                }
            }
            c.Thumbnail = recipe.Image;
            c.Earnings  = (int)(1.5 * c.Ingredients.Count);
        }
Exemplo n.º 7
0
        private static IRestContext CreateRestContext()
        {
            IHttpFacade  httpFacade = new TestDataHttpFacade();
            IRestContext context    = new RestContext(BaseAddress, httpFacade, new JsonContentSerializer());

            return(context);
        }
Exemplo n.º 8
0
 private void AppResolve(IApplicationBuilder app)
 {
     RestContext.GetContext().Initialize(app.ApplicationServices);
     app.ApplicationServices.GetRequiredService <ObjectAccessor <IApplicationBuilder> >().Value = app;
     app.UseStaticFiles();
     app.UseRouting();
     _moduleProvider.Configure(new ApplicationInitializationContext(app.ApplicationServices));
     app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); });
     app.Run(async context =>
     {
         var messageId = Guid.NewGuid().ToString("N");
         var sender    = new HttpServerMessageSender(_serializer, context, _diagnosticListener);
         try
         {
             var filters   = app.ApplicationServices.GetServices <IAuthorizationFilter>();
             var isSuccess = await OnAuthorization(context, sender, messageId, filters);
             if (isSuccess)
             {
                 var actionFilters = app.ApplicationServices.GetServices <IActionFilter>();
                 await OnReceived(sender, messageId, context, actionFilters);
             }
         }
         catch (Exception ex)
         {
             var filters = app.ApplicationServices.GetServices <IExceptionFilter>();
             WirteDiagnosticError(messageId, ex);
             await OnException(context, sender, messageId, ex, filters);
         }
     });
 }
 public void FixtureSetup()
 {
     // Tests against the sample OData service.
     _customerContext = new RestContext <NorthwindCustomer>(
         new JsonRestClient(new Uri("http://services.odata.org/Northwind/Northwind.svc/Customers")),
         new TestODataSerializerFactory());
 }
        protected override void Delete(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return;
            }

            var playlist = (PlayList)synchronizer.CreateEntity(operation.Item);

            var parameters = new Dictionary <string, object>
            {
                { "playlist_id", playlist.Id },
                { "cascade", "true" },
            };

            var authenticator = new BrightcoveAthenticator(operation.AccountItem);

            var updateData = new PostData("delete_playlist", authenticator, parameters);

            var context = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            context.Delete <PostData, ResultData <PlayList> >("update_data", updateData);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Deletes a label.
        /// </summary>
        /// <param name="operation">
        /// The operation.
        /// </param>
        protected override void Delete(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return;
            }

            var authenticator = new OoyalaAthenticator(operation.AccountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var label = (Label)synchronizer.CreateEntity(operation.Item);

            context.Delete <Label, RestEmptyType>(
                "delete_label",
                parameters:
                new List <Parameter>
            {
                new Parameter
                {
                    Type  = ParameterType.UrlSegment,
                    Name  = "id",
                    Value = label.Id
                }
            });
        }
Exemplo n.º 12
0
        /// <summary>
        /// Deletes a video.
        /// </summary>
        /// <param name="operation">
        /// The operation.
        /// </param>
        protected override void Delete(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return;
            }

            var authenticator = new OoyalaAthenticator(operation.AccountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var video = (Video)synchronizer.CreateEntity(operation.Item);

            context.Delete <Video, RestEmptyType>(
                "delete_video",
                parameters:
                new List <Parameter>
            {
                new Parameter
                {
                    Name  = "embedcode",
                    Type  = ParameterType.UrlSegment,
                    Value = video.EmbedCode
                }
            });
        }
Exemplo n.º 13
0
 /// <summary>
 /// Called when [authorization].
 /// </summary>
 /// <param name="filterContext">The filter context.</param>
 public async Task OnAuthorization(AuthorizationFilterContext filterContext)
 {
     if (filterContext.Route != null && filterContext.Route.ServiceDescriptor.DisableNetwork())
     {
         filterContext.Result = new HttpResultMessage <object> {
             IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error"
         };
     }
     else
     {
         if (filterContext.Route != null && filterContext.Route.ServiceDescriptor.EnableAuthorization())
         {
             if (filterContext.Route.ServiceDescriptor.AuthType() == AuthorizationType.JWTBearer.ToString())
             {
                 if (filterContext.Context.User.Identity?.IsAuthenticated == true)
                 {
                     RestContext.GetContext().SetClaimsPrincipal("payload", filterContext.Context.User);
                 }
                 else
                 {
                     filterContext.Result = new HttpResultMessage <object>
                     {
                         IsSucceed  = false,
                         StatusCode = (int)ServiceStatusCode.AuthorizationFailed,
                         Message    = "Invalid authentication credentials"
                     };
                 }
             }
         }
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Creates a channel.
        /// </summary>
        /// <param name="operation">
        /// The operation.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        protected override object Create(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return(null);
            }

            var authenticator = new OoyalaAthenticator(operation.AccountItem);

            var context = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var channel = (Channel)synchronizer.CreateEntity(operation.Item);

            channel.EmbedCode            = null;
            channel.CreatedAt            = null;
            channel.UpdatedAt            = null;
            channel.Duration             = null;
            channel.PostProcessingStatus = null;
            channel.Metadata             = null;
            channel.PreviewImageUrl      = null;
            channel.Status = null;

            var createdChannel = context.Create <Channel, Channel>("create_channel", channel).Data;

            this.UpdateLineup(operation, createdChannel.EmbedCode);
            this.UpdateLabels(operation, createdChannel.EmbedCode);
            this.UpdatePlayer(operation, createdChannel.EmbedCode);
            this.UpdateMetadata(operation, createdChannel.EmbedCode);

            return(createdChannel);
        }
Exemplo n.º 15
0
        protected virtual void MarkAs(Item accountItem, Video video, string mark)
        {
            var authenticator = new OoyalaAthenticator(accountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);
            var i             = 0;

            while (i < 5)
            {
                var res = context.Update <Video, Video>(
                    "update_video_upload_status",
                    new Video {
                    Status = mark
                },
                    new List <Parameter>
                {
                    new Parameter
                    {
                        Type  = ParameterType.UrlSegment,
                        Name  = "embedcode",
                        Value = video.EmbedCode
                    }
                });

                if (res.StatusCode == HttpStatusCode.OK)
                {
                    return;
                }

                Thread.Sleep(5000);
                i++;
            }
        }
        /// <summary>
        /// Updates player for an asset.
        /// </summary>
        /// <param name="operation">
        /// The operation.
        /// </param>
        /// <param name="assetEmbedCode">
        /// The asset embed code.
        /// </param>
        protected virtual void UpdatePlayer(ExportOperation operation, string assetEmbedCode)
        {
            var authenticator = new OoyalaAthenticator(operation.AccountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            string playerId = this.GetPlayerId(operation.Item);

            context.Update <RestEmptyType, RestEmptyType>(
                "update_player_of_asset",
                null,
                new List <Parameter>
            {
                new Parameter
                {
                    Type  = ParameterType.UrlSegment,
                    Name  = "embedcode",
                    Value = assetEmbedCode
                },

                new Parameter
                {
                    Type  = ParameterType.UrlSegment,
                    Name  = "id",
                    Value = playerId
                }
            });
        }
Exemplo n.º 17
0
        public async Task <bool> OnAuthorization(HttpContext context, HttpServerMessageSender sender, string messageId, IEnumerable <IAuthorizationFilter> filters)
        {
            foreach (var filter in filters)
            {
                var path         = HttpUtility.UrlDecode(GetRoutePath(context.Request.Path.ToString()));
                var serviceRoute = await _serviceRouteProvider.GetRouteByPathRegex(path);

                if (serviceRoute == null)
                {
                    serviceRoute = await _serviceRouteProvider.GetLocalRouteByPathRegex(path);
                }
                RestContext.GetContext().SetAttachment("route", serviceRoute);
                var filterContext = new AuthorizationFilterContext
                {
                    Path    = path,
                    Context = context,
                    Route   = serviceRoute
                };
                await filter.OnAuthorization(filterContext);

                if (filterContext.Result != null)
                {
                    await sender.SendAndFlushAsync(new TransportMessage(messageId, filterContext.Result));

                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Updates a player.
        /// </summary>
        /// <param name="operation">
        /// The operation.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        protected override object Update(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return(null);
            }

            var authenticator = new OoyalaAthenticator(operation.AccountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var player = (Player)synchronizer.CreateEntity(operation.Item);

            string playerId = player.Id;

            player.Id = null;

            return(context.Update <Player, Player>(
                       "update_player",
                       player,
                       new List <Parameter>
            {
                new Parameter
                {
                    Type = ParameterType.UrlSegment,
                    Name = "id",
                    Value = playerId
                }
            }).Data);
        }
Exemplo n.º 19
0
        protected virtual Video CreateVideo(Item accountItem, VideoToUpload video)
        {
            var authenticator = new OoyalaAthenticator(accountItem);
            var context       = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            return(context.Create <VideoToUpload, Video>("upload_video_create", video).Data);
        }
        public ConditionsViewModel(RestContext restContext)
        {
            _restContext = restContext;
            //_restContext.ConnectionChanged += ;

            InitializeConditions();
        }
        protected override object Create(ExportOperation operation)
        {
            var synchronizer = MediaFrameworkContext.GetItemSynchronizer(operation.Item);

            if (synchronizer == null)
            {
                return(null);
            }

            var playlist = (PlayList)synchronizer.CreateEntity(operation.Item);

            playlist.Id           = null;
            playlist.ReferenceId  = null;
            playlist.ThumbnailUrl = null;

            //Video ids used only for EXPLICIT playlist.
            //In other case will be used filter tags & tag inclusion
            if (playlist.PlaylistType == PlaylistType.EXPLICIT.ToString())
            {
                playlist.FilterTags   = null;
                playlist.TagInclusion = null;
            }
            else
            {
                playlist.VideoIds = null;
            }

            var authenticator = new BrightcoveAthenticator(operation.AccountItem);

            var updateData = new PostData("create_playlist", authenticator, "playlist", playlist);

            var context = new RestContext(Constants.SitecoreRestSharpService, authenticator);

            var data = context.Create <PostData, ResultData <string> >("update_data", updateData).Data;


            if (data != null && !string.IsNullOrEmpty(data.Result))
            {
                //we could not to use existing playlist object because it does not contain all data
                var playlistData = context.Read <PlayList>("read_playlist_by_id",
                                                           new List <Parameter>
                {
                    new Parameter {
                        Type = ParameterType.UrlSegment, Name = "playlist_id", Value = data.Result
                    }
                }).Data;

                if (playlistData == null)
                {
                    playlist.Id = data.Result;
                    return(playlist);
                }

                return(playlistData);
            }

            return(null);
        }
Exemplo n.º 22
0
        public Challenge CreateChallenge(RestContext context, ChallengeViewModel cvm)
        {
            var challenge = CreateInstance();

            FillGeneralData(challenge, cvm);
            FillSpecificData(challenge, context, cvm);

            return(challenge);
        }
        public void ShouldCreateBaseHeaders()
        {
            // Arrange

            // Act
            RestContext context = new RestContext("http://base_address", "app_name", "app_api_key");

            // Assert
            context.BaseHeaders.ShouldNotBe(null);
        }
Exemplo n.º 24
0
        public void ShouldCreateBaseHeaders()
        {
            // Arrange

            // Act
            RestContext context = new RestContext(BaseAddress);

            // Assert
            context.BaseHeaders.ShouldNotBe(null);
        }
Exemplo n.º 25
0
        public void ShouldCreateContentSerializer()
        {
            // Arrange

            // Act
            RestContext context = new RestContext(BaseAddress);

            // Assert
            context.ContentSerializer.ShouldNotBe(null);
        }
Exemplo n.º 26
0
        public void ShouldCreateHttpFacade()
        {
            // Arrange

            // Act
            RestContext context = new RestContext(BaseAddress);

            // Assert
            context.HttpFacade.ShouldNotBe(null);
        }
        public void ShouldCreateContentSerializer()
        {
            // Arrange

            // Act
            RestContext context = new RestContext("http://base_address", "app_name", "app_api_key");

            // Assert
            context.ContentSerializer.ShouldNotBe(null);
        }
        public void ShouldUseCustomContentSerializer()
        {
            // Arrange
            IContentSerializer serializer = Mock.Of <IContentSerializer>();

            // Act
            RestContext context = new RestContext("http://base_address", "app_name", "app_api_key", null, Mock.Of <IHttpFacade>(), serializer);

            // Assert
            context.ContentSerializer.ShouldBeSameAs(serializer);
        }
Exemplo n.º 29
0
        public void ShouldUseCustomContentSerializer()
        {
            // Arrange
            IContentSerializer serializer = Mock.Of <IContentSerializer>();

            // Act
            RestContext context = new RestContext(BaseAddress, Mock.Of <IHttpFacade>(), serializer);

            // Assert
            context.ContentSerializer.ShouldBeSameAs(serializer);
        }
Exemplo n.º 30
0
        public void ShouldUseCustomHttpFacade()
        {
            // Arrange
            IHttpFacade facade = Mock.Of <IHttpFacade>();

            // Act
            RestContext context = new RestContext(BaseAddress, facade, new JsonContentSerializer());

            // Assert
            context.HttpFacade.ShouldBeSameAs(facade);
        }
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var c = challenge as CreativeCookingChallenge;

            if (data.IngredientsId == null)
                throw new NullReferenceException("Ingredients are required.");

            if (data.RecipeId == -1)
                throw new ArgumentException("Well then please just give a recipe.");

            var recipe = context.Recipes.FirstOrDefault(r => r.RecipeId == data.RecipeId);
            if (recipe == null)
                throw new NullReferenceException($"No recipe was found with id {data.RecipeId}.");
            c.Recipe = recipe;

            foreach (int ingredientId in data.IngredientsId) {
                var ingredient = context.Ingredients.FirstOrDefault(i => i.IngredientId == ingredientId);
                if (ingredient != null)
                    c.Ingredients.Add(ingredient);
            }
            c.Thumbnail = recipe.Image;
            c.Earnings = (int)(1.5 * c.Ingredients.Count);
        }
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var recipe = context.Recipes.FirstOrDefault(r => r.RecipeId == data.RecipeId);
            var c = (challenge as RecipeChallenge);
            if (recipe == null)
                throw new NullReferenceException($"Recipe with id {data.RecipeId} was not found.");

            c.Recipe = recipe;
            c.PrepareFor = (TargetSubject)R.Next(0, 4);
            c.Earnings = 1;
            c.Thumbnail = recipe.Image;
        }
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var restaurant = context.Restaurants.FirstOrDefault(r => r.RestaurantId == data.RestaurantId);
            var c = (challenge as RestaurantChallenge);
            if (restaurant == null)
                throw new NullReferenceException($"Restaurant with id {data.RestaurantId} was not found.");

            c.Earnings = 3;
            c.Restaurant = restaurant;
        }
 protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
 {
 }
Exemplo n.º 35
0
 public PeopleContext(Uri uri, Format format) {
     restContext = new RestContext<Person>(GetRestClient(uri, format), GetSerializerFactory(format));
 }