public PcFieldBaseOptions InitPcFieldBaseOptions(PageComponentContext context)
        {
            var options = new PcFieldBaseOptions();

            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(LabelRenderMode)))
            {
                options.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
            }
            else
            {
                options.LabelMode = LabelRenderMode.Stacked;
            }


            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(FieldRenderMode)))
            {
                options.Mode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
            }
            else
            {
                options.Mode = FieldRenderMode.Form;
            }

            return(options);
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcGridFilterFieldOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcGridFilterFieldOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                var selectedQueryOptionsConverted = new List <string>();
                foreach (var option in options.QueryOptions)
                {
                    selectedQueryOptionsConverted.Add(((int)option).ToString());
                }
                ViewBag.ConvertedSelectedQueryOptions = selectedQueryOptionsConverted;

                if (context.Mode == ComponentMode.Options)
                {
                    ViewBag.FieldTypeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldType>();
                    var filterOptions = ModelExtensions.GetEnumAsSelectOptions <FilterType>();
                    var idField       = filterOptions.Single(x => x.Value == ((int)FilterType.Undefined).ToString());
                    filterOptions.Remove(idField);
                    ViewBag.FilterTypeOptions = filterOptions;
                }

                ViewBag.ValueOptions = new List <SelectOption>();
                var entity = context.DataModel.GetProperty("Entity");
                if (options.TryConnectToEntity)
                {
                    var fieldName   = options.Name;
                    var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    if (entityField != null)
                    {
                        //Connection success override the local options
                        //Init model
                        if (String.IsNullOrWhiteSpace(options.Label))
                        {
                            options.Label = entityField.Label;
                        }

                        //Specific model properties
                        var fieldOptions = new List <SelectOption>();
                        switch (entityField.GetFieldType())
                        {
                        case FieldType.AutoNumberField:
                            options.FieldType = FieldType.AutoNumberField;
                            break;

                        case FieldType.CheckboxField:
                            options.FieldType = FieldType.CheckboxField;
                            break;

                        case FieldType.CurrencyField:
                            options.FieldType = FieldType.CurrencyField;
                            break;

                        case FieldType.DateField:
                            options.FieldType = FieldType.DateField;
                            break;

                        case FieldType.DateTimeField:
                            options.FieldType = FieldType.DateTimeField;
                            break;

                        case FieldType.EmailField:
                            options.FieldType = FieldType.EmailField;
                            break;

                        case FieldType.FileField:
                            options.FieldType = FieldType.FileField;
                            break;

                        case FieldType.GuidField:
                            options.FieldType = FieldType.GuidField;
                            break;

                        case FieldType.HtmlField:
                            options.FieldType = FieldType.HtmlField;
                            break;

                        case FieldType.ImageField:
                            options.FieldType = FieldType.ImageField;
                            break;

                        case FieldType.MultiLineTextField:
                            options.FieldType = FieldType.MultiLineTextField;
                            break;

                        case FieldType.NumberField:
                            options.FieldType = FieldType.NumberField;
                            break;

                        case FieldType.PercentField:
                            options.FieldType = FieldType.PercentField;
                            break;

                        case FieldType.PhoneField:
                            options.FieldType = FieldType.PhoneField;
                            break;

                        case FieldType.SelectField:
                            options.FieldType = FieldType.SelectField;
                            var selectField = ((SelectField)entityField);
                            ViewBag.ValueOptions = selectField.Options;
                            break;

                        case FieldType.MultiSelectField:
                            options.FieldType = FieldType.MultiSelectField;
                            break;

                        case FieldType.TextField:
                            options.FieldType = FieldType.TextField;
                            break;

                        case FieldType.UrlField:
                            options.FieldType = FieldType.UrlField;
                            break;

                        default:
                            throw new Exception("No such field Type");
                        }
                    }
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #3
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcChartOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcChartOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                var theme            = new Theme();
                var colorOptionsList = new List <string>()
                {
                    theme.TealColor, theme.PinkColor, theme.GreenColor, theme.OrangeColor, theme.RedColor, theme.PurpleColor, theme.DeepPurpleColor,
                    theme.BlueColor, theme.LightBlueColor, theme.CyanColor, theme.GreenColor, theme.IndigoColor, theme.LightGreenColor, theme.LimeColor, theme.YellowColor,
                    theme.AmberColor, theme.DeepOrangeColor
                };

                var bkgColorOptionsList = new List <string>()
                {
                    theme.TealLightColor, theme.PinkLightColor, theme.GreenLightColor, theme.OrangeLightColor, theme.RedLightColor, theme.PurpleLightColor, theme.DeepPurpleLightColor,
                    theme.BlueLightColor, theme.LightBlueLightColor, theme.CyanLightColor, theme.GreenLightColor, theme.IndigoLightColor, theme.LightGreenLightColor, theme.LimeLightColor, theme.YellowLightColor,
                    theme.AmberLightColor, theme.DeepOrangeLightColor
                };

                List <ErpChartDataset> dataSets = context.DataModel.GetPropertyValueByDataSource(options.Datasets) as List <ErpChartDataset> ?? new List <ErpChartDataset>();

                if (dataSets == null || dataSets.Count == 0)
                {
                    var decimalList = new List <decimal>();
                    decimalList = context.DataModel.GetPropertyValueByDataSource(options.Datasets) as List <decimal> ?? new List <decimal>();
                    if ((dataSets == null || dataSets.Count == 0) && !String.IsNullOrWhiteSpace(options.Datasets) && options.Datasets.Contains(","))
                    {
                        var optionValueCsv   = options.Datasets.Split(",");
                        var csvDecimalList   = new List <decimal>();
                        var csvParseHasError = false;
                        foreach (var valueString in optionValueCsv)
                        {
                            if (Decimal.TryParse(valueString.Trim(), out decimal outDecimal))
                            {
                                csvDecimalList.Add(outDecimal);
                            }
                            else
                            {
                                csvParseHasError = true;
                                break;
                            }
                        }
                        if (!csvParseHasError)
                        {
                            decimalList = csvDecimalList;
                        }
                    }

                    if (decimalList != null && decimalList.Count > 0)
                    {
                        var dataSet = new ErpChartDataset();
                        dataSet.Data = decimalList;
                        if (options.Type == ErpChartType.Area || options.Type == ErpChartType.Line)
                        {
                            dataSet.BorderColor     = colorOptionsList[0];
                            dataSet.BackgroundColor = bkgColorOptionsList[0];
                        }
                        else
                        {
                            dataSet.BorderColor     = new List <string>();
                            dataSet.BackgroundColor = new List <string>();
                            var index = 0;
                            foreach (var value in decimalList)
                            {
                                ((List <string>)dataSet.BorderColor).Add(colorOptionsList[index]);
                                if (options.Type == ErpChartType.Bar || options.Type == ErpChartType.HorizontalBar)
                                {
                                    ((List <string>)dataSet.BackgroundColor).Add(bkgColorOptionsList[index]);
                                }
                                else
                                {
                                    ((List <string>)dataSet.BackgroundColor).Add(colorOptionsList[index]);
                                }
                                index++;
                            }
                        }
                        dataSets.Add(dataSet);
                    }
                }

                List <string> labels = context.DataModel.GetPropertyValueByDataSource(options.Labels) as List <string> ?? new List <string>();
                if ((labels == null || labels.Count == 0) && !String.IsNullOrWhiteSpace(options.Labels) && options.Labels.Contains(","))
                {
                    labels = options.Labels.Split(",").ToList();
                }

                ViewBag.DataSets = dataSets;
                ViewBag.Labels   = labels;
                var chartTypeOptions = ModelExtensions.GetEnumAsSelectOptions <ErpChartType>();
                chartTypeOptions.First(x => x.Value == "4").Label = "area";
                ViewBag.ChartTypeOptions = chartTypeOptions;
                ViewBag.ShowLegend       = options.ShowLegend;
                ViewBag.Height           = options.Height;
                ViewBag.Width            = options.Width;
                ViewBag.Type             = (ErpChartType)options.Type;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #4
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var instanceOptions = new PcSectionOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcSectionOptions>(context.Options.ToString());
                }

                //Check if it is defined in form group
                if (instanceOptions.LabelMode == LabelRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(LabelRenderMode)))
                    {
                        instanceOptions.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
                    }
                    else
                    {
                        instanceOptions.LabelMode = LabelRenderMode.Stacked;
                    }
                }

                //Check if it is defined in form group
                if (instanceOptions.FieldMode == FieldRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(FieldRenderMode)))
                    {
                        instanceOptions.FieldMode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
                    }
                    else
                    {
                        instanceOptions.FieldMode = FieldRenderMode.Form;
                    }
                }
                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options            = instanceOptions;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                if (context.Mode == ComponentMode.Display || context.Mode == ComponentMode.Design)
                {
                    ViewBag.ProcessedTitle = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Title);
                }

                context.Items[typeof(LabelRenderMode)] = instanceOptions.LabelMode;
                context.Items[typeof(FieldRenderMode)] = instanceOptions.FieldMode;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    ViewBag.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();
                    ViewBag.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #5
0
        public PcFieldBaseOptions InitPcFieldBaseOptions(PageComponentContext context)
        {
            var options = new PcFieldBaseOptions();

            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(LabelRenderMode)))
            {
                options.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
            }
            else
            {
                options.LabelMode = LabelRenderMode.Stacked;
            }


            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(FieldRenderMode)))
            {
                options.Mode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
            }
            else
            {
                options.Mode = FieldRenderMode.Form;
            }

            var baseOptions = JsonConvert.DeserializeObject <PcFieldBaseOptions>(context.Options.ToString());

            Entity mappedEntity = null;
            var    entity       = context.DataModel.GetProperty("Entity");

            if (options.ConnectedEntityId != null)
            {
                mappedEntity = new EntityManager().ReadEntity(options.ConnectedEntityId.Value).Object;
            }
            else if (options.ConnectedEntityId == null && entity is Entity)
            {
                mappedEntity = (Entity)entity;
            }

            if (mappedEntity != null)
            {
                var fieldName = baseOptions.Name;

                EntityRelation relation = null;
                if (fieldName.StartsWith("$"))
                {
                    //Field with relation is set. Mapped entity should be changed
                    var fieldNameArray = fieldName.Replace("$", "").Split(".", StringSplitOptions.RemoveEmptyEntries);
                    if (fieldNameArray.Length == 2)
                    {
                        var relationName = fieldNameArray[0];
                        fieldName = fieldNameArray[1];
                        relation  = new EntityRelationManager().Read(relationName).Object;
                        if (relation != null)
                        {
                            if (relation.OriginEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.TargetEntityId).Object;
                            }
                            else if (relation.TargetEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.OriginEntityId).Object;
                            }
                        }
                    }
                }

                var entityField = mappedEntity.Fields.FirstOrDefault(x => x.Name == fieldName);

                //for many to many relation field is always ID and that is not correct
                //so hide this field meta as field is not found
                if (relation != null && relation.RelationType == EntityRelationType.ManyToMany)
                {
                    entityField = null;
                }

                if (entityField != null)
                {
                    switch (entityField.GetFieldType())
                    {
                    case FieldType.AutoNumberField:
                    {
                        var fieldMeta = (AutoNumberField)entityField;
                        options.Template = fieldMeta.DisplayFormat;
                    }
                    break;

                    case FieldType.CurrencyField:
                    {
                        var fieldMeta = (CurrencyField)entityField;
                        options.Min          = fieldMeta.MinValue;
                        options.Min          = fieldMeta.MinValue;
                        options.CurrencyCode = fieldMeta.Currency.Code;
                    }
                    break;

                    case FieldType.EmailField:
                    {
                        var fieldMeta = (EmailField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.NumberField:
                    {
                        var fieldMeta = (NumberField)entityField;
                        options.Min = fieldMeta.MinValue;
                        options.Min = fieldMeta.MinValue;
                        if (fieldMeta.DecimalPlaces != null)
                        {
                            if (int.TryParse(fieldMeta.DecimalPlaces.ToString(), out int outInt))
                            {
                                options.DecimalDigits = outInt;
                            }
                        }
                    }
                    break;

                    case FieldType.PasswordField:
                    {
                        var fieldMeta = (PasswordField)entityField;
                        options.Min = (decimal?)fieldMeta.MinLength;
                        options.Max = (decimal?)fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.PercentField:
                    {
                        var fieldMeta = (PercentField)entityField;
                        options.Min = fieldMeta.MinValue;
                        options.Min = fieldMeta.MinValue;
                        if (fieldMeta.DecimalPlaces != null)
                        {
                            if (int.TryParse(fieldMeta.DecimalPlaces.ToString(), out int outInt))
                            {
                                options.DecimalDigits = outInt;
                            }
                        }
                    }
                    break;

                    case FieldType.PhoneField:
                    {
                        var fieldMeta = (PhoneField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.TextField:
                    {
                        var fieldMeta = (TextField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    default:
                        break;
                    }
                }
            }

            return(options);
        }
Exemple #6
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var instanceOptions = new PcButtonOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcButtonOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options        = instanceOptions;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    instanceOptions.Text      = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Text) as string;
                    instanceOptions.Class     = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Class) as string;
                    instanceOptions.IconClass = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IconClass) as string;

                    ViewBag.ProcessedHref = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Href);
                }
                #region << Select options >>
                ViewBag.CssSize = ModelExtensions.GetEnumAsSelectOptions <CssSize>();

                ViewBag.ColorOptions = ModelExtensions.GetEnumAsSelectOptions <ErpColor>().OrderBy(x => x.Label).ToList();

                ViewBag.TypeOptions = ModelExtensions.GetEnumAsSelectOptions <ButtonType>();

                #endregion
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcPageHeaderOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcPageHeaderOptions>(context.Options.ToString());
                }
                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = instanceOptions;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.InstanceOptions  = instanceOptions;
                ViewBag.ComponentContext = context;



                ViewBag.ProccessedTitle        = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Title);
                ViewBag.ProccessedSubTitle     = context.DataModel.GetPropertyValueByDataSource(instanceOptions.SubTitle);
                ViewBag.ProccessedAreaLabel    = context.DataModel.GetPropertyValueByDataSource(instanceOptions.AreaLabel);
                ViewBag.ProccessedAreaSubLabel = context.DataModel.GetPropertyValueByDataSource(instanceOptions.AreaSubLabel);
                ViewBag.ProccessedDescription  = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Description);
                ViewBag.ProccessedColor        = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Color);
                ViewBag.ProccessedIconColor    = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IconColor);
                ViewBag.ProccessedIconClass    = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IconClass);

                if (!String.IsNullOrWhiteSpace(instanceOptions.ReturnUrl))
                {
                    ViewBag.ProccessedReturnUrl = context.DataModel.GetPropertyValueByDataSource(instanceOptions.ReturnUrl);
                }

                else if (ErpRequestContext != null && ErpRequestContext.PageContext != null && ErpRequestContext.PageContext.HttpContext.Request.Query.ContainsKey("returnUrl") &&
                         !String.IsNullOrWhiteSpace(ErpRequestContext.PageContext.HttpContext.Request.Query["returnUrl"]))
                {
                    ViewBag.ProccessedReturnUrl = ErpRequestContext.PageContext.HttpContext.Request.Query["returnUrl"].ToString();
                }

                var switchItemPages    = new List <ErpPage>();
                var currentSitemapArea = ErpRequestContext.SitemapArea;
                var currentSitemapNode = ErpRequestContext.SitemapNode;
                var currentApp         = ErpRequestContext.App;
                if (instanceOptions.ShowPageSwitch && currentPage != null && currentPage.Type == PageType.Site)
                {
                    var allPages = new PageService().GetAll();
                    switchItemPages = allPages.FindAll(x => x.Type == currentPage.Type).ToList();
                }
                else if (instanceOptions.ShowPageSwitch && currentPage != null && currentPage.AppId != null && currentPage.Type == PageType.Application)
                {
                    var allPages = new PageService().GetAll();
                    switchItemPages = allPages.FindAll(x => x.Type == currentPage.Type && x.AppId == currentApp.Id && x.NodeId == currentPage.NodeId).ToList();
                }
                if (instanceOptions.ShowPageSwitch && currentPage != null && currentSitemapNode != null)
                {
                    var allPages      = new PageService().GetAll();
                    var sameTypePages = allPages.FindAll(x => x.Type == currentPage.Type).ToList();
                    foreach (var page in sameTypePages)
                    {
                        if (page.NodeId == context.Node.Id)
                        {
                            switchItemPages.Add(page);
                        }
                        else if (currentSitemapNode.Type == SitemapNodeType.EntityList && page.EntityId == currentSitemapNode.EntityId)
                        {
                            switchItemPages.Add(page);
                        }
                    }
                }

                switchItemPages = switchItemPages.OrderBy(x => x.Weight).ToList();

                var switchItems        = new List <PageSwitchItem>();
                var currentEntity      = ErpRequestContext.Entity;
                var parentEntity       = ErpRequestContext.ParentEntity;
                var currentUrlTemplate = "/";
                //Site pages
                if (currentPage.Type == PageType.Site)
                {
                    currentUrlTemplate = $"/s/[[pageName]]";
                }
                //App pages without nodes
                else if (currentApp != null && currentSitemapNode == null)
                {
                    currentUrlTemplate = $"/{currentApp.Name}/a/[[pageName]]";
                }
                //App pages with sitemap node
                else if (currentApp != null && currentSitemapArea != null && currentSitemapNode != null)
                {
                    //App pages
                    if (currentPage.Type == PageType.Application)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/a/[[pageName]]";
                    }
                    //Record create page, No relation
                    else if (currentPage.Type == PageType.RecordCreate && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/c/[[pageName]]";
                    }
                    //Record create page, With relation
                    else if (currentPage.Type == PageType.RecordCreate && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/c/[[pageName]]";
                    }
                    //Record manage page, No relation
                    else if (currentPage.Type == PageType.RecordManage && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/m/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record manage page, With relation
                    else if (currentPage.Type == PageType.RecordManage && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/m/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record details page, No relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record details page, With relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/r/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record list page, No relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/l/[[pageName]]";
                    }
                    //Record list page, With relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/l/[[pageName]]";
                    }
                }

                foreach (var switchPage in switchItemPages)
                {
                    var isSelected = false;
                    if (currentPage != null && switchPage.Id == currentPage.Id)
                    {
                        isSelected = true;
                    }
                    switchItems.Add(new PageSwitchItem()
                    {
                        IsSelected = isSelected,
                        Label      = switchPage.Label,
                        Url        = currentUrlTemplate.Replace("[[pageName]]", switchPage.Name)
                    });
                }

                ViewBag.PageSwitchItems = switchItems;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query parameter 'pid', when requesting this component")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldDataCsvOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldDataCsvOptions>(context.Options.ToString());
                }

                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }

                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
                if (requiredOverride != null)
                {
                    model.Required = requiredOverride.Value;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs))
                    {
                        if (options.RequiredOverrideDs.ToLowerInvariant() == "true")
                        {
                            model.Required = true;
                        }
                        else if (options.RequiredOverrideDs.ToLowerInvariant() == "false")
                        {
                            model.Required = false;
                        }
                    }
                }
                #endregion

                ViewBag.Options            = options;
                ViewBag.Model              = model;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);

                    var delimiter = context.DataModel.GetPropertyValueByDataSource(options.DelimiterValueDs) as string;
                    var lang      = context.DataModel.GetPropertyValueByDataSource(options.LangDs) as string;
                    var hasHeader = context.DataModel.GetPropertyValueByDataSource(options.HasHeaderValueDs) as bool?;

                    ViewBag.Delimiter = ErpDataCsvDelimiterType.COMMA;
                    if (!String.IsNullOrWhiteSpace(delimiter) && delimiter == "tab")
                    {
                        ViewBag.Delimiter = ErpDataCsvDelimiterType.TAB;
                    }
                    ViewBag.Lang = "en";
                    if (!String.IsNullOrWhiteSpace(lang))
                    {
                        ViewBag.Lang = lang;
                    }
                    ViewBag.HasHeader = true;
                    if (hasHeader != null)
                    {
                        ViewBag.HasHeader = hasHeader;
                    }
                }



                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #9
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcRepeaterOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcRepeaterOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    if (!isVisible && context.Mode == ComponentMode.Display)
                    {
                        return(await Task.FromResult <IViewComponentResult>(Content("")));
                    }

                    ViewBag.Records = context.DataModel.GetPropertyValueByDataSource(options.Records) as List <EntityRecord> ?? new List <EntityRecord>();
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #10
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcFeedListOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFeedListOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.CurrentUser      = SecurityContext.CurrentUser;
                ViewBag.CurrentUserJson  = JsonConvert.SerializeObject(SecurityContext.CurrentUser);

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var inputRecords    = context.DataModel.GetPropertyValueByDataSource(options.Records) as List <EntityRecord> ?? new List <EntityRecord>();
                    var groupedRecords  = inputRecords.GroupBy(x => ((DateTime)x["created_on"]).ToString("dd MMMM")).ToList();
                    var groupedFeedList = new EntityRecord();
                    foreach (var feedDate in groupedRecords)
                    {
                        groupedFeedList[feedDate.Key] = feedDate;
                    }
                    ViewBag.RecordsJson = JsonConvert.SerializeObject(groupedFeedList);
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldCheckboxOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldCheckboxOptions>(context.Options.ToString());
                    ////Check for connection to entity field
                    //if (instanceOptions.TryConnectToEntity)
                    //{
                    //	var entity = context.DataModel.GetProperty("Entity");
                    //	if (entity != null && entity is Entity)
                    //	{
                    //		var fieldName = instanceOptions.Name;
                    //		var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    //		if (entityField != null && entityField is CheckboxField)
                    //		{
                    //			var castedEntityField = ((CheckboxField)entityField);
                    //			//No options connected
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as FieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                #endregion



                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    #region << Init DataSources >>
                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(options.Value);
                    if (valueResult == null)
                    {
                        model.Value = false;
                    }
                    else if (valueResult is bool)
                    {
                        model.Value = (bool)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = false;
                            stringProcessed = true;
                        }
                        if (!stringProcessed && ((string)valueResult) == "true")
                        {
                            model.Value = true;
                        }
                        else
                        {
                            model.Value = false;
                        }
                    }
                    #endregion
                }


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #12
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcFormOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcFormOptions>(context.Options.ToString());
                    if (instanceOptions.LabelMode == LabelRenderMode.Undefined)
                    {
                        instanceOptions.LabelMode = LabelRenderMode.Stacked;
                    }
                    if (instanceOptions.Mode == FieldRenderMode.Undefined)
                    {
                        instanceOptions.Mode = FieldRenderMode.Form;
                    }
                }

                if (String.IsNullOrWhiteSpace(instanceOptions.Id))
                {
                    instanceOptions.Id = "wv-" + context.Node.Id.ToString();
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                var isVisible   = true;
                var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IsVisible);
                if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                {
                    if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                    {
                        isVisible = outBool;
                    }
                }
                else if (isVisibleDS is Boolean)
                {
                    isVisible = (bool)isVisibleDS;
                }
                ViewBag.IsVisible = isVisible;

                ViewBag.Options            = instanceOptions;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                ViewBag.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();

                ViewBag.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();


                context.Items[typeof(LabelRenderMode)] = instanceOptions.LabelMode;
                context.Items[typeof(FieldRenderMode)] = instanceOptions.Mode;

                var validation = context.DataModel.GetProperty("Validation") as ValidationException ?? new ValidationException();

                context.Items[typeof(ValidationException)] = validation;
                ViewBag.Validation = validation;

                ViewBag.Action = "";
                if (!String.IsNullOrWhiteSpace(instanceOptions.HookKey))
                {
                    var queryList = new List <SelectOption>();
                    foreach (var key in HttpContext.Request.Query.Keys)
                    {
                        if (key != "hookKey")
                        {
                            queryList.Add(new SelectOption(key, HttpContext.Request.Query[key].ToString()));
                        }
                    }
                    queryList.Add(new SelectOption("hookKey", instanceOptions.HookKey));                    //override even if already present

                    ViewBag.Action = string.Format(HttpContext.Request.Path + "?{0}", string.Join("&", queryList.Select(kvp => string.Format("{0}={1}", kvp.Value, kvp.Label))));
                }

                ViewBag.MethodOptions = new List <SelectOption>()
                {
                    new SelectOption("get", "get"),
                    new SelectOption("post", "post")
                };


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcTimelogListOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcTimelogListOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.CurrentUser      = SecurityContext.CurrentUser;
                ViewBag.CurrentUserJson  = JsonConvert.SerializeObject(SecurityContext.CurrentUser);

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var relatedRecordId = (Guid?)context.DataModel.GetProperty("Record.id");
                    if (relatedRecordId == null)
                    {
                        throw new Exception("Record.id detasource returns null");
                    }

                    var entityName     = (string)context.DataModel.GetProperty("Entity.Name");
                    var relatedRecords = new List <Guid>();
                    relatedRecords.Add(relatedRecordId.Value);
                    switch (entityName)
                    {
                    case "task":
                    {
                        var eqlCommand = "SELECT $project_nn_task.id FROM task WHERE id = @recordId";
                        var eqlParams  = new List <EqlParameter>()
                        {
                            new EqlParameter("recordId", relatedRecordId)
                        };
                        var eqlResult = new EqlCommand(eqlCommand, eqlParams).Execute();
                        if (eqlResult.Any())
                        {
                            var taskRecord = eqlResult[0];
                            if (taskRecord.Properties.ContainsKey("$project_nn_task") && taskRecord["$project_nn_task"] != null)
                            {
                                if (((List <EntityRecord>)taskRecord["$project_nn_task"]).Any())
                                {
                                    var projectRecord = ((List <EntityRecord>)taskRecord["$project_nn_task"])[0];
                                    if (projectRecord.Properties.ContainsKey("id") && projectRecord["id"] != null)
                                    {
                                        relatedRecords.Add((Guid)projectRecord["id"]);
                                    }
                                }
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }

                    ViewBag.RelatedRecordId    = relatedRecordId;
                    ViewBag.RelatedRecordsJson = JsonConvert.SerializeObject(relatedRecords);

                    var inputRecords = context.DataModel.GetPropertyValueByDataSource(options.Records) as List <EntityRecord> ?? new List <EntityRecord>();
                    ViewBag.RecordsJson = JsonConvert.SerializeObject(inputRecords);
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTimesheetOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTimesheetOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;
                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;

                    var             nowDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, DateTimeKind.Local);
                    List <DateTime> last7Days = Enumerable.Range(0, 7).Select(i => nowDate.AddDays(-6).Date.AddDays(i)).ToList();
                    var             startDate = new DateTime(last7Days[0].Year, last7Days[0].Month, last7Days[0].Day, 0, 0, 0, DateTimeKind.Local);
                    var             endDate   = nowDate.AddDays(1);       //Get End of current date

                    var projectTimelogs = new TimeLogService().GetTimelogsForPeriod(projectId, userId, startDate, endDate);

                    var users = new UserService().GetAll();

                    #region << Generate Grid Columns >>
                    var gridColumns = new List <GridColumn>()
                    {
                        new GridColumn()
                    };
                    foreach (var date in last7Days)
                    {
                        gridColumns.Add(new GridColumn()
                        {
                            Label = date.ToString("dd MMM"),
                            Width = "10%",
                            Class = "text-right"
                        });
                    }
                    gridColumns.Add(new GridColumn()
                    {
                        Label = "Total",
                        Width = "10%",
                        Class = "font-weight-bold text-right"
                    });
                    ViewBag.GridColumns = gridColumns;
                    #endregion

                    var records = new List <EntityRecord>();                    //id and other fields
                    #region << Init Rows >>
                    {
                        var billableRow = new EntityRecord();
                        billableRow["id"]    = "billable";
                        billableRow["label"] = "Billable";
                        billableRow["total"] = (decimal)0;
                        records.Add(billableRow);
                        var nonbillableRow = new EntityRecord();
                        nonbillableRow["id"]    = "nonbillable";
                        nonbillableRow["label"] = "Non-Billable";
                        nonbillableRow["total"] = (decimal)0;
                        records.Add(nonbillableRow);
                        var totalRow = new EntityRecord();
                        totalRow["id"]    = "total";
                        totalRow["label"] = "Total";
                        totalRow["total"] = (decimal)0;
                        records.Add(totalRow);
                    }
                    #endregion

                    var timelogsGroupByDate = projectTimelogs.GroupBy(x => (((DateTime?)x["logged_on"]).ConvertToAppDate() ?? DateTime.Now).ToString("dd-MM")).ToList();

                    for (int i = 0; i < 7; i++)
                    {
                        var billableRow    = records.First(x => (string)x["id"] == "billable");
                        var nonbillableRow = records.First(x => (string)x["id"] == "nonbillable");
                        var totalRow       = records.First(x => (string)x["id"] == "total");

                        billableRow.Properties.Add("day" + (i + 1), (decimal)0);
                        nonbillableRow.Properties.Add("day" + (i + 1), (decimal)0);
                        totalRow.Properties.Add("day" + (i + 1), (decimal)0);

                        var dateString   = last7Days[i].ToString("dd-MM");
                        var dateLogGroup = timelogsGroupByDate.FirstOrDefault(x => x.Key == dateString);
                        if (dateLogGroup != null)
                        {
                            var dateLogs = dateLogGroup.ToList();
                            foreach (var timelog in dateLogs)
                            {
                                totalRow["day" + (i + 1)] = (decimal)totalRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                if ((bool)timelog["is_billable"])
                                {
                                    billableRow["day" + (i + 1)] = (decimal)billableRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                    billableRow["total"]         = (decimal)billableRow["total"] + (decimal)timelog["minutes"];
                                }
                                else
                                {
                                    nonbillableRow["day" + (i + 1)] = (decimal)nonbillableRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                    nonbillableRow["total"]         = (decimal)nonbillableRow["total"] + (decimal)timelog["minutes"];
                                }
                                totalRow["total"] = (decimal)totalRow["total"] + (decimal)timelog["minutes"];
                            }
                        }
                    }

                    if (userId == null)
                    {
                        var timelogsGroupByCreator = projectTimelogs.GroupBy(x => (Guid)x["created_by"]).ToList();
                        foreach (var userGroup in timelogsGroupByCreator)
                        {
                            var user      = users.First(x => (Guid)x["id"] == userGroup.Key);
                            var imagePath = "/assets/avatar.png";
                            if (user["image"] != null && (string)user["image"] != "")
                            {
                                imagePath = "/fs" + (string)user["image"];
                            }

                            var userTimelogs            = userGroup.ToList();
                            var userTimelogsGroupByDate = userTimelogs.GroupBy(x => (((DateTime?)x["logged_on"]).ConvertToAppDate() ?? DateTime.Now).ToString("dd-MM")).ToList();
                            var userRow = new EntityRecord();
                            userRow["id"]    = (string)user["username"];
                            userRow["label"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                            userRow["total"] = (decimal)0;

                            for (int i = 0; i < 7; i++)
                            {
                                userRow.Properties.Add("day" + (i + 1), (decimal)0);
                                var dateString   = last7Days[i].ToString("dd-MM");
                                var dateLogGroup = userTimelogsGroupByDate.FirstOrDefault(x => x.Key == dateString);
                                if (dateLogGroup != null)
                                {
                                    var dateLogs = dateLogGroup.ToList();
                                    foreach (var timelog in dateLogs)
                                    {
                                        userRow["day" + (i + 1)] = (decimal)userRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                        userRow["total"]         = (decimal)userRow["total"] + (decimal)timelog["minutes"];
                                    }
                                }
                            }
                            records.Add(userRow);
                        }
                    }
                    ViewBag.Records = records;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #15
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTasksDueTodayOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksDueTodayOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid? ?? Guid.Empty;

                    if (projectId == Guid.Empty)
                    {
                        return(await Task.FromResult <IViewComponentResult>(Content("Error: ProjectId is required")));
                    }

                    var projectRecord = new ProjectService().Get(projectId);
                    var projectTasks  = new TaskService().GetTasks(projectId, null);

                    var overdueTasks = new List <EntityRecord>();
                    var users        = new UserService().GetAll();

                    foreach (var task in projectTasks)
                    {
                        var targetDate = (DateTime?)task["target_date"];

                        if (targetDate != null)
                        {
                            var erpTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ErpSettings.TimeZoneName);
                            targetDate = TimeZoneInfo.ConvertTimeFromUtc(targetDate.Value, erpTimeZone);
                            if (targetDate.Value.Date == DateTime.Now.Date)
                            {
                                var user      = users.First(x => (Guid)x["id"] == (Guid)task["owner_id"]);
                                var imagePath = "/assets/avatar.png";
                                if (user["image"] != null && (string)user["image"] != "")
                                {
                                    imagePath = "/fs" + (string)user["image"];
                                }

                                string iconClass = "";
                                string color     = "";
                                new TaskService().GetTaskIconAndColor((string)task["priority"], out iconClass, out color);

                                var row = new EntityRecord();
                                row["task"] = $"<i class='{iconClass}' style='color:{color}'></i> <a target=\"_blank\" href=\"/projects/tasks/tasks/r/{(Guid)task["id"]}/details\">[{task["key"]}] {task["subject"]}</a>";
                                row["user"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                                row["date"] = targetDate;
                                overdueTasks.Add(row);
                            }
                        }
                    }
                    ViewBag.Records = overdueTasks;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldMultiSelectOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldMultiSelectOptions>(context.Options.ToString());
                }
                var modelFieldLabel = "";
                var model           = (PcFieldMultiSelectModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldMultiSelectModel");
                if (String.IsNullOrWhiteSpace(options.LabelText) && context.Mode != ComponentMode.Options)
                {
                    options.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
                if (requiredOverride != null)
                {
                    model.Required = requiredOverride.Value;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs))
                    {
                        if (options.RequiredOverrideDs.ToLowerInvariant() == "true")
                        {
                            model.Required = true;
                        }
                        else if (options.RequiredOverrideDs.ToLowerInvariant() == "false")
                        {
                            model.Required = false;
                        }
                    }
                }
                #endregion


                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    #region << Init DataSources >>

                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(options.Value);
                    if (valueResult == null)
                    {
                        model.Value = new List <string>();
                    }
                    else if (valueResult is List <string> )
                    {
                        model.Value = (List <string>)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = new List <string>();
                            stringProcessed = true;
                        }
                        if (!stringProcessed && (((string)valueResult).StartsWith("{") || ((string)valueResult).StartsWith("[")))
                        {
                            try
                            {
                                model.Value     = JsonConvert.DeserializeObject <List <string> >(valueResult.ToString());
                                stringProcessed = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Value Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && !((string)valueResult).Contains("{") && !((string)valueResult).Contains("["))
                        {
                            var valueArray = ((string)valueResult).Split(',', StringSplitOptions.RemoveEmptyEntries);
                            model.Value     = new List <string>(valueArray);
                            stringProcessed = true;
                        }
                        if (!stringProcessed && ((string)valueResult).StartsWith("[") && ((string)valueResult).EndsWith("]"))
                        {
                            model.Value = JsonConvert.DeserializeObject <List <string> >((string)valueResult);
                        }
                    }
                    else if (valueResult is List <Guid> )
                    {
                        model.Value = ((List <Guid>)valueResult).Select(x => x.ToString()).ToList();
                    }
                    else if (valueResult is Guid)
                    {
                        model.Value = new List <string>(valueResult.ToString());
                    }
                    else if (valueResult is List <EntityRecord> )
                    {
                        if (((List <EntityRecord>)valueResult).Count > 0)
                        {
                            if (!((List <EntityRecord>)valueResult)[0].Properties.ContainsKey("id"))
                            {
                                throw new Exception("The provided list of entity records does not contain an 'id' property");
                            }
                        }
                        model.Value = ((List <EntityRecord>)valueResult).Select(x => ((Guid)x["id"]).ToString()).ToList();
                    }

                    var     dataSourceOptions = new List <SelectOption>();
                    dynamic optionsResult     = context.DataModel.GetPropertyValueByDataSource(options.Options);
                    if (optionsResult == null)
                    {
                    }
                    if (optionsResult is List <SelectOption> )
                    {
                        dataSourceOptions = (List <SelectOption>)optionsResult;
                    }
                    else if (optionsResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(optionsResult))
                        {
                            dataSourceOptions = new List <SelectOption>();
                            stringProcessed   = true;
                        }
                        //AJAX Options
                        if (!stringProcessed && ((string)optionsResult).StartsWith("{"))
                        {
                            try
                            {
                                options.AjaxDatasource = JsonConvert.DeserializeObject <SelectOptionsAjaxDatasource>(optionsResult, new JsonSerializerSettings()
                                {
                                    MissingMemberHandling = MissingMemberHandling.Error
                                });
                                stringProcessed = true;
                                ViewBag.Options = options;
                            }
                            catch
                            {
                            }
                        }
                        if (!stringProcessed && (((string)optionsResult).StartsWith("{") || ((string)optionsResult).StartsWith("[")))
                        {
                            try
                            {
                                dataSourceOptions = JsonConvert.DeserializeObject <List <SelectOption> >(optionsResult);
                                stringProcessed   = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Options Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && ((string)optionsResult).Contains(",") && !((string)optionsResult).Contains("{") && !((string)optionsResult).Contains("["))
                        {
                            var optionsArray = ((string)optionsResult).Split(',');
                            var optionsList  = new List <SelectOption>();
                            foreach (var optionString in optionsArray)
                            {
                                optionsList.Add(new SelectOption(optionString, optionString));
                            }
                            dataSourceOptions = optionsList;
                        }
                    }
                    if (dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }
                    #endregion
                }

                ViewBag.SelectMatchOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvSelectMatchType>();

                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #17
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcHtmlBlockOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcHtmlBlockOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = instanceOptions;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                ViewBag.ProccessedHtml = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Html);

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #18
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldSelectOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldSelectOptions>(context.Options.ToString());
                    ////Check for connection to entity field
                    //if (instanceOptions.TryConnectToEntity)
                    //{
                    //	var entity = context.DataModel.GetProperty("Entity");
                    //	if (entity != null && entity is Entity)
                    //	{
                    //		var fieldName = instanceOptions.Name;
                    //		var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    //		if (entityField != null && entityField is PhoneField)
                    //		{
                    //			var castedEntityField = ((PhoneField)entityField);
                    //			//No options connected
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldSelectModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldSelectModel");
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }
                //PcFieldSelectModel model = PcFieldSelectModel.CopyFromBaseModel(baseModel);

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as FieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                #endregion


                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    #region << Init DataSources >>
                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);

                    dynamic optionsResult = context.DataModel.GetPropertyValueByDataSource(options.Options);

                    var dataSourceOptions = new List <SelectOption>();
                    if (optionsResult == null)
                    {
                    }
                    if (optionsResult is List <SelectOption> )
                    {
                        dataSourceOptions = (List <SelectOption>)optionsResult;
                    }
                    else if (optionsResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(optionsResult))
                        {
                            dataSourceOptions = new List <SelectOption>();
                            stringProcessed   = true;
                        }
                        //AJAX Options
                        if (!stringProcessed && ((string)optionsResult).StartsWith("{"))
                        {
                            try
                            {
                                options.AjaxDatasource = JsonConvert.DeserializeObject <SelectOptionsAjaxDatasource>(optionsResult, new JsonSerializerSettings()
                                {
                                    MissingMemberHandling = MissingMemberHandling.Error
                                });
                                stringProcessed = true;
                                ViewBag.Options = options;
                            }
                            catch {
                            }
                        }
                        if (!stringProcessed && (((string)optionsResult).StartsWith("{") || ((string)optionsResult).StartsWith("[")))
                        {
                            try
                            {
                                dataSourceOptions = JsonConvert.DeserializeObject <List <SelectOption> >(optionsResult);
                                stringProcessed   = true;
                            }
                            catch
                            {
                                stringProcessed = false;
                                return(await Task.FromResult <IViewComponentResult>(Content("Error: Options Json De-serialization failed!")));
                            }
                        }
                        if (!stringProcessed && ((string)optionsResult).Contains(",") && !((string)optionsResult).Contains("{") && !((string)optionsResult).Contains("["))
                        {
                            var optionsArray = ((string)optionsResult).Split(',');
                            var optionsList  = new List <SelectOption>();
                            foreach (var optionString in optionsArray)
                            {
                                optionsList.Add(new SelectOption(optionString, optionString));
                            }
                            dataSourceOptions = optionsList;
                        }
                    }

                    if (dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }

                    #endregion
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #19
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTasksPriorityChartOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksPriorityChartOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;
                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;


                    var projectTasks   = new TaskService().GetTaskQueue(projectId, userId, TasksDueType.StartTimeDue);
                    int lowPriority    = 0;
                    int normalPriority = 0;
                    int highPriority   = 0;

                    foreach (var task in projectTasks)
                    {
                        var taskPriority = (string)task["priority"];
                        switch (taskPriority)
                        {
                        case "1":
                            lowPriority++;
                            break;

                        case "2":
                            normalPriority++;
                            break;

                        case "3":
                            highPriority++;
                            break;

                        default:
                            throw new Exception("Unknown task priority: " + taskPriority);
                        }
                    }


                    var theme         = new Theme();
                    var chartDatasets = new List <ErpChartDataset>()
                    {
                        new ErpChartDataset()
                        {
                            Data = new List <decimal>()
                            {
                                highPriority, normalPriority, lowPriority
                            },
                            BackgroundColor = new List <string> {
                                theme.RedColor, theme.LightBlueColor, theme.GreenColor
                            },
                            BorderColor = new List <string> {
                                theme.RedColor, theme.LightBlueColor, theme.GreenColor
                            }
                        }
                    };

                    ViewBag.LowPriority     = lowPriority;
                    ViewBag.NormalPriority  = normalPriority;
                    ViewBag.HighPriority    = highPriority;
                    ViewBag.PriorityOptions = ((SelectField) new EntityManager().ReadEntity("task").Object.Fields.First(x => x.Name == "priority")).Options;
                    ViewBag.Datasets        = chartDatasets;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcTaskRepeatRecurrenceSetOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcTaskRepeatRecurrenceSetOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.CurrentUser      = SecurityContext.CurrentUser;
                ViewBag.CurrentUserJson  = JsonConvert.SerializeObject(SecurityContext.CurrentUser);

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var record = (EntityRecord)context.DataModel.GetProperty("Record");
                    if (record == null)
                    {
                        throw new ValidationException()
                              {
                                  Message = "Record not found"
                              }
                    }
                    ;

                    ViewBag.RecurrenceTemplateString = "";
                    if (record.Properties.ContainsKey("recurrence_template") && record["recurrence_template"] is string)
                    {
                        ViewBag.RecurrenceTemplateString = (string)record["recurrence_template"];
                    }
                    ViewBag.TemplateDefault = JsonConvert.SerializeObject(new RecurrenceTemplate());

                    ViewBag.RecurrenceTypeOptions    = JsonConvert.SerializeObject(ModelExtensions.GetEnumAsSelectOptions <RecurrenceType>());
                    ViewBag.RecurrenceEndTypeOptions = JsonConvert.SerializeObject(ModelExtensions.GetEnumAsSelectOptions <RecurrenceEndType>());
                    var periodTypes = ModelExtensions.GetEnumAsSelectOptions <RecurrencePeriodType>();
                    periodTypes = periodTypes.FindAll(x => x.Value != "0" && x.Value != "1" && x.Value != "2").ToList();                     // remove seconds minutes and hour
                    ViewBag.PeriodTypeOptions           = JsonConvert.SerializeObject(periodTypes);
                    ViewBag.RecurrenceChangeTypeOptions = JsonConvert.SerializeObject(ModelExtensions.GetEnumAsSelectOptions <RecurrenceChangeType>());
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcApplicationsOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcApplicationsOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = instanceOptions;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var currentUser = AuthService.GetUser(HttpContext.User);

                    var currentUserRoles = currentUser.Roles.Select(x => x.Id);
                    var apps             = new AppService().GetAllApplications().OrderBy(x => x.Weight).ToList();
                    var allowedApps      = new List <App>();
                    if (apps != null)
                    {
                        foreach (var app in apps)
                        {
                            if (app.Access == null || app.Access.Count == 0)
                            {
                                continue;
                            }

                            IEnumerable <Guid> accessRoles = app.Access.Intersect(currentUserRoles);
                            if (accessRoles.Any())
                            {
                                allowedApps.Add(app);
                            }
                        }
                    }
                    //Generate Url
                    foreach (var app in allowedApps)
                    {
                        app.HomePages = app.HomePages.FindAll(x => x.Weight < 1000).OrderBy(x => x.Weight).ToList();
                        foreach (var area in app.Sitemap.Areas)
                        {
                            foreach (var node in area.Nodes)
                            {
                                node.Url = PageUtils.GenerateSitemapNodeUrl(node, area, app);
                            }
                        }
                        app.Sitemap = new AppService().OrderSitemap(app.Sitemap);
                    }
                    ViewBag.Apps = allowedApps;
                }


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var instanceOptions = new PcBtnToolbarOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcBtnToolbarOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options            = instanceOptions;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                ViewBag.CssSize = ModelExtensions.GetEnumAsSelectOptions <CssSize>();

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions     = InitPcFieldBaseOptions(context);
                var instanceOptions = PcFieldDateTimeOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcFieldDateTimeOptions>(context.Options.ToString());
                    ////Check for connection to entity field
                    //if (instanceOptions.TryConnectToEntity)
                    //{
                    //	var entity = context.DataModel.GetProperty("Entity");
                    //	if (entity != null && entity is Entity)
                    //	{
                    //		var fieldName = instanceOptions.Name;
                    //		var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    //		if (entityField != null && entityField is DateTimeField)
                    //		{
                    //			var castedEntityField = ((DateTimeField)entityField);
                    //			//No options mapped
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, instanceOptions, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(instanceOptions.LabelText))
                {
                    instanceOptions.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = instanceOptions.LabelMode;
                ViewBag.Mode      = instanceOptions.Mode;

                if (instanceOptions.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (instanceOptions.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    model.Value = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Value);
                }

                ViewBag.Options        = instanceOptions;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #24
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldHtmlOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldHtmlOptions>(context.Options.ToString());
                    if (context.Mode != ComponentMode.Options)
                    {
                        if (String.IsNullOrWhiteSpace(options.LabelHelpText))
                        {
                            options.LabelHelpText = baseOptions.LabelHelpText;
                        }

                        if (String.IsNullOrWhiteSpace(options.Description))
                        {
                            options.Description = baseOptions.Description;
                        }
                    }
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText) && context.Mode != ComponentMode.Options)
                {
                    options.LabelText = modelFieldLabel;
                }

                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
                if (requiredOverride != null)
                {
                    model.Required = requiredOverride.Value;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs))
                    {
                        if (options.RequiredOverrideDs.ToLowerInvariant() == "true")
                        {
                            model.Required = true;
                        }
                        else if (options.RequiredOverrideDs.ToLowerInvariant() == "false")
                        {
                            model.Required = false;
                        }
                    }
                }
                #endregion


                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);

                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;
                }

                ViewBag.UploadModeOptions  = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <HtmlUploadMode>();
                ViewBag.ToolbarModeOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <HtmlToolbarMode>();

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #25
0
        public dynamic InitPcFieldBaseModel(PageComponentContext context, PcFieldBaseOptions options, out string label, string targetModel = "PcFieldBaseModel")
        {
            label = "";
            var model = new PcFieldBaseModel();

            if (context.Items.ContainsKey(typeof(ValidationException)))
            {
                model.ValidationErrors = ((ValidationException)context.Items[typeof(ValidationException)]).Errors;
            }

            model.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();

            model.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();

            if (context.Mode == ComponentMode.Options)
            {
                model.EntitySelectOptions = new MetaService().GetEntitiesAsSelectOptions();
            }

            var recordId = context.DataModel.GetProperty("RecordId");

            if (recordId != null && recordId is Guid)
            {
                model.RecordId = (Guid)recordId;
            }

            var entity = context.DataModel.GetProperty("Entity");

            if (entity != null && entity is Entity)
            {
                model.EntityName = ((Entity)entity).Name;
                if (!String.IsNullOrWhiteSpace(model.EntityName) && model.RecordId != null)
                {
                    model.ApiUrl = $"/api/v3/en_US/record/{model.EntityName}/{model.RecordId}/";
                }
            }

            Entity mappedEntity = null;

            if (options.ConnectedEntityId != null)
            {
                mappedEntity = new EntityManager().ReadEntity(options.ConnectedEntityId.Value).Object;
            }
            else if (options.ConnectedEntityId == null && entity is Entity)
            {
                mappedEntity = (Entity)entity;
            }

            if (mappedEntity != null)
            {
                var fieldName = options.Name;

                if (fieldName.StartsWith("$"))
                {
                    //Field with relation is set. Mapped entity should be changed
                    var fieldNameArray = fieldName.Replace("$", "").Split(".", StringSplitOptions.RemoveEmptyEntries);
                    if (fieldNameArray.Length == 2)
                    {
                        var relationName = fieldNameArray[0];
                        fieldName = fieldNameArray[1];
                        var relation = new EntityRelationManager().Read(relationName).Object;
                        if (relation != null)
                        {
                            if (relation.OriginEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.TargetEntityId).Object;
                            }
                            else if (relation.TargetEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.OriginEntityId).Object;
                            }
                        }
                    }
                }

                var entityField = mappedEntity.Fields.FirstOrDefault(x => x.Name == fieldName);
                if (entityField != null)
                {
                    //Connection success set local options if needed
                    if (String.IsNullOrWhiteSpace(model.Placeholder))
                    {
                        model.Placeholder = entityField.PlaceholderText;
                    }

                    if (String.IsNullOrWhiteSpace(model.Description))
                    {
                        model.Description = entityField.Description;
                    }

                    if (String.IsNullOrWhiteSpace(model.LabelHelpText))
                    {
                        model.LabelHelpText = entityField.HelpText;
                    }

                    if (String.IsNullOrWhiteSpace(label))
                    {
                        label = entityField.Label;
                    }

                    model.Required = entityField.Required;

                    if (entityField.EnableSecurity)
                    {
                        var currentUser = context.DataModel.GetProperty("CurrentUser");
                        if (currentUser != null && currentUser is ErpUser)
                        {
                            var canRead   = false;
                            var canUpdate = false;
                            var user      = (ErpUser)currentUser;
                            foreach (var role in user.Roles)
                            {
                                if (entityField.Permissions.CanRead.Any(x => x == role.Id))
                                {
                                    canRead = true;
                                }
                                if (entityField.Permissions.CanUpdate.Any(x => x == role.Id))
                                {
                                    canUpdate = true;
                                }
                            }
                            if (canUpdate)
                            {
                                model.Access = FieldAccess.Full;
                            }
                            else if (canRead)
                            {
                                model.Access = FieldAccess.ReadOnly;
                            }
                            else
                            {
                                model.Access = FieldAccess.Forbidden;
                            }
                        }
                    }

                    //Specific model properties
                    var fieldOptions = new List <SelectOption>();
                    switch (entityField.GetFieldType())
                    {
                    case FieldType.SelectField:
                        var selectField = ((SelectField)entityField);
                        model.DefaultValue = selectField.DefaultValue;
                        fieldOptions       = selectField.Options;
                        break;

                    case FieldType.MultiSelectField:
                        var multiselectField = ((MultiSelectField)entityField);
                        model.DefaultValue = multiselectField.DefaultValue;
                        fieldOptions       = multiselectField.Options;
                        break;

                    default:
                        break;
                    }
                    switch (targetModel)
                    {
                    case "PcFieldSelectModel":
                        return(PcFieldSelectModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldRadioListModel":
                        return(PcFieldRadioListModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldCheckboxListModel":
                        return(PcFieldCheckboxListModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldMultiSelectModel":
                        return(PcFieldMultiSelectModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldCheckboxGridModel":
                        return(PcFieldCheckboxGridModel.CopyFromBaseModel(model, new List <SelectOption>(), new List <SelectOption>()));

                    default:
                        return(model);
                    }
                }
            }

            switch (targetModel)
            {
            case "PcFieldSelectModel":
                return(PcFieldSelectModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldRadioListModel":
                return(PcFieldRadioListModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldCheckboxListModel":
                return(PcFieldCheckboxListModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldMultiSelectModel":
                return(PcFieldMultiSelectModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldCheckboxGridModel":
                return(PcFieldCheckboxGridModel.CopyFromBaseModel(model, new List <SelectOption>(), new List <SelectOption>()));

            default:
                return(model);
            }
        }
Exemple #26
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTasksQueueOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksQueueOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.TypeOptions      = ModelExtensions.GetEnumAsSelectOptions <TasksDueType>();

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;

                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;
                    var  limit     = options.Type == TasksDueType.EndTimeNotDue ? 10 : 50;
                    var  taskQueue = new TaskService().GetTaskQueue(projectId, userId, options.Type, limit);

                    var users = new UserService().GetAll();

                    var resultRecords = new List <EntityRecord>();

                    foreach (var task in taskQueue)
                    {
                        var imagePath = "/webvella-erp-web/assets/avatar.png";
                        var user      = new EntityRecord();
                        user["username"] = "******";
                        if (task["owner_id"] != null)
                        {
                            user = users.First(x => (Guid)x["id"] == (Guid)task["owner_id"]);
                            if (user["image"] != null && (string)user["image"] != "")
                            {
                                imagePath = "/fs" + (string)user["image"];
                            }
                        }
                        string iconClass = "";
                        string color     = "";
                        new TaskService().GetTaskIconAndColor((string)task["priority"], out iconClass, out color);

                        var row = new EntityRecord();
                        row["task"] = $"<i class='{iconClass}' style='color:{color}'></i> <a href=\"/projects/tasks/tasks/r/{(Guid)task["id"]}/details\">[{task["key"]}] {task["subject"]}</a>";
                        row["user"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                        row["date"] = ((DateTime?)task["end_time"]).ConvertToAppDate();
                        resultRecords.Add(row);
                    }
                    ViewBag.Records = resultRecords;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldAutonumberOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldAutonumberOptions>(context.Options.ToString());

                    if (context.Mode != ComponentMode.Options)
                    {
                        if (String.IsNullOrWhiteSpace(options.Template))
                        {
                            options.Template = baseOptions.Template;
                        }
                    }
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);
                }

                var isVisible   = true;
                var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                {
                    if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                    {
                        isVisible = outBool;
                    }
                }
                else if (isVisibleDS is Boolean)
                {
                    isVisible = (bool)isVisibleDS;
                }
                ViewBag.IsVisible = isVisible;

                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #28
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcGridOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcGridOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;


                ViewBag.CssBreakpointOptions = ModelExtensions.GetEnumAsSelectOptions <CssBreakpoint>();
                ViewBag.Page       = 1;
                ViewBag.TotalCount = 0;

                if (options.PageSize != null)
                {
                    ViewBag.PageSize = options.PageSize;
                }
                else
                {
                    ViewBag.PageSize = 0;
                }


                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    ViewBag.Records = context.DataModel.GetPropertyValueByDataSource(options.Records) as EntityRecordList ?? new EntityRecordList();

                    if (ViewBag.Records is EntityRecordList)
                    {
                        ViewBag.TotalCount = ((EntityRecordList)ViewBag.Records).TotalCount;
                    }
                    string pageKey = options.Prefix + options.QueryStringPage;
                    if (HttpContext.Request.Query.ContainsKey(pageKey))
                    {
                        var queryValue = HttpContext.Request.Query[pageKey].ToString();
                        if (Int16.TryParse(queryValue, out Int16 outInt))
                        {
                            ViewBag.Page = outInt;
                        }
                    }

                    string pagesizeKey = options.Prefix + options.QueryStringPageSize;
                    if (HttpContext.Request.Query.ContainsKey(pagesizeKey))
                    {
                        var queryValue = HttpContext.Request.Query[pagesizeKey].ToString();
                        if (Int16.TryParse(queryValue, out Int16 outInt))
                        {
                            ViewBag.PageSize = outInt;
                        }
                    }
                }
                else
                {
                    ViewBag.VerticalAlignmentOptions   = ModelExtensions.GetEnumAsSelectOptions <VerticalAlignmentType>();
                    ViewBag.HorizontalAlignmentOptions = ModelExtensions.GetEnumAsSelectOptions <HorizontalAlignmentType>();
                }
                var columns = new List <GridColumn>();

                #region << Init Columns >>
                if (options.VisibleColumns > 0)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container1Id,
                        Name        = options.Container1Name,
                        Label       = options.Container1Label,
                        Searchable  = options.Container1Searchable,
                        Sortable    = options.Container1Sortable,
                        Width       = options.Container1Width
                    });
                }
                if (options.VisibleColumns > 1)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container2Id,
                        Name        = options.Container2Name,
                        Label       = options.Container2Label,
                        Searchable  = options.Container2Searchable,
                        Sortable    = options.Container2Sortable,
                        Width       = options.Container2Width
                    });
                }
                if (options.VisibleColumns > 2)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container3Id,
                        Name        = options.Container3Name,
                        Label       = options.Container3Label,
                        Searchable  = options.Container3Searchable,
                        Sortable    = options.Container3Sortable,
                        Width       = options.Container3Width
                    });
                }
                if (options.VisibleColumns > 3)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container4Id,
                        Name        = options.Container4Name,
                        Label       = options.Container4Label,
                        Searchable  = options.Container4Searchable,
                        Sortable    = options.Container4Sortable,
                        Width       = options.Container4Width
                    });
                }
                if (options.VisibleColumns > 4)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container5Id,
                        Name        = options.Container5Name,
                        Label       = options.Container5Label,
                        Searchable  = options.Container5Searchable,
                        Sortable    = options.Container5Sortable,
                        Width       = options.Container5Width
                    });
                }
                if (options.VisibleColumns > 5)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container6Id,
                        Name        = options.Container6Name,
                        Label       = options.Container6Label,
                        Searchable  = options.Container6Searchable,
                        Sortable    = options.Container6Sortable,
                        Width       = options.Container6Width
                    });
                }
                if (options.VisibleColumns > 6)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container7Id,
                        Name        = options.Container7Name,
                        Label       = options.Container7Label,
                        Searchable  = options.Container7Searchable,
                        Sortable    = options.Container7Sortable,
                        Width       = options.Container7Width
                    });
                }
                if (options.VisibleColumns > 7)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container8Id,
                        Name        = options.Container8Name,
                        Label       = options.Container8Label,
                        Searchable  = options.Container8Searchable,
                        Sortable    = options.Container8Sortable,
                        Width       = options.Container8Width
                    });
                }
                if (options.VisibleColumns > 8)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container9Id,
                        Name        = options.Container9Name,
                        Label       = options.Container9Label,
                        Searchable  = options.Container9Searchable,
                        Sortable    = options.Container9Sortable,
                        Width       = options.Container9Width
                    });
                }
                if (options.VisibleColumns > 9)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container10Id,
                        Name        = options.Container10Name,
                        Label       = options.Container10Label,
                        Searchable  = options.Container10Searchable,
                        Sortable    = options.Container10Sortable,
                        Width       = options.Container10Width
                    });
                }
                if (options.VisibleColumns > 10)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container11Id,
                        Name        = options.Container11Name,
                        Label       = options.Container11Label,
                        Searchable  = options.Container11Searchable,
                        Sortable    = options.Container11Sortable,
                        Width       = options.Container11Width
                    });
                }
                if (options.VisibleColumns > 11)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container12Id,
                        Name        = options.Container12Name,
                        Label       = options.Container12Label,
                        Searchable  = options.Container12Searchable,
                        Sortable    = options.Container12Sortable,
                        Width       = options.Container12Width
                    });
                }
                #endregion

                ViewBag.Columns = columns;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (EqlException ex)
            {
                var errors = new List <ValidationError>();
                foreach (var error in ex.Errors)
                {
                    errors.Add(new ValidationError("eql", $"Line {error.Line}, Column {error.Column}: {error.Message}"));
                }
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message,
                    Errors  = errors
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);

                var options = PcFieldCheckboxListOptions.CopyFromBaseOptions(baseOptions);

                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldCheckboxListOptions>(context.Options.ToString());
                }
                var modelFieldLabel = "";
                var model           = (PcFieldCheckboxListModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldCheckboxListModel");
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }
                //PcFieldCheckboxListModel model = PcFieldCheckboxListModel.CopyFromBaseModel(baseModel);

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;


                    #region << Init DataSources >>
                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(options.Value);
                    if (valueResult == null)
                    {
                        model.Value = new List <string>();
                    }
                    else if (valueResult is List <string> )
                    {
                        model.Value = (List <string>)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = new List <string>();
                            stringProcessed = true;
                        }
                        if (!stringProcessed && (((string)valueResult).StartsWith("{") || ((string)valueResult).StartsWith("[")))
                        {
                            try
                            {
                                model.Value     = JsonConvert.DeserializeObject <List <string> >(valueResult.ToString());
                                stringProcessed = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Value Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && ((string)valueResult).Contains(",") && !((string)valueResult).Contains("{") && !((string)valueResult).Contains("["))
                        {
                            var valueArray = ((string)valueResult).Split(',');
                            model.Value = new List <string>(valueArray);
                        }
                    }

                    var     dataSourceOptions = new List <SelectOption>();
                    dynamic optionsResult     = context.DataModel.GetPropertyValueByDataSource(options.Options);
                    if (optionsResult == null)
                    {
                    }
                    if (optionsResult is List <SelectOption> )
                    {
                        dataSourceOptions = (List <SelectOption>)optionsResult;
                    }
                    else if (optionsResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(optionsResult))
                        {
                            dataSourceOptions = new List <SelectOption>();
                            stringProcessed   = true;
                        }
                        if (!stringProcessed && (((string)optionsResult).StartsWith("{") || ((string)optionsResult).StartsWith("[")))
                        {
                            try
                            {
                                dataSourceOptions = JsonConvert.DeserializeObject <List <SelectOption> >(optionsResult);
                                stringProcessed   = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Options Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && ((string)optionsResult).Contains(",") && !((string)optionsResult).Contains("{") && !((string)optionsResult).Contains("["))
                        {
                            var optionsArray = ((string)optionsResult).Split(',');
                            var optionsList  = new List <SelectOption>();
                            foreach (var optionString in optionsArray)
                            {
                                optionsList.Add(new SelectOption(optionString, optionString));
                            }
                            dataSourceOptions = optionsList;
                        }
                    }
                    if (dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }
                    #endregion
                }


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Exemple #30
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }


                var optionsObject = InitOptions(context.Options);

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                #endregion

                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.Options          = optionsObject;
                ViewBag.ComponentContext = context;

                ViewBag.WvFlexSelfAlignTypeOptions   = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFlexSelfAlignType>();
                ViewBag.FlexVerticalAlignmentOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFlexVerticalAlignmentType>();

                ViewBag.FlexHorizontalAlignmentOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFlexHorizontalAlignmentType>();

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }