コード例 #1
0
        static async Task <object> LoadCodeLookupDictRows(AsyncExprCtx ae, IList args)
        {
            var conn = (IDbConn)await OPs.ConstValueOf(ae, args[0]);

            var table = Convert.ToString(await OPs.ConstValueOf(ae, args[1])).Replace(' ', '_').Replace(',', '_');
            var query = $"SELECT {nameof(LookupEntry.Code)}, {nameof(LookupEntry.Description)}, {nameof(LookupEntry.ReplacedWith_Code)} FROM {table}";
            var cmd   = new SqlCommandData()
            {
                Kind = CommandKind.Query, SqlText = query, ConvertMultiResultsToLists = false
            };
            var rows = (IIndexedDict[])await conn.ExecCmd(cmd, ae.Cancellation);

            var dict = new Dictionary <string, LookupEntry>(rows.Length);

            foreach (var r in rows)
            {
                var entry = new LookupEntry()
                {
                    Code              = r.ValuesList[0].ToString(),
                    Description       = Convert.ToString(r.ValuesList[1]),
                    ReplacedWith_Code = Convert.ToString(r.ValuesList[2]),
                };
                dict.Add(entry.Code, entry);
            }
            // incapsulate into tuple to mask IList interface
            return(Tuple.Create(dict));
        }
コード例 #2
0
ファイル: Impl.cs プロジェクト: WVitek/DotGlue
 private static Fn FuncRawIntervalQuery(QueryTemplate qt)
 {
     return((IList args) =>
     {
         return (LazyAsync)(async ctx =>
         {
             var begTime = OPs.FromExcelDate(Convert.ToDouble(args[1]));
             var endTime = OPs.FromExcelDate(Convert.ToDouble(args[2]));
             var conn = (IDbConn)await ctx.GetValue(qt.connName);
             var mq = qt.GetQuery(new object[] { args[0] }
                                  , conn.dbms.TimeToSqlText(begTime)
                                  , conn.dbms.TimeToSqlText(endTime)
                                  );
             if (mq == null)
             {
                 return ValuesDictionary.Empties;
             }
             var cmd = new SqlCommandData()
             {
                 Kind = CommandKind.Query,
                 ConvertMultiResultsToLists = qt.arrayResults
             };
             using (mq)
             {
                 cmd.SqlText = mq.QueryText;
                 var res = await conn.ExecCmd(cmd, ctx.Cancellation);
                 if (((IList)res).Count == 0)
                 {
                     res = ValuesDictionary.Empties;
                 }
                 return res;
             }
         });
     });
 }
コード例 #3
0
        public static async Task <object> _ReportRow(AsyncExprCtx ae, IList args)
        {
            // get/calculate values
            var lstVals = (IList)await OPs.VectorValueOf(ae, args[3]);

            int n    = lstVals.Count;
            var vals = new object[n];

            for (int i = n - 1; i >= 0; i--)
            {
                try { vals[i] = await OPs.ConstValueOf(ae, lstVals[i]); }
                catch (TaskCanceledException) { throw; }
            }
コード例 #4
0
        public static object LookupHelperFuncs(CallExpr ce, Generator.Ctx ctx)
        {
            var dbConn     = ce.args[0];
            var dbConnName = OPs.TryAsName(dbConn, ctx);

            if (dbConnName == null)
            {
                throw new Generator.Exception($"Can't get DB connection name: {dbConn}");
            }

            var pairs = ctx.GetConstant(ce.args[1]) as IList;

            if (pairs == null)
            {
                throw new Generator.Exception($"Can't interpet as array of constants: {ce.args[1]}");
            }
            if (pairs.Count % 2 != 0)
            {
                throw new Generator.Exception($"Items count must be even (cause it must be array of pairs): {ce.args[1]}");
            }

            var location = Convert.ToString(ctx.GetConstant(ce.args[2]));

            var defs = new List <FuncDef>(pairs.Count / 2);

            for (int i = 0; i < pairs.Count; i += 2)
            {
                var dbTableName = pairs[i].ToString();
                var substance   = pairs[i + 1].ToString();

                // Dictionary loader func
                defs.Add(FuncDefs_Core.macroFuncImpl(ctx,
                                                     // name
                                                     new ConstExpr($"{dbConnName}:{dbTableName}_LoadDict"),
                                                     // inputs
                                                     new ArrayExpr(),
                                                     // outputs
                                                     new ArrayExpr(new ConstExpr($"{substance}_DICT_{location}")),
                                                     // body
                                                     new CallExpr(LoadCodeLookupDictRows, dbConn, new ConstExpr(dbTableName)),
                                                     //
                                                     null, false
                                                     ));
            }



            return(defs);
        }
コード例 #5
0
        public static async Task <object> WRptGetXmlWriter(AsyncExprCtx ae, IList args)
        {
            var outputFiles = (IWriteFiles)await OPs.ConstValueOf(ae, args[0]);

            var parts = new string[args.Count - 1];

            for (int i = args.Count - 1; i >= 1; i--)
            {
                parts[i - 1] = Convert.ToString(await OPs.ConstValueOf(ae, args[i]));
            }
            var stream = await outputFiles.CreateFile(Path.Combine(parts), ae.Cancellation);

            var writer = new XmlTextWriter(stream, Encoding.UTF8);

            return(writer);
        }
コード例 #6
0
        public static object COLUMN(CallExpr ce, Generator.Ctx ctx)
        {
            var cellName = OPs.TryAsName(ce.args[0], ctx);

            if (cellName == null)
            {
                throw new Generator.Exception($"COLUMN(cellName): can't get cell name from expession // {ce.args[0]}");
            }
            int i = 0;

            if (CellRange.ParseCellName(cellName, ref i, cellName.Length, out int row, out int col))
            {
                return(col);
            }
            throw new Generator.Exception($"COLUMN(cellName): can't parse given cell name // {cellName}");
        }
コード例 #7
0
ファイル: Impl.cs プロジェクト: WVitek/DotGlue
 private static Fn FuncTimedSliceQuery(TimeSpan actuality, QueryTemplate qt)
 {
     return((IList args) =>
     {
         return (LazyAsync)(async ctx =>
         {
             var lst = args[0] as IList;
             if (lst != null && lst.Count == 0)
             {
                 return lst;
             }
             bool range = args.Count > 2;
             var begTime = OPs.FromExcelDate(Convert.ToDouble(range ? args[2] : args[1]));
             var minTime = range ? OPs.FromExcelDate(Convert.ToDouble(args[1])) : begTime - actuality;
             var conn = (IDbConn)await ctx.GetValue(qt.connName);
             var mq = qt.GetQuery(new object[] { args[0] }, conn.dbms.TimeToSqlText(minTime), conn.dbms.TimeToSqlText(begTime));
             if (mq == null)
             {
                 return ValuesDictionary.Empties;
             }
             var cmd = new SqlCommandData()
             {
                 Kind = CommandKind.Query,
                 ConvertMultiResultsToLists = qt.arrayResults
             };
             using (mq)
             {
                 cmd.SqlText = mq.QueryText;
                 var res = await conn.ExecCmd(cmd, ctx.Cancellation);
                 if (((IList)res).Count == 0)
                 {
                     res = ValuesDictionary.Empties;
                 }
                 return res;
             }
         });
     });
 }
コード例 #8
0
        static void Main(string[] args)
        {
            OPs.Add("^");
            OPs.Add("*");
            OPs.Add("/");
            OPs.Add("+");
            OPs.Add("-");
            Console.Write(">>>");
            string str = Console.ReadLine();

            while (str != "exit")
            {
                if (str.Contains("clear function "))
                {
                    string funcName = str.Substring("clear function ".Length);
                    if (func_dic.ContainsKey(funcName))
                    {
                        func_dic.Remove(funcName);
                        Console.WriteLine("function[" + funcName + "] cleared");
                    }
                    else
                    {
                        Console.WriteLine("not found");
                    }
                    Console.Write(">>>");
                    str = Console.ReadLine();
                }

                string res = Calculator(str);
                if (res != "None")
                {
                    Console.WriteLine(res);
                }
                Console.Write(">>>");
                str = Console.ReadLine();
            }
        }
コード例 #9
0
        /// <summary>
        /// Iterative topological sorting of expressions (ability of calculated values names is taked into account)
        /// </summary>
        /// <param name="srcItems"></param>
        /// <param name="parentCtx"></param>
        /// <returns></returns>
        public static IEnumerable <Expr> DoSort2(IEnumerable <Expr> srcItems, Generator.Ctx parentCtx)
        {
            var items = new List <Expr>(srcItems);

            var mh      = new ModifyHelper();
            var allLets = new Dictionary <string, Expr>();

            while (true)
            {
                mh.ctx = new Generator.Ctx(parentCtx);
                mh.ctx.CreateValue(FuncDefs_Core.stateTryGetConst, string.Empty);

                for (int i = 0; i < items.Count; i++)
                {
                    var item = items[i];
                    item     = mh.modify(item);
                    items[i] = item;
                    foreach (var letName in mh.lets)
                    {
                        allLets[letName] = item;
                        //mh.ctx.CreateValue(letName);
                    }
                    mh.lets.Clear();
                }

                {
                    var values = mh.ctx.values;
                    var lets   = new List <Expr>();
                    foreach (var p in mh.ctx.name2ndx)
                    {
                        if (p.Value == 0)
                        {
                            continue;
                        }
                        var v = values[p.Value];
                        if (v == null || allLets.ContainsKey(p.Key) || OPs.KindOf(v) != ValueKind.Const)
                        {
                            continue;
                        }
                        var le = CallExpr.let(new ReferenceExpr(p.Key), new ConstExpr(v));
                        allLets.Add(p.Key, le);
                        lets.Add(le);
                    }
                    if (lets.Count > 0)
                    {
                        items.InsertRange(0, lets);
                    }
                }

                if (!mh.thereIsNameResolve && !mh.thereIsNonresolved)
                {
                    break;
                }

                mh.thereIsNonresolved = mh.thereIsNameResolve = false;

                items = TopoSort.DoSort(items,
                                        e => EnumRefs(e)
                                        .Where(s => s != null && allLets.ContainsKey(s))
                                        .Select(s => allLets[s])
                                        );

                allLets.Clear();
            }

            return(items);
        }
コード例 #10
0
            public ModifyHelper()
            {
                modify = Expr.RecursiveModifier(e =>
                {
                    if (e.nodeType == ExprType.Reference || e.nodeType == ExprType.Constant)
                    {
                        return(e);
                    }
                    if (e.nodeType != ExprType.Call)
                    {
                        goto tryConst;
                    }
                    var ce     = (CallExpr)e;
                    bool isLet = ce.funcName == "let";
                    bool isDef = isLet || ce.funcName == "SV" || ce.funcName == "SSV";
                    if (!isDef && ce.funcName != "GV" && ce.funcName != "GSV")
                    {
                        goto tryConst;
                    }
                    var arg0 = ce.args[0];
                    string name;
                    if (arg0.nodeType == ExprType.Constant)
                    {
                        name = Convert.ToString((arg0 as ConstExpr).value);
                        if (!isLet && ce.args.Count == 1)
                        {
                            e = new ReferenceExpr(name);
                        }
                        goto constResolved;
                    }
                    if (arg0.nodeType == ExprType.Reference)
                    {
                        name = (arg0 as ReferenceExpr).name;
                        goto nameResolved;
                    }
                    // try to resolve name
                    var nameObj = TryGen(ctx, arg0);
                    if (nameObj == Fail || OPs.KindOf(nameObj) != ValueKind.Const)
                    {
                        thereIsNonresolved = true;
                        return(e);
                    }
                    name = Convert.ToString(nameObj);
                    thereIsNameResolve = true;
                    constResolved:
                    var args = new Expr[ce.args.Count];
                    if (isLet)
                    {
                        args[0] = new ReferenceExpr(name);
                    }
                    else
                    {
                        if (ce.args.Count == 1 && ce.funcName != "GSV")
                        {
                            return(new ReferenceExpr(name));
                        }
                        args[0] = new ConstExpr(name);
                    }
                    for (int i = 1; i < args.Length; i++)
                    {
                        args[i] = modify(ce.args[i]);
                    }
                    e = new CallExpr(ce.funcName, args);
                    nameResolved:
                    if (isDef && ce.args.Count == 2)
                    {
                        lets.Add(name);
                        //var value = modify(ce.args[1]);
                        //if (value.nodeType == ExprType.Constant)
                        //{ }
                    }
                    return(e);

                    tryConst:
                    var val = TryGen(ctx, e);
                    if (val == Fail || OPs.KindOf(val) != ValueKind.Const)
                    {
                        return(e);
                    }
                    return(new ConstExpr(val));
                });
            }
コード例 #11
0
        /// <summary>
        /// Iterative topological sorting of expressions (ability of calculated values names is taked into account)
        /// </summary>
        /// <param name="srcItems"></param>
        /// <param name="parentCtx"></param>
        /// <returns></returns>
        public static IEnumerable <Expr> DoSort(IEnumerable <Expr> srcItems, Generator.Ctx parentCtx)
        {
            List <ItemInfo> infos = srcItems.Select(item => new ItemInfo(item)).ToList();

            while (true)
            {
                //****** sort items with defined names
                var allLets = new Dictionary <string, ItemInfo>();

                foreach (var nfo in infos)
                {
                    foreach (var name in nfo.lets.Keys)
                    {
                        allLets[name] = nfo;
                    }
                }

                infos = TopoSort.DoSort(infos, ii => ii.refs.Keys.Where(s => allLets.ContainsKey(s)).Select(s => allLets[s]));

                var thereIsNameResolve = false;
                var allNamesRosolved   = true;
                var ctx = new Generator.Ctx(parentCtx);

                //****** calculate unresolved names
                for (int i = 0; i < infos.Count; i++)
                {
                    var nfo = infos[i];
                    // side effect?: new values can be declared in context
                    var value = TryGen(ctx, nfo.expr);
                    var lets2 = nfo.lets2;
                    for (int j = 0; j < lets2.Count;)
                    {
                        var let2    = lets2[j];
                        var letName = TryGen(ctx, let2);
                        if (letName != Fail && OPs.KindOf(letName) == ValueKind.Const)
                        {
                            thereIsNameResolve = true;
                            lets2.RemoveAt(j);
                            nfo.lets[Convert.ToString(letName)] = true;
                        }
                        else
                        {
                            j++; allNamesRosolved = false;
                        }
                    }
                    var refs2 = nfo.refs2;
                    for (int j = 0; j < refs2.Count;)
                    {
                        var ref2    = refs2[j];
                        var refName = TryGen(ctx, ref2);
                        if (refName != Fail && OPs.KindOf(refName) == ValueKind.Const)
                        {
                            thereIsNameResolve = true;
                            refs2.RemoveAt(j);
                            nfo.refs[Convert.ToString(refName)] = true;
                        }
                        else
                        {
                            j++; allNamesRosolved = false;
                        }
                    }
                    if (nfo.refs.Keys.Any(s => ctx.IndexOf(s) < 0))
                    {
                        allNamesRosolved = false;
                    }
                }

                if (allNamesRosolved || !thereIsNameResolve)
                {
                    break;
                }
            }
            return(infos.Select(ii => ii.expr));
        }
コード例 #12
0
            Expr SpecFuncs(CallExpr ce)
            {
                Expr src, ndx;
                bool forPrev = false, forCell = false;
                int  nMinArgs = 1;

                switch (ce.funcName)
                {
                case "PREVCELL":
                    forCell = true; forPrev = true; break;

                case "PREV":
                    nMinArgs = 0; forPrev = true; break;

                case "INDIRECT":
                    forCell = true; break;

                case nameof(FuncDefs_Xlsx.COLUMN):
                    // avoid COLUMN(args) fixing
                    return(new CallExpr(nameof(FuncDefs_Xlsx.COLUMN), ce.args));

                default:
                    return(ce);
                }
                if (ce.args.Count < nMinArgs)
                {
                    return(ce);
                }

                Expr   arg;
                string name;

                if (ce.args.Count == 0)
                {
                    arg  = null;
                    name = FCurrName;
                }
                else
                {
                    arg = ce.args[0];
                    if (arg.nodeType == ExprType.Reference)
                    {
                        name = ((ReferenceExpr)arg).name;
                        if (IsColumnName(name) || !forPrev && IsFullRelativeCell(CellRange.FromName(name)))
                        {
                            forCell = true;
                        }
                        else
                        {
                            name = OPs.TryAsString(arg, ctxRow) ?? name;
                        }
                    }
                    else
                    {
                        arg  = FixRowExpr(arg);
                        name = OPs.TryAsName(arg, ctxRow);
                    }
                }

                if (name == null)
                {
                    var undefs = string.Join(", ", ctxHdr.NamesOfUndefinedValues().Concat(ctxRow.NamesOfUndefinedValues()));
                    throw new Source.Exception($"Constant expected as value of {ce.args[0]}={arg} // ??? {undefs}");
                }

                if (forCell || IsColumnName(name) || !forPrev && IsFullRelativeCell(CellRange.FromName(name)))
                {
                    if (forPrev)
                    {
                        src = new IndexExpr(PrevValsRef, new ConstExpr(ctxRow.IndexOf(CellValsRef.name)));
                    }
                    else
                    {
                        var re1 = new ReferenceExpr(name);
                        var re2 = FixHdrCellRef(re1);
                        if (re2 != re1)
                        {
                            // ref to header cell
                            return(re2);
                        }
                        else
                        {
                            // ref to row cell
                            src = CellValsRef;
                        }
                    }
                    ndx = new ConstExpr(name);
                }
                else
                {
                    int i = ctxRow.IndexOf(name);
                    if (i < 0 || Generator.Ctx.ctxDepthStep <= i)
                    {
                        throw new Source.Exception($"Value named '{name}' not found in row context");
                    }
                    src = PrevValsRef;
                    ndx = new ConstExpr(i);
                }
                return(new IndexExpr(src, ndx));
            }
コード例 #13
0
            public static IEnumerable <Metadata> Create(TextReader txt, Generator.Ctx ctxParent)
            {
                var       exprsHdr      = new List <NE>();
                var       exprsRow      = new List <NE>();
                List <NE> exprsRes      = null;
                string    tmplParamName = null;

                bool withFileContentKind   = false;
                bool withFileNameExtension = false;

                foreach (var(Section, Key, Value) in Ini.Read(txt, true))
                {
                    var       expr     = Parser.ParseToExpr(Value);
                    List <NE> exprsLst = null;
                    switch (Section)
                    {
                    case sHdr:
                        if (Key.StartsWith(sTemplateParameterValuesPrefix))
                        {
                            if (tmplParamName != null)
                            {
                                throw new Exception($"Template parameter already defined as '{tmplParamName}'");
                            }
                            tmplParamName = Key;
                        }
                        else
                        {
                            switch (Key)
                            {
                            case sFileContentKind: withFileContentKind = true; break;

                            case sFileNameExtension: withFileNameExtension = true; break;
                            }
                        }
                        exprsLst = exprsHdr;
                        break;

                    case sRow:
                        exprsLst = exprsRow; break;

                    case sRes:
                        if (exprsRes == null)
                        {
                            exprsRes = new List <NE>();
                        }
                        exprsLst = exprsRes;
                        break;

                    default:
                        throw new Exception($"Unknown section '{Section}' in source metadata. Expected '{sHdr}' or '{sRow}' sections.");
                    }
                    exprsLst.Add(new NE(Key ?? $".{exprsLst.Count}", expr));
                }

                if (withFileContentKind && !withFileNameExtension)
                {
                    throw new Exception($"{ctxParent.GetConstant(sMetadataFile)} : specified FileContentKind also requires FileNameExtension specification");
                }


                if (tmplParamName != null)
                {
                    var    ctx      = new Generator.Ctx(ctxParent);
                    object tmplVals = null;
                    Expr   tmplExpr = null;
                    for (int i = 0; i < exprsHdr.Count; i++)
                    {
                        var p   = exprsHdr[i];
                        var val = Generator.Generate(p.expr, ctx);
                        if (p.name == tmplParamName)
                        {
                            tmplVals = val;
                            exprsHdr.RemoveAt(i);
                            break;
                        }
                        ctx.CreateValue(p.name, val);
                    }
                    var tmplParamVals = tmplVals as IList;
                    if (OPs.KindOf(tmplVals) != ValueKind.Const || tmplParamVals == null)
                    {
                        throw new Exception($"Can't interpret template parameter as list of constants //{tmplParamName}={tmplExpr}={tmplVals}");
                    }
                    tmplParamName = tmplParamName.Substring(sTemplateParameterValuesPrefix.Length);
                    foreach (var tmplVal in tmplParamVals)
                    {
                        exprsHdr.Insert(0, new NE(tmplParamName, new ConstExpr(tmplVal)));
                        yield return(new Metadata(exprsHdr, exprsRow, exprsRes, ctxParent));

                        exprsHdr.RemoveAt(0);
                    }
                }
                else
                {
                    yield return(new Metadata(exprsHdr, exprsRow, exprsRes, ctxParent));
                }
            }
コード例 #14
0
            private Metadata(IEnumerable <NE> exprsHdr, IEnumerable <NE> exprsRow, IEnumerable <NE> exprsRes, Generator.Ctx parentCtx)
            {
                var sb = new StringBuilder();

                FixSheetExpr = Expr.RecursiveModifier(FixSheetImpl);
                FixRowExpr   = Expr.RecursiveModifier(FixRowImpl);

                #region generate header code
                ctxHdr = new Generator.Ctx(parentCtx);
                ctxHdr.CreateValue(HdrCellsRef.name, Generator.LazyDummy);
                ctxHdr.CreateValue(PrevValsRef.name, Generator.LazyDummy);

                foreach (var p in exprsHdr)
                {
                    FCurrName = p.name;
                    var expr = FixSheetExpr(p.expr);
                    var val  = Generator.Generate(expr, ctxHdr);
                    ctxHdr.CreateValue(p.name, val);
                    if (OPs.KindOf(val) == ValueKind.Const)
                    {
                        expr = new ConstExpr(val);
                    }
                    sb.AppendLine($"{p.name} = {expr}");
                }
                sb.AppendLine();

                RequiredInHdr(sSourceKey);
                RequiredInHdr(sSourceName);
                RequiredInHdr(sCondition);
                RequiredInHdr(sFirstDataRowNum);

                {
                    if (ctxHdr.name2ndx.TryGetValue(sFileContentKind, out int i))
                    {
                        FileContentKind = Convert.ToString(ctxHdr.GetConstant(sFileContentKind));
                    }
                    else
                    {
                        FileContentKind = "XLSX";
                    }
                }
                {
                    if (ctxHdr.name2ndx.TryGetValue(sFileNameExtension, out int i))
                    {
                        var val = ctxHdr.GetConstant(sFileNameExtension);
                        FileNameExtension = Utils.AsIList(val).Cast <object>().Select(Convert.ToString).ToArray();
                    }
                    else
                    {
                        FileNameExtension = new string[] { "xls", "xlsx", "xlsm" }
                    };
                }
                #endregion

                #region generate row code
                ctxRow = new Generator.Ctx(ctxHdr);
                ctxRow.CreateValue(sDataKey, Generator.LazyDummy);         // [0] - iKey
                ctxRow.CreateValue(sDataSubkey, Generator.LazyDummy);      // [1] - iSubkey
                ctxRow.CreateValue(CellValsRef.name, Generator.LazyDummy); // [2] - iRowVals

                foreach (var p in exprsRow)
                {
                    string name;
                    if (p.name.StartsWith("~"))
                    {
                        // calculated name
                        name = OPs.TryAsString(Parser.ParseToExpr(p.name.Substring(1)), ctxHdr) ?? p.name;
                    }
                    else
                    {
                        name = p.name;
                    }
                    FCurrName = name;
                    int i    = ctxRow.GetOrCreateIndexOf(name);
                    var expr = FixRowExpr(p.expr);
                    var val  = Generator.Generate(expr, ctxRow);
                    ctxRow.values[i] = val;
                    if (OPs.KindOf(val) == ValueKind.Const)
                    {
                        expr = new ConstExpr(val);
                    }
                    sb.AppendLine($"{name} = {expr}");
                }

                RequiredInRow(sDataKey);
                RequiredInRow(sDataSubkey);

                ctxRow.values[iRowVals] = null;
                ctxRow.CheckUndefinedValues();

                #endregion

                #region generate res code
                if (exprsRes != null)
                {
                    // copy all code from row to res
                    ctxRes = new Generator.Ctx(ctxHdr);
                    foreach (var p in ctxRow.name2ndx.OrderBy(p => p.Value))
                    {
                        ctxRes.values[ctxRes.CreateValue(p.Key)] = ctxRow.values[p.Value];
                    }

                    foreach (var p in exprsRes)
                    {
                        string name;
                        if (p.name.StartsWith("~"))
                        {
                            // calculated name
                            name = OPs.TryAsString(Parser.ParseToExpr(p.name.Substring(1)), ctxHdr) ?? p.name;
                        }
                        else
                        {
                            name = p.name;
                        }
                        FCurrName = name;
                        int i    = ctxRes.GetOrCreateIndexOf(name);
                        var expr = FixRowExpr(p.expr);
                        var val  = Generator.Generate(expr, ctxRes);
                        ctxRes.values[i] = val;
                        if (OPs.KindOf(val) == ValueKind.Const)
                        {
                            expr = new ConstExpr(val);
                        }
                    }
                    ctxRes.values[iRowVals] = null;
                    ctxRes.CheckUndefinedValues();
                }
                #endregion

                ctxHdr[HdrCellsRef.name] = null;
                ctxHdr[PrevValsRef.name] = null;
                ctxHdr.CheckUndefinedValues();

                FCodeText = sb.ToString();

                if (iHdrMinUsedRow > iHdrMaxUsedRow)
                {
                    iHdrMinUsedRow = iHdrMaxUsedRow;
                }
            }
コード例 #15
0
        public static async Task <object> _ReportSheet(AsyncExprCtx ae, IList args)
        {
            using (var wr = (XmlWriter)await OPs.ConstValueOf(ae, args[0]))
            {
                var xmls = (IEnumerable <Xlsx.XmlItem>) await OPs.ConstValueOf(ae, args[1]);

                wr.WriteStartDocument();
                object result = string.Empty;

                foreach (var xml in xmls)
                {
                    xml.WriteStartElementAndAttrs(wr);

                    var xmlSheetData = new Xlsx.XmlItem();
                    {   // write xml before "sheetData"
                        bool stop = false;
                        xml.Traverse(x =>
                        {
                            if (stop)
                            {
                                return;
                            }
                            if (x.Name != "sheetData")
                            {
                                if (x.Name == "dimension")
                                {
                                    return;
                                }
                                x.WritePart(wr);
                                return;
                            }
                            x.WriteStartElementAndAttrs(wr);
                            xmlSheetData = x;
                            stop         = true;
                        });
                    }
                    if (xmlSheetData.IsEmpty)
                    {
                        continue; // no sheet data
                    }
                    // write sheet data (rows)
                    for (int i = 2; i < args.Count; i++)
                    {
                        result = await OPs.ConstValueOf(ae, args[i]);

                        //Console.WriteLine(res); // debug
                    }

                    {   // write xml after "sheetData"
                        bool skip = true;
                        xml.Traverse(x =>
                        {
                            if (!skip)
                            {
                                x.WritePart(wr); return;
                            }
                            else if (x.Name == "sheetData")
                            {
                                skip = false;
                                wr.WriteEndElement();
                            }
                        });
                    }
                    wr.WriteEndElement();
                }
                wr.WriteEndDocument();
                return(result);
            }
        }
コード例 #16
0
ファイル: SearchPositionQuery.cs プロジェクト: BionStt/NHCM
        public async Task <List <SearchedPosition> > Handle(SearchPositionQuery request, CancellationToken cancellationToken)
        {
            List <SearchedPosition>    result       = new List <SearchedPosition>();
            List <SearchedOrgPosition> OrgPositions = await _mediator.Send(new SearchOrgPositionQuery()
            {
            }).ConfigureAwait(false);

            if (request.Id != null)
            {
                result = await(from p in _context.Position
                               join w in _context.WorkArea on p.WorkingAreaId equals w.Id into pw
                               from rpw in pw.DefaultIfEmpty()
                               join OP in OrgPositions on p.PositionTypeId equals OP.Id into OPs
                               from rops in OPs.DefaultIfEmpty()
                               join ST in _context.SalaryType on p.SalaryTypeId equals ST.Id into STs
                               from str in STs.DefaultIfEmpty()
                               join L in _context.Location on p.LocationId equals L.Id into Ls
                               from Lr in Ls.DefaultIfEmpty()
                               join PT in _context.PlanType on p.PlanTypeId equals PT.Id into PTs
                               from PTr in PTs.DefaultIfEmpty()
                               where p.Id == request.Id
                               select new SearchedPosition
                {
                    Id               = p.Id,
                    ParentId         = p.ParentId,
                    NodeId           = Convert.ToInt32(p.Id),
                    ParentNodeId     = Convert.ToInt32(p.ParentId),
                    WorkingAreaId    = p.WorkingAreaId,
                    Code             = p.Code,
                    PositionTypeId   = p.PositionTypeId,
                    LocationId       = p.LocationId,
                    SalaryTypeId     = p.SalaryTypeId,
                    Sorter           = p.Sorter,
                    OrganoGramId     = p.OrganoGramId,
                    PlanTypeId       = p.PlanTypeId,
                    WorkAreaText     = rpw.Title,
                    RankText         = rops.RankText,
                    PositionTypeText = rops.PositionTypeText,
                    OrgUnitText      = rops.OrgUnitText,
                    SalaryTypeText   = str.Dari,
                    LocationText     = Lr.Dari,
                    PlanTypeText     = PTr.Name,
                }).OrderBy(c => c.Sorter).DefaultIfEmpty().ToListAsync(cancellationToken);
            }
            //if (request.ParentId != null)
            //{
            //    result = await (from p in _context.Position
            //                    join w in _context.WorkArea on p.WorkingAreaId equals w.Id into pw
            //                    from rpw in pw.DefaultIfEmpty()
            //                    join OP in OrgPositions on p.PositionTypeId equals OP.Id into OPs
            //                    from rops in OPs.DefaultIfEmpty()
            //                    join ST in _context.SalaryType on p.SalaryTypeId equals ST.Id into STs
            //                    from str in STs.DefaultIfEmpty()
            //                    join L in _context.Location on p.LocationId equals L.Id into Ls
            //                    from Lr in Ls.DefaultIfEmpty()
            //                    join PT in _context.PlanType on p.PlanTypeId equals PT.Id into PTs
            //                    from PTr in PTs.DefaultIfEmpty()
            //                    where p.ParentId == request.ParentId
            //                    select new SearchedPosition
            //                    {
            //                        Id = p.Id,
            //                        ParentId = p.ParentId,
            //                        NodeId = Convert.ToInt32(p.Id),
            //                        ParentNodeId = Convert.ToInt32(p.ParentId),
            //                        WorkingAreaId = p.WorkingAreaId,
            //                        Code = p.Code,
            //                        PositionTypeId = p.PositionTypeId,
            //                        LocationId = p.LocationId,
            //                        SalaryTypeId = p.SalaryTypeId,
            //                        Sorter = p.Sorter,
            //                        OrganoGramId = p.OrganoGramId,
            //                        PlanTypeId = p.PlanTypeId,
            //                        WorkAreaText = rpw.Title,
            //                        RankText = rops.RankText,
            //                        PositionTypeText = rops.PositionTypeText,
            //                        OrgUnitText = rops.OrgUnitText,
            //                        SalaryTypeText = str.Dari,
            //                        LocationText = Lr.Dari,
            //                        PlanTypeText = PTr.Name,
            //                    }).OrderBy(c => c.Sorter).DefaultIfEmpty().ToListAsync(cancellationToken);
            //}

            else if (request.OrganoGramId != null)
            {
                result = await(from position in _context.Position
                               join w in _context.WorkArea on position.WorkingAreaId equals w.Id into pw
                               from rpw in pw.DefaultIfEmpty()
                               join OP in OrgPositions on position.PositionTypeId equals OP.Id into OPs
                               from rops in OPs.DefaultIfEmpty()
                               join ST in _context.SalaryType on position.SalaryTypeId equals ST.Id into STs
                               from str in STs.DefaultIfEmpty()
                               join L in _context.Location on position.LocationId equals L.Id into Ls
                               from Lr in Ls.DefaultIfEmpty()
                               join PT in _context.PlanType on position.PlanTypeId equals PT.Id into PTs
                               from PTr in PTs.DefaultIfEmpty()
                               where position.OrganoGramId == request.OrganoGramId
                               select new SearchedPosition
                {
                    Id               = position.Id,
                    ParentId         = position.ParentId,
                    NodeId           = Convert.ToInt32(position.Id),
                    ParentNodeId     = Convert.ToInt32(position.ParentId),
                    WorkingAreaId    = position.WorkingAreaId,
                    Code             = position.Code,
                    PositionTypeId   = position.PositionTypeId,
                    LocationId       = position.LocationId,
                    SalaryTypeId     = position.SalaryTypeId,
                    Sorter           = position.Sorter,
                    OrganoGramId     = position.OrganoGramId,
                    PlanTypeId       = position.PlanTypeId,
                    WorkAreaText     = rpw.Title,
                    RankText         = rops.RankText,
                    PositionTypeText = rops.PositionTypeText,
                    OrgUnitText      = rops.OrgUnitText,
                    SalaryTypeText   = str.Dari,
                    LocationText     = Lr.Dari,
                    PlanTypeText     = PTr.Name,
                }).OrderBy(c => c.Sorter).ToListAsync(cancellationToken);
            }
            return(result);
        }
コード例 #17
0
ファイル: Impl.cs プロジェクト: WVitek/DotGlue
        static Dictionary <TAttr, object> ParseAttrs <TAttr>(Generator.Ctx ctx, IEnumerable <string> comments,
                                                             params TAttr[] firstLineDefaultKeys
                                                             )
            where TAttr : struct
        {
            bool firstLine = true;
            var  lstDescr  = new List <string>();
            Dictionary <TAttr, object> attrs = null;
            int iDefaultKey = (firstLineDefaultKeys.Length > 0) ? 0 : -1;

            foreach (var txt in comments)
            {
                bool isKeyValueComment;
                {
                    int iEqualSign = txt.IndexOf('=');
                    if (iEqualSign > 0)
                    {
                        isKeyValueComment = !Enumerable.Range(0, iEqualSign - 1).Any(i => char.IsWhiteSpace(txt[i]));
                    }
                    else
                    {
                        isKeyValueComment = false;
                    }
                }
                if ((firstLineDefaultKeys.Length == 0 || !firstLine) && !isKeyValueComment)
                {
                    if (txt.Trim().Length == 0)
                    {
                        lstDescr.Clear();
                    }
                    else
                    {
                        lstDescr.Add(txt);
                    }
                    continue; // do not parse simple comment lines
                }
                foreach (Expr attr in Parser.ParseSequence(txt, comparison: StringComparison.InvariantCulture))
                {
                    string attrName;
                    Expr   attrValue;
                    if (attr.nodeType == ExprType.Equal)
                    {   // named attribute
                        var be = (BinaryExpr)attr;
                        if (be.left.nodeType == ExprType.Reference)
                        {
                            attrName = Convert.ToString(be.left);
                        }
                        else
                        {
                            var name = Generator.Generate(be.left, ctx);
                            if (OPs.KindOf(name) != ValueKind.Const)
                            {
                                ctx.Error("ParseAttrs: attribute name must be constant\t" + be.left.ToString());
                            }
                            attrName = Convert.ToString(name);
                        }
                        attrValue = be.right;
                    }
                    else if (firstLine && iDefaultKey >= 0)
                    {   // unnamed attributes possible in first line
                        attrs = attrs ?? new Dictionary <TAttr, object>();
                        attrs.Add(firstLineDefaultKeys[iDefaultKey], attr);
                        if (++iDefaultKey >= firstLineDefaultKeys.Length)
                        {
                            iDefaultKey = -1;
                        }
                        continue;
                    }
                    else
                    {
                        break;  // it is simple comment to the end of line?
                    }
                    if (attrValue.nodeType != ExprType.Constant)
                    {
                        attrValue = new CallExpr(FuncDefs_Core._block, attrValue);
                    }
                    var value = Generator.Generate(attrValue, ctx);
                    if (OPs.KindOf(value) != ValueKind.Const)
                    {
                        ctx.Error(string.Format("ParseAttrs: attribute value must be constant\t{0}={1}", attrName, attrValue));
                    }
                    if (attrName != null)
                    {
                        if (!Enum.TryParse <TAttr>(attrName, out var attrKey))
                        {
                            throw new Generator.Exception($"Unrecognized attribute name, {attrName}={attrValue} // enum {typeof(TAttr)}");
                        }
                        attrs = attrs ?? new Dictionary <TAttr, object>();
                        Attr.Add(attrs, attrKey, value, false);
                    }
                }
                firstLine = false;
            }
            if (lstDescr.Count > 0)
            {
                attrs = attrs ?? new Dictionary <TAttr, object>();
                if (!Enum.TryParse <TAttr>(nameof(Attr.Tbl.Description), out var attrDescription))
                {
                    throw new Generator.Exception($"ParseAttrs: enum '{typeof(TAttr)}' does not contains value named '{nameof(Attr.Tbl.Description)}'");
                }
                attrs.Add(attrDescription, lstDescr);
            }
            return(attrs);
        }