Example #1
0
        private ApplicationResource CreateManagedApplication(string location)
        {
            var managedApp = SafeGetResource(() =>
                                             this.SfrpMcClient.Applications.Get(
                                                 this.ResourceGroupName,
                                                 this.ClusterName,
                                                 this.Name),
                                             false);

            if (managedApp != null)
            {
                WriteError(new ErrorRecord(new InvalidOperationException($"Managed application '{this.Name}' already exists."),
                                           "ResourceAlreadyExists", ErrorCategory.InvalidOperation, null));
                return(managedApp);
            }

            WriteVerbose($"Creating managed application '{this.Name}'");

            ApplicationResource appParams = GetNewAppParameters(location);

            var beginRequestResponse = this.SfrpMcClient.Applications.BeginCreateOrUpdateWithHttpMessagesAsync(
                this.ResourceGroupName,
                this.ClusterName,
                this.Name,
                appParams).GetAwaiter().GetResult();

            return(this.PollLongRunningOperation(beginRequestResponse));
        }
Example #2
0
        public async Task <IActionResult> PutApplicationResource(string id, ApplicationResource applicationResource)
        {
            if (id != applicationResource.Id)
            {
                return(BadRequest());
            }

            _context.Entry(applicationResource).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ApplicationResourceExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #3
0
        public void UpdatePermissions_ShouldAddRolePermissionsUpdatedEvent_WhenCommandIsValid()
        {
            var roleCmdGen        = new RoleCmdGenerator();
            var createCmd         = roleCmdGen.CreateRoleCommand;
            var role              = Role.Create(createCmd);
            var createResourceCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var resource          = ApplicationResource.Create(createResourceCmd);
            var action            = resource.AddResourceAction(ApplicationResourceCmdGenerator.AddResourceActionCommand);
            var addPermissionCmd  = roleCmdGen.UpdateRolePermissionsCommand;

            addPermissionCmd.Permissions.First().Action = action;

            try
            {
                role.UpdatePermissions(addPermissionCmd);
            }
            catch (DomainValidationException ex)
            {
                Assert.True(false, Newtonsoft.Json.JsonConvert.SerializeObject(ex.ValidationErrors));
            }

            Assert.Equal(2, role.Events.Count());

            var addedEvent = Assert.IsType <RolePermissionsUpdatedEvent>(role.Events.Last());

            Assert.Equal(role.RolePermissions.Count(), addedEvent.Permissions.Count());
            Assert.All(role.RolePermissions, (item)
                       => Assert.Contains(addedEvent.Permissions, evi => evi.Action.Id == item.Action.Id && evi.Permission == item.Permission));
        }
Example #4
0
        public void UpdatePermissions_ShouldUpdatePermissions_WhenCommandIsValid()
        {
            var roleCmdGen        = new RoleCmdGenerator();
            var createCmd         = roleCmdGen.CreateRoleCommand;
            var role              = Role.Create(createCmd);
            var createResourceCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var resource          = ApplicationResource.Create(createResourceCmd);
            var action            = resource.AddResourceAction(ApplicationResourceCmdGenerator.AddResourceActionCommand);
            var command           = new UpdateRolePermissionsCommand
            {
                Permissions = new[] { new UpdateRolePermissionItem {
                                          Action = action, Permission = Permission.Allow
                                      } }
            };

            try
            {
                role.UpdatePermissions(command);
            }
            catch (DomainValidationException ex)
            {
                Assert.True(false, Newtonsoft.Json.JsonConvert.SerializeObject(ex.ValidationErrors));
            }

            Assert.Contains(role.RolePermissions,
                            p => p.Action == command.Permissions.Single().Action &&
                            p.Permission == command.Permissions.Single().Permission);
        }
        private async Task <string> GetAppId(IApiContext apiContext)
        {
            var applicationResource = new ApplicationResource(apiContext);
            var app = await applicationResource.ThirdPartyGetApplicationAsync();

            return(app.AppId);
        }
Example #6
0
        public void RemoveResourceAction_ShouldAddApplicationResourceActionRemovedEvent_WhenCommandIsValid()
        {
            var createCmd   = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var newResource = ApplicationResource.Create(createCmd);

            var addActionCommand = ApplicationResourceCmdGenerator.AddResourceActionCommand;
            var action           = newResource.AddResourceAction(addActionCommand);

            // Set the Id through reflaction because it's private and generated by the database.
            // Doing this we can confirm that the event contains the right informationl
            var actionIdProp = action.GetType().GetProperty(nameof(ResourceAction.Id));

            actionIdProp.SetValue(action, 42);

            var newResourceIdProp = newResource.GetType().GetProperty(nameof(ApplicationResource.Id));

            newResourceIdProp.SetValue(newResource, 42);

            newResource.RemoveResourceAction(new RemoveResourceActionCommand {
                Action = action
            });
            var @event = Assert.IsType <ApplicationResourceActionRemovedEvent>(newResource.Events.Last());

            Assert.Equal(newResource.Id, @event.Id);
            Assert.Equal(action.Id, @event.ResourceActionId);
        }
Example #7
0
        // POST: Admin/Create

        public ActionResult CreateOnAccept(string Cpr)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View("Index"));
                }
                var         app           = _proxy.GetAllApplications().SingleOrDefault(x => x.Cpr == Cpr);
                string      generPassword = Membership.GeneratePassword(10, 0);
                SenderModel courier       = new SenderModel(app.Cpr, app.FirstName, app.LastName, app.PhoneNumber, app.Email, app.Address, app.ZipCode, app.City)
                {
                    AccountType = (int)AccountTypeEnum.COURIER, Points = 0
                };
                _proxy.AddCourier(new SenderResource {
                    AccountType = courier.AccountType, Address = courier.Address, City = courier.City, ZipCode = courier.ZipCode, Cpr = courier.Cpr, Email = courier.Email, FirstName = courier.FirstName, LastName = courier.LastName, PhoneNumber = courier.PhoneNumber, Points = courier.Points, Username = courier.Email, Password = generPassword
                });
                ApplicationResource appToDelete = new ApplicationResource {
                    Cpr = app.Cpr
                };
                _proxy.DeleteApplication(appToDelete, false);
                //client.Disconnect();
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
 public void Initialize_App()
 {
     var applicationResource = new ApplicationResource(_apiContext);
     var application = applicationResource.ThirdPartyGetApplicationAsync().Result;
     application.Initialized = true;
     applicationResource.ThirdPartyUpdateApplicationAsync(application).Wait();
 }
        private void CreateApplication(
            ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
            string resourceGroup,
            string clusterName,
            string clusterId,
            string appName,
            string versionResourceId)
        {
            var applicationResourceId = $"{clusterId}/applications/{appName}";

            var applicationParams = new ApplicationResource(
                name: appName,
                location: Location,
                id: applicationResourceId,
                version: versionResourceId,
                upgradePolicy: new ApplicationUpgradePolicy(recreateApplication: true));

            var applicationResult = serviceFabricMcClient.Applications.CreateOrUpdate(
                resourceGroup,
                clusterName,
                appName,
                applicationParams);

            Assert.Equal("Succeeded", applicationResult.ProvisioningState);
            Assert.True(applicationResult.UpgradePolicy.RecreateApplication);
            Assert.Equal(versionResourceId, applicationResult.Version);
        }
        public async Task <IHttpActionResult> PutApplicationResource(ApplicationResource applicationResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (applicationResource.Id == null)
            {
                return(BadRequest());
            }
            db = Request.GetOwinContext().Get <SecurityDbContext>();
            db.Entry(applicationResource).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ApplicationResourceExists(applicationResource.Id))
                {
                    return(NotFound());
                }
                throw;
            }

            return(Ok(applicationResource));
        }
 private ApplicationResource StartUpdate(ApplicationResource appResource)
 {
     //TODO: use BeginUpdateWithHttpMessagesAsync (Patch) once fix is deployed in SFRP
     return(StartRequestAndWait <ApplicationResource>(
                () => this.SFRPClient.Applications.BeginCreateOrUpdateWithHttpMessagesAsync(this.ResourceGroupName, this.ClusterName, this.Name, appResource),
                () => string.Format("Provisioning state: {0}", GetAppProvisioningStatus() ?? "Not found")));
 }
