public DetailsTagHelper(IDataProtectionProvider protector, IHttpContextAccessor contextAccessor) { var options = NccReflectionService.NccGetClassInstanceWithDi(contextAccessor.HttpContext, NccConstants.OptionsAssemblyName); _nccSettings = options != null ? ((IOptions <NccSettings>)options).Value : new NccSettings(); _protector = protector.CreateProtector(_nccSettings.DataProtectionKey); }
public NccRenderControl(IDataProtectionProvider protector, IRazorViewEngine razorViewEngine, IHttpContextAccessor contextAccessor) { var options = NccReflectionService.NccGetClassInstanceWithDi(contextAccessor.HttpContext, NccConstants.OptionsAssemblyName); _nccSettings = options != null ? ((IOptions <NccSettings>)options).Value : new NccSettings(); _protector = protector.CreateProtector(_nccSettings.DataProtectionKey); _razorViewEngine = razorViewEngine; }
public override async Task ProcessAsync(TagHelperContext tagContext, TagHelperOutput output) { output.SuppressOutput(); if (tagContext.Items.ContainsKey(typeof(NccRepeaterContext))) { _context = (NccRepeaterContext)tagContext.Items[typeof(NccRepeaterContext)]; } else { return; } var gridViewContext = (NccRepeaterContext)tagContext.Items[typeof(NccRepeaterContext)]; var data = gridViewContext.DataObjects.GetType().ToString().Contains("Microsoft.EntityFrameworkCore.Internal.InternalDbSet") || gridViewContext.DataObjects.GetType().ToString().Contains("Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable") ? ((IQueryable <object>)gridViewContext.DataObjects).ToList() : gridViewContext.DataObjects as IList; if (data != null && data.Count > 0) { object service = null; if (!string.IsNullOrEmpty(_context.EventHandlerClass)) { service = NccReflectionService.NccGetClassInstance(_context.EventHandlerClass, null); } foreach (var item in data) { service?.NccInvokeMethod(NccRepeaterEventsEnum.ItemDataBound.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = _context, DataObjects = data }, item }); var itemData = item.NccToExpando() as IDictionary <string, object>; ViewContext.ViewData.Model = itemData.ExtToExpandoObject(); var childContent = await output.GetChildContentAsync(false); _nccTagContext.RepeaterItems.Add(childContent.GetContent()); } } }
public override async Task ProcessAsync(TagHelperContext tagContext, TagHelperOutput output) { if (!string.IsNullOrEmpty(EventHandler)) { Context.EventHandlerClass = EventHandler; } if (!string.IsNullOrEmpty(DataKeys) && DataKeys != Context.DataKeys) { Context.DataKeys = DataKeys; } object service = null; if (!string.IsNullOrEmpty(Context.EventHandlerClass)) { service = NccReflectionService.NccGetClassInstance(Context.EventHandlerClass, null); } service?.NccInvokeMethod(NccEventsEnum.Load.ToString(), new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext } }); //Get grid id and share it with siblings parents if (string.IsNullOrEmpty(Context.Id)) { Context.Id = Guid.NewGuid().ToString(); } output.TagName = "div"; output.Attributes.SetAttribute("id", Context.Id); output.Attributes.SetAttribute("style", "position:relative"); if (Context.Visible) { if (RenderForm) { var form = new TagBuilder("form"); form.TagRenderMode = TagRenderMode.StartTag; output.PreContent.AppendHtml(form); } //Get data from datasource NccControlsService.BindData(Context, ViewContext.HttpContext, null, null); service?.NccInvokeMethod(NccEventsEnum.DataBound.ToString(), new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext, DataObjects = Context.DataObjects } }); var data = Context.DataObjects.GetType().ToString().Contains("Microsoft.EntityFrameworkCore.Internal.InternalDbSet") || Context.DataObjects.GetType().ToString().Contains("Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable") ? ((IQueryable <object>)Context.DataObjects).FirstOrDefault() : Context.DataObjects as object; if (data != null) { if (!string.IsNullOrEmpty(Context.DataKeys)) { Context.DataKeysValues = new List <Dictionary <string, object> >(); var dataKeys = Context.DataKeys.Split(',')?.ToList(); var dataKeysRow = new Dictionary <string, object>(); foreach (var dataKey in dataKeys) { var keyValue = data.NccGetPropertyValue <object>(dataKey); if (keyValue != null) { dataKeysRow[dataKey] = keyValue; } } Context.DataKeysValues.Add(dataKeysRow); } ViewContext.ViewData.Model = data; var content = await output.GetChildContentAsync(); output.Content.SetHtmlContent(content.GetContent()); } if (RenderForm) { output.PostContent.AppendHtml(new TagBuilder("form") { TagRenderMode = TagRenderMode.EndTag }); } } else { output.SuppressOutput(); } service?.NccInvokeMethod(NccEventsEnum.PreRender.ToString(), new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext } }); output.PostContent.AppendHtml(NccControlsService.GetEncodedContext(_protector, Context.Id, Context)); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderOverlay()); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderImage()); }
public override async Task ProcessAsync(TagHelperContext tagContext, TagHelperOutput output) { output.SuppressOutput(); if (tagContext.Items.ContainsKey(typeof(NccGridContext))) { _context = (NccGridContext)tagContext.Items[typeof(NccGridContext)]; } else { return; } var gridViewContext = (NccGridContext)tagContext.Items[typeof(NccGridContext)]; var global = ViewContext.ViewData.Model; output.TagName = null; var data = gridViewContext.DataObjects as IList; _nccTagContext.RowNumber = 0; ViewContext.ViewBag.EmptyData = false; if (data != null && data.Count > 0) { object service = null; if (!string.IsNullOrEmpty(_context.EventHandlerClass)) { service = NccReflectionService.NccGetClassInstance(_context.EventHandlerClass, null); } _nccTagContext.GridRows = new List <GridRow>(); if (data.Count > _context.PageSize) { if (_context.Filters.ContainsKey("pageSize")) { var pageSize = Convert.ToInt32(_context.Filters["pageSize"]); data = new List <object>(data.Cast <object>()).Skip(pageSize * (_context.PageNumber - 1)).Take(pageSize).ToList(); } else { data = new List <object>(data.Cast <object>()).Skip(_context.PageSize * (_context.PageNumber - 1)).Take(_context.PageSize).ToList(); } } _context.DataObjects = data; var dataKeys = _context.DataKeys?.Split(',')?.ToList(); if (dataKeys != null) { _context.DataKeysValues = new List <Dictionary <string, object> >(); } foreach (var row in data) { if (dataKeys != null) { var dataKeysRow = new Dictionary <string, object>(); foreach (var dataKey in dataKeys) { var keyValue = row.NccGetPropertyValue <object>(dataKey); if (keyValue != null) { dataKeysRow[dataKey] = keyValue; } } _context.DataKeysValues.Add(dataKeysRow); } service?.NccInvokeMethod(NccGridEventsEnum.RowDataBound.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = _context, DataObjects = data }, row }); _nccTagContext.GridRows.Add(new GridRow { Cells = new List <GridCell>(), RowNumber = _nccTagContext.RowNumber }); var rowData = row.NccToExpando() as IDictionary <string, object>; rowData["NccRowNumber"] = _nccTagContext.RowNumber; ViewContext.ViewData.Model = rowData.NccToExpando(); await output.GetChildContentAsync(false); if (_context.AutoGenerateEditButton) { var rowModel = _nccTagContext.GridRows.LastOrDefault(); if (_context.AdditionalData.ContainsKey("EditRowNumber") && _context.AdditionalData["EditRowNumber"].ToString() == _nccTagContext.RowNumber.ToString()) { var model = new NccActionModel { TargetIds = new[] { _context.Id } }; model.Parameters.Add($"{DefaultParameters.ActionType.ToString().NccAddPrefix()}", "GridAction"); model.Parameters.Add($"{DefaultParameters.EventName.ToString().NccAddPrefix()}", "CancelEditRow"); model.Parameters.Add($"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}", _nccTagContext.RowNumber.ToString()); var link = new TagBuilder("a") { Attributes = { { "style", "cursor:pointer;" }, { "onclick", $"nccAction(null, $(this), '{JsonConvert.SerializeObject(model)}', '{NccConstants.AttributePrefix}');" } } }; link.InnerHtml.AppendHtml("Cancel"); model.Parameters[$"{DefaultParameters.EventName.ToString().NccAddPrefix()}"] = "UpdateRow"; var link2 = new TagBuilder("a") { Attributes = { { "style", "cursor:pointer;" }, { "onclick", $"nccAction(null, $(this), '{JsonConvert.SerializeObject(model)}', '{NccConstants.AttributePrefix}');" } } }; link2.InnerHtml.AppendHtml("Save"); var cell = new GridCell(); cell.Value.AppendHtml(link); rowModel?.Cells.Add(cell); var cell2 = new GridCell(); cell2.Value.SetHtmlContent(link2); rowModel?.Cells.Add(cell2); } else { var model = new NccActionModel { TargetIds = new[] { _context.Id } }; model.Parameters.Add($"{DefaultParameters.ActionType.ToString().NccAddPrefix()}", "GridAction"); model.Parameters.Add($"{DefaultParameters.EventName.ToString().NccAddPrefix()}", "EditRow"); model.Parameters.Add($"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}", _nccTagContext.RowNumber.ToString()); var link = new TagBuilder("a") { Attributes = { { "style", "cursor:pointer;" }, { "onclick", $"nccAction(null, $(this), '{JsonConvert.SerializeObject(model)}', '{NccConstants.AttributePrefix}');" } } }; link.InnerHtml.AppendHtml("Edit"); var cell = new GridCell(); cell.Value.AppendHtml(link); rowModel?.Cells.Add(cell); } } //ViewContext.ViewBag.RowCount _nccTagContext.RowNumber++; _nccTagContext.ColCountComplete = true; service?.NccInvokeMethod(NccGridEventsEnum.RowCreated.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = _context, DataObjects = data }, _nccTagContext.GridRows.LastOrDefault() }); } } }
public override async Task ProcessAsync(TagHelperContext tagContext, TagHelperOutput output) { if (Context == null) { throw new Exception("The NccGridContext is null... Please check the reference."); } _nccTagContext.CssClassGrid = CssClassTable; _nccTagContext.CssClassBody = CssClassBody; _nccTagContext.CssClassHeader = CssClassHeader; _nccTagContext.CssClassFooter = CssClassFooter; _nccTagContext.CssClassHeaderContainer = CssClassHeaderContainer; _nccTagContext.CssClassTableContainer = CssClassTableContainer; _nccTagContext.CssClassFooterContainer = CssClassFooterContainer; if (!string.IsNullOrEmpty(DataKeys) && DataKeys != Context.DataKeys) { Context.DataKeys = DataKeys; } if (RenderForm.HasValue) { Context.RenderForm = RenderForm.Value; } if (AutoGenerateEditButton.HasValue) { Context.AutoGenerateEditButton = AutoGenerateEditButton.Value; } if (AllowPaging.HasValue) { Context.AllowPaging = AllowPaging.Value; } if (Context.AllowPaging) { if (PagerNavigationSize.HasValue) { Context.PagerNavigationSize = PagerNavigationSize.Value; } if (Context.Filters.ContainsKey("pageSize")) { Context.PageSize = Convert.ToInt32(Context.Filters["pageSize"]); } else if (PageSize.HasValue) { Context.PageSize = PageSize.Value; } if (Context.PageSize == 0 || Context.PageSize == int.MaxValue) { Context.PageSize = 10; } } else { Context.PageSize = int.MaxValue; } if (Context.Filters.ContainsKey("pageNumber")) { Context.PageNumber = Convert.ToInt32(Context.Filters["pageNumber"]); } object service = null; if (!string.IsNullOrEmpty(Context.EventHandlerClass)) { service = NccReflectionService.NccGetClassInstance(Context.EventHandlerClass, null); } service?.NccInvokeMethod(NccEventsEnum.Load.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = Context, ViewContext = ViewContext } }); //Get grid id and share it with siblings parents if (string.IsNullOrEmpty(Context.Id)) { Context.Id = Guid.NewGuid().ToString(); } output.TagName = "div"; output.Attributes.SetAttribute("id", Context.Id); output.Attributes.SetAttribute("style", "position:relative"); if (Context.Visible) { tagContext.Items.Add(typeof(NccGridContext), Context); if (Context.RenderForm) { var form = new TagBuilder("form") { TagRenderMode = TagRenderMode.StartTag }; output.PreContent.AppendHtml(form); } NccActionsService.ExtraParameters <NccGridContext> setExtraParameters = GridService.GetExtraParameters; NccActionsService.DataResult <NccGridContext> setDataResult = GridService.SetDataResult; NccControlsService.BindData(Context, ViewContext.HttpContext, setExtraParameters, setDataResult); service?.NccInvokeMethod(NccEventsEnum.DataBound.ToString(), new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext, DataObjects = Context.DataObjects } }); _nccTagContext.GridHeader = new GridRow { Cells = new List <GridCell>(), CssClass = CssClassHeader }; await output.GetChildContentAsync(); var tableContainerDiv = new TagBuilder("div"); if (!string.IsNullOrEmpty(_nccTagContext.CssClassTableContainer)) { tableContainerDiv.Attributes.Add("class", _nccTagContext.CssClassTableContainer); } tableContainerDiv.InnerHtml.AppendHtml(GridService.BuildTableHtml(_nccTagContext, Context)); output.Content.SetHtmlContent(tableContainerDiv); if (Context.AllowPaging) { output.Content.AppendHtml(GridService.BuildTablePager(_nccTagContext, Context)); } output.PreContent.AppendHtml(_nccTagContext.PreContent); output.PostContent.AppendHtml(_nccTagContext.PostContent); if (Context.RenderForm) { var antiforgeryTag = Generator.GenerateAntiforgery(ViewContext); if (antiforgeryTag != null) { output.PostContent.AppendHtml(antiforgeryTag); } output.PostContent.AppendHtml(new TagBuilder("form") { TagRenderMode = TagRenderMode.EndTag }); } } service?.NccInvokeMethod(NccEventsEnum.PreRender.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = Context, ViewContext = ViewContext } }); _nccTagContext.ControlContext = Context; output.PostContent.AppendHtml(NccControlsService.GetEncodedContext(_protector, Context.Id, Context)); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderOverlay()); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderImage()); }
public override async Task ProcessAsync(TagHelperContext tagContext, TagHelperOutput output) { if (Context == null) { throw new Exception("The NccRepeaterContext is null... Please check the reference."); } object service = null; if (!string.IsNullOrEmpty(Context.EventHandlerClass)) { service = NccReflectionService.NccGetClassInstance(Context.EventHandlerClass, null); } service?.NccInvokeMethod(NccEventsEnum.Load.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = Context, ViewContext = ViewContext } }); //Get grid id and share it with siblings parents if (string.IsNullOrEmpty(Context.Id)) { Context.Id = Guid.NewGuid().ToString(); } output.TagName = "div"; output.Attributes.SetAttribute("id", Context.Id); output.Attributes.SetAttribute("style", "position:relative"); if (Context.Visible) { tagContext.Items.Add(typeof(NccRepeaterContext), Context); //NccActionsService.ExtraParameters<NccRepeaterContext> setExtraParameters = RepeaterService.GetExtraParameters; //NccActionsService.DataResult<NccRepeaterContext> setDataResult = RepeaterService.SetDataResult; NccControlsService.BindData(Context, ViewContext.HttpContext, null, null); service?.NccInvokeMethod(NccEventsEnum.DataBound.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = Context, ViewContext = ViewContext, DataObjects = Context.DataObjects } }); await output.GetChildContentAsync(); } var content = ""; foreach (var repeaterItem in _nccTagContext.RepeaterItems) { content += repeaterItem; } output.Content.AppendHtml(_nccTagContext.RepeaterHeader); output.Content.AppendHtml(content); output.Content.AppendHtml(_nccTagContext.RepeaterFooter); service?.NccInvokeMethod(NccEventsEnum.PreRender.ToString(), new object[] { new NccEventArgs { NccTagContext = _nccTagContext, NccControlContext = Context, ViewContext = ViewContext } }); _nccTagContext.ControlContext = Context; output.PostContent.AppendHtml(NccControlsService.GetEncodedContext(_protector, Context.Id, Context)); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderOverlay()); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderImage()); }
//[ValidateAntiForgeryToken] public async Task <IActionResult> ControlAction(IFormCollection formCollection, string[] context, Dictionary <string, string> parameters) { var controlCtxs = new List <object>(); var viewResult = new List <string>(); foreach (var ctx in context) { try { if (context.Length == 0) { throw new Exception("An error as occured when processing the controls context. Please, verify that all target id's are correct."); } controlCtxs.Add(NccJsonService.GetObjectFromJson <object>(_protector.Unprotect(ctx))); } catch (Exception e) { viewResult.Add(NccEventService.ProcessError(e)); } } foreach (var controlCtx in controlCtxs) { var renderControl = true; try { if (controlCtx == null) { throw new Exception("The control context is invalid! Please, refresh the page to get a new valid context."); } //if (controlCtx.NccGetPropertyValue<string>("Error") != null) // continue; var parametersList = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); if (parameters != null && parameters.Count > 0) { parametersList = new Dictionary <string, string>(parameters, StringComparer.OrdinalIgnoreCase); } if (!parametersList.ContainsKey($"{DefaultParameters.ActionType.ToString().NccAddPrefix()}")) { throw new Exception("No action type was specified!"); } var eventHandler = controlCtx.NccGetPropertyValue <string>("EventHandlerClass"); var service = NccReflectionService.NccGetClassInstance(eventHandler, null); service?.NccInvokeMethod(NccEventsEnum.PostBack, new object[] { new NccEventArgs { Controller = this, NccControlContext = controlCtx, FormCollection = formCollection, Parameters = parametersList } }); switch (parametersList[$"{DefaultParameters.ActionType.ToString().NccAddPrefix()}"].ToLower()) { case "refresh": //Do nothing, just reload data just like it is! break; case "exportexcel": var gridContext = (NccGridContext)controlCtx; if (gridContext != null) { var excelPackage = GridService.GetExcelPackage(gridContext, HttpContext); var xlsxContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //Response.Headers.Add("Content-Disposition", "attachment; filename=\"Export.xlsx\""); return(File(excelPackage, xlsxContentType, "Export.xlsx")); } break; case "filter": if (!(parametersList.Keys.Any(k => k.StartsWith($"{DefaultParameters.ElemName.ToString().NccAddPrefix()}")) && parametersList.Keys.Any(k => k.StartsWith($"{DefaultParameters.ElemValue.ToString().NccAddPrefix()}")))) { throw new Exception("The filter doesn't contain the necessary name and value pair."); } var filters = controlCtx.NccGetPropertyValue <Dictionary <string, string> >("Filters") ?? new Dictionary <string, string>(); var resetPaging = true; foreach (var inputFilters in parametersList.Where(x => x.Key.StartsWith($"{DefaultParameters.ElemName.ToString().NccAddPrefix()}")).ToList()) { if (inputFilters.Value.Contains("pageNumber")) { resetPaging = false; } var filterId = inputFilters.Key.Replace($"{DefaultParameters.ElemName.ToString().NccAddPrefix()}", ""); filters[inputFilters.Value] = parametersList[$"{DefaultParameters.ElemValue.ToString().NccAddPrefix()}{filterId}"]; } if (resetPaging) { filters["pageNumber"] = "1"; } var additionalData = controlCtx.NccGetPropertyValue <Dictionary <string, object> >("AdditionalData"); additionalData.Remove("EditRowNumber"); controlCtx.NccSetPropertyValue("AdditionalData", additionalData); controlCtx.NccSetPropertyValue("Filters", filters); break; case "event": if (service == null) { throw new Exception("EventHandler must be registered and must exist to process events"); } NccEventService.ProcessEvent(service, this, controlCtx, formCollection, parametersList); break; //Events from Controls are mapped here case "gridaction": if (!parametersList.ContainsKey($"{DefaultParameters.EventName.ToString().NccAddPrefix()}")) { throw new Exception("No EventName specified for the GridView action!"); } if (!(controlCtx is NccGridContext)) { throw new Exception("A GridAction was specified but the context is not of type NccGridContext!"); } if (service == null) { service = NccReflectionService.NccGetClassInstance(typeof(NccGridEvents).AssemblyQualifiedName, null); } switch (parametersList[$"{DefaultParameters.EventName.ToString().NccAddPrefix()}"].ToLower()) { case "update": service.NccInvokeMethod(NccGridEventsEnum.Update.ToString(), new object[] { new NccEventArgs { Controller = this, NccControlContext = controlCtx, FormCollection = formCollection, Parameters = parametersList } }); break; case "updaterow": if (!parametersList.ContainsKey($"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}")) { throw new Exception("The row number wasn't received... Something wrong has happened..."); } var updateRowPos = Convert.ToInt32(parametersList[$"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}"]); service.NccInvokeMethod(NccGridEventsEnum.UpdateRow.ToString(), new object[] { new NccEventArgs { Controller = this, NccControlContext = controlCtx, FormCollection = formCollection, Parameters = parametersList }, updateRowPos }); break; case "editrow": if (!parametersList.ContainsKey($"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}")) { throw new Exception("The row number wasn't received... Something wrong has happened..."); } var editRowPos = Convert.ToInt32(parametersList[$"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}"]); var additionalData2 = controlCtx.NccGetPropertyValue <Dictionary <string, object> >("AdditionalData"); additionalData2["EditRowNumber"] = editRowPos; controlCtx.NccSetPropertyValue("AdditionalData", additionalData2); break; case "canceleditrow": if (!parametersList.ContainsKey($"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}")) { throw new Exception("The row number wasn't received... Something wrong has happened..."); } var additionalData3 = controlCtx.NccGetPropertyValue <Dictionary <string, object> >("AdditionalData"); additionalData3.Remove("EditRowNumber"); controlCtx.NccSetPropertyValue("AdditionalData", additionalData3); break; case "deleterow": if (!parametersList.ContainsKey($"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}")) { throw new Exception("The row number wasn't received... Something wrong has happened..."); } var deleteRowPos = Convert.ToInt32(parametersList[$"{NccGridParametersEnum.RowNumber.ToString().NccAddPrefix()}"]); service.NccInvokeMethod(NccGridEventsEnum.DeleteRow.ToString(), new object[] { new NccEventArgs { Controller = this, NccControlContext = controlCtx, FormCollection = formCollection, Parameters = parametersList }, deleteRowPos }); break; default: throw new Exception("The specified EventName it's not supported on the NccGrid Component!"); } break; case "linkaction": if (service == null) { service = NccReflectionService.NccGetClassInstance(typeof(NccSelectEvents).AssemblyQualifiedName, null); } if (!(parametersList.Keys.Any(k => k.StartsWith($"{DefaultParameters.ElemName.ToString().NccAddPrefix()}")) && parametersList.Keys.Any(k => k.StartsWith($"{DefaultParameters.ElemValue.ToString().NccAddPrefix()}")))) { throw new Exception("The submitted data doesn't contain the necessary name and value pair."); } var controlFilters = controlCtx.NccGetPropertyValue <Dictionary <string, string> >("Filters") ?? new Dictionary <string, string>(); var linkFilters = parametersList.FirstOrDefault(x => x.Key.StartsWith($"{DefaultParameters.ElemName.ToString().NccAddPrefix()}")); var filterName = linkFilters.Key.Replace($"{DefaultParameters.ElemName.ToString().NccAddPrefix()}", ""); if (linkFilters.Value != null) { controlFilters[linkFilters.Value] = parametersList[$"{DefaultParameters.ElemValue.ToString().NccAddPrefix()}{filterName}"]; } var submitElem = parametersList.FirstOrDefault(x => x.Key.StartsWith($"{DefaultParameters.ElemId.ToString().NccAddPrefix()}")); var value = formCollection["target_ids"].FirstOrDefault(); var targetIds = value.Split(','); var posCurrent = Array.IndexOf(targetIds, controlCtx.NccGetPropertyValue <string>("Id")); var posCaller = Array.IndexOf(targetIds, submitElem.Value); if (posCurrent - posCaller == 1) { controlCtx.NccSetPropertyValue("RenderDefault", false); } else if (posCurrent - posCaller > 1) { controlCtx.NccSetPropertyValue("RenderDefault", true); controlCtx.NccSetPropertyValue("SelectedValue", ""); } else { renderControl = false; } if (posCurrent == posCaller) { controlCtx.NccSetPropertyValue("SelectedValue", linkFilters.Value); } controlCtx.NccSetPropertyValue("Filters", controlFilters); break; default: throw new Exception("The specified ActionType it's not supported on the NetCoreControls!"); } var id = controlCtx.NccGetPropertyValue <string>("Id"); var controlViewPath = controlCtx.NccGetPropertyValue <ViewsPathsModel>("ViewPaths").ViewPath; ViewData[id] = controlCtx; if (renderControl) { viewResult.Add(await this.NccRenderToStringAsync(_razorViewEngine, controlViewPath, null)); } else { viewResult.Add(string.Empty); } } catch (Exception e) { var div = new TagBuilder("div"); var encContext = new TagBuilder("input"); var error = NccEventService.ProcessError(e); var id = controlCtx.NccGetPropertyValue <string>("Id"); if (!string.IsNullOrEmpty(id)) { div.Attributes["id"] = id; ViewData[id] = controlCtx; encContext.Attributes.Add("name", "encContext"); encContext.Attributes.Add("id", $"{id}_context"); encContext.Attributes.Add("type", "hidden"); encContext.Attributes.Add("value", _protector.Protect(NccJsonService.SetObjectAsJson(controlCtx))); } div.InnerHtml.AppendHtml(error); div.InnerHtml.AppendHtml(encContext); var writer = new StringWriter(); div.WriteTo(writer, HtmlEncoder.Default); viewResult.Add(writer.ToString()); } } return(Json(viewResult)); }
public virtual async void Update(NccEventArgs eventArgs) { var detailsContext = (NccDetailsContext)eventArgs.NccControlContext; if (detailsContext == null) { return; } var type = Type.GetType(detailsContext.DatabaseModelType); if (type == null) { throw new Exception("The DatabaseModelType was incorrectly set. Please correct it on the Grid context."); } dynamic model = Activator.CreateInstance(type); if (model == null) { throw new Exception("The DatabaseModelType specified could not be instantiated. Is it public?"); } var ok = await eventArgs.Controller.TryUpdateModelAsync(model, detailsContext.Id); if (!ok) { throw new Exception("Error binding model to object or list"); } ok = NccEventService.NccBindDataKeys(model, detailsContext.DataKeysValues, 0); if (!ok) { throw new Exception("DataKeys list is bigger than submited list. No match possible!!"); } if (model == null) { throw new Exception("It was not possible to bind the forms value to model."); } var options = NccReflectionService.NccGetClassInstanceWithDi(eventArgs.Controller.HttpContext, NccConstants.OptionsAssemblyName); var nccSettings = options != null ? ((IOptions <NccSettings>)options).Value : new NccSettings(); var dbService = nccSettings.UseDependencyInjection ? NccReflectionService.NccGetClassInstanceWithDi(eventArgs.Controller.HttpContext, detailsContext.DataAccessClass) : NccReflectionService.NccGetClassInstance(detailsContext.DataAccessClass, detailsContext.DataAccessParameters); if (dbService == null) { throw new Exception("Could not get an instance of DataAccessClass. Wrong assembly full name?"); } var updateParameters = detailsContext.UpdateParameters?.ToDictionary(x => x.Key, x => x.Value).NccToExpando() ?? new ExpandoObject() as IDictionary <string, object>; updateParameters["model"] = model; try { var result = dbService.NccInvokeMethod(detailsContext.UpdateMethod, (ExpandoObject)updateParameters); eventArgs.Controller.ViewBag.Message = "Updated successfully!"; eventArgs.Controller.ViewBag.MessageType = "success"; } catch (Exception) { eventArgs.Controller.ViewBag.Message = "An error occured!"; eventArgs.Controller.ViewBag.MessageType = "danger"; } }
public override async Task ProcessAsync(TagHelperContext tagContext, TagHelperOutput output) { if (Context == null) { throw new Exception("The NccSelectContext is null... Please check the reference."); } object service = null; if (!string.IsNullOrEmpty(Context.EventHandlerClass)) { service = NccReflectionService.NccGetClassInstance(Context.EventHandlerClass, null); } service?.NccInvokeMethod(NccEventsEnum.Load, new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext } }); if (string.IsNullOrEmpty(Context.Id)) { Context.Id = Guid.NewGuid().ToString(); } output.TagName = "select"; output.Attributes.SetAttribute("id", Context.Id); if (!string.IsNullOrEmpty(DataValue)) { Context.DataValue = DataValue; } if (string.IsNullOrEmpty(Context.DataValue)) { throw new Exception($"Please set the DataValue property on NccSelect with id {Context.Id}."); } if (!string.IsNullOrEmpty(TextValue)) { Context.TextValue = TextValue; } if (string.IsNullOrEmpty(Context.TextValue)) { throw new Exception($"Please set the TextValue property on NccSelect with id {Context.Id}."); } if (!string.IsNullOrEmpty(FirstItem)) { Context.FirstItem = FirstItem; } if (Context.Visible) { NccActionsService.ExtraParameters <NccSelectContext> setExtraParameters = SelectService.GetExtraParameters; NccActionsService.DataResult <NccSelectContext> setDataResult = SelectService.SetDataResult; NccControlsService.BindData(Context, ViewContext.HttpContext, setExtraParameters, setDataResult); output.Content.AppendHtml(await output.GetChildContentAsync()); if (!string.IsNullOrEmpty(Context.FirstItem)) { var select = new TagBuilder("option") { Attributes = { { "value", "" } } }; select.InnerHtml.SetContent(Context.FirstItem); service?.NccInvokeMethod(NccSelectEventsEnum.OptionBound.ToString(), new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext, DataObjects = Context.DataObjects } }); output.Content.AppendHtml(select); } //var data = Context.DataObjects.GetType().ToString().Contains("Microsoft.EntityFrameworkCore.Internal.InternalDbSet") || // Context.DataObjects.GetType().ToString().Contains("Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable") ? // ((IQueryable<object>)Context.DataObjects).ToList() : Context.DataObjects as IList; var data = Context.DataObjects as IList; if (data?.Count > 0) { foreach (var elem in data) { var val = elem.NccGetPropertyValue <string>(Context.DataValue); var txt = elem.NccGetPropertyValue <string>(Context.TextValue); var select = new TagBuilder("option") { Attributes = { { "value", val } } }; select.InnerHtml.Append(txt); if (val == SelectedValue) { select.Attributes.Add("selected", "selected"); } service?.NccInvokeMethod(NccSelectEventsEnum.OptionBound.ToString(), new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext, DataObjects = Context.DataObjects } }); output.Content.AppendHtml(select); } } else { output.Attributes.Add("disabled", "disabled"); } service?.NccInvokeMethod(NccEventsEnum.PreRender, new object[] { new NccEventArgs { NccControlContext = Context, ViewContext = ViewContext } }); output.PostContent.AppendHtml(NccControlsService.GetEncodedContext(_protector, Context.Id, Context)); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderOverlay()); output.PostContent.AppendHtml(NccControlsService.GetAjaxLoaderImage()); var divContainer = new TagBuilder("div") { Attributes = { { "id", Context.Id }, { "style", "position:relative" } }, TagRenderMode = TagRenderMode.StartTag }; output.PreElement.AppendHtml(divContainer); var endDivContainer = new TagBuilder("div") { TagRenderMode = TagRenderMode.EndTag }; output.PostElement.AppendHtml(endDivContainer); } }