示例#1
0
        public static void SortDescending(ExcelTemplateView view, IBindingContextItem contextItem)
        {
            ITemplateDefinition templateDefinition = contextItem.ParentElement.ParentPart.TemplateDefinitionPart.Parent;
            ISorterDefinition   sortDefinition     = SortDefinitionFactory.CreateInstance(templateDefinition, contextItem.BindingDefinition, true, false);

            ExecuteSort(view, sortDefinition);
        }
示例#2
0
 public SortersAndFilters(ITemplateDefinition templateDefinition, IEnumerable <IFilterDefinition> filters, IEnumerable <ISorterDefinition> sorters)
 {
     TemplateDefinition = templateDefinition;
     Filters            = filters?.ToList();
     Sorters            = sorters?.ToList();
     SetFilterMethod();
 }
        private bool TryParseField(string mustache, ITemplateDefinition template, Dictionary <string, Type> types)
        {
            var colonPos = mustache.IndexOf(':');

            if (colonPos < 0)
            {
                return(false);
            }

            if (colonPos == 0)
            {
                throw new TemplateBuilderException(
                          "Mustache expressions in templates can not begin with colon. Your template contains '{{" + mustache + "}}'");
            }

            var typeName  = mustache.Substring(0, colonPos);
            var fieldName = mustache.Substring(colonPos + 1);

            var type = types.ContainsKey(typeName)
                ? types[typeName]
                : ResolveTypeName(typeName);

            template.AddDataField(type, fieldName);

            return(true);
        }
示例#4
0
        internal void Process(string t4Template, string outputFilePath, ITemplateDefinition definition, ProcessorParameters parameters)
        {
            var ttParams = new TextTemplatingParameters(
                t4Template,
                outputFilePath,
                definition.OverrideFileIfExists,
                definition.AddToProject);

            string tmpOutputFilePath;

            try
            {
                var state = this.TextTemplatingEngine.Process(ttParams, out tmpOutputFilePath);

                if (state == ProcessStateEnum.Processed)
                {
                    // SQL scripts...

                    if (definition.ExecuteSqlScript)
                    {
                        bool canExecuted = true;
                        if (definition is TemplateDefinitions.Database.InsertAllStoredProceduresGeneratedSqlTemplateDefinition && !parameters.WithSqlProcedureIntegration)
                        {
                            canExecuted = false;
                        }

                        if (canExecuted)
                        {
                            this.PublishProcessMessage("Executing {0}...", Path.GetFileName(tmpOutputFilePath));

                            try
                            {
                                SmoHelper.RunSqlScript(tmpOutputFilePath, this.SmoContext);
                            }
                            catch
                            {
                                // Create a copy of the tmpOutputFilePath file (for debug) because it will be deleted at the end of the whole process...
                                FileHelper.TryCopy(tmpOutputFilePath, string.Concat(tmpOutputFilePath, ".err"), withOverwrite: true);

                                throw;
                            }
                        }
                    }
                }

                this.HasErrors |= state == ProcessStateEnum.Failed;
            }
            catch (Exception x)
            {
                this.PublishErrorMessage("Failed while processing {0} -> {1}", Path.GetFileName(t4Template), x.Message);
            }

            foreach (CompilerError error in this.TextTemplatingEngine.Errors)
            {
                this.PublishErrorMessage(
                    "Template error: {0}({1},{2}): error {3}: {4}",
                    Path.GetFileName(this.TextTemplatingEngine.Errors.First().FileName), error.Line, error.Column, error.ErrorNumber, error.ErrorText);
            }
        }
示例#5
0
 public FilterOnConditions(ITemplateDefinition templateDefinition, IBindingDefinition definition, string condition, FilterDefinitionRelation relation, bool caseSensitive)
 {
     TemplateDefinition = templateDefinition;
     DefinitionToFilter = definition;
     Condition          = condition;
     Relation           = relation;
     CaseSensitive      = caseSensitive;
 }
示例#6
0
 public ExcelTemplateView(ITemplateDefinition templateDefinition, ExcelInterop.Worksheet sheetDestination, ExcelInterop.Range firstOutputCell, ExcelInterop.Range clearingCell)
     : base(templateDefinition)
 {
     ViewSheet                   = sheetDestination;
     FirstOutputCell             = firstOutputCell;
     ClearingCell                = clearingCell;
     AutoFit                     = AutoFitMode.WidthHeight;
     CellsThatContainSearchValue = new List <ExcelBindingSearchContextItem>();
 }
示例#7
0
        public SortDefinition(ITemplateDefinition templateDefinition, IBindingDefinition bindingDefinition, bool descending, bool caseSensitive)
        {
            TemplateDefinition = templateDefinition;
            BindingDefinition  = bindingDefinition;
            Descending         = descending;
            CaseSensitive      = caseSensitive;

            SetExpression();
        }
        public static ISortersAndFilters CreateInstance(ITemplateDefinition templateDefinition, IEnumerable <IFilterDefinition> filters, IEnumerable <ISorterDefinition> sorters)
        {
            if (templateDefinition == null)
            {
                return(null);
            }

            MethodInfo createLambdaExpression = typeof(SortersAndFilterersFactory).GetMethod("CreateInstance", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(templateDefinition.BindingType.BindType);

            return(createLambdaExpression.Invoke(null, new object[] { templateDefinition, filters, sorters }) as ISortersAndFilters);
        }
        public static ISorterDefinition CreateInstance(ITemplateDefinition templateDefinition, IBindingDefinition bindingDefinition, bool descending, bool caseSensitive)
        {
            if (templateDefinition == null || bindingDefinition == null)
            {
                return(null);
            }

            MethodInfo createLambdaExpression = typeof(SortDefinitionFactory).GetMethod("CreateInstance", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(templateDefinition.BindingType.BindType, bindingDefinition.BindingType);

            return(createLambdaExpression.Invoke(null, new object[] { templateDefinition, bindingDefinition, descending, caseSensitive }) as ISorterDefinition);
        }
        private bool TryParseEndRepeat(string mustache, ITemplateDefinition template, Dictionary <string, Type> types)
        {
            if (mustache.Length == 0 || mustache[0] != '/')
            {
                return(false);
            }

            template.RepeatEnd();

            return(true);
        }
 protected EventCallback RetrieveMethodInfo(ITemplateDefinition templateDefinition, string option, string callbackName)
 {
     try
     {
         return(EventCallbacksManager.RetrieveCallback(templateDefinition, callbackName));
     }
     catch (Exception ex)
     {
         throw new Exception($"Property option '{option}'. {ex.Message}");
     }
 }
示例#12
0
 public FilterOnValues(ITemplateDefinition templateDefinition, IBindingDefinition definition, IEnumerable <object> selectedValues, bool useOrEquals)
 {
     TemplateDefinition = templateDefinition;
     DefinitionToFilter = definition;
     SelectedValues     = selectedValues;
     UseOrEquals        = useOrEquals;
     if (selectedValues != null && selectedValues.Any())
     {
         SetFilterExpression();
     }
 }
示例#13
0
 public TemplateView(ITemplateDefinition templateDefinition)
 {
     Ident = Guid.NewGuid();
     if (templateDefinition == null)
     {
         string message = "Cannot create a 'view' without a 'template dataAccessor'.";
         throw new EtkException(message);
     }
     TemplateDefinition = templateDefinition;
     FilterValueByFilterDefinitionByElement = new Dictionary <object, Dictionary <BindingFilterDefinition, string> >();
 }
示例#14
0
        private EventCallback GetCallBackFromMainBindingDefinition(ITemplateDefinition templateDefinition, string methodName)
        {
            EventCallback ret = null;

            if (templateDefinition?.MainBindingDefinition != null && templateDefinition.MainBindingDefinition.BindingType != null)
            {
                var inType     = templateDefinition.MainBindingDefinition.BindingType;
                var methodInfo = TypeHelpers.GetMethod(inType, methodName);
                ret = new EventCallback(null, null, methodInfo);
            }
            return(ret);
        }
示例#15
0
        internal string GetOutputFilePathToCreate(ITemplateDefinition definition, string name = null)
        {
            string outputPath  = this.Context.SolutionDirectory;
            string outFileName = string.Format(definition.OutputFileNamePattern, name);

            string[] cutter = definition.TemplatePath.Split('\\');

            cutter[1] = string.Format("{0}.{1}", this.Context.ProjectName, cutter[1]);

            outputPath = Path.Combine(outputPath, Path.GetDirectoryName(string.Join(@"\", cutter)));

            return(Path.Combine(outputPath, outFileName));
        }
示例#16
0
        public TemplateViewModel(SortAndFilterViewModel parent, ITemplateDefinition templateDefinition, IEnumerable <IBindingContextItem> items)
        {
            this.parent = parent;
            //&&this.owner = owner;
            //DefinitionToFilterOwner = templateDefinition;
            //foreach (IBindingDefinition bindingDefinition in templateDefinition.BindingDefinitions.Where(b => b.IsBoundWithData))
            //{
            //    IEnumerable<IBindingContextItem> childItems = items.Where(e => e.BindingDefinition == bindingDefinition);
            //    if(childItems.Any())
            //        bindingDefinitions.Add(new BindingDefinitionViewModel(this, bindingDefinition, childItems));
            //}

            //BindingDefinitionSelected += OnBindingDefinitionSelected;
        }
        public LinkedTemplateDefinition(ITemplateDefinition parent, ITemplateDefinition templateDefinition, TemplateLink linkDefinition)
        {
            try
            {
                Parent             = parent;
                TemplateDefinition = templateDefinition;
                Positioning        = linkDefinition.Positioning;
                if (!string.IsNullOrEmpty(linkDefinition.With))
                {
                    Type type = parent.MainBindingDefinition != null ? parent.MainBindingDefinition.BindingType : null;
                    BindingDefinitionDescription definitionDescription = new BindingDefinitionDescription()
                    {
                        BindingExpression = linkDefinition.With,
                        Description       = linkDefinition.Description,
                        Name       = linkDefinition.Name,
                        IsReadOnly = true
                    };
                    BindingDefinition = BindingDefinitionFactory.CreateInstance(type, definitionDescription);
                }

                if (!string.IsNullOrEmpty(linkDefinition.MinOccurencesMethod))
                {
                    try
                    {
                        if (templateDefinition.Header != null && ((TemplateDefinitionPart)templateDefinition.Header).HasLinkedTemplates ||
                            templateDefinition.Body != null && ((TemplateDefinitionPart)templateDefinition.Body).HasLinkedTemplates ||
                            templateDefinition.Footer != null && ((TemplateDefinitionPart)templateDefinition.Footer).HasLinkedTemplates)
                        {
                            throw new Exception("'MinOccurencesMethod' is not supported with templates linked with other templates");
                        }

                        Type type = TemplateDefinition.MainBindingDefinition == null ? null : TemplateDefinition.MainBindingDefinition.BindingType;
                        MinOccurencesMethod = TypeHelpers.GetMethod(type, linkDefinition.MinOccurencesMethod);
                        if (MinOccurencesMethod.GetParameters().Length > 2)
                        {
                            throw new Exception("The min occurences resolver method signature must be 'int <MethodName>([instance of element of the collection that owned the link declaration])'");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"Cannot retrieve the min occurences resolver method:{ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                string message = $"Cannot resolve linked template definition 'To={linkDefinition.To}, With='{linkDefinition.With}'";
                throw new Exception(message, ex);
            }
        }
        public DocumentToProcess(Guid requesterIdentifier, ITemplateDefinition templateDefinition,
                                 Guid?id = null) : base(id)
        {
            if (requesterIdentifier == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(requesterIdentifier));
            }
            if (templateDefinition == null)
            {
                throw new ArgumentNullException(nameof(templateDefinition));
            }

            RequesterIdentifier = requesterIdentifier;
            TemplateDefinition  = templateDefinition;
        }
示例#19
0
        private XElement GetTemplateContentElement(XElement controlTemplateElement, ITemplateDefinition templateDefinition)
        {
            foreach (var xElement in controlTemplateElement.Elements())
            {
                var name = xElement.Name.ToString();
                if (!name.StartsWith($"{templateDefinition.FullName.LocalName}."))
                {
                    return(xElement);
                }

                if (name.Equals($"{templateDefinition.FullName.LocalName}.Template"))
                {
                    return(xElement.Elements().FirstOrDefault());
                }
            }

            return(null);
        }
示例#20
0
        /// <summary>
        /// Creates the specified definition.
        /// </summary>
        /// <param name="definition">The definition.</param>
        /// <param name="changeMonitor">The change monitor.</param>
        /// <returns>IEnumerable{Control}.</returns>
        /// <exception cref="System.ArgumentNullException">Template definition was expected.</exception>
        public IEnumerable <Control> Create(ITemplateDefinition definition, IChangeMonitor changeMonitor)
        {
            IEnumerable <Control> retval = null;

            if (definition == null || !definition.TemplateElements.Any())
            {
                throw new ArgumentNullException("Template definition was expected.");
            }

            if (changeMonitor == null)
            {
                throw new ArgumentNullException("ChangeMonitor definition was expected.");
            }

            ChangeMonitor = changeMonitor;
            retval        = CreateHelper(definition);

            return(retval);
        }
示例#21
0
        public ExcelRenderer(ExcelRenderer parent, ITemplateDefinition templateDefinition, IBindingContext bindingContext, ExcelInterop.Range firstOutputCell, MethodInfo minOccurencesMethod)
        {
            NestedRenderer = new List <ExcelRenderer>();
            if (parent == null)
            {
                RootRenderer = this as ExcelRootRenderer;
            }
            else
            {
                RootRenderer = parent.RootRenderer;
                Parent       = parent;
            }

            this.templateDefinition = templateDefinition;
            this.bindingContext     = bindingContext;
            this.firstOutputCell    = firstOutputCell;
            MinOccurencesMethod     = minOccurencesMethod;
            DataRows = new List <List <IBindingContextItem> >();
        }
        private bool TryParseStartRepeat(string mustache, ITemplateDefinition template, Dictionary <string, Type> types)
        {
            if (mustache.Length == 0 || mustache[0] != '#')
            {
                return(false);
            }

            var indexOfColon = mustache.IndexOf(':');

            var typeName  = indexOfColon < 0 ? mustache.Substring(1) : mustache.Substring(1, indexOfColon - 1);
            var scopeName = indexOfColon < 0 ? null : mustache.Substring(indexOfColon + 1);

            var type = types.ContainsKey(typeName)
                ? types[typeName]
                : ResolveTypeName(typeName);

            template.RepeatStart(type, scopeName);

            return(true);
        }
示例#23
0
        public EventCallback RetrieveCallback(ITemplateDefinition templateDefinition, string callbackName)
        {
            EventCallback ret = null;

            if (callbackName.StartsWith("$")) // The callback is not a .Net one
            {
                ret = new EventCallback(callbackName.TrimStart('$'), null, null);
            }
            else
            {
                ret = GetRegisteredCallback(callbackName); // Is the callback registred (from xml)
                if (ret == null)
                {
                    string[] parts = callbackName.Split(',');
                    if (parts.Length == 1) // The callback is a member of the 'templateDefinition.MainBindingDefinition.BindingType' class
                    {
                        ret = GetCallBackFromMainBindingDefinition(templateDefinition, parts[0]);
                    }
                    if (parts.Length == 3) // assembly, type and nam are supplied
                    {
                        if (string.IsNullOrEmpty(parts[0]) && string.IsNullOrEmpty(parts[1]))
                        {
                            ret = GetCallBackFromMainBindingDefinition(templateDefinition, parts[2]);
                        }
                        else
                        {
                            MethodInfo methodInfo = TypeHelpers.GetMethod(null, callbackName);
                            ret = new EventCallback(null, null, methodInfo);
                        }
                    }
                }
            }

            if (ret == null)
            {
                throw new Exception($"Cannot find the callback '{callbackName}'");
            }

            return(ret);
        }
示例#24
0
        /// <summary>
        /// Creates the helper.
        /// </summary>
        /// <param name="definition">The definition.</param>
        /// <returns></returns>
        private IEnumerable <Control> CreateHelper(ITemplateDefinition definition)
        {
            var retval = new List <Control>();

            var flag = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;

            var targetAsm = AppDomain.CurrentDomain.GetAssemblies()
                            .FirstOrDefault(x => string.Equals(x.GetName().Name, "System.Windows.Forms", StringComparison.OrdinalIgnoreCase));

            if (targetAsm != null)
            {
                definition.TemplateElements.ToList().ForEach(x => {
                    try {
                        var controlType = targetAsm.GetTypes().FirstOrDefault(z => z.IsSubclassOf(typeof(Control)) && !z.IsAbstract &&
                                                                              z.Name.ToUpperInvariant().Contains(x.Class.ToUpperInvariant()));

                        // Expected to have a default constructor without any parameters
                        var control = controlType.GetConstructors(flag).FirstOrDefault().Invoke(null) as Control;

                        PropertySetter(control, x);

                        // Does it have a TextChanged event?
                        var ei = control.GetType().GetEvent("TextChanged");

                        if (ei != null)
                        {
                            ei.AddEventHandler(control, new EventHandler((sender, args) => ChangeMonitor.HasChanges = true));
                        }

                        retval.Add(control);
                    } catch (Exception ex) {
                        Logger.LogError(ex);
                    }
                });
            }

            return(retval);
        }
示例#25
0
        private void PopulateTemplates(ITemplateDefinition templateDefinition, IEnumerable <IBindingContext> bindingContexts)
        {
            //IEnumerable<IBindingContextElement> elements = bindingContexts.SelectMany(e => e.Elements)
            //                                                              .Where(e => e != null);
            //if(elements.Any())
            //{
            //    IEnumerable<IBindingContextItem> items = elements.SelectMany(e => e.BindingContextItems);
            //    if (templateDefinition.IsSortableAndFilterable)
            //    {
            //        TemplateViewModel templateViewModel = new TemplateViewModel(this, templateDefinition, items);
            //        TemplateViewModels.Add(templateViewModel);
            //    }

            //    //&&foreach (ILinkedTemplateDefinition childTemplate in templateDefinition.LinkedTemplates)
            //    //{
            //    //    IEnumerable<IBindingContext> childContexts = elements.SelectMany(e => e.LinkedBindingContexts)
            //    //                                                         .Where(e => e.DefinitionToFilterOwner.Name.Equals(childTemplate.DefinitionToFilterOwner.Name));

            //    //    if (bindingContexts.Any())
            //    //        PopulateTemplates(childTemplate.DefinitionToFilterOwner, childContexts);
            //    //}
            //}
        }
示例#26
0
 public abstract Decorator CreateSimpleDecorator(ITemplateDefinition templateDefinition, string callbackName);
        private BindingDefinitionDescription(ITemplateDefinition templateDefinition, string bindingExpression, bool isConst, List <string> options)
        {
            BindingExpression = bindingExpression;
            IsConst           = isConst;
            if (options != null)
            {
                IsReadOnly = options.Contains("R");
                options.Remove("R");

                if (options.Count > 0)
                {
                    foreach (string option in options)
                    {
                        // Formula
                        if (option.StartsWith("F="))
                        {
                            Formula = option.Substring(2);
                            continue;
                        }

                        // Description
                        if (option.StartsWith("D="))
                        {
                            Description = option.Substring(2);
                            continue;
                        }
                        // Name
                        if (option.StartsWith("N="))
                        {
                            Name = option.Substring(2);
                            continue;
                        }
                        // Decorator
                        if (option.StartsWith("DEC="))
                        {
                            string decoratorIdent = option.Substring(4);
                            Decorator = DecoratorsManager.GetDecorator(decoratorIdent);
                            continue;
                        }
                        // Decorator 2
                        if (option.StartsWith("DEC2="))
                        {
                            string decoratorDescription = option.Substring(5);
                            Decorator = DecoratorsManager.CreateSimpleDecorator(templateDefinition, decoratorDescription);
                            continue;
                        }
                        // On Selection
                        if (option.StartsWith("S="))
                        {
                            string methodInfoName = option.Substring(2);
                            OnSelection = RetrieveMethodInfo(templateDefinition, option, methodInfoName);
                            continue;
                        }
                        // On double left click
                        if (option.StartsWith("LDC="))
                        {
                            string methodInfoName = option.Substring(4);
                            OnLeftDoubleClick = RetrieveMethodInfo(templateDefinition, option, methodInfoName);
                            continue;
                        }
                        // MultiLine based on the number of line passed as parameter
                        if (option.StartsWith("M="))
                        {
                            IsMultiLine = true;
                            string factor = option.Substring(2);
                            double multiLineFactor;
                            if (!string.IsNullOrEmpty(factor) && double.TryParse(factor, out multiLineFactor))
                            {
                                MultiLineFactor = multiLineFactor;
                            }
                            else
                            {
                                MultiLineFactor = 1.5;
                            }
                            continue;
                        }
                        // MultiLine where the number of line is determinated by a callback invocation
                        if (option.StartsWith("ME="))
                        {
                            string methodInfoName = option.Substring(3);
                            if (!string.IsNullOrEmpty(methodInfoName))
                            {
                                try
                                {
                                    MultiLineFactorResolver = RetrieveMethodInfo(templateDefinition, null, methodInfoName);
                                    if (MultiLineFactorResolver != null)
                                    {
                                        if (!MultiLineFactorResolver.IsNotDotNet)
                                        {
                                            int parametersCpt = MultiLineFactorResolver.Callback.GetParameters().Length;
                                            if (MultiLineFactorResolver.Callback.ReturnType != typeof(int) || parametersCpt > 1 || (parametersCpt == 1 && !(MultiLineFactorResolver.Callback.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(object)))))
                                            {
                                                throw new Exception("The function prototype must be defined as 'int <Function Name>([param]) with 'param' inheriting from 'system.object'");
                                            }
                                        }
                                        IsMultiLine = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception($"Cannot resolve the 'ME' attribute for the binding definition '{bindingExpression}'", ex);
                                }
                            }
                        }
                        // On double left click, Show/Hide the x following/preceding colums/rows. Start hidden
                        if (option.StartsWith("SH_COL_S="))
                        {
                            string numberOfConcernedColumns = option.Substring(9);
                            int    wrk;
                            if (!string.IsNullOrEmpty(numberOfConcernedColumns) && int.TryParse(numberOfConcernedColumns, out wrk))
                            {
                                SpecificEventCallback callback      = EventCallbacksManager.GetRegisteredCallback("ETK_ShowHideColumns") as SpecificEventCallback;
                                SpecificEventCallback callbackToUse = new SpecificEventCallback(callback);
                                callbackToUse.Parameters = new[] { new SpecificEventCallbackParameter {
                                                                       IsSender = true
                                                                   },
                                                                   new SpecificEventCallbackParameter {
                                                                       ParameterValue = wrk
                                                                   } };
                                OnLeftDoubleClick = callbackToUse;
                                continue;
                            }
                            throw new Exception("The 'Show/Hide' prototype must be defined as 'SH_COL_S=<int>' where '<int>' is a integer");
                        }
                        // On double left click, Show/Hide the x following/preceding colums/rows. Start shown
                        if (option.StartsWith("SH_COL_H="))
                        {
                            string numberOfConcernedColumns = option.Substring(9);
                            int    wrk;
                            if (!string.IsNullOrEmpty(numberOfConcernedColumns) && int.TryParse(numberOfConcernedColumns, out wrk))
                            {
                                SpecificEventCallback callback      = EventCallbacksManager.GetRegisteredCallback("ETK_ShowHideColumns") as SpecificEventCallback;
                                SpecificEventCallback callbackToUse = new SpecificEventCallback(callback);
                                callbackToUse.Parameters = new[] { new SpecificEventCallbackParameter {
                                                                       IsSender = true
                                                                   },
                                                                   new SpecificEventCallbackParameter {
                                                                       ParameterValue = wrk
                                                                   } };
                                OnLeftDoubleClick = callbackToUse;
                                OnAfterRendering  = callbackToUse;
                                continue;
                            }
                            throw new Exception("The 'Show/Hide' columns prototype must be defined as 'SH_COL_H==<int>' where '<int>' is a integer");
                        }
                    }
                }
            }
        }
        public static BindingDefinitionDescription CreateBindingDescription(ITemplateDefinition templateDefinition, string toAnalyze, string trimmedToAnalyze)
        {
            BindingDefinitionDescription ret = null;
            List <string> options            = null;

            if (!string.IsNullOrEmpty(trimmedToAnalyze))
            {
                string bindingExpression;
                bool   isConstante = false;
                // Constante
                if (!trimmedToAnalyze.StartsWith("{") || trimmedToAnalyze.StartsWith("["))
                {
                    isConstante = true;
                    if (trimmedToAnalyze.StartsWith("["))
                    {
                        if (!trimmedToAnalyze.EndsWith("]"))
                        {
                            throw new BindingTemplateException($"Cannot create constante BindingDefinition from '{toAnalyze}': cannot find the closing ']'");
                        }
                        bindingExpression = trimmedToAnalyze.Substring(1, trimmedToAnalyze.Length - 2);

                        int postSep = bindingExpression.LastIndexOf("::");
                        if (postSep != -1)
                        {
                            string   optionsString = bindingExpression.Substring(0, postSep);
                            string[] optionsArray  = optionsString.Split(';');
                            options           = optionsArray.Where(p => !string.IsNullOrEmpty(p)).Select(p => p.Trim()).ToList();
                            bindingExpression = bindingExpression.Substring(postSep + 2);
                        }
                    }
                    else
                    {
                        bindingExpression = toAnalyze;
                    }
                }
                // No Constante
                else
                {
                    if (!trimmedToAnalyze.EndsWith("}"))
                    {
                        throw new BindingTemplateException($"Cannot create BindingDefinition from '{toAnalyze}': cannot find the closing '}}'");
                    }
                    bindingExpression = trimmedToAnalyze.Substring(1, trimmedToAnalyze.Length - 2);

                    int postSep = bindingExpression.LastIndexOf("::");
                    if (postSep != -1)
                    {
                        string   optionsString = bindingExpression.Substring(0, postSep);
                        string[] optionsArray  = optionsString.Split(';');
                        options           = optionsArray.Where(p => !string.IsNullOrEmpty(p)).Select(p => p.Trim()).ToList();
                        bindingExpression = bindingExpression.Substring(postSep + 2);
                    }
                    else if (bindingExpression.StartsWith("=")) // USe for Formula not bind with the model
                    {
                        options           = new List <string>(new [] { "F" + bindingExpression });
                        bindingExpression = string.Empty;
                    }
                }

                ret = new BindingDefinitionDescription(templateDefinition, bindingExpression, isConstante, options);
            }
            return(ret);
        }
        private void ParseMustache(ITemplateDefinition template, string text)
        {
            var matches = _mustacheRegex.Matches(text);

            if (matches == null || matches.Count == 0)
            {
                template.AddHtml(text);
                return;
            }

            var types = new Dictionary <string, Type>(StringComparer.InvariantCultureIgnoreCase);

            var pos            = 0;
            var startOfContent = false;
            var matchIndex     = 0;

            while (!startOfContent)
            {
                if (char.IsWhiteSpace(text[pos]))
                {
                    pos++;
                }
                else if (matches.Count > matchIndex && pos == matches[matchIndex].Index)
                {
                    pos = matches[matchIndex].Index + matches[matchIndex].Length;
                    matchIndex++;
                }
                else
                {
                    startOfContent = true;
                }
            }

            foreach (Match match in matches)
            {
                if (match.Index > pos)
                {
                    template.AddHtml(text.Substring(pos, match.Index - pos));
                }

                if (pos <= match.Index)
                {
                    pos = match.Index + match.Length;
                }

                var mustache = match.Groups[1].Value.Replace(" ", "");

                if (TryParseAlias(mustache, types))
                {
                    continue;
                }
                if (TryParseStartRepeat(mustache, template, types))
                {
                    continue;
                }
                if (TryParseEndRepeat(mustache, template, types))
                {
                    continue;
                }
                if (TryParseField(mustache, template, types))
                {
                    continue;
                }
            }

            if (pos < text.Length)
            {
                template.AddHtml(text.Substring(pos));
            }
        }
示例#30
0
        public BindingContext(IBindingContextElement parent, ITemplateView owner, ITemplateDefinition templateDefinition, object dataSource, List <IFilterDefinition> templatedFilters)
        {
            try
            {
                if (owner == null)
                {
                    throw new ArgumentNullException("The parameter 'owner' cannot be null");
                }
                if (templateDefinition == null)
                {
                    throw new ArgumentNullException("The parameter 'templateDefinition' cannot be null");
                }

                Owner = owner;
                TemplateDefinition = templateDefinition;
                TemplatedFilters   = templatedFilters;
                IsExpanded         = TemplateDefinition.TemplateOption.HeaderAsExpander != HeaderAsExpander.StartClosed;

                //TemplatedSortsAndFilters = templatedSortsAndFilters;
                Parent     = parent;
                DataSource = dataSource;

                if (DataSource != null)
                {
                    List <object>      dataSourceAsList;
                    IBindingDefinition dataSourceType;
                    if (DataSource is IEnumerable)
                    {
                        dataSourceAsList = (DataSource as IEnumerable).Cast <object>().ToList();
                        dataSourceType   = BindingDefinitionRoot.CreateInstance(dataSourceAsList.GetType());
                    }
                    else
                    {
                        dataSourceAsList = new List <object>();
                        dataSourceAsList.Add(DataSource); //new object[] { DataSource };
                        dataSourceType = BindingDefinitionRoot.CreateInstance(DataSource.GetType());
                    }

                    if (TemplateDefinition.MainBindingDefinition != null)
                    {
                        CheckType(TemplateDefinition.MainBindingDefinition, dataSourceType);
                    }

                    ISortersAndFilters externalSortersAndFilters = null;
                    owner.ExternalSortersAndFilters?.TryGetValue(TemplateDefinition, out externalSortersAndFilters);

                    //Occurrences = dataSourceAsList.Count;
                    if (TemplateDefinition.Body != null)
                    {
                        IEnumerable <IFilterDefinition> templatedFiltersToTakeIntoAccount = null;
                        if (templatedFilters != null)
                        {
                            IEnumerable <IFilterDefinition> templatedFiltersToTakeIntoAccountFound = templatedFilters.Where(tf => tf.TemplateDefinition == templateDefinition);
                            if (templatedFiltersToTakeIntoAccountFound.Any())
                            {
                                templatedFiltersToTakeIntoAccount = templatedFiltersToTakeIntoAccountFound;
                            }
                        }

                        ISorterDefinition[] sortersDefinition = null;
                        if (((TemplateView)owner).SorterDefinition != null && ((TemplateView)owner).SorterDefinition.TemplateDefinition == templateDefinition)
                        {
                            sortersDefinition = new ISorterDefinition[] { ((TemplateView)owner).SorterDefinition }
                        }
                        ;

                        ISortersAndFilters sortersAndFilters = null;
                        if (templatedFilters != null || sortersDefinition != null)
                        {
                            sortersAndFilters = SortersAndFilterersFactory.CreateInstance(templateDefinition, templatedFiltersToTakeIntoAccount, sortersDefinition);
                        }
                        Body = BindingContextPart.CreateBodyBindingContextPart(this, TemplateDefinition.Body, dataSourceAsList, externalSortersAndFilters, sortersAndFilters);
                    }

                    if (TemplateDefinition.Header != null)
                    {
                        Header = BindingContextPart.CreateHeaderOrFooterBindingContextPart(this, TemplateDefinition.Header, BindingContextPartType.Header, DataSource);
                    }
                    if (TemplateDefinition.Footer != null)
                    {
                        Footer = BindingContextPart.CreateHeaderOrFooterBindingContextPart(this, TemplateDefinition.Footer, BindingContextPartType.Header, DataSource);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = $"Create the 'BindingContext' for template '{(templateDefinition == null ? string.Empty : templateDefinition.Name)}' failed . {ex.Message}";
                throw new EtkException(message);
            }
        }