Exemple #1
0
        private void Test(string input, string expectedX, string expectedY, string expectedZ, string expectedT)
        {
            string expected = string.Empty;
            string actual   = string.Empty;

            try
            {
                FunctionParser parser   = new FunctionParser();
                FunctionTree   function = parser.Parse(input);

                expected = expectedX;
                actual   = function.Expression.Derive(function.Parameters.X).ToString();
                Assert.AreEqual(expected, actual);

                expected = expectedY;
                actual   = function.Expression.Derive(function.Parameters.Y).ToString();
                Assert.AreEqual(expected, actual);

                expected = expectedZ;
                actual   = function.Expression.Derive(function.Parameters.Z).ToString();
                Assert.AreEqual(expected, actual);

                expected = expectedT;
                actual   = function.Expression.Derive(function.Parameters.T).ToString();
                Assert.AreEqual(expected, actual);
            }
            catch (Exception ex)
            {
                Assert.Fail(MessageHandler.GetMessage(ex, input, expected, actual));
            }
        }
        private void Test(string input, Type expectedException)
        {
            Exception actualException = null;

            try
            {
                try
                {
                    FunctionParser parser   = new FunctionParser();
                    FunctionTree   function = parser.Parse(input);

                    throw new ArgumentException();
                }
                catch (SyntaxException ex)
                {
                    actualException = ex;
                    Assert.AreEqual(expectedException.FullName, actualException.GetType().FullName);
                }
            }
            catch (Exception ex)
            {
                if (actualException == null)
                {
                    actualException = ex;
                }

                Assert.Fail(MessageHandler.GetMessage(ex, input, expectedException, actualException));
            }
        }
        private bool ComputeAnswer()
        {
            immediate.Focus();
            Buffer = Buffer.Trim();

            if (Buffer.Length == 0)
            {
                Buffer = AnswerKey;
            }

            // Print what we're about to evaluate
            ScreenBuffer += "> " + Buffer.Trim() + "\n";
            ShowScreenText();

            try
            {
                var exp = FunctionParser.Parse(Buffer);
                _lastAnswer = exp.Simplify();
                if (_lastAnswer is ConstantExpression)
                {
                    VariableExpression.Define(AnswerKey, ((ConstantExpression)_lastAnswer).Value);
                }
                return(true);
            }
            catch (FunctionParserException)
            {
                ScreenBuffer += "Error!\n";
                _lastAnswer   = new ConstantExpression(0);
                VariableExpression.Define(AnswerKey, 0.0);
                Buffer = string.Empty;
                return(false);
            }
        }
Exemple #4
0
        private static void BuildDocumentation(string content, List <string> matches, string schemaName)
        {
            PGSchema schema = SchemaProcessor.GetSchema(schemaName);

            content = content.Replace("[DBName]", Program.Database.ToUpperInvariant());
            content = content.Replace("[SchemaName]", schemaName);

            content = SequenceParser.Parse(content, matches, SequenceProcessor.GetSequences(schemaName));
            content = TableParser.Parse(content, matches, schema.Tables);
            content = ViewParser.Parse(content, matches, schema.Views);
            content = SequenceParser.Parse(content, matches, schema.Sequences);
            content = MaterializedViewParser.Parse(content, matches, schema.MaterializedViews);
            content = FunctionParser.Parse(content, matches, schema.Functions);
            content = FunctionParser.ParseTriggers(content, matches, schema.TriggerFunctions);
            content = TypeParser.Parse(content, matches, schema.Types);

            foreach (PgTable table in schema.Tables)
            {
                Console.WriteLine("Generating documentation for table \"{0}\".", table.Name);
                TableRunner.Run(table);
            }


            foreach (PgFunction function in schema.Functions)
            {
                Console.WriteLine("Generating documentation for function \"{0}\".", function.Name);
                FunctionRunner.Run(function);
            }

            foreach (PgFunction function in schema.TriggerFunctions)
            {
                Console.WriteLine("Generating documentation for trigger function \"{0}\".", function.Name);
                FunctionRunner.Run(function);
            }

            foreach (PgMaterializedView materializedView in schema.MaterializedViews)
            {
                Console.WriteLine("Generating documentation for materialized view \"{0}\".", materializedView.Name);
                MaterializedViewRunner.Run(materializedView);
            }

            foreach (PgView view in schema.Views)
            {
                Console.WriteLine("Generating documentation for view \"{0}\".", view.Name);
                ViewRunner.Run(view);
            }
            foreach (PgType type in schema.Types)
            {
                Console.WriteLine("Generating documentation for type \"{0}\".", type.Name);
                TypeRunner.Run(type);
            }

            string targetPath = System.IO.Path.Combine(OutputPath, schemaName + ".html");

            FileHelper.WriteFile(content, targetPath);
        }
    public void TestValidStartFunction()
    {
        InitCompiler("function(a+b) * 2", 8);
        IdentifierToken functionName = new IdentifierToken("function", 0);

        compiler.Parent.AddChild(functionName);

        Assert.IsTrue(parser.Parse(compiler));

        Assert.AreEqual(13, compiler.Pos);
        Assert.AreEqual(1, root.Children.Count);

        FunctionToken expected = new FunctionToken(8, functionName);

        expected.Children.Add(new AdditionToken(10,
                                                new IdentifierToken("a", 9), new IdentifierToken("b", 11)));
        Assert.AreEqual(expected, root.Children[0]);

        Assert.AreSame(root, compiler.Parent);
    }
