示例#1
0
        private bool CheckFunctionParams(FunctionDeclarationAST fDecl)
        {
            int posParam = 0;

            //get from the scope the function signature.
            if (_scope.HasFunction(fDecl.FunctionId) == ScopeLocation.NotDeclared)
            {
                _errorListener.Add(AnalysisError.FunctionNotDeclared(fDecl));
                return(false);
            }
            var funInfo = _scope.GetFunction(fDecl.FunctionId);

            foreach (var parameter in funInfo.ParameterList)
            {
                //existen dos parametros con el mismo nombre.
                if (_scope.HasVar(parameter.Key) == ScopeLocation.DeclaredLocal)
                {
                    _errorListener.Add(AnalysisError.FunctionParameterAlreadyExists(fDecl, parameter.Key));
                    fDecl.ReturnType = TigerType.GetType <ErrorType>();
                    return(false);
                }
                //existe una variable con el mismo nombre que este parametro en un ambito mas externo
                if (_scope.HasVar(parameter.Key) != ScopeLocation.NotDeclared)
                {
                    _errorListener.Add(AnalysisError.VariableHidesAnotherOne(fDecl));
                }
                //se anade este valor al scope de la funcion
                var parameterTypeId = fDecl.ParameterList.First(x => x.Key == parameter.Key).Value;
                _scope.AddVarParameter(parameter.Key, parameterTypeId, posParam, fDecl.FunctionId);
                posParam++;
            }
            return(true);
        }
示例#2
0
        /// <summary>
        /// DataTable转换成xml
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string DtToXml(DataTable dt)
        {
            try
            {
                System.IO.TextWriter tw = new System.IO.StringWriter();
                if (dt != null)//2015-12-04加是否为null判断
                {
                    dt.TableName = dt.TableName.Length == 0 ? "Table1" : dt.TableName;
                    dt.WriteXml(tw);
                    dt.WriteXmlSchema(tw);
                }
                return(tw.ToString());
            }
            catch (Exception ex)
            {
                AnalysisError Analysis_Error = new AnalysisError();
                string        SaveError      = Analysis_Error.CatchErrorForSave(ex, "无", "xmlhelper_DtToXml");
                //保存错误信息在Logs中
                Deal_error Dealerror = new Deal_error();
                Dealerror.deal_Error(SaveError, "OtherError", "xmlhelper_DtToXml", 0);

                //错误信息返回本地
                string SendError = Analysis_Error.CatchErrorForClient(ex);

                return(SendError);
            }
        }
示例#3
0
        /// <summary>
        /// 执行存储过程,返回一个 DataTable 对象
        /// </summary>
        public DataSet GetDataSet(string procName, params SqlParameter[] parameters)
        {
            DataSet ds = new DataSet();

            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter(procName, _conn as SqlConnection);
                adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                foreach (SqlParameter parameter in parameters)
                {
                    adapter.SelectCommand.Parameters.Add(parameter);
                }
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                AnalysisError Analysis_Error = new AnalysisError();
                string        SaveError      = Analysis_Error.CatchErrorForSave(ex, procName, "Conn_GetDataSet_2");
                //保存错误信息在Logs中
                Deal_error Dealerror = new Deal_error();
                Dealerror.deal_Error(SaveError, "OtherError", "Conn_GetDataSet_2", 0);

                ds = null;
            }
            return(ds);
        }
示例#4
0
        //小英正在用
        public DataSet Proc_GetDataSet(List <string> sql, List <string> tablename)//完整sql语句List,对应表名List,这个是传递多个查询语句以对应的表名,访问固定存储过程,返回一个dataset,目的是查询的不需要在语句中open key ,close key 的
        {
            string sqls = "";

            try
            {
                DataSet ds = new DataSet();
                for (int i = 0; i < sql.Count; i++)
                {
                    sqls = sql[i];
                    SqlDataAdapter da_getall = new SqlDataAdapter("GetQueryData", _conn);
                    da_getall.SelectCommand.CommandType = CommandType.StoredProcedure;
                    da_getall.SelectCommand.Parameters.Add("@sqls", SqlDbType.VarChar, -1);
                    da_getall.SelectCommand.Parameters["@sqls"].Value = sqls;
                    da_getall.Fill(ds, tablename[i]);
                }
                return(ds);
            }
            catch (Exception ex)
            {
                AnalysisError Analysis_Error = new AnalysisError();
                string        SaveError      = Analysis_Error.CatchErrorForSave(ex, sqls, "Proc_GetDataSet");
                //保存错误信息在Logs中
                Deal_error Dealerror = new Deal_error();
                Dealerror.deal_Error(SaveError, "OtherError", "Proc_GetDataSet", 0);
                return(null);
            }
        }
