Exemplo n.º 1
0
 //constructor
 public CrudGet(string ctrl, EditDto editDto, string dbStr = "")
     : base(ctrl, editDto, dbStr)
 {
     _ctrl    = ctrl;
     _editDto = editDto;
     _dbStr   = dbStr;
 }
Exemplo n.º 2
0
        public async Task <IActionResult> Edit([FromBody] EditDto editModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(editModel.Id.ToString());

                if (user != null)
                {
                    user.Email    = editModel.Email;
                    user.UserName = editModel.UserName;

                    var result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "Users"));
                    }
                    else
                    {
                        return(BadRequest("Error"));
                    }
                }
            }
            return(Ok(editModel));
        }
Exemplo n.º 3
0
        private Dictionary <string, string> PrefetchLinks(EditDto editData)
        {
            try
            {
                // Step 1: try to find hyperlink fields
                var bundlesHavingLinks = BundleWithLinkFields(editData);

                var links = bundlesHavingLinks.SelectMany(set
                                                          => set.Hyperlink.SelectMany(h
                                                                                      => h.Value?.Select(linkAttrib
                                                                                                         => new
                {
                    set.Guid,
                    Link = linkAttrib.Value
                })))
                            .Where(set => set != null)
                            // Step 2: Check which ones have a link reference
                            .Where(set => ValueConverterBase.CouldBeReference(set.Link))
                            .ToList();

                // Step 3: Look them up
                // Step 4: return dictionary with these
                return(links.ToDictionary(
                           s => s.Link,
                           s => _valueConverter.ToValue(s.Link, s.Guid)
                           ));
            }
            catch
            {
                return(new Dictionary <string, string>
                {
                    { "Error", "An error occurred pre-fetching the links" }
                });
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// delegate for setNewKey
 /// </summary>
 /// <param name="inputJson"></param>
 /// <param name="edit"></param>
 /// <returns></returns>
 private bool MySetNewKey(CrudEdit editService, JObject inputJson, EditDto edit)
 {
     return(
         editService.SetNewKey(inputJson, edit) &&
         editService.SetRelatId(inputJson, 1, "StartNode", "00") &&
         editService.SetRelatId(inputJson, 1, "EndNode", "00"));
 }
        public async void OnEdit()
        {
            var ids = View.SelectedBotIds;

            if (!ids.Any())
            {
                _mbs.ShowInformation("No Bots selected");
                return;
            }

            var botsToEdit = _bots.Where(x => ids.Contains(x.Id)).ToList();

            if (botsToEdit.Any(x => x.Type != "Bot::SingleBot"))
            {
                _mbs.ShowError("Sorry, Bulk Edit only works for Simple Bots, not advanced.");
                return;
            }

            var     dlg      = new EditDialog.EditDialog(botsToEdit.Count);
            EditDto editData = new EditDto();

            dlg.EditDto = editData;
            var dr = dlg.ShowDialog(View);

            if (dr == DialogResult.OK)
            {
                var loadingView = new ProgressView(botsToEdit, editData, _keys, _logger);
                loadingView.ShowDialog(View);

                _logger.LogInformation("Refreshing Bots");
                await RefreshBots();
            }
        }
Exemplo n.º 6
0
 public EditPrefetchDto TryToPrefectAdditionalData(int appId, EditDto editData)
 {
     return(new EditPrefetchDto
     {
         Links = PrefetchLinks(appId, editData),
         Entities = PrefetchEntities(appId, editData),
         Adam = PrefetchAdam(appId, editData),
     });
 }
Exemplo n.º 7
0
 public ProgressView(List <Bot> bots, EditDto newSettings, Misc.Keys keys, ILogger logger)
 {
     _bots        = bots;
     _newSettings = newSettings;
     _keys        = keys;
     _logger      = logger;
     _mbs         = new MessageBoxService();
     InitializeComponent();
 }
Exemplo n.º 8
0
        public void EditDeveloper(EditDto editDeveloper)
        {
            var Dev = db.Developers.Where(x => x.Id == editDeveloper.Id).SingleOrDefault();

            Dev.FirstName   = editDeveloper.FirstName;
            Dev.LastName    = editDeveloper.LastName;
            Dev.UserName    = editDeveloper.UserName;
            Dev.Email       = editDeveloper.UserName;
            Dev.PhoneNumber = editDeveloper.PhoneNumber;
            db.SaveChanges();
        }
        public void EditManager(EditDto editManager)
        {
            var manager = db.ProjectManagers.Where(x => x.Id == editManager.Id).SingleOrDefault();

            manager.FirstName      = editManager.FirstName;
            manager.LastName       = editManager.LastName;
            manager.UserName       = editManager.UserName;
            manager.PhoneNumber    = editManager.PhoneNumber;
            manager.EmailConfirmed = true;
            db.SaveChanges();
        }
        public IActionResult Remove([FromForm] EditDto entry)
        {
            if (!_isAdmin)
            {
                return(Unauthorized());
            }

            _leaderboard.RemoveEntry(entry.Mode, entry.Position);
            _hubContext.Clients.All.SendAsync("Update");
            return(Redirect(Request.Headers["Referer"]));
        }
Exemplo n.º 11
0
 public static EditViewModel CreateFrom(EditDto editDto)
 {
     return(new EditViewModel
     {
         TargetArticleContent = editDto.TargetArticleContent,
         AgainstArticleContent = editDto.AgainstArticleContent,
         ArticleTitle = editDto.ArticleTitle,
         TargetEdit = CompactEditViewModel.CreateFrom(editDto.TargetEdit),
         AgainstEdit = CompactEditViewModel.CreateFrom(editDto.AgainstEdit),
     });
 }
        public void EditTeamLeader(EditDto editTeamLeader)
        {
            var teamLeader = db.TeamLeaders.Where(x => x.Id == editTeamLeader.Id).SingleOrDefault();

            teamLeader.FirstName   = editTeamLeader.FirstName;
            teamLeader.LastName    = editTeamLeader.LastName;
            teamLeader.UserName    = editTeamLeader.UserName;
            teamLeader.Email       = editTeamLeader.UserName;
            teamLeader.PhoneNumber = editTeamLeader.PhoneNumber;
            db.SaveChanges();
        }
Exemplo n.º 13
0
        private static IEnumerable <BundleWithLinkField> BundleWithLinkFields(EditDto editData)
        {
            var bundlesHavingLinks = editData.Items
                                     // Only these with hyperlinks
                                     .Where(b => b.Entity?.Attributes?.Hyperlink?.Any() ?? false)
                                     .Select(b => new BundleWithLinkField
            {
                Guid            = b.Entity.Guid,
                Hyperlink       = b.Entity.Attributes.Hyperlink,
                ContentTypeName = b.Entity.Type.Name,
            });

            return(bundlesHavingLinks);
        }
Exemplo n.º 14
0
        public EditDto GetEditDetails(bool createMode, bool isDiary, Guid?id)
        {
            var details = new EditDto();

            details.Document = createMode ? new CreateModelDto() : GetDocumentForEdit(id.Value, isDiary);

            // Populating edit comboboxes
            details.Categories = new List <List <SelectListItem> >();
            details.Categories.Add(articleHelper.GetCategoriesToCombo().OrderBy(x => x.Text).ToList());
            details.Categories.Add(articleHelper.GetSubCategoriesToCombo().OrderBy(x => x.Text).ToList());
            details.Categories.Add(articleHelper.GetSeriesToCombo().OrderBy(x => x.Text).ToList());

            details.ArticleImage = articleHelper.GetImageRelativePathByArticleId(id.Value);
            details.IsCreate     = createMode;
            return(details);
        }
        public IActionResult NewEntry([FromForm] EditDto entry)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_isAdmin)
            {
                return(Unauthorized());
            }

            _leaderboard.InsertEntry(entry.Name1, entry.Name2, entry.Score, entry.Mode);
            _hubContext.Clients.All.SendAsync("Update");
            return(Redirect(Request.Headers["Referer"]));
        }