Example #12
0
        public void Create_ShoudThrowDomainValidationException_WhenCommandIsInvalid(CreateApplicationResourceCommand command, ValidationError[] errors)
        {
            var ex = Assert.Throws <DomainValidationException>(() => ApplicationResource.Create(command));

            Assert.Equal(errors.Length, ex.ValidationErrors.Count());
            Assert.All(ex.ValidationErrors, e => errors.Any(er => er.Code == e.Code && er.Member == e.Member));
        }
Example #13
0
        public void ToString_ShouldReturnCorrectFormat()
        {
            var createCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var resource  = ApplicationResource.Create(createCmd);

            Assert.Equal($"{nameof(ApplicationResource)}: {resource.Id}-{resource.Name}", resource.ToString());
        }
        public IActionResult Get(Guid id)
        {
            try
            {
                using (var db = new AllInOneContext.AllInOneContext())
                {
                    ApplicationResource data = db.ApplicationResource
                                               .Include(t => t.Actions)
                                               .Include(t => t.Application)
                                               .Include(t => t.ParentResource)
                                               .FirstOrDefault(p => p.ApplicationResourceId.Equals(id));
                    if (data == null)
                    {
                        return(NoContent());
                    }

                    return(new ObjectResult(data));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Get:Message:{0}\r\n,StackTrace:{1}", ex.Message, ex.StackTrace);
                return(BadRequest(new ApplicationException {
                    ErrorCode = "Unknown", ErrorMessage = ex.Message
                }));
            }
        }
        public async Task <IHttpActionResult> PostApplicationResource(ApplicationResource applicationResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            applicationResource.Id = Guid.NewGuid().ToString();
            db = Request.GetOwinContext().Get <SecurityDbContext>();
            db.Resources.Add(applicationResource);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ApplicationResourceExists(applicationResource.Id))
                {
                    return(Conflict());
                }
                throw;
            }

            return(Ok(applicationResource.Id));
        }