示例#5
0
 /// <summary>
 /// 小周用:查询数据得到一个DataTable
 /// </summary>
 /// <param name="SQLString"></param>
 /// <returns></returns>
 public static DataTable GetDataTable(string SQLString)
 {
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         DataTable dt = new DataTable();
         try
         {
             DataSet ds = new DataSet();
             connection.Open();
             SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
             command.Fill(ds, "ds");
             if (ds.Tables.Count > 0)
             {
                 dt = ds.Tables[0];
             }
         }
         catch (System.Data.SqlClient.SqlException ex)
         {
             AnalysisError Analysis_Error = new AnalysisError();
             string        SaveError      = Analysis_Error.CatchErrorForSave(ex, SQLString, "Db_GetDataTable");
             //保存错误信息在Logs中
             Deal_error Dealerror = new Deal_error();
             Dealerror.deal_Error(SaveError, "OtherError", "Db_GetDataTable", 0);
         }
         return(dt);
     }
 }
示例#6
0
        //#region 小万: 执行存储过程,返回一个DataSet对象 public DataSet GetDataSet(string procName, params SqlParameter[] parameters)
        ///// <summary>
        ///// 执行存储过程,返回一个DataSet 对象
        ///// </summary>
        //public DataSet GetDataSet(string procName, params SqlParameter[] parameters)
        //{
        //    SqlDataAdapter adapter = new SqlDataAdapter(procName, _conn as SqlConnection);
        //    adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        //    foreach (SqlParameter parameter in parameters)
        //    {
        //        adapter.SelectCommand.Parameters.Add(parameter);
        //    }
        //    DataSet ds = new DataSet();
        //    adapter.Fill(ds);
        //    return ds;
        //}
        //#endregion


        //王思远写的方法

        public DataSet GetDataSet(List <string> sqls, List <string> Dt_Name)
        {
            string SqlText = "";

            try
            {
                DataSet ds = new DataSet();
                for (int i = 0; i < sqls.Count; i++)
                {
                    SqlText = sqls[i];
                    SqlDataAdapter da = new SqlDataAdapter(SqlText, _conn);
                    da.Fill(ds, Dt_Name[i]);
                }
                return(ds);
            }
            catch (Exception ex)
            {
                AnalysisError Analysis_Error = new AnalysisError();
                string        SaveError      = Analysis_Error.CatchErrorForSave(ex, SqlText, "Conn_GetDataSet");
                //保存错误信息在Logs中
                Deal_error Dealerror = new Deal_error();
                Dealerror.deal_Error(SaveError, "OtherError", "Conn_GetDataSet", 0);
                return(null);
            }
        }
示例#7
0
 //潘化英:写的用来访问指定存储过程,并执行,通过参数获取返回值,不需要返回其他某个类型的
 public static void ExecProc_NoReturn(string storedProcName, IDataParameter[] parameters)
 {
     try
     {
         SqlConnection connection = new SqlConnection(connectionString);
         connection.Open();
         SqlCommand command = new SqlCommand(storedProcName, connection);
         command.CommandType = CommandType.StoredProcedure;
         foreach (SqlParameter parameter in parameters)
         {
             if (parameter != null)
             {
                 // 检查未分配值的输出参数,将其分配以DBNull.Value.
                 if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                 {
                     parameter.Value = DBNull.Value;
                 }
                 command.Parameters.Add(parameter);
             }
         }
         command.ExecuteNonQuery();
         connection.Close();
     }
     catch (Exception ex)
     {
         AnalysisError Analysis_Error = new AnalysisError();
         string        SaveError      = Analysis_Error.CatchErrorForSave(ex, storedProcName, "ExecProc_NoReturn_1");
         //保存错误信息在Logs中
         Deal_error Dealerror = new Deal_error();
         Dealerror.deal_Error(SaveError, "OtherError", "ExecProc_NoReturn_1", 0);
     }
 }
示例#8
0
        ///// <summary>
        ///// 执行SQL语句,返回影响的记录数
        ///// </summary>
        ///// <param name="SQLString">SQL语句</param>
        ///// <returns>影响的记录数</returns>
        /////
        //public static int ExecuteSql(string SQLString)
        //{
        //    using (SqlConnection connection = new SqlConnection(connectionString))
        //    {
        //        using (SqlCommand cmd = new SqlCommand(SQLString, connection))
        //        {
        //            try
        //            {
        //                connection.Open();
        //                int rows = cmd.ExecuteNonQuery();
        //                return rows;
        //            }
        //            catch (System.Data.SqlClient.SqlException e)
        //            {
        //                connection.Close();
        //                throw e;
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        ///小万改造
        public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return(rows);
                    }
                    catch (Exception e)
                    {
                        AnalysisError Analysis_Error = new AnalysisError();
                        string        SaveError      = Analysis_Error.CatchErrorForSave(e, SQLString, "DbHelperExecuteSql");
                        Deal_error    Dealerror      = new Deal_error();
                        Dealerror.deal_Error(SaveError, "OtherError", "DbHelperExecuteSql", 0);
                        return(-1);
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }
示例#9
0
 /// <summary>
 /// 执行查询语句,返回DataSet
 /// </summary>
 /// <param name="SQLString">查询语句</param>
 /// <returns>DataSet</returns>
 /// //袁依平在用。。。。执行查询sql语句的方法
 public static DataSet Query(string SQLString)
 {
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         DataSet ds = new DataSet();
         try
         {
             connection.Open();
             SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
             command.Fill(ds, "ds");
         }
         catch (System.Data.SqlClient.SqlException ex)
         {
             AnalysisError Analysis_Error = new AnalysisError();
             string        SaveError      = Analysis_Error.CatchErrorForSave(ex, SQLString, "DbHelperSQLQuery");
             //保存错误信息在Logs中
             Deal_error Dealerror = new Deal_error();
             Dealerror.deal_Error(SaveError, "OtherError", "DbHelperSQLQuery", 0);
         }
         finally
         {
             connection.Close();
         }
         return(ds);
     }
 }