Exemplo n.º 16
0
        public ResultDto EditUser(EditDto model)
        {
            var user  = ctx.Users.Find(model.Id);
            var userA = ctx.UserAdditionalInfo.Find(model.Id);

            userA.FullName   = model.FullName;
            userA.Age        = model.Age;
            userA.Image      = model.Image;
            user.PhoneNumber = model.PhoneNumber;
            user.Email       = model.Email;

            ctx.SaveChanges();

            return(new ResultDto
            {
                IsSuccessful = true
            });
        }
Exemplo n.º 17
0
        private List <EntityForPickerDto> PrefetchEntities(int appId, EditDto editData)
        {
            try
            {
                // Step 1: try to find entity fields
                var bundlesHavingEntities = editData.Items
                                            // Only these with entity fields
                                            .Where(b => b.Entity?.Attributes?.Entity?.Any() ?? false)
                                            .Select(b => new
                {
                    b.Entity.Guid,
                    b.Entity.Attributes.Entity
                });

                var entities = bundlesHavingEntities.SelectMany(set
                                                                => set.Entity.SelectMany(e
                                                                                         => e.Value?.SelectMany(entityAttrib => entityAttrib.Value)))
                               .Where(guid => guid != null)
                               .Select(guid => guid.ToString())
                               // Step 2: Check which ones have a link reference
                               .ToArray();

                // stop here if nothing found, otherwise the backend will return all entities
                if (!entities.Any())
                {
                    return(new List <EntityForPickerDto>());
                }

                var backend = _entityPickerBackend.Init(Log);
                var items   = backend.GetAvailableEntities(appId, entities, null, false);
                return(items.ToList());
            }
            catch
            {
                return(new List <EntityForPickerDto>
                {
                    new EntityForPickerDto {
                        Id = -1, Text = "Error occurred pre-fetching entities", Value = Guid.Empty
                    }
                });
            }
        }