Example #16
0
        public void Create_ShouldThrowDomainValidationException_WhenRoleLevelIsAccountAndNoAccountIdsProvided(ApplicationLevel level, string errorCode)
        {
            var createAppResourceCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;

            createAppResourceCmd.ApplicationLevel = level;
            var appResource = ApplicationResource.Create(createAppResourceCmd);

            var addActionCmd = ApplicationResourceCmdGenerator.AddResourceActionCommand;
            var action       = appResource.AddResourceAction(addActionCmd);

            var roleCmdGen    = new RoleCmdGenerator();
            var createRoleCmd = roleCmdGen.CreateRoleCommand;

            createRoleCmd.ApplicationLevel = level;
            var role = Role.Create(createRoleCmd);
            var updateRolePermissions = roleCmdGen.UpdateRolePermissionsCommand;

            updateRolePermissions.Permissions.First().Action = action;

            role.UpdatePermissions(updateRolePermissions);

            var userCmdGen    = new UserCmdGenerator();
            var createUserCmd = userCmdGen.CreateUserCommand;

            createUserCmd.UserRoles = new[] { new UserCommandRole {
                                                  Role = role
                                              } };

            var ex = Assert.Throws <DomainValidationException>(() => User.Create(createUserCmd));

            Assert.Single(ex.ValidationErrors);
            Assert.Equal(errorCode, ex.ValidationErrors.Single().Code);
        }
 public static BamResourceAdapter Create(ApplicationResource resource)
 {
     if (resource.Type != ResourceTypes.Bam)
     {
         throw new ApplicationException("Invalid resource type");
     }
     return(new BamResourceAdapter(resource));
 }
Example #18
0
        public void Create_ShoudAddApplicationResourceCreatedEvent_WhenCommandIsValid()
        {
            var command     = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var newResource = ApplicationResource.Create(command);

            Assert.Single(newResource.Events);
            Assert.IsType <ApplicationResourceCreatedEvent>(newResource.Events.Single());
        }
Example #19
0
        public void RemoveResourceAction_ShouldThrowDomainValidationException_WhenCommandIsInvalid(RemoveResourceActionCommand command,
                                                                                                   ValidationError[] errors)
        {
            var newResource = ApplicationResource.Create(ApplicationResourceCmdGenerator.CreateApplicationResourceCommand);

            var ex = Assert.Throws <DomainValidationException>(() => newResource.RemoveResourceAction(command));

            Assert.All(ex.ValidationErrors, e => Assert.Contains(e, errors));
        }