示例#10
0
        public override bool VisitArrayDeclaration(ArrayDeclarationAST arrayDeclaration)
        {
            arrayDeclaration.CurrentScope = _scope;

            //la clase base chequea q el id sea valido
            if (VisitTypeDeclaration(arrayDeclaration))
            {
                TigerType tt;
                if (_scope.HasType(arrayDeclaration.BaseTypeID, out tt) != ScopeLocation.NotDeclared)
                {
                    var at = new ArrayType(tt, arrayDeclaration.TypeId);
                    _scope.AddType(arrayDeclaration.TypeId, at);
                    return(true);
                }
                int savedErrorPos = _errorListener.Count;
                _scope.TypeAdded += (sender, args) =>
                {
                    if (args.TypeName == arrayDeclaration.BaseTypeID)
                    {
                        _scope.AddType(arrayDeclaration.TypeId, new ArrayType(args.NewType, arrayDeclaration.TypeId));
                    }
                };
                _scope.FinalizeScope += (sender, args) =>
                {
                    if (sender.HasType(arrayDeclaration.BaseTypeID) == ScopeLocation.NotDeclared)
                    {
                        _errorListener.Insert(savedErrorPos, AnalysisError.TypeIsNotDefined(arrayDeclaration, arrayDeclaration.BaseTypeID));
                        arrayDeclaration.ReturnType = TigerType.GetType <ErrorType>();
                    }
                };
                return(true);
            }
            return(false);
        }
示例#11
0
        public override bool VisitArrayAccess(ArrayAccessAST arrayAccess)
        {
            //esto es para quedarme con el scope actual
            arrayAccess.CurrentScope = _scope;


            arrayAccess.ReturnType = TigerType.GetType <ErrorType>();
            //visit the expression represeting the array
            arrayAccess.Array.Accept(this);
            //verifico que la expresion 'array' sea de tipo ArrayType
            var arrayType = arrayAccess.Array.ReturnType as ArrayType;

            if (arrayType != null)
            {
                arrayAccess.Indexer.Accept(this);
                //verifico que la expresion que indexada sea del tipo IntType
                var intType = arrayAccess.Indexer.ReturnType as IntType;
                if (intType != null)
                {
                    arrayAccess.ReturnType = arrayType.BaseType;
                    return(arrayAccess.AlwaysReturn = true);
                }
                _errorListener.Add(new AnalysisError(AnalysisError.LoadMessage("ArrayIndex"), arrayAccess.Line, arrayAccess.Columns));
                return(false);
            }
            _errorListener.Add(new AnalysisError(AnalysisError.LoadMessage("Index"), arrayAccess.Line, arrayAccess.Columns));
            return(false);
        }
示例#12
0
        //周海梅:找到指定节点的值并返回给调用者
        public string GetInnerText(string strXml, string parentNode, string xmlNode) //strXml:xml字符串//parentNode:父节点或者需要查找的大节点//xmlNode:需要找到的节点
        {
            string nodeText = "";

            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(strXml);
                XmlNode     root     = xml.SelectSingleNode(parentNode);
                XmlNodeList nodelist = root.ChildNodes;
                foreach (XmlNode node in nodelist)
                {
                    if (node.Name == xmlNode)
                    {
                        XmlElement ele = (XmlElement)node;
                        nodeText = ele.InnerText;
                    }
                }
            }
            catch (Exception ex)
            {
                AnalysisError Analysis_Error = new AnalysisError();
                string        SaveError      = Analysis_Error.CatchErrorForSave(ex, strXml, "xmlhelper_GetInnerText");
                //保存错误信息在Logs中
                Deal_error Dealerror = new Deal_error();
                Dealerror.deal_Error(SaveError, "OtherError", "xmlhelper_GetInnerText", 0);
            }
            return(nodeText);
        }