Exemplo n.º 18
0
        public ResultDto GetUser([FromRoute] string id)
        {
            var     user  = ctx.Users.Find(id);
            var     userA = ctx.UserAdditionalInfo.Find(id);
            EditDto res   = new EditDto()
            {
                Id          = userA.Id,
                FullName    = userA.FullName,
                Age         = userA.Age,
                Email       = user.Email,
                PhoneNumber = user.PhoneNumber,
                Image       = userA.Image
            };

            return(new SingleResultDto <EditDto>
            {
                IsSuccessful = true,
                Data = res
            });
        }
Exemplo n.º 19
0
        private static List <BundleWithLinkField> BundleWithLinkFields(EditDto editData, bool includeStringFields = false)
        {
            var bundlesHavingLinks = editData.Items
                                     // Only these with hyperlinks
                                     .Where(b =>
            {
                var hasLinks  = b.Entity?.Attributes?.Hyperlink?.Any() ?? false;
                var hasString = includeStringFields && (b.Entity?.Attributes?.String?.Any() ?? false);
                return(hasLinks || hasString);
            })
                                     .Select(b => new BundleWithLinkField
            {
                Guid            = b.Entity.Guid,
                HyperlinkFields = b.Entity.Attributes.Hyperlink,
                StringFields    = b.Entity.Attributes.String,
                ContentTypeName = b.Entity.Type.Name,
            });

            return(bundlesHavingLinks.ToList());
        }
Exemplo n.º 20
0
        public virtual OperationResult EditRecording([FromBody] EditDto dto)
        {
            try
            {
                OperationResult result = RecordingsService.EditRecording(
                    LmsCompany,
                    this.GetAdminProvider(),
                    CourseId,
                    dto.recordingId,
                    dto.meetingId,
                    dto.name,
                    dto.summary);

                return(result);
            }
            catch (Exception ex)
            {
                string errorMessage = GetOutputErrorMessage("EditRecording", ex);
                return(OperationResult.Error(errorMessage));
            }
        }
Exemplo n.º 21
0
        private Dictionary <string, LinkInfoDto> PrefetchLinks(int appId, EditDto editData)
        {
            try
            {
                // Step 1: try to find hyperlink fields
                var bundlesHavingLinks = BundleWithLinkFields(editData);

                var links = bundlesHavingLinks
                            .SelectMany(set => set.HyperlinkFields
                                        .SelectMany(h => h.Value?.Select(linkAttrib => new
                {
                    Link      = linkAttrib.Value,
                    Converted = TryToConvertOrErrorText(appId, set.ContentTypeName, h.Key, linkAttrib.Value, set.Guid),
                })))
                            .Where(set => set != null)
                            // Step 2: Check which ones have a link reference
                            .Where(set => ValueConverterBase.CouldBeReference(set.Link))
                            // Make distinct by Link
                            .GroupBy(l => l.Link)
                            .Select(g => g.First())
                            .ToList();


                // Step 3: Look them up
                // Step 4: return dictionary with these
                return(links.ToDictionary(
                           s => s.Link,
                           s => s.Converted));
            }
            catch (Exception ex)
            {
                return(new Dictionary <string, LinkInfoDto>
                {
                    { "Error", new LinkInfoDto {
                          Value = "An error occurred pre-fetching the links " + ex.Message
                      } }
                });
            }
        }
Exemplo n.º 22
0
 // todo #mvcSec [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)]
 public Dictionary <Guid, int> Save([FromBody] EditDto package, int appId, bool partOfPage)
 => _saveBackendLazy.Value.Init(appId, Log).Save(package, partOfPage);
Exemplo n.º 23
0
 public SaveDataValidator(EditDto package, ILog parentLog)
     : base("Val.Save", parentLog, "start save validator", nameof(SaveDataValidator))
 {
     Package = package;
 }
Exemplo n.º 24
0
        private Dictionary <string, Dictionary <string, IEnumerable <AdamItemDto> > > PrefetchAdam(int appId, EditDto editData)
        {
            // Step 1: try to find hyperlink fields
            var bundlesHavingLinks = BundleWithLinkFields(editData, true);

            var bundlesWithAllKeys = bundlesHavingLinks.Select(set =>
            {
                var keys  = new List <string>();
                var hKeys = set.HyperlinkFields?.Select(h => h.Key);
                if (hKeys != null)
                {
                    keys.AddRange(hKeys);
                }
                var sKeys = set.StringFields?.Select(s => s.Key);
                if (sKeys != null)
                {
                    keys.AddRange(sKeys);
                }
                return(new
                {
                    Set = set,
                    Keys = keys
                });
            });

            var links = bundlesWithAllKeys
                        .GroupBy(b => b.Set.Guid)
                        .ToDictionary(
                b => b.Key.ToString(),
                b =>
                b.SelectMany(selector: bundle => bundle.Keys.Select(key => new
            {
                Key = key,
                Dic = GetAdamListOfItems(appId, bundle.Set, key),
            }))
                // skip empty bits to avoid UI from relying on these nodes to always exist
                .Where(r => r.Dic.Any())
                // Step 2: Check which ones have a link reference
                .ToDictionary(r => r.Key, r => r.Dic)
                );

            return(links);
        }