Example #20
0
        public void AddResourceAction_ShouReturnTheNewAddedAction_WhenCommandIsValid()
        {
            var createCmd        = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var newResource      = ApplicationResource.Create(createCmd);
            var addActionCommand = ApplicationResourceCmdGenerator.AddResourceActionCommand;
            var action           = newResource.AddResourceAction(addActionCommand);

            Assert.Equal(addActionCommand.Name, action.Name);
        }
Example #21
0
 public static ScriptResourceAdapter Create(ApplicationResource resource)
 {
     if ((resource.Type != ResourceTypes.PostProcessingScript) &&
         (resource.Type != ResourceTypes.PreProcessingScript))
     {
         throw new ApplicationException("Invalid resource type");
     }
     return(new ScriptResourceAdapter(resource));
 }
        public async Task <ActionResult> DeleteConfirmed(Guid id)
        {
            ApplicationResource applicationResource = await db.Resources.FindAsync(id);

            db.Resources.Remove(applicationResource);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public static WebDirectoryResourceAdapter Create(ApplicationResource resource)
        {
            if (resource.Type != ResourceTypes.WebDirectory)
            {
                throw new ApplicationException("Invalid resource type");
            }

            return(new WebDirectoryResourceAdapter(resource));
        }
Example #24
0
        public static IEnumerable <ValidationError> Validate(this RemoveResourceActionCommand command,
                                                             ApplicationResource resource, bool throws = false)
        {
            var context = new ValidationContext <RemoveResourceActionCommand>(command);

            context.RootContextData.Add(nameof(ApplicationResource.AvailableActions), resource.AvailableActions);

            return(validator.ValidateCommand(context, throws));
        }
Example #25
0
        public void FullName_ShouldReturnCorrectFormat()
        {
            var createResourceCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var resource          = ApplicationResource.Create(createResourceCmd);
            var addActionCmd      = ApplicationResourceCmdGenerator.AddResourceActionCommand;
            var action            = resource.AddResourceAction(addActionCmd);

            Assert.Equal(action.FullName, action.FullName);
        }
Example #26
0
        public void ToString_ShouldReturnCorrectFormat()
        {
            var createResourceCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var resource          = ApplicationResource.Create(createResourceCmd);
            var addActionCmd      = ApplicationResourceCmdGenerator.AddResourceActionCommand;
            var action            = resource.AddResourceAction(addActionCmd);

            Assert.Equal($"{nameof(ResourceAction)}: {action.Id}-{action.Name}", action.ToString());
        }
Example #27
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        ApplicationResource.Delete(pathSid: "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    }
Example #28
0
        public void UpdateResourceAction_ShouldThrowDomainValidationException_WhenCommandIsInvalid(UpdateResourceActionCommand command, ValidationError[] errors)
        {
            var createCmd = ApplicationResourceCmdGenerator.CreateApplicationResourceCommand;
            var resource  = ApplicationResource.Create(createCmd);

            var ex = Assert.Throws <DomainValidationException>(() => resource.UpdateAction(command));

            Assert.Equal(errors.Length, ex.ValidationErrors.Count());
            Assert.All(ex.ValidationErrors, err => errors.Contains(err));
        }
Example #29
0
        public bool IsAllowed(IPrincipal user)
        {
            var userId = user.Identity.GetUserId();
            ApplicationResource          resource    = db.Resources.First(x => x.Name.ToLower() == resourceName);
            List <ApplicationPermission> permissions = resource.Permissions.ToList();
            IdentityUserRole             userRole    = db.ApplicationUserRoles.FirstOrDefault(x => x.UserId == userId);
            bool isAllowed = permissions.Any(x => x.RoleId == userRole.RoleId && x.IsAllowed);

            return(isAllowed);
        }
Example #30
0
        public ApplicationResource GetApplicationResource(string key)
        {
            ApplicationResource ApplicationResource = new ApplicationResource();

            if (ApplicationResourceCollectionList.Any())
            {
                ApplicationResource = ApplicationResourceCollectionList.FirstOrDefault(o => o.Key == key);
            }
            return(ApplicationResource);
        }