示例#13
0
        public override bool VisitRecordDeclaration(RecordDeclarationAST recordDeclaration)
        {
            recordDeclaration.CurrentScope = _scope;

            //se asuma que no habra problemas
            recordDeclaration.ReturnType = TigerType.GetType <NoType>();
            //la clase base verifica el ID del type
            if (VisitTypeDeclaration(recordDeclaration))
            {
                var rt = new RecordType(recordDeclaration.TypeId);
                //se anade el record creado al scope para q puedan haber records recursivos en su def
                _scope.AddType(recordDeclaration.TypeId, rt);
                //se verifica cada una de las declaraciones de los campos del record
                int savedErrorPos = _errorListener.Count;
                foreach (var kvp in recordDeclaration.Fields)
                {
                    if (!rt.Contains(kvp.Key))
                    {
                        TigerType tt;
                        if (_scope.HasType(kvp.Value, out tt) == ScopeLocation.NotDeclared)
                        {
                            KeyValuePair <string, string> savedKvp = kvp;
                            _scope.TypeAdded += (sender, args) =>
                            {
                                if (args.TypeName == savedKvp.Value)
                                {
                                    rt.AddField(savedKvp.Key, args.NewType);
                                }
                            };
                            _scope.FinalizeScope += (sender, args) =>
                            {
                                if (sender.HasType(savedKvp.Value) ==
                                    ScopeLocation.NotDeclared)
                                {
                                    _errorListener.Insert(savedErrorPos,
                                                          new AnalysisError(
                                                              string.Format(
                                                                  AnalysisError.LoadMessage("TypeUndecl"),
                                                                  savedKvp.Value), recordDeclaration.Line, recordDeclaration.Columns));
                                    recordDeclaration.ReturnType = TigerType.GetType <ErrorType>();
                                }
                            };
                        }
                        else
                        {
                            rt.AddField(kvp.Key, tt);
                        }
                    }
                    else
                    {
                        _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("RecDecl"), kvp.Key, recordDeclaration.TypeId),
                                                             recordDeclaration.Line, recordDeclaration.Columns));
                    }
                }
                //TODO aqui se ve el prob con los ret Types y los return true pq no se puede decir nada en este momento
                return(true);
            }
            return(false);
        }
示例#14
0
        public void WriteModularManifestFiles(IEnumerable <ConfigModel> services, Dictionary <string, Dictionary <string, string> > legacyAliases)
        {
            foreach (var project in services.GroupBy(service => service.AssemblyName)
                     .Where(project => project.Any((service) => !string.IsNullOrWhiteSpace(service.ServiceModuleGuid))))
            {
                try
                {
                    if (!legacyAliases.TryGetValue(project.Key, out var projectAliases))
                    {
                        projectAliases = new Dictionary <string, string>();
                    }

                    var dependencies = services
                                       .Where(service => !string.IsNullOrWhiteSpace(service.ServiceModuleGuid) &&
                                              project.First().SDKDependencies.Contains(service.AssemblyName))
                                       .ToArray();

                    var mainServiceConfig = project.Single(service => !string.IsNullOrEmpty(service.ServiceModuleGuid));

                    var fileContents = ManifestFileTemplate.Generate(
                        $"AWS.Tools.{project.Key}",
                        $"AWS.Tools.{project.Key}.dll",
                        mainServiceConfig.ServiceModuleGuid,
                        ModuleVersionNumber,
                        $"The {mainServiceConfig.AssemblyName} module of AWS Tools for PowerShell lets developers and administrators manage {mainServiceConfig.ServiceName} from the PowerShell scripting environment. In order to manage each AWS service, install the corresponding module (e.g. AWS.Tools.EC2, AWS.Tools.S3...)." + Environment.NewLine +
                        "The module AWS.Tools.Installer (https://www.powershellgallery.com/packages/AWS.Tools.Installer/) makes it easier to install, update and uninstall the AWS.Tools modules." + Environment.NewLine +
                        "This version of AWS Tools for PowerShell is compatible with Windows PowerShell 5.1+ and PowerShell Core 6+ on Windows, Linux and macOS. When running on Windows PowerShell, .NET Framework 4.7.2 or newer is required. Alternative modules AWSPowerShell.NetCore and AWSPowerShell, provide support for all AWS services from a single module and also support older versions of Windows PowerShell and .NET Framework.",
                        compatiblePowerShellVersion: 5,
                        compatiblePowerShellMinorVersion: 1,
                        assemblies: new string[] { $"AWSSDK.{project.Key}" }.Except(AwsToolsCommonSdkAssemblies),
                        formatsToProcessFiles: new string[] { $"AWS.Tools.{project.Key}.Format.ps1xml" },
                        fileList: new string[] { $"AWS.Tools.{project.Key}.dll-Help.xml" },
                        nestedModulesFiles: new string[] { $"AWS.Tools.{project.Key}.Completers.psm1",
                                                           $"AWS.Tools.{project.Key}.Aliases.psm1" },
                        requiredModules: dependencies
                        .Select(service => new ManifestFileTemplate.DependencyModule($"AWS.Tools.{service.AssemblyName}", service.ServiceModuleGuid))
                        .Concat(new ManifestFileTemplate.DependencyModule[] {
                        new ManifestFileTemplate.DependencyModule("AWS.Tools.Common", AWSPowerShellCommonGuid)
                    }),
                        cmdletsToExport: project
                        .SelectMany(service => service.ServiceOperationsList
                                    .Where(operation => !operation.Exclude))
                        .Select(operation => $"{operation.SelectedVerb}-{operation.SelectedNoun}")
                        .Concat(project
                                .SelectMany(service => service.AdvancedCmdlets.Keys))
                        .OrderBy(name => name),
                        aliasesToExport: projectAliases.Keys);

                    File.WriteAllText(Path.Combine(AwsPowerShellModuleFolder, CmdletGenerator.CmdletsOutputSubFoldername, project.Key, $"AWS.Tools.{project.Key}.psd1"), fileContents);
                }
                catch (Exception e)
                {
                    foreach (var service in project)
                    {
                        AnalysisError.ExceptionWhileWritingServiceProjectFile(service, e);
                    }
                }
            }
        }