Exemplo n.º 25
0
        public EditDto Load(int appId, List <ItemIdentifier> items)
        {
            // Security check
            var wrapLog = Log.Call($"load many a#{appId}, items⋮{items.Count}");

            var context = _ctxResolver.App(appId);

            var showDrafts = context.UserMayEdit;

            // do early permission check - but at this time it may be that we don't have the types yet
            // because they may be group/id combinations, without type information which we'll look up afterwards
            var appIdentity = State.Identity(null, appId);

            items = _contentGroupList.Init(appIdentity, Log, showDrafts).ConvertListIndexToId(items);
            TryToAutoFindMetadataSingleton(items, context.AppState);

            // now look up the types, and repeat security check with type-names
            // todo: 2020-03-20 new feat 11.01, may not check inner type permissions ATM
            var permCheck = ServiceProvider.Build <MultiPermissionsTypes>().Init(context, context.AppState, items, Log);

            if (!permCheck.EnsureAll(GrantSets.WriteSomething, out var error))
            {
                throw HttpException.PermissionDenied(error);
            }

            // load items - similar
            var result         = new EditDto();
            var entityApi      = _entityApi.Init(appId, permCheck.EnsureAny(GrantSets.ReadDraft), Log);
            var typeRead       = entityApi.AppRead.ContentTypes;
            var list           = entityApi.GetEntitiesForEditing(items);
            var jsonSerializer = ServiceProvider.Build <JsonSerializer>();

            result.Items = list.Select(e => new BundleWithHeader <JsonEntity>
            {
                Header = e.Header,
                Entity = GetSerializeAndMdAssignJsonEntity(appId, e, jsonSerializer, typeRead)
            }).ToList();

            // set published if some data already exists
            if (list.Any())
            {
                result.IsPublished = list.First().Entity?.IsPublished ?? true; // Entity could be null (new), then true
                // only set draft-should-branch if this draft already has a published item
                if (!result.IsPublished)
                {
                    result.DraftShouldBranch = list.First().Entity?.GetPublished() != null;
                }
            }

            // since we're retrieving data - make sure we're allowed to
            // this is to ensure that if public forms only have create permissions, they can't access existing data
            // important, this code is shared/duplicated in the EntitiesController.GetManyForEditing
            if (list.Any(set => set.Entity != null))
            {
                if (!permCheck.EnsureAll(GrantSets.ReadSomething, out error))
                {
                    throw HttpException.PermissionDenied(error);
                }
            }

            // load content-types
            var types = UsedTypes(list, typeRead);

            result.ContentTypes = types
                                  .Select(ct => JsonSerializer.ToJson(ct, true))
                                  .ToList();

            //// TEMP DEBUG
            //var inputTypes = types.SelectMany(t => t.Attributes.Select(a =>
            //{
            //    var Lookup = a.InputType();
            //    var mdAll = a.Metadata.Where(md => md.Type.Is(Constants.MetadataFieldTypeAll)).ToList();
            //    var MdAllCount = mdAll.Count;
            //    var MdAllAttribCount = mdAll.FirstOrDefault()?.Attributes.Count;
            //    var MdAllWithAttrib = mdAll.FirstOrDefault(md => md.Attributes.ContainsKey(Constants.MetadataFieldTypeAll));
            //    var MdAllAttrib = MdAllWithAttrib?.GetBestValue<string>(Constants.MetadataFieldTypeAll);
            //    var MdAllAttribZero = MdAllWithAttrib?.GetBestValue<string>(Constants.MetadataFieldTypeAll, new string[0]);
            //    var MdAllAttribEmpty = MdAllWithAttrib?.GetBestValue<string>(Constants.MetadataFieldTypeAll, new []{""});
            //    var MdAllAttribEn = MdAllWithAttrib?.GetBestValue<string>(Constants.MetadataFieldTypeAll, new[] { "en-us" });
            //    var MdAllAttribTr = MdAllWithAttrib?.GetBestValue<string>(Constants.MetadataFieldTypeAll, new[] { "tr-tr" });
            //    var MdAllType = a.Metadata.GetBestValue<string>(Constants.MetadataFieldAllInputType, Constants.MetadataFieldTypeAll);
            //    return new {Lookup, MdAllCount, MdAllType, MdAllAttribCount, MdAllWithAttrib?.EntityId, MdAllAttrib, MdAllAttribZero, MdAllAttribEmpty, MdAllAttribEn, MdAllAttribTr };
            //}));
            //var serializedDebug = JsonConvert.SerializeObject(inputTypes);
            //Log.Add("Test / debug: " + serializedDebug);

            // ensure that sub-properties of the content-types are included
            // this is for UI Formulas (children of @All) - WIP
            // and the warning/error Regex specials - WIP
            var entList = types.SelectMany(
                // in all Content-Type attributes like title, body etc.
                t => t.Attributes.SelectMany(
                    // check all metadata of these attributes - get possible sub-entities attached
                    a => a.Metadata.SelectMany(m => m.Children())
                    )
                );

            result.ContentTypeItems = entList.Select(e => jsonSerializer.ToJson(e, 0, Log)).ToList();

            // Fix not-supported input-type names; map to correct name
            result.ContentTypes
            .ForEach(jt => jt.Attributes
                     .ForEach(at => at.InputType = InputTypes.MapInputTypeV10(at.InputType)));

            // load input-field configurations
            result.InputTypes = GetNecessaryInputTypes(result.ContentTypes, typeRead);

            // also include UI features
            result.Features = FeaturesHelpers.FeatureListWithPermissionCheck(permCheck).ToList();

            // Attach context, but only the minimum needed for the UI
            result.Context = _contextBuilder.SetZoneAndApp(appIdentity.ZoneId, context.AppState)
                             .Get(Ctx.AppBasic | Ctx.Language | Ctx.Site | Ctx.System);

            try
            {
                result.Prefetch = TryToPrefectAdditionalData(appId, result);
            }
            catch (Exception) { /* ignore */ }

            // done - return
            wrapLog($"ready, sending items:{result.Items.Count}, " +
                    $"types:{result.ContentTypes.Count}, " +
                    $"inputs:{result.InputTypes.Count}, " +
                    $"feats:{result.Features.Count}");
            return(result);
        }
Exemplo n.º 26
0
        public async void OnEdit()
        {
            var ids = View.SelectedBotIds;

            if (IsValid(ids))
            {
                var     dlg      = new EditDialog.EditDialog(ids.Count, new BotManager(_keys, _logger));
                EditDto editData = new EditDto();
                dlg.EditDto = editData;
                var dr = dlg.ShowDialog(View);
                if (dr == DialogResult.OK)
                {
                    var cancellationTokenSource = new CancellationTokenSource();
                    var loadingView             = new ProgressView.ProgressView("Applying new settings", cancellationTokenSource, ids.Count);
                    loadingView.Show(View);

                    var botMgr = new BotManager(_keys, _logger);

                    int i = 0;
                    foreach (var botId in ids)
                    {
                        i++;
                        loadingView.SetProgress(i);

                        if (cancellationTokenSource.IsCancellationRequested)
                        {
                            break;
                        }

                        if (editData.IsEnabled.HasValue)
                        {
                            if (editData.IsEnabled.Value)
                            {
                                await botMgr.Enable(botId);
                            }
                            else
                            {
                                await botMgr.Disable(botId);
                            }
                        }

                        var bot = await botMgr.GetBotById(botId);

                        var updateData = new BotUpdateData(bot);
                        if (editData.ActiveSafetyOrdersCount.HasValue)
                        {
                            updateData.ActiveSafetyOrdersCount = editData.ActiveSafetyOrdersCount.Value;
                        }
                        if (editData.BaseOrderVolume.HasValue)
                        {
                            updateData.BaseOrderVolume = editData.BaseOrderVolume.Value;
                        }
                        if (editData.Cooldown.HasValue)
                        {
                            updateData.Cooldown = editData.Cooldown.Value;
                        }
                        if (editData.MartingaleStepCoefficient.HasValue)
                        {
                            updateData.MartingaleStepCoefficient = editData.MartingaleStepCoefficient.Value;
                        }
                        if (editData.MartingaleVolumeCoefficient.HasValue)
                        {
                            updateData.MartingaleVolumeCoefficient = editData.MartingaleVolumeCoefficient.Value;
                        }
                        if (editData.MaxSafetyOrders.HasValue)
                        {
                            updateData.MaxSafetyOrders = editData.MaxSafetyOrders.Value;
                        }
                        if (!string.IsNullOrWhiteSpace(editData.Name))
                        {
                            updateData.Name = BotManager.GenerateNewName(editData.Name, bot.Strategy.ToString(), bot.Pairs.Single(), bot.AccountName);
                        }
                        if (editData.SafetyOrderStepPercentage.HasValue)
                        {
                            updateData.SafetyOrderStepPercentage = editData.SafetyOrderStepPercentage.Value;
                        }
                        if (editData.StartOrderType.HasValue)
                        {
                            updateData.StartOrderType = editData.StartOrderType.Value;
                        }
                        if (editData.SafetyOrderVolume.HasValue)
                        {
                            updateData.SafetyOrderVolume = editData.SafetyOrderVolume.Value;
                        }
                        if (editData.TakeProfit.HasValue)
                        {
                            updateData.TakeProfit = editData.TakeProfit.Value;
                        }
                        if (editData.TakeProfitType.HasValue)
                        {
                            updateData.TakeProfitType = editData.TakeProfitType.Value;
                        }
                        if (editData.TrailingDeviation.HasValue)
                        {
                            updateData.TrailingDeviation = editData.TrailingDeviation.Value;
                        }
                        if (editData.TrailingEnabled.HasValue)
                        {
                            updateData.TrailingEnabled = editData.TrailingEnabled.Value;
                        }
                        if (editData.BaseOrderVolumeType.HasValue)
                        {
                            updateData.BaseOrderVolumeType = editData.BaseOrderVolumeType.Value;
                        }
                        if (editData.SafetyOrderVolumeType.HasValue)
                        {
                            updateData.SafetyOrderVolumeType = editData.SafetyOrderVolumeType.Value;
                        }
                        if (editData.StopLossPercentage.HasValue)
                        {
                            updateData.StopLossPercentage = editData.StopLossPercentage.Value;
                        }
                        if (editData.StopLossType.HasValue)
                        {
                            updateData.StopLossType = editData.StopLossType.Value;
                        }
                        if (editData.StopLossTimeoutEnabled.HasValue)
                        {
                            updateData.StopLossTimeoutEnabled = editData.StopLossTimeoutEnabled.Value;
                        }
                        if (editData.StopLossTimeout.HasValue)
                        {
                            updateData.StopLossTimeoutInSeconds = editData.StopLossTimeout.Value;
                        }
                        if (editData.LeverageType.HasValue)
                        {
                            updateData.LeverageType = editData.LeverageType.Value;
                        }
                        if (editData.LeverageCustomValue.HasValue)
                        {
                            updateData.LeverageCustomValue = editData.LeverageCustomValue.Value;
                        }

                        if (editData.DisableAfterDealsCountInfo != null)
                        {
                            if (editData.DisableAfterDealsCountInfo.Enable)
                            {
                                updateData.DisableAfterDealsCount = editData.DisableAfterDealsCountInfo.Value;
                            }
                            else
                            {
                                updateData.DisableAfterDealsCount = null;
                            }
                        }

                        if (editData.DealStartConditions.Any())
                        {
                            updateData.Strategies.Clear();
                            updateData.Strategies.AddRange(editData.DealStartConditions);
                        }

                        var res = await botMgr.SaveBot(botId, updateData);

                        if (res.IsSuccess)
                        {
                            _logger.LogInformation($"Bot {botId} updated");
                        }
                        else
                        {
                            _logger.LogError($"Could not update Bot {botId}. Reason: {res.Error}");
                        }
                    }

                    loadingView.Close();
                    if (cancellationTokenSource.IsCancellationRequested)
                    {
                        _logger.LogInformation("Operation cancelled");
                        _mbs.ShowError("Operation cancelled!", "");
                    }
                    else
                    {
                        _mbs.ShowInformation("Bulk Edit finished. See output section for details.");
                    }

                    _logger.LogInformation("Refreshing Bots");
                    await RefreshBots();
                }
            }
        }