Exemple #6
0
        private void GraphScene3D(Canvas screenCanvas, String eqX, String eqY, String eqZ)
        {
            // We do this so we can get good error information.
            // The values return by these calls are ignored.
            FunctionParser.Parse(eqX);
            FunctionParser.Parse(eqY);
            FunctionParser.Parse(eqZ);


            PerspectiveCamera camera = new PerspectiveCamera();

            camera.Position          = new Point3D(0, 0, 5);
            camera.LookDirection     = new Vector3D(0, 0, -2);
            camera.UpDirection       = new Vector3D(0, 1, 0);
            camera.NearPlaneDistance = 1;
            camera.FarPlaneDistance  = 100;
            camera.FieldOfView       = 45;

            Model3DGroup group = null;


            group = new Model3DGroup();
            FunctionMesh mesh = new FunctionMesh(eqX, eqY, eqZ, UMin, UMax, VMin, VMax);

            group.Children.Add(new GeometryModel3D(mesh.CreateMesh(UGrid + 1, VGrid + 1), new DiffuseMaterial(Brushes.Blue)));
            group.Children.Add(new DirectionalLight(Colors.White, new Vector3D(-1, -1, -1)));


            Viewport3D viewport = new Viewport3D();

            //<newcode>
            ModelVisual3D sceneVisual = new ModelVisual3D();

            sceneVisual.Content = group;
            viewport.Children.Clear();
            viewport.Children.Add(sceneVisual);
            //</newcode>


            //viewport.Models = group;
            viewport.Camera       = camera;
            viewport.Width        = CanvasWidth;
            viewport.Height       = CanvasHeight;
            viewport.ClipToBounds = true;

            screenCanvas.Children.Clear();
            screenCanvas.Children.Add(viewport);
            _tb = new Trackball();
            _tb.Attach(screenCanvas);
            _tb.Enabled = true;
            _tb.Servants.Add(viewport);
            screenCanvas.IsVisibleChanged += new DependencyPropertyChangedEventHandler(screenCanvas_IsVisibleChanged);
        }
 private IExpression Parse(string equation, string labelName, string registryName)
 {
     try
     {
         var exp = FunctionParser.Parse(equation);
         Registry.SetValue(_regSaveBase, registryName, equation, RegistryValueKind.String);
         return(exp);
     }
     catch (FunctionParserException ex)
     {
         throw new InvalidExpressionException("Error in equation: \"" + labelName + "\"", ex);
     }
 }
 private void ValidateOption(string value, string registryName)
 {
     try
     {
         var exp = FunctionParser.Parse(value).Simplify();
         if (!(exp is ConstantExpression))
         {
             throw new InvalidExpressionException("The input expression must be constant");
         }
         Registry.SetValue(_regSaveBase, registryName, value, RegistryValueKind.String);
     }
     catch (FunctionParserException ex)
     {
         throw new InvalidExpressionException("Cannot save value for \"" + registryName + "\"", ex);
     }
 }
Exemple #9
0
        private void Test(string input, string expected)
        {
            string actual = string.Empty;

            try
            {
                FunctionParser parser   = new FunctionParser();
                FunctionTree   function = parser.Parse(input);
                actual = function.Expression.ToString();

                Assert.AreEqual(expected, actual);
            }
            catch (Exception ex)
            {
                Assert.Fail(MessageHandler.GetMessage(ex, input, expected, actual));
            }
        }