示例#15
0
        /// <summary>
        /// This method verifies that the function signature is correct. That is that the return type and parameter types are already
        /// defined. It also verifies that the function does not exist in the scope.
        /// </summary>
        /// <param name="fDecl"></param>
        /// <returns></returns>
        private bool CheckFunctionSignature(FunctionDeclarationAST fDecl)
        {
            TigerType ret = null;

            if (!string.IsNullOrEmpty(fDecl.ReturnTypeId))
            {
                //si se especifica retorno pero este no es un tipo ya definido ERROR
                //esto lo garantiza haber organizado las declaraciones
                if (_scope.HasType(fDecl.ReturnTypeId, out ret) == ScopeLocation.NotDeclared)
                {
                    _errorListener.Add(AnalysisError.TypeIsNotDefined(fDecl, fDecl.ReturnTypeId));
                    fDecl.ReturnType = TigerType.GetType <ErrorType>();
                    return(false);
                }
                if (!ret.IsLegalType)
                {
                    //TODO: Hasta que punto interesa lanzar este error??
                    _errorListener.Add(new AnalysisError(
                                           string.Format(AnalysisError.LoadMessage("InavalidRet"), fDecl.ReturnTypeId), fDecl.Line,
                                           fDecl.Columns));
                    fDecl.ReturnType = TigerType.GetType <ErrorType>();
                    return(false);
                }
            }

            //ver que la funcion no este previamente declarada
            if (_scope.HasFunction(fDecl.FunctionId) == ScopeLocation.NotDeclared)
            {
                var paramsInfo = new List <KeyValuePair <string, TigerType> >();
                foreach (var nameType in fDecl.ParameterList)
                {
                    TigerType t;
                    //verificar si existe el tipo del parametro.
                    if (_scope.HasType(nameType.Value, out t) == ScopeLocation.NotDeclared)
                    {
                        _errorListener.Add(new AnalysisError(
                                               $"Type {nameType.Value} in parameter {fDecl.FunctionId} is not defined", fDecl.Line, fDecl.Columns));
                        fDecl.ReturnType = TigerType.GetType <ErrorType>();
                        return(false);
                    }
                    paramsInfo.Add(new KeyValuePair <string, TigerType>(nameType.Key, t));
                }
                var funInfo = new FunctionInfo(paramsInfo, ret ?? TigerType.GetType <NoType>())
                {
                    FunctionName   = fDecl.FunctionId,
                    FunctionParent = _scope.CurrentFunction
                };
                //se anade en el padre para q este disponible en el scope donde se declara
                _scope.AddFunction(fDecl.FunctionId, funInfo);
                return(true);
            }

            //ya habia una funcion con ese nombre
            _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("FuncDecl"), fDecl.FunctionId), fDecl.Line,
                                                 fDecl.Columns));
            return(false);
        }
示例#16
0
        /// <summary>
        /// Analyzes the supplied method to determine the cmdlet that should be generated
        /// and the inputs/outputs for the cmdlet. Once analysis is complete, the cmdlet
        /// source file will be generated.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="configModel"></param>
        private void CreateCmdlet(MethodInfo method, ConfigModel configModel)
        {
            Logger.Log();
            Logger.Log("Analyzing method [{0}.{1}]", method.DeclaringType.FullName, method.Name);

            // operation config
            var serviceOperation = configModel.ServiceOperations[method.Name];

            CurrentOperation = serviceOperation;

            try
            {
                // capture the analyzer so we can serialize the config as json later
                serviceOperation.Analyzer = new OperationAnalyzer(ModelCollection, CurrentModel, CurrentOperation, CurrentServiceNDoc);
                serviceOperation.Analyzer.Analyze(this, method);
            }
            catch (Exception e)
            {
                AnalysisError.ExceptionWhileAnalyzingSDKLibrary(CurrentModel, CurrentOperation, e);
            }

            if (serviceOperation.AnalysisErrors.Count == 0)
            {
                // set file name and location
                var filePath = Path.Combine(configModel.AssemblyName, GeneratedCmdletsFoldername, $"{serviceOperation.SelectedVerb}-{serviceOperation.SelectedNoun}-Cmdlet.cs");

                try
                {
                    using (var sw = new StringWriter())
                    {
                        using (var writer = new IndentedTextWriter(sw))
                        {
                            new CmdletSourceWriter(serviceOperation.Analyzer, Options).Write(writer);
                        }

                        var fileContents = sw.ToString();
                        File.WriteAllText(Path.Combine(CmdletsOutputPath, filePath), fileContents);
                    }
                }
                catch (Exception e)
                {
                    AnalysisError.ExceptionWhileWritingCmdletCode(CurrentModel, CurrentOperation, e);
                }

                if (!method.Name.EndsWith(AsyncSuffix))
                {
                    throw new ArgumentException($"Method {method.Name} name doesn't end with suffix {AsyncSuffix}");
                }

                string methodName = method.Name.Substring(0, method.Name.Length - AsyncSuffix.Length);

                AliasStore.Instance.AddAlias(string.Format("{0}-{1}", serviceOperation.SelectedVerb, serviceOperation.SelectedNoun),
                                             string.Format("{0}-{1}", configModel.ServiceNounPrefix, methodName));
            }
        }
示例#17
0
        public override bool VisitFunctionDeclaration(FunctionDeclarationAST functionDeclaration)
        {
            //chequear la semantica del cuerpo de la funcion, la signatura ya fue chequeada en el let correspondiente
            //here we create a new scope for this function and its parameters
            PushScope(new Scope(_scope));

            //verificar que todos los tipos de los parametros existan y si ya existe el nombre de los parametros
            //en el scope

            if (!CheckFunctionParams(functionDeclaration))
            {
                PopScope();
                return(false);
            }

            functionDeclaration.CurrentScope = _scope;
            TigerType retType = functionDeclaration.ReturnTypeId != null?
                                functionDeclaration.CurrentScope.GetType(functionDeclaration.ReturnTypeId) : TigerType.GetType <NoType>();


            //poner esta funcion como la funcion actual de scope donde se encuentra.
            FunctionInfo temp = _scope.CurrentFunction;

            _scope.CurrentFunction = _scope.GetFunction(functionDeclaration.FunctionId);

            functionDeclaration.ExprInstructions.Accept(this);

            _scope.CurrentFunction = temp;

            if (!functionDeclaration.ExprInstructions.AlwaysReturn && retType != TigerType.GetType <NoType>())
            {
                _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("FuncDeclRet"), functionDeclaration.FunctionId),
                                                     functionDeclaration.Line, functionDeclaration.Columns));
            }
            else if (string.IsNullOrEmpty(functionDeclaration.ReturnTypeId) ||
                     functionDeclaration.ExprInstructions.ReturnType.CanConvertTo(
                         _scope.GetType(functionDeclaration.ReturnTypeId)))
            {
                PopScope();
                return(true);
            }
            else
            {
                _errorListener.Add(
                    new AnalysisError(
                        string.Format(AnalysisError.LoadMessage("Match"), functionDeclaration.ReturnTypeId,
                                      functionDeclaration.ExprInstructions.ReturnType), functionDeclaration.Line,
                        functionDeclaration.Columns));
            }
            functionDeclaration.ReturnType = TigerType.GetType <ErrorType>();

            PopScope();
            return(false);
        }
示例#18
0
 private bool VisitTypeDeclaration(TypeDeclarationAST typeDeclaration)
 {
     if (_scope.HasType(typeDeclaration.TypeId, out _) != ScopeLocation.NotDeclared)
     {
         _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("TypeDecl"), typeDeclaration.TypeId), typeDeclaration.Line, typeDeclaration.Columns));
         typeDeclaration.ReturnType = TigerType.GetType <ErrorType>();
         return(false);
     }
     typeDeclaration.ReturnType = TigerType.GetType <NoType>();
     return(true);
 }
示例#19
0
 private ErrorTask CreateErrorTask(AnalysisError analysisError)
 {
     return(new ErrorTask
     {
         ErrorCategory =
             analysisError.Severity == AnalysisErrorSeverity.Error ? TaskErrorCategory.Error
                                 : analysisError.Severity == AnalysisErrorSeverity.Warning ? TaskErrorCategory.Warning
                                 : TaskErrorCategory.Message,
         Text = analysisError.Message,
         Document = analysisError.Location.File,
         Line = analysisError.Location.StartLine - 1,                 // Line appears to be 0-based in VS! :-(
         Column = analysisError.Location.StartColumn
     });
 }
示例#20
0
        public override bool VisitBreakStatement(BreakAST breakStm)
        {
            breakStm.CurrentScope = _scope;

            if (!_scope.IsInLoop)
            {
                _errorListener.Add(new AnalysisError(AnalysisError.LoadMessage("Break"), breakStm.Line, breakStm.Columns));
                breakStm.ReturnType = TigerType.GetType <ErrorType>();
                return(false);
            }
            breakStm.BreakeableLoop = _scope.ContainerLoop;
            breakStm.ReturnType     = TigerType.GetType <NoType>();
            return(true);
        }
示例#21
0
        private void CheckForServicePrefixDuplication()
        {
            //We count the distinct service namespaces because DDB has two clients but a single namespace.
            var duplicatedPrefixes = ModelCollection.ConfigModels.Values
                                     .GroupBy(service => service.ServiceNounPrefix, StringComparer.InvariantCultureIgnoreCase)
                                     .Where(group => group.Select(service => service.ServiceNamespace).Distinct().Count() > 1);

            foreach (var group in duplicatedPrefixes)
            {
                foreach (var service in group)
                {
                    AnalysisError.DuplicatedServicePrefix(service, group);
                }
            }
        }