Exemplo n.º 27
0
        public Dictionary <Guid, int> Save(EditDto package, bool partOfPage)
        {
            Log.Add($"save started with a#{_appId}, i⋮{package.Items.Count}, partOfPage:{partOfPage}");

            var validator = new SaveDataValidator(package, Log);

            // perform some basic validation checks
            if (!validator.ContainsOnlyExpectedNodes(out var exp))
            {
                throw exp;
            }

            // todo: unsure about this - thought I should check contentblockappid in group-header, because this is where it should be saved!
            //var contextAppId = appId;
            //var targetAppId = package.Items.First().Header.Group.ContentBlockAppId;
            //if (targetAppId != 0)
            //{
            //    Log.Add($"detected content-block app to use: {targetAppId}; in context of app {contextAppId}");
            //    appId = targetAppId;
            //}

            var appMan  = _appManagerLazy.Value.Init(_appId, Log);
            var appRead = appMan.Read;
            var ser     = ServiceProvider.Build <JsonSerializer>().Init(appRead.AppState, Log);

            // Since we're importing directly into this app, we would prefer local content-types
            ser.PreferLocalAppTypes = true;
            validator.PrepareForEntityChecks(appRead);

            #region check if it's an update, and do more security checks then - shared with EntitiesController.Save
            // basic permission checks
            var permCheck = new Save.SaveSecurity(_context, Log)
                            .DoPreSaveSecurityCheck(_appId, package.Items);

            var foundItems = package.Items.Where(i => i.Entity.Id != 0 && i.Entity.Guid != Guid.Empty)
                             .Select(i => i.Entity.Guid != Guid.Empty
                        ? appRead.Entities.Get(i.Entity.Guid) // prefer guid access if available
                        : appRead.Entities.Get(i.Entity.Id)   // otherwise id
                                     );
            if (foundItems.Any(i => i != null) && !permCheck.EnsureAll(GrantSets.UpdateSomething, out var error))
            {
                throw HttpException.PermissionDenied(error);
            }
            #endregion


            var items = package.Items.Select(i =>
            {
                var ent = ser.Deserialize(i.Entity, false, false) as Entity;

                var index = package.Items.IndexOf(i); // index is helpful in case of errors
                if (!validator.EntityIsOk(index, ent, out exp))
                {
                    throw exp;
                }

                if (!validator.IfUpdateValidateAndCorrectIds(index, ent, out exp))
                {
                    throw exp;
                }

                ent.IsPublished        = package.IsPublished;
                ent.PlaceDraftInBranch = package.DraftShouldBranch;

                // new in 11.01
                if (i.Header.ListHas())
                {
                    // Check if Add was true, and fix if it had already been saved (EntityId != 0)
                    // the entityId is reset by the validator if it turns out to be an update
                    // todo: verify use - maybe it's to set before we save, as maybe afterwards it's always != 0?
                    var add      = i.Header.ListAdd();
                    i.Header.Add = add;
                    if (ent.EntityId > 0 && add)
                    {
                        i.Header.Add = false;
                    }
                }

                return(new BundleWithHeader <IEntity>
                {
                    Header = i.Header,
                    Entity = ent
                });
            })
                        .ToList();

            Log.Add("items to save generated, all data tests passed");

            return(_pagePublishing.SaveInPagePublishing(_ctxResolver.RealBlockOrNull(), _appId, items, partOfPage,
                                                        forceSaveAsDraft => DoSave(appMan, items, forceSaveAsDraft),
                                                        permCheck));
        }
Exemplo n.º 28
0
 public Dictionary <Guid, int> Save([FromBody] EditDto package, int appId, bool partOfPage)
 => GetService <EditSaveBackend>().Init(appId, Log).Save(package, partOfPage);
Exemplo n.º 29
0
        public async Task <IActionResult> Put(string id, [FromBody] EditDto model)
        {
            User user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NoContent());
            }

            Warehouse warehouse = _context.Warehouses.Find(model.Warehouse);

            if (warehouse == null)
            {
                return(BadRequest("No Warehouse"));
            }
            Department department = _context.Departments.Find(model.Department);

            if (department == null)
            {
                return(BadRequest("No Departamento"));
            }

            IdentityRole Role = await _roleManager.FindByIdAsync(model.Role);

            if (Role == null)
            {
                return(BadRequest("NO ROL"));
            }

            user.UserName   = model.Email;
            user.Email      = model.Email;
            user.Name       = model.Name;
            user.LastName   = model.LastName;
            user.SAPID      = model.SAPID;
            user.Active     = model.Active;
            user.Warehouse  = warehouse;
            user.Department = department;

            var result = await _userManager.UpdateAsync(user);

            if (model.Password != null)
            {
                await _userManager.RemovePasswordAsync(user);

                await _userManager.AddPasswordAsync(user, model.Password);
            }

            if (result.Succeeded)
            {
                IList <string> userRoleNames = await _userManager.GetRolesAsync(user);

                string ActualRole = userRoleNames.FirstOrDefault();
                if (Role.Name != ActualRole)
                {
                    if (ActualRole != null)
                    {
                        await _userManager.RemoveFromRoleAsync(user, ActualRole);
                    }
                    await _userManager.AddToRoleAsync(user, Role.Name);
                }

                var UserClaims = await _userManager.GetClaimsAsync(user);

                var Permissions = UserClaims.Where(x => x.Type == CustomClaimTypes.Permission);

                foreach (var permission in Permissions)
                {
                    if (!model.PermissionsExtra.Exists(x => x == permission.Value))
                    {
                        await _userManager.RemoveClaimAsync(user, permission);
                    }
                }

                var PermissionList = Permissions.ToList();
                foreach (var permission in model.PermissionsExtra)
                {
                    if (!PermissionList.Exists(x => x.Value == permission))
                    {
                        await _userManager.AddClaimAsync(user, new Claim(CustomClaimTypes.Permission, permission));
                    }
                }

                return(Ok());
            }

            StringBuilder stringBuilder = new StringBuilder();

            foreach (IdentityError m in result.Errors.ToList())
            {
                stringBuilder.AppendFormat("Codigo: {0} Descripcion: {1}\n", m.Code, m.Description);
            }
            return(BadRequest(stringBuilder.ToString()));
        }
Exemplo n.º 30
0
        private Dictionary <string, IEnumerable <AdamItemDto> > PrefetchAdam(int appId, EditDto editData)
        {
            // Step 1: try to find hyperlink fields
            var bundlesHavingLinks = BundleWithLinkFields(editData);

            var links = bundlesHavingLinks.SelectMany(set
                                                      => set.Hyperlink.Select(h
                                                                              =>
            {
                var adamListMaker = ServiceProvider.Build <IAdamTransGetItems>();
                adamListMaker.Init(appId, set.ContentTypeName, set.Guid, h.Key, false, Log);
                return(new
                {
                    set.Guid,
                    h.Key,
                    Dic = adamListMaker.ItemsInField(string.Empty) as IEnumerable <AdamItemDto>,
                });
            }))
                        //.Where(set => set != null)
                        // Step 2: Check which ones have a link reference
                        .ToDictionary(r => r.Key, r => r.Dic);

            return(links);
        }