Exemple #10
0
        private void Differentiate(object sender, RoutedEventArgs args)
        {
            ScreenBuffer += "> d/dx(" + Buffer.Trim() + ")\n";
            ShowScreenText();

            try
            {
                var exp = FunctionParser.Parse(Buffer);
                exp           = exp.Differentiate("x").Simplify();
                ScreenBuffer += exp.ToString() + "\n";
                Buffer        = string.Empty;
            }
            catch (FunctionParserException)
            {
                ScreenBuffer += "Error!\n";
                Buffer        = string.Empty;
            }
        }
Exemple #11
0
        private static FunctionTree ParseFunction(string input)
        {
            FunctionParser parser = new FunctionParser();

            try
            {
                return(parser.Parse(input));
            }
            catch (SyntaxException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Internal parser error: " + ex.Message);
            }

            return(null);
        }
Exemple #12
0
        private void GraphScene2DP(Canvas c, String inputX, String inputY)
        {
            IExpression xExp = FunctionParser.Parse(inputX);
            IExpression yExp = FunctionParser.Parse(inputY);

            double width          = CanvasWidth;
            double height         = CanvasHeight;
            double graphToCanvasX = width / (XMax2D - XMin2D);
            double graphToCanvasY = height / (YMax2D - YMin2D);

            // distance from origin of graph to origin of canvas
            double offsetX = -XMin2D;
            double offsetY = YMax2D;

            PointCollection points = new PointCollection();

            for (double t = TMin2D; t <= TMax2D + 0.000001; t += TStep2D)
            {
                VariableExpression.Define("t", t);
                double xGraph = xExp.Evaluate();
                double yGraph = yExp.Evaluate();

                // Translate the origin based on the max/min parameters (y axis is flipped), then scale to canvas.
                double xCanvas = (xGraph + offsetX) * graphToCanvasX;
                double yCanvas = (offsetY - yGraph) * graphToCanvasY;

                points.Add(ClampedPoint(xCanvas, yCanvas));
            }
            VariableExpression.Undefine("t");

            c.Children.Clear();
            DrawAxisHelper axisHelper = new DrawAxisHelper(c, new Size(width, height));

            axisHelper.DrawAxes(XMin2D, XMax2D, YMin2D, YMax2D);


            Polyline polyLine = new Polyline();

            polyLine.Stroke          = Brushes.Black;
            polyLine.StrokeThickness = 1;
            polyLine.Points          = points;
            c.Children.Add(polyLine);
        }
Exemple #13
0
        private void Show2D(Canvas c, String input)
        {
            IExpression exp = FunctionParser.Parse(input);

            double width          = CanvasWidth;
            double height         = CanvasHeight;
            double offsetX        = -XMin;
            double offsetY        = YMax;
            double graphToCanvasX = width / (XMax - XMin);
            double graphToCanvasY = height / (YMax - YMin);

            PointCollection points = new PointCollection();

            for (double x = XMin; x < XMax; x += 1 / graphToCanvasX)
            {
                VariableExpression.Define("x", x);

                // Translate the origin based on the max/min parameters (y axis is flipped), then scale to canvas.
                double xCanvas = (x + offsetX) * graphToCanvasX;
                double yCanvas = (offsetY - exp.Evaluate()) * graphToCanvasY;

                points.Add(ClampedPoint(xCanvas, yCanvas));
            }
            VariableExpression.Undefine("x");

            c.Children.Clear();
            DrawAxisHelper axisHelper = new DrawAxisHelper(c, new Size(c.Width, c.Height));

            axisHelper.DrawAxes(XMin, XMax, YMin, YMax);


            Polyline graphLine = new Polyline();

            graphLine.Stroke          = Brushes.Black;
            graphLine.StrokeThickness = 1;
            graphLine.Points          = points;

            c.Children.Add(graphLine);
        }
Exemple #14
0
    public static bool Gen(string[] args)
    {
        string commandStr = "command:\nserverFuncDefFilePath clientFuncDefFilePath protoDir protoExe serverGenDir clientGenDir";

        if (6 != args.Count())
        {
            Console.WriteLine("Args Error");
            Console.WriteLine(commandStr);
            var key = Console.ReadKey(true).Key;

            return(false);
        }

        for (int i = 0; i < args.Count(); i++)
        {
            var s = args[i];
            args[i] = s.Replace("\\", "/");
        }

        //服务器函数定义文件
        var serverFuncDefFilePath = args[0];
        //客户端函数定义文件
        var clientFuncDefFilePath = args[1];
        //proto 文件目录
        var protoExe = args[2];
        //proto 文件目录
        var protoDir = args[3];
        //服务器生成目录
        var serverGenDir = args[4];
        //客户端生成目录
        var clientGenDir = args[5];

        if (!File.Exists(serverFuncDefFilePath))
        {
            Console.WriteLine(serverFuncDefFilePath + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("serverFuncDefFilePath=" + serverFuncDefFilePath);

        if (!File.Exists(clientFuncDefFilePath))
        {
            Console.WriteLine(clientFuncDefFilePath + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("clientFuncDefFilePath=" + clientFuncDefFilePath);

        if (!Directory.Exists(protoDir))
        {
            Console.WriteLine(protoDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("protoDir=" + protoDir);

        if (!File.Exists(protoExe))
        {
            Console.WriteLine(protoExe + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("protoExe=" + protoExe);

        if (!Directory.Exists(serverGenDir))
        {
            Console.WriteLine(serverGenDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("serverGenDir=" + serverGenDir);

        if (!Directory.Exists(clientGenDir))
        {
            Console.WriteLine(clientGenDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("clientGenDir=" + clientGenDir);

        var STRING_S2C     = "ServerService";
        var STRING_C2S     = "ClientService";
        var CSHARP_POSTFIX = ".cs";

        UTF8Encoding encoding    = new UTF8Encoding(false);
        var          serverFuncs = FunctionParser.Parse(serverFuncDefFilePath);
        var          clientFuncs = FunctionParser.Parse(clientFuncDefFilePath);

        var className = "";

        {        //Server
            var interfaceName = "IServer";
            className = interfaceName;
            using (TextWriter textWriter5 = new StreamWriter(Path.Combine(serverGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ServerInterface(textWriter5, className, STRING_S2C, serverFuncs);
            }

            className = "ServerInterfaceReaction";
            using (TextWriter textWriter6 = new StreamWriter(Path.Combine(serverGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ServerInterfaceReaction(textWriter6, className, interfaceName, STRING_S2C, serverFuncs);
            }

            className = "ClientFunctions";
            using (TextWriter textWriter7 = new StreamWriter(Path.Combine(serverGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientFunctions(textWriter7, className, STRING_C2S, clientFuncs);
            }
        }

        {        //Client
            var interfaceName = "IClient";
            className = interfaceName;
            using (TextWriter ClientInterfacetextWriter = new StreamWriter(Path.Combine(clientGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientInterface(ClientInterfacetextWriter, className, STRING_C2S, clientFuncs);
            }

            className = "ClientInterfaceReaction";
            using (TextWriter ClientInterfaceReactiontextWriter = new StreamWriter(Path.Combine(clientGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientInterfaceReaction(ClientInterfaceReactiontextWriter, className, interfaceName, STRING_C2S, clientFuncs);
            }

            className = "ServerFunctions";
            using (TextWriter textWriter8 = new StreamWriter(Path.Combine(clientGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ServerFunctions(textWriter8, className, STRING_S2C, serverFuncs);
            }
        }



        using (TextWriter textWriter = new StreamWriter(Path.Combine(protoDir, STRING_S2C + "Proto.proto"), false, encoding))
        {
            CreateProtoFile.GenerateProto(textWriter, STRING_S2C, serverFuncs);
        }
        using (TextWriter textWriter = new StreamWriter(Path.Combine(protoDir, STRING_C2S + "Proto.proto"), false, encoding))
        {
            CreateProtoFile.GenerateProto(textWriter, STRING_C2S, clientFuncs);
        }

        CreateProtoFile.GenerateCSCode(protoExe, protoDir, clientGenDir);
        CreateProtoFile.GenerateCSCode(protoExe, protoDir, serverGenDir);

        return(true);
    }
Exemple #15
0
        /// <summary>
        /// </summary>
        /// <param name="iInstrType"></param>
        /// <param name="iInstrOPType"></param>
        /// <param name="hInputValues"></param>
        /// <param name="sErrMsg"></param>
        /// <param name="alErrorMsg"></param>
        /// <returns>Calculated result</returns>
        public static Double DoCalculate(int iInstrType, int iInstrOPType, Hashtable hInputValues, ref string sErrMsg, ref ArrayList alErrorMsg)
        {
            Double dResult = 0;

            try
            {
                // Validate input fields
                dResult = ValidateFields(hInputValues, iInstrType, iInstrOPType, ref sErrMsg, ref alErrorMsg);
                if (dResult > 0)
                {
                    if (iInstrType == Constants.cStr_IT_SavingsAccount || iInstrType == Constants.cStr_IT_CurrentAccount || iInstrType == Constants.cStr_IT_CashAtHand)
                    {
                        if (iInstrType == Constants.cStr_IT_CashAtHand)
                        {
                            dResult = Convert.ToDouble(hInputValues["DAMT"]);
                        }
                        else
                        {
                            dResult = Convert.ToDouble(hInputValues["AAB"]);
                        }
                        return(dResult);
                    }

                    // Set calculated field values.
                    setCalculatedFields(iInstrType, iInstrOPType, hInputValues);

                    string sFormula = null;
                    int    nCount   = dsFormula.Tables[0].Rows.Count;

                    DataTable dtFormula = dsFormula.Tables[0];

                    var resultFormula = from formula in dtFormula.AsEnumerable()
                                        where formula.Field <Int32>("OFM_InstrumentTypeId") == iInstrType &&
                                        formula.Field <Int32>("OFM_OutputId") == iInstrOPType
                                        select formula;

                    foreach (var formula in resultFormula)
                    {
                        // If interest calculation basis is simple use formula 9 or formula 2 for the instruments,
                        if ((iInstrType == Constants.cStr_IT_FixedDeposits || iInstrType == Constants.cStr_IT_CompanyFD || iInstrType == Constants.cStr_IT_GOIReliefBonds || iInstrType == Constants.cStr_IT_GOITaxSavingBonds || iInstrType == Constants.cStr_IT_TaxSavingBonds) && (iInstrOPType == Constants.cStr_IO_CurrentValue || iInstrOPType == Constants.cStr_IO_MaturityValue || iInstrOPType == Constants.cStr_IO_InterestAccumulatedEarnedTillDate || iInstrOPType == Constants.cStr_IO_InterestAccumulatedEarnedTillMaturity) && hInputValues["ICB"].Equals("Simple"))
                        {
                            if (formula["OFM_FormulaId"].ToString().Equals(Constants.cStr_Formula_SimpleInterestBasis) && formula.ItemArray[3].ToString().Equals(Constants.cStr_Formula_SimpleInterestBasis))
                            {
                                sFormula = formula["FM_Formula"].ToString();
                                break;
                            }
                            else if (formula["OFM_FormulaId"].ToString().Equals(Constants.cStr_Formula_InterestAccumulatedEarnedTillDate) && formula.ItemArray[3].ToString().Equals(Constants.cStr_Formula_InterestAccumulatedEarnedTillDate))
                            {
                                sFormula = formula["FM_Formula"].ToString();
                                break;
                            }
                        }
                        else if (iInstrType == Constants.cStr_IT_SeniorCitizensSavingsScheme || iInstrType == Constants.cStr_IT_PostOfficeSavingsBankAcc || iInstrType == Constants.cStr_IT_PostOfficeMIS)
                        {
                            sFormula = formula["FM_Formula"].ToString();
                            break;
                        }
                        else
                        {
                            if (formula["OFM_FormulaId"].ToString().Equals(Constants.cStr_Formula_SimpleInterestBasis) && formula.ItemArray[3].ToString().Equals(Constants.cStr_Formula_SimpleInterestBasis))
                            {
                                continue;
                            }
                            else if (formula["OFM_FormulaId"].ToString().Equals(Constants.cStr_Formula_InterestAccumulatedEarnedTillDate) && formula.ItemArray[3].ToString().Equals(Constants.cStr_Formula_InterestAccumulatedEarnedTillDate))
                            {
                                continue;
                            }
                            else if (formula["OFM_FormulaId"].ToString().Equals(Constants.cStr_Formula_CompoundInterestAccumulatedEarnedTillDate) && formula.ItemArray[3].ToString().Equals(Constants.cStr_Formula_CompoundInterestAccumulatedEarnedTillDate))
                            {
                                sFormula = formula["FM_Formula"].ToString();
                                break;
                            }
                            else if (formula["OFM_FormulaId"].ToString().Equals(Constants.cStr_Formula_CurrentValueOrMaturityValue) && formula.ItemArray[3].ToString().Equals(Constants.cStr_Formula_CurrentValueOrMaturityValue))
                            {
                                sFormula = formula["FM_Formula"].ToString();
                                break;
                            }
                            else
                            {
                                sFormula = formula["FM_Formula"].ToString();
                                break;
                            }
                        }
                    }
                    // Months will be rounded of to the nearest year if the covered under Gratuity Act otherwise no rounded off
                    if (iInstrType == Constants.cStr_IT_Gratuity)
                    {
                        int nNoOfMonthComp = Convert.ToInt32(hInputValues["NOMC"]);
                        int nNoOfYearsComp = Convert.ToInt32(hInputValues["CYOS"]);
                        if (iInstrOPType == Constants.cStr_IO_GratuityAmountWhenCoveredUnderGratuityAct)
                        {
                            if (nNoOfMonthComp > 5)
                            {
                                nNoOfYearsComp += 1;
                            }
                            hInputValues["CYOS"] = nNoOfYearsComp;
                        }
                        else
                        {
                            hInputValues["CYOS"] = nNoOfYearsComp;
                        }
                    }
                    IDictionaryEnumerator en = hInputValues.GetEnumerator();
                    while (en.MoveNext())
                    {
                        string str = en.Key.ToString();
                        if (sFormula.Contains(str))
                        {
                            sFormula = sFormula.Replace(str, en.Value.ToString());
                        }
                    }

                    FunctionParser fn = new FunctionParser();
                    fn.Parse(sFormula);
                    fn.Infix2Postfix();
                    fn.EvaluatePostfix();
                    dResult = Math.Round(fn.Result, 2);
                }
                return(dResult);
            }
            catch (BaseApplicationException Ex)
            {
                throw Ex;
            }
            catch (Exception Ex)
            {
                BaseApplicationException exBase       = new BaseApplicationException(Ex.Message, Ex);
                NameValueCollection      FunctionInfo = new NameValueCollection();

                object[] objects = new object[4];
                objects[0] = iInstrType;
                objects[1] = iInstrOPType;
                objects[2] = hInputValues;
                objects[3] = sErrMsg;
                objects[4] = alErrorMsg;
                FunctionInfo.Add("Method", "CalculatorBo.cs:DoCalculate()");
                FunctionInfo = exBase.AddObject(FunctionInfo, objects);
                exBase.AdditionalInformation = FunctionInfo;
                ExceptionManager.Publish(exBase);
                throw exBase;
            }
        }
Exemple #16
0
    public static bool Gen(string[] args)
    {
        string commandStr = "command:\nserverFuncDefFilePath clientFuncDefFilePath protoDir protoExe serverGenDir clientGenDir";

        if (args.Count() != 8)
        {
            Console.WriteLine("Args Error");
            Console.WriteLine(commandStr);
            var key = Console.ReadKey(true).Key;

            return(false);
        }

        for (int i = 0; i < args.Count(); i++)
        {
            var s = args[i];
            args[i] = s.Replace("\\", "/");
        }
        //proto 文件目录
        var protoDir = args[0];
        //proto 文件目录
        var protoExe = args[1];
        //客户端生成目录
        var clientGenDir = args[2];
        //服务器生成目录
        var serverGenDir = args[3];
        //interface
        var interfaceDir = args[4];
        //InterfaceReaction
        var InterfaceReactionDir = args[5];
        //公共
        var sharedDataDir = args[6];
        //grainCollection
        var grainCollectionDir = args[7];

        var protoTemp = protoDir + "/temp";

        if (!Directory.Exists(protoDir))
        {
            Console.WriteLine(protoDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("protoDir=" + protoDir);

        if (!File.Exists(protoExe))
        {
            Console.WriteLine(protoExe + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("protoExe=" + protoExe);

        if (!Directory.Exists(serverGenDir))
        {
            Console.WriteLine(serverGenDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("serverGenDir=" + serverGenDir);
        Utility.ClearFolder(serverGenDir);

        if (!Directory.Exists(clientGenDir))
        {
            Console.WriteLine(clientGenDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("clientGenDir=" + clientGenDir);
        Utility.ClearFolder(clientGenDir, "*.cs");

        if (!Directory.Exists(interfaceDir))
        {
            Console.WriteLine(interfaceDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("interfaceDir=" + interfaceDir);
        Utility.ClearFolder(interfaceDir);

        if (!Directory.Exists(InterfaceReactionDir))
        {
            Console.WriteLine(InterfaceReactionDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("InterfaceReactionDir=" + InterfaceReactionDir);
        Utility.ClearFolder(InterfaceReactionDir);

        if (!Directory.Exists(sharedDataDir))
        {
            Console.WriteLine(sharedDataDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("sharedDataDir=" + sharedDataDir);
        Utility.ClearFolder(sharedDataDir);

        if (!Directory.Exists(grainCollectionDir))
        {
            Console.WriteLine(grainCollectionDir + " do not exist.");
            var key = Console.ReadKey(true).Key;
            return(false);
        }
        Console.WriteLine("grainCollectionDir=" + grainCollectionDir);
        Utility.ClearFolder(grainCollectionDir);

        if (Directory.Exists(protoTemp))
        {
            Directory.Delete(protoTemp, true);
        }
        Directory.CreateDirectory(protoTemp);


        var STRING_S2C     = "ServerService";
        var STRING_C2S     = "ClientService";
        var CSHARP_POSTFIX = ".cs";

        UTF8Encoding encoding = new UTF8Encoding(false);

        var dirInfo = new DirectoryInfo(protoDir);
        var files   = dirInfo.GetFiles("*.h", SearchOption.AllDirectories);

        var serverFuncs      = new List <Function>();
        var clientFuncs      = new List <Function>();
        var gate2ClientFuncs = new List <Function>();

        foreach (var file in files)
        {
            var allFuncs = FunctionParser.Parse(file.FullName);
            serverFuncs.AddRange(allFuncs.Where(f => f.Direction == CallDirection.Client2GameServer));

            clientFuncs.AddRange(allFuncs.Where(f => f.Direction == CallDirection.GameServer2Client ||
                                                f.Direction == CallDirection.Server2Client));
            gate2ClientFuncs.AddRange(allFuncs.Where(f => f.Direction == CallDirection.Server2Client).ToList());
        }



        {        //Server
            var interfaceName = "IServer";
            var className     = interfaceName;
            using (TextWriter textWriter5 = new StreamWriter(Path.Combine(serverGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ServerInterface(textWriter5, className, STRING_S2C, serverFuncs);
            }

            className = "ServerInterfaceReaction";
            using (TextWriter textWriter6 = new StreamWriter(Path.Combine(serverGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ServerInterfaceReaction(textWriter6, className, interfaceName, STRING_S2C, serverFuncs);
            }

            className = "ClientFunctions";
            using (TextWriter textWriter7 = new StreamWriter(Path.Combine(serverGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientFunctions(textWriter7, className, STRING_C2S, clientFuncs);
            }
        }

        {        //Client
            var interfaceName = "IClient";
            var className     = interfaceName;
            using (TextWriter ClientInterfacetextWriter = new StreamWriter(Path.Combine(clientGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientInterface(ClientInterfacetextWriter, className, STRING_C2S, clientFuncs);
            }

            className = "ClientInterfaceReaction";
            using (TextWriter ClientInterfaceReactiontextWriter = new StreamWriter(Path.Combine(clientGenDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientInterfaceReaction(ClientInterfaceReactiontextWriter, className, interfaceName, STRING_C2S, clientFuncs);
            }
        }

        //ServerFunctions
        foreach (var file in files)
        {
            var fileName = file.Name.Substring(0, file.Name.LastIndexOf('.'));
            var allFuncs = FunctionParser.Parse(file.FullName);
            var ss       = allFuncs.Where(f => f.Direction == CallDirection.Client2GameServer || f.Direction == CallDirection.Client2Server).ToList();

            if (ss.Count < 1)
            {
                continue;
            }

            var className = "ServerFunctions";
            var outFile   = className + fileName + CSHARP_POSTFIX;
            using (TextWriter textWriter8 = new StreamWriter(Path.Combine(clientGenDir, outFile), false, encoding))
            {
                CSharpCodeGenerator.ServerFunctions(textWriter8, className, STRING_S2C, ss);
            }
        }

        //Server2Server
        {
            foreach (var file in files)
            {
                var fileName = file.Name.Substring(0, file.Name.LastIndexOf('.'));
                var allFuncs = FunctionParser.Parse(file.FullName);
                var ss       = allFuncs.Where(f => f.Direction == CallDirection.Server2Server).ToList();

                if (ss.Count < 1)
                {
                    continue;
                }

                var className = "I" + fileName;
                var outFile   = className + "SS" + CSHARP_POSTFIX;
                using (TextWriter textWriter5 = new StreamWriter(Path.Combine(interfaceDir, outFile), false, encoding))
                {
                    CSharpCodeGenerator.GrainInterface(textWriter5, className, STRING_S2C, ss, false);
                }
            }
        }

        //client2GateFuncs
        foreach (var file in files)
        {
            var fileName         = file.Name.Substring(0, file.Name.LastIndexOf('.'));
            var allFuncs         = FunctionParser.Parse(file.FullName);
            var client2GateFuncs = allFuncs.Where(f => f.Direction == CallDirection.Client2Server).ToList();

            if (client2GateFuncs.Count < 1)
            {
                continue;
            }

            var interfaceName = "I" + fileName;
            var className     = interfaceName;
            using (TextWriter textWriter5 = new StreamWriter(Path.Combine(interfaceDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.GrainInterface(textWriter5, className, STRING_S2C, client2GateFuncs);
            }

            className = fileName + "GrainInterfaceReaction";
            using (TextWriter textWriter6 = new StreamWriter(Path.Combine(InterfaceReactionDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.GrainInterfaceReaction(textWriter6, "GrainInterfaceReaction", interfaceName, STRING_S2C, fileName, client2GateFuncs);
            }

            using (TextWriter textWriter = new StreamWriter(Path.Combine(protoTemp, "CG" + fileName + "Proto.proto"), false, encoding))
            {
                CreateProtoFile.GenerateProto(textWriter, STRING_S2C, client2GateFuncs);
            }
        }

        //Gate2clientFuncs
        if (gate2ClientFuncs.Count > 0)
        {
            var interfaceName = "IClientConnection";
            var className     = interfaceName;
            using (TextWriter textWriter5 = new StreamWriter(Path.Combine(interfaceDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientConnectionInterface(textWriter5, className, STRING_S2C, gate2ClientFuncs);
            }

            className = "ClientConnection";
            using (TextWriter textWriter6 = new StreamWriter(Path.Combine(grainCollectionDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientConnectionImpl(textWriter6, "ClientConnection", STRING_S2C, gate2ClientFuncs);
            }

            className = "IClientConnectionObserver";
            using (TextWriter textWriter6 = new StreamWriter(Path.Combine(interfaceDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientConnectionObserverInterface(textWriter6, "IClientConnectionObserver", STRING_S2C, gate2ClientFuncs);
            }

            className = "ClientConnectionObserver";
            using (TextWriter textWriter6 = new StreamWriter(Path.Combine(InterfaceReactionDir, className + CSHARP_POSTFIX), false, encoding))
            {
                CSharpCodeGenerator.ClientConnectionObserverImpl(textWriter6, "ClientConnectionObserver", STRING_S2C, "IClientConnectionObserver", gate2ClientFuncs);
            }

            using (TextWriter textWriter = new StreamWriter(Path.Combine(protoTemp, "Gate2clientFuncs" + "Proto.proto"), false, encoding))
            {
                CreateProtoFile.GenerateProto(textWriter, STRING_S2C, gate2ClientFuncs);
            }
        }

        using (TextWriter textWriter = new StreamWriter(Path.Combine(protoTemp, STRING_S2C + "Proto.proto"), false, encoding))
        {
            CreateProtoFile.GenerateProto(textWriter, STRING_S2C, serverFuncs);
        }
        using (TextWriter textWriter = new StreamWriter(Path.Combine(protoTemp, STRING_C2S + "Proto.proto"), false, encoding))
        {
            CreateProtoFile.GenerateProto(textWriter, STRING_C2S, clientFuncs);
        }



        CreateProtoFile.GenerateCSCode(protoExe, protoDir, clientGenDir);
        CreateProtoFile.GenerateCSCode(protoExe, protoDir, sharedDataDir);

        Utility.CopyFile(protoDir, "*.cs", clientGenDir);
        Utility.CopyFile(protoDir, "*.cs", sharedDataDir);

        return(true);
    }