示例#22
0
 public override bool VisitNegExpression(NegExpressionAST negExpression)
 {
     negExpression.CurrentScope = _scope;
     if (negExpression.Expression.Accept(this))
     {
         if (negExpression.Expression.ReturnType == TigerType.GetType <IntType>())
         {
             negExpression.ReturnType = TigerType.GetType <IntType>();
             return(true);
         }
         _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("NegExp"), negExpression.Expression.ReturnType), negExpression.Line,
                                              negExpression.Columns));
     }
     negExpression.ReturnType = TigerType.GetType <ErrorType>();
     return(false);
 }
示例#23
0
 public void AddLegacyAlias(string cmdletName, string aliasName)
 {
     if (LegacyAliases.TryGetValue(CurrentModel.AssemblyName, out var aliases))
     {
         if (aliases.TryGetValue(aliasName, out var existingCmdletName))
         {
             AnalysisError.DuplicatedLegacyAlias(CurrentModel, aliasName, cmdletName, existingCmdletName);
             return;
         }
     }
     else
     {
         aliases = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
         LegacyAliases.Add(CurrentModel.AssemblyName, aliases);
     }
     aliases.Add(aliasName, cmdletName);
 }
示例#24
0
        //袁依平正在用。。。执行sql语句插入、修改、删除的方法
        public static int ExecuteSqlTran(List <String> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                int    count  = 0;
                string strsql = "";
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count          += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return(count);
                }
                catch (Exception ex)
                {
                    tx.Rollback();

                    AnalysisError Analysis_Error = new AnalysisError();
                    string        SaveError      = Analysis_Error.CatchErrorForSave(ex, strsql, "DbHelperExecuteSqlTran");
                    //保存错误信息在Logs中
                    Deal_error Dealerror = new Deal_error();
                    Dealerror.deal_Error(SaveError, "OtherError", "DbHelperExecuteSqlTran", 0);

                    return(-1);
                    // throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
        }
示例#25
0
        public override bool VisitFunctionInvocation(CallFunctionAST functionInvocation)
        {
            //probablemente se cambie
            functionInvocation.CurrentScope = _scope;

            bool ok = true;

            FunctionInfo functionInfo;
            string       message;

            //verificar que la funcion existe.
            if (_scope.HasFunction(functionInvocation.FunctionId, out functionInfo) != ScopeLocation.NotDeclared)
            {
                //coger su tipo de retorno
                if (functionInfo.ParameterList.Count == functionInvocation.RealParam.Count)
                {
                    for (int i = 0; i < functionInfo.ParameterList.Count; i++)
                    {
                        //no es necesario chequear q el chequeo de los parametros sea true o no
                        functionInvocation.RealParam[i].Accept(this);
                        ok = ok && (functionInvocation.RealParam[i].ReturnType.CanConvertTo(functionInfo.ParameterList[i].Value));
                    }
                    if (ok)
                    {
                        functionInvocation.AlwaysReturn = !(functionInfo.FunctionReturnType is NoType);
                        functionInvocation.ReturnType   = functionInfo.FunctionReturnType;
                        return(true);
                    }
                    message = string.Format(AnalysisError.LoadMessage("FuncParams"), functionInvocation.FunctionId);
                }
                else
                {
                    message = string.Format(AnalysisError.LoadMessage("FuncParamsCount"), functionInvocation.FunctionId, functionInvocation.RealParam.Count);
                }
            }
            else
            {
                message = string.Format(AnalysisError.LoadMessage("FuncUndecl"), functionInvocation.FunctionId);
            }
            _errorListener.Add(new AnalysisError(message, functionInvocation.Line, functionInvocation.Columns));
            functionInvocation.ReturnType = TigerType.GetType <ErrorType>();
            return(false);
        }
示例#26
0
        public override bool VisitRecordInstantiation(RecordInstantiationAST recordInstantiation)
        {
            recordInstantiation.CurrentScope = _scope;

            TigerType  tt;
            RecordType rt;

            //verificando que exista el tipo,
            if (_scope.HasType(recordInstantiation.Id, out tt) != ScopeLocation.NotDeclared && (rt = tt as RecordType) != null)
            {
                recordInstantiation.ReturnType = rt;
                if (recordInstantiation.ExpressionValue == null)
                {
                    return(true);
                }

                foreach (var kvp in recordInstantiation.ExpressionValue)
                {
                    kvp.Value.Accept(this);
                    if (rt.Contains(kvp.Key))
                    {
                        if (kvp.Value.ReturnType.CanConvertTo(rt[kvp.Key]))
                        {
                            continue;
                        }
                        _errorListener.Add(
                            new AnalysisError(
                                string.Format(AnalysisError.LoadMessage("Match"), kvp.Value.ReturnType, rt[kvp.Key].TypeID),
                                recordInstantiation.Line, recordInstantiation.Columns));
                    }
                    else
                    {
                        _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("RecField"), recordInstantiation.Id, kvp.Key), recordInstantiation.Line,
                                                             recordInstantiation.Columns));
                    }
                    recordInstantiation.ReturnType = TigerType.GetType <ErrorType>();
                }
                return(recordInstantiation.ReturnType != TigerType.GetType <ErrorType>());
            }
            recordInstantiation.ReturnType = TigerType.GetType <ErrorType>();
            _errorListener.Add(AnalysisError.TypeIsNotDefined(recordInstantiation, recordInstantiation.Id));
            return(false);
        }
示例#27
0
        public override bool VisitBinaryExpression(BinaryExpressionAst expr)
        {
            expr.LeftExp.Accept(this);
            TigerType leftType = expr.LeftExp.ReturnType;

            expr.RightExp.Accept(this);
            TigerType rightType = expr.RightExp.ReturnType;

            if (CheckOperator(leftType, rightType, expr.Operator, out var tt))
            {
                expr.ReturnType = tt;
                return(true);
            }
            _errorListener.Add(
                new AnalysisError(string.Format(AnalysisError.LoadMessage("SupportOp"), expr.Operator, leftType, rightType), expr.Line,
                                  expr.Columns));
            expr.ReturnType = TigerType.GetType <ErrorType>();
            return(false);
        }
示例#28
0
        public override bool VisitForExpression(ForExpressionAST forExpression)
        {
            forExpression.ExpressionFrom.Accept(this);
            forExpression.ReturnType = TigerType.GetType <ErrorType>();
            //si la expresion "from" no es de tipo entero.
            if (forExpression.ExpressionFrom.ReturnType != TigerType.GetType <IntType>())
            {
                _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("ForInit"), forExpression.VarId), forExpression.Line,
                                                     forExpression.Columns));
            }
            else
            {
                forExpression.ExpressionTo.Accept(this);
                // si la expresion "to" no es tipo entero.
                if (forExpression.ExpressionTo.ReturnType != TigerType.GetType <IntType>())
                {
                    _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("ForStop"), forExpression.VarId),
                                                         forExpression.Line, forExpression.Columns));
                }
                else
                {
                    var sc = new Scope(_scope, forExpression);
                    forExpression.CurrentScope = sc;
                    if (_scope.HasVar(forExpression.VarId) != ScopeLocation.NotDeclared)
                    {
                        _errorListener.Add(new AnalysisError(string.Format(AnalysisError.LoadMessage("VarDecl"), forExpression.VarId),
                                                             forExpression.Line, forExpression.Columns));
                        forExpression.ReturnType = TigerType.GetType <ErrorType>();
                        return(false);
                    }
                    //annado la variable al scope
                    sc.AddVarFor(forExpression.VarId, TigerType.Int);

                    if (forExpression.BodyExpressions.Accept(this))
                    {
                        forExpression.ReturnType = forExpression.BodyExpressions.ReturnType;
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#29
0
        public override bool VisitAssignExpression(AssignExpressionAST assignExpression)
        {
            assignExpression.CurrentScope = _scope;

            assignExpression.ReturnType = TigerType.GetType <ErrorType>();
            if (!assignExpression.LeftExpression.Accept(this) || !assignExpression.RightExpression.Accept(this))
            {
                return(false);
            }
            if (assignExpression.RightExpression.ReturnType.CanConvertTo(assignExpression.LeftExpression.ReturnType))
            {
                assignExpression.ReturnType = TigerType.GetType <NoType>();
                return(true);
            }
            _errorListener.Add(
                new AnalysisError(
                    string.Format(AnalysisError.LoadMessage("Match"), assignExpression.LeftExpression.ReturnType, assignExpression.RightExpression.ReturnType),
                    assignExpression.Line, assignExpression.Columns));
            return(false);
        }
示例#30
0
        public override bool VisitArrayInstantiation(ArrayInstatiationAST arrayInstatiation)
        {
            arrayInstatiation.CurrentScope = _scope;

            arrayInstatiation.ReturnType = TigerType.GetType <ErrorType>();
            TigerType t;

            if (_scope.HasType(arrayInstatiation.ArrayTypeIdentifier, out t) != ScopeLocation.NotDeclared)
            //Chequeo si este tipo de array fue declarado
            {
                var typeArray = t as ArrayType;
                if (typeArray != null)
                {
                    arrayInstatiation.SizeExp.Accept(this);
                    if (arrayInstatiation.SizeExp.ReturnType != TigerType.GetType <IntType>())
                    {
                        //Chequeo que el length del array sea un entero
                        _errorListener.Add(new AnalysisError(AnalysisError.LoadMessage("ArrayIndex"), arrayInstatiation.Line, arrayInstatiation.Columns));
                    }
                    else
                    {
                        arrayInstatiation.InitializationExp.Accept(this);
                        if (!arrayInstatiation.InitializationExp.ReturnType.CanConvertTo(typeArray.BaseType))
                        {
                            _errorListener.Add(
                                new AnalysisError(
                                    string.Format(AnalysisError.LoadMessage("Match"), arrayInstatiation.InitializationExp.ReturnType,
                                                  typeArray.BaseType), arrayInstatiation.Line, arrayInstatiation.Columns));
                        }
                        else
                        {
                            arrayInstatiation.ReturnType = typeArray;
                            return(arrayInstatiation.AlwaysReturn = true);
                        }
                    }
                    return(false);
                }
            }
            _errorListener.Add(AnalysisError.TypeIsNotDefined(arrayInstatiation, arrayInstatiation.ArrayTypeIdentifier));
            return(false);
        }