Exemplo n.º 1
0
        private void Analyzer(SyntaxNodeAnalysisContext context)
        {
            var mainConstrutor = new MethodInformation(
                "Uri",
                "System.Uri.Uri(string)",
                args =>
            {
                {
                    if (args[0] == null)
                    {
                        return;
                    }
                    new Uri(args[0].ToString());
                }
            }
                );
            var constructorWithUriKind = new MethodInformation(
                "Uri",
                "System.Uri.Uri(string, System.UriKind)",
                args =>
            {
                if (args[0] == null)
                {
                    return;
                }
                new Uri(args[0].ToString(), (UriKind)args[1]);
            }
                );

            var checker = new MethodChecker(context, Rule);

            checker.AnalyzeConstrutor(mainConstrutor);
            checker.AnalyzeConstrutor(constructorWithUriKind);
        }
Exemplo n.º 2
0
        public void AddMethod(Guid classId, MethodInformation m)
        {
            var methodId = Guid.NewGuid();

            this.writer.AddDocument(new Document
            {
                new StringField("_id", methodId.ToString(), Field.Store.NO),
                new StringField("_classId", classId.ToString(), Field.Store.NO),
                new TextField("name", m.Name, Field.Store.YES),
                new TextField("returnType", m.ReturnType, Field.Store.YES),
                new StringField("type", "Method", Field.Store.YES),
            });

            int order = 0;

            foreach (var p in m.Parameters)
            {
                this.writer.AddDocument(new Document
                {
                    new StringField("_methodId", methodId.ToString(), Field.Store.YES),
                    new TextField("name", p.ParameterType, Field.Store.YES),
                    new StoredField("parameterOrder", order++),
                    new StoredField("clrType", p.ParameterType),
                    new Int32Field("type", (int)DocumentType.MethodParameter, Field.Store.YES),
                });
            }
        }
        public void GetTypeInformation_ReturnsCalculationObjectWithValidPrintMethod()
        {
            // Act
            IEnumerable <TypeInformation> result = WhenTypeInformationForTheAssemblyIsCreated(GetEmptyDatasetExampleAssembly());

            // Assert
            result.Should().NotBeNull("Result should not be null");

            result.Should().Contain(c => c.Name == "Calculations");

            TypeInformation calculationType = result.Where(e => e.Name == "Calculations").FirstOrDefault();

            calculationType.Methods.Should().ContainSingle(c => c.Name == "Print", "a single Print function should exist");

            MethodInformation printFunction = calculationType.Methods.Where(c => c.Name == "Print").SingleOrDefault();

            printFunction.Name.Should().Be("Print");

            printFunction.Parameters.Should().HaveCount(3);
            List <ParameterInformation> parameters = new List <ParameterInformation>(printFunction.Parameters);

            parameters[0].Name.Should().Be("value");
            parameters[0].Description.Should().Be("value");
            parameters[0].Type.Should().Be("T");

            parameters[1].Name.Should().Be("name");
            parameters[1].Description.Should().Be("name");
            parameters[1].Type.Should().Be("String");

            parameters[2].Name.Should().Be("rid");
            parameters[2].Description.Should().Be("rid");
            parameters[2].Type.Should().Be("String");

            printFunction.ReturnType.Should().BeNull();
        }
Exemplo n.º 4
0
        public static async Task SaveUserChanges()
        {
            MethodInformation info = null;

            CurrentUser = ControllerRepository.Db(x => x.SaveUser(CurrentUser), (u, i) => { info = u; });
            await info?.ExecuteTrigger();
        }
Exemplo n.º 5
0
        public void WriteParameters()
        {
            MethodInformation mi = Procedures[current_method];

            if (mi.arg_names != null && mi.arg_names.Length > 0)
            {
                indent_level += 3;
                for (int i = 0; i < mi.arg_names.Length; i++)
                {
                    Indent();
                    if (variables.Contains(mi.arg_names[i].ToLower()))
                    {
                        stream.Write(" ??_Variable");
                        variables.Remove(mi.arg_names[i]);
                    }
                    else if (arrays.Contains(current_method.ToLower()))
                    {
                        stream.Write(" ??_Array");
                        arrays.Remove(mi.arg_names[i]);
                    }
                    else if (arrays_2d.Contains(current_method.ToLower()))
                    {
                        stream.Write(" ??_Array_2D");
                        arrays_2d.Remove(mi.arg_names[i]);
                    }
                    else
                    {
                        stream.Write(" ??");
                    }
                    if (mi.args_are_output[i])
                    {
                        stream.Write(" *");
                    }
                    else
                    {
                        stream.Write(" ");
                    }
                    stream.Write(mi.arg_names[i]);

                    if (i < mi.arg_names.Length - 1)
                    {
                        stream.WriteLine(";");
                    }
                    else
                    {
                        stream.WriteLine(")");
                    }
                }
                indent_level -= 3;

                indent_level -= 3;
                Indent();
                stream.WriteLine("{");
                indent_level += 3;
            }
            else
            {
                stream.WriteLine(" {");
            }
        }
Exemplo n.º 6
0
        public T ExecuteInterfaceMethod <T>(MethodInformation method, Action <T> action)
        {
            DataOptType dataOptType = ((IDataInterface)this).dataOptType;

            method.dataProviderNamespace = dataProviderNamespace;
            method.dataProviderClassName = dataProviderClassName;
            method.fields           = fields;
            method.fieldsType       = fieldsType;
            method.ResultExecMethod = ResultExecMethod;
            method.sqlExecType      = sqlExecType;

            string sqlVarName = "sql";
            DynamicCodeAutoCall dynamicCodeAutoCall = new DynamicCodeAutoCall();

            sql = dynamicCodeAutoCall.ExecReplaceForSqlByFieldName(sql, sqlVarName, method);

            DynamicCodeChange dynamicCodeChange = new DynamicCodeChange();

            try
            {
                dynamicCodeChange.AnalyzeSql(method, dataOptType, sqlVarName, ref sql);
            }
            catch (Exception ex)
            {
                e(ex.ToString(), ErrorLevels.severe);
                throw ex;
            }

            DynamicEntity dynamicEntity = new DynamicEntity();
            T             result        = dynamicEntity.Exec <T>(method, dataOptType, action, sql);

            return(result);
        }
Exemplo n.º 7
0
        public static MethodInformation ProcessMethod(MethodInfo method)
        {
            MappingAttribute mappingAttribute = null;
            GetAttribute     getAttribute     = null;
            IList <Type>     args             = method.GetParameters().Select(arg => arg.ParameterType).ToList();

            foreach (var attr in method.GetCustomAttributes <Attribute>())
            {
                switch (attr)
                {
                case MappingAttribute ma:
                    mappingAttribute = ma;
                    break;

                case GetAttribute ga:
                    getAttribute = ga;
                    break;
                }
            }

            var info = new MethodInformation {
                Name = method.Name, ReturnType = method.ReturnType, Args = args
            };

            if (mappingAttribute != null)
            {
                info.Mapping = mappingAttribute;
            }
            if (getAttribute != null)
            {
                info.Get = getAttribute;
            }
            info.MethodAttrs = method.Attributes;
            return(info);
        }
Exemplo n.º 8
0
        public async Task DataBinder(MethodInformation method = null)
        {
            if (!this.UserIsLogedIn())
            {
                return;
            }


            var l = await this.StartLoading();

            myPlaylist.ItemsSource              = UserData.VideoCategoryViews;
            myPlaylist.Header.IsVisible         = myPlaylist.HasItems;
            playListSuggesting.ItemsSource      = ControllerRepository.Db(x => x.GetUserSuggestion(UserData.CurrentUser.EntityId.Value));
            playListSuggesting.Header.IsVisible = playListSuggesting.HasItems;
            playListUserSeach.ItemsSource       = ControllerRepository.Y(x => x.SearchAsync(UserData.CurrentUser.EntityId.Value, "", 10, 1, null, VideoSearchType.Recommendation)).Await()?.ToItemList();
            playListUserSeach.Header.IsVisible  = playListUserSeach.HasItems;
            //adsBanner.IsVisible = UserData.CurrentUser.UserType != UserType.Premium;
            l.EndLoading();

            if (!myPlaylist.HasItems && !UserData.Notified)
            {
                UserData.Notified = true;
                var config = new ToastConfig("BackgroundModeMessage".GetString())
                             .SetDuration(TimeSpan.FromSeconds(8))
                             .SetMessageTextColor(Color.Red)
                             .SetBackgroundColor(Color.WhiteSmoke)
                             .SetPosition(ToastPosition.Bottom);
                UserDialogs.Instance.Toast(config);
            }
            // start the ads
            //await Methods.ReguastNewAdd?.Invoke();
        }
Exemplo n.º 9
0
 public void Start_Method(string name)
 {
     if (name == "Main")
     {
         // I'm not sure how to work globals into the output.  This appears to be an abstract class that is 
         // called by other methods in Martin's code.  I'll proceed with all local variables for now . . .
         Indent();
         stream.WriteLine("public static void main(String[] args)");
         Indent();
         stream.WriteLine("{");
     }
     else
     {
         Indent();
         // Without globals, we can't use static, or class methods; we can only use instance methods
         // Class methods can only act on global (static) variables
         MethodInformation mi = Procedures[name];
         if (hasReturnValue(mi, name))
         {
              stream.Write("public static ??" ); 
             // finish writing method name with parameters if has return value
             // have to test for array return, cannot do here
         }
         else
         {
             stream.Write("public static void " + name+"(" );
         }
     }
     variables.Clear();
     arrays.Clear();
     arrays_2d.Clear();
     strings.Clear();
     current_method = name;
     indent_level += 3;
 }
Exemplo n.º 10
0
        public void GetTypeInformation_ReturnsCalculationObjectWithValidIntellisenseMethod()
        {
            // Arrange
            ICodeMetadataGeneratorService generator = GetCodeGenerator();

            byte[] assembly = GetEmptyDatasetExampleAssembly();

            // Act
            IEnumerable <TypeInformation> result = generator.GetTypeInformation(assembly);

            // Assert
            result.Should().NotBeNull("Result should not be null");

            result.Should().Contain(c => c.Name == "Calculations");

            TypeInformation calculationType = result.Where(e => e.Name == "Calculations").FirstOrDefault();

            calculationType.Methods.Should().ContainSingle(c => c.Name == "Print", "a single Print function should exist");

            MethodInformation intellisenseMethod = calculationType.Methods.Where(c => c.Name == "Intellisense").SingleOrDefault();

            intellisenseMethod.Name.Should().Be("Intellisense");
            intellisenseMethod.Parameters.Should().HaveCount(0);

            intellisenseMethod.ReturnType.Should().Be("Decimal");
            intellisenseMethod.EntityId.Should().Be("24a85b7f-200a-4bd3-a1d0-ed883c4eb868");
        }
Exemplo n.º 11
0
        public void GetTypeInformation_WhenFeatureToggleIsOn_SetsIsCustomToTrue()
        {
            // Arrange
            ICodeMetadataGeneratorService generator = GetCodeGenerator();

            byte[] assembly = GetCalculationClassWithListDescriptionsExampleAssembly();

            // Act
            IEnumerable <TypeInformation> result = generator.GetTypeInformation(assembly);

            // Assert
            result.Should().NotBeNull("Result should not be null");

            result.Should().ContainSingle(c => c.Name == "Calculations");

            TypeInformation datasetType = result.Where(e => e.Name == "Calculations").FirstOrDefault();

            datasetType.Name.Should().Be("Calculations");
            datasetType.Description.Should().BeNull();
            datasetType.Type.Should().Be("Calculations");

            List <MethodInformation> methods = new List <MethodInformation>(datasetType.Methods);

            methods.Should().HaveCount(5, "Calculations should contain expected number of methods");

            MethodInformation firstCalculation = methods.Where(m => m.Name == "ABHighNeedsCalc002").SingleOrDefault();

            firstCalculation.Should().NotBeNull("firstCalculation should not be null");
            firstCalculation.Name.Should().Be("ABHighNeedsCalc002");
            firstCalculation.FriendlyName.Should().Be("AB High Needs Calc 002");
            firstCalculation.Description.Should().Be("test");
            firstCalculation.IsCustom.Should().BeTrue();
        }
Exemplo n.º 12
0
        internal static MethodInfo FindBestMethod(DynamicMetaObject target, IEnumerable <DynamicMetaObject> args, string methodName, bool @static, PSMethodInvocationConstraints invocationConstraints)
        {
            bool       flag         = false;
            MethodInfo methodInfo   = null;
            PSMethod   dotNetMethod = PSObject.dotNetInstanceAdapter.GetDotNetMethod <PSMethod>(PSObject.Base(target.Value), methodName);

            if (dotNetMethod != null)
            {
                DotNetAdapter.MethodCacheEntry methodCacheEntry = (DotNetAdapter.MethodCacheEntry)dotNetMethod.adapterData;
                string str  = null;
                string str1 = null;
                MethodInformation[]             methodInformationArray       = methodCacheEntry.methodInformationStructures;
                PSMethodInvocationConstraints   pSMethodInvocationConstraint = invocationConstraints;
                IEnumerable <DynamicMetaObject> dynamicMetaObjects           = args;
                MethodInformation methodInformation = Adapter.FindBestMethod(methodInformationArray, pSMethodInvocationConstraint, dynamicMetaObjects.Select <DynamicMetaObject, object>((DynamicMetaObject arg) =>
                {
                    if (arg.Value == AutomationNull.Value)
                    {
                        return(null);
                    }
                    else
                    {
                        return(arg.Value);
                    }
                }
                                                                                                                                                                                         ).ToArray <object>(), ref str, ref str1, out flag);
                if (methodInformation != null)
                {
                    methodInfo = (MethodInfo)methodInformation.method;
                }
            }
            return(methodInfo);
        }
Exemplo n.º 13
0
        public void ResolveMethodInformation_SecondTime_ReturnsSameInformation()
        {
            MethodInformation information1 = _service.ResolveMethodInformation(typeof(RuntimeType), "MyMethod", new Type[] { typeof(string) });
            MethodInformation information2 = _service.ResolveMethodInformation(typeof(RuntimeType), "MyMethod", new Type[] { typeof(string) });

            Assert.AreSame(information1, information2);
        }
Exemplo n.º 14
0
        public PageModel(List <ApiControllerInformation> apiInformation, string apiId, string controllerName = "", string methodName = "", string attributeId = "")
        {
            ApiId         = apiId;
            ApiInfo       = apiInformation;
            CurrentMethod = new MethodInformation();

            if (!String.IsNullOrEmpty(controllerName))
            {
                CurrentApi = ApiInfo.Where(x => x.ControllerName == controllerName).FirstOrDefault();

                if (!String.IsNullOrEmpty(methodName))
                {
                    CurrentMethod = CurrentApi.Methods.Where(x => x.Name == methodName && x.Attributes.Contains(attributeId)).FirstOrDefault();
                }
                else
                {
                    CurrentMethod = new MethodInformation {
                        Name = "METHOD NOT FOUND"
                    };
                }
            }
            else
            {
                CurrentApi = new ApiControllerInformation();
            }
        }
Exemplo n.º 15
0
        protected override IEnumerable <MethodInformation> GetMethods(ProxyContext proxyContext)
        {
            if (proxyContext == null)
            {
                throw new ArgumentNullException("proxyContext");
            }

            MethodInformation iteratorVariable1 = new MethodInformation
            {
                Name                   = "ReturnInt",
                IsStatic               = false,
                OperationType          = OperationType.Default,
                ClientLibraryTargets   = ClientLibraryTargets.All,
                OriginalName           = "ReturnInt",
                WildcardPath           = false,
                ReturnType             = typeof(int),
                ReturnODataType        = ODataType.Primitive,
                RESTfulExtensionMethod = true,
                ResourceUsageHints     = ResourceUsageHints.None,
                RequiredRight          = ResourceRight.Default
            };

            yield return(iteratorVariable1);

            MethodInformation iteratorVariable2 = new MethodInformation
            {
                Name                   = "ReturnDate",
                IsStatic               = false,
                OperationType          = OperationType.Default,
                ClientLibraryTargets   = ClientLibraryTargets.All,
                OriginalName           = "ReturnDate",
                WildcardPath           = false,
                ReturnType             = typeof(DateTime),
                ReturnODataType        = ODataType.Primitive,
                RESTfulExtensionMethod = true,
                ResourceUsageHints     = ResourceUsageHints.None,
                RequiredRight          = ResourceRight.Default
            };

            yield return(iteratorVariable2);

            MethodInformation iteratorVariable3 = new MethodInformation
            {
                Name                   = ".ctor",
                IsStatic               = false,
                OperationType          = OperationType.Default,
                ClientLibraryTargets   = ClientLibraryTargets.RESTful,
                OriginalName           = ".ctor",
                WildcardPath           = false,
                ReturnType             = null,
                ReturnODataType        = ODataType.Invalid,
                RESTfulExtensionMethod = false,
                ResourceUsageHints     = ResourceUsageHints.None,
                RequiredRight          = ResourceRight.None
            };

            yield return(iteratorVariable3);
        }
Exemplo n.º 16
0
        public static async Task ExecuteTrigger(this MethodInformation methodInformation)
        {
            var triggers = ObjectCacher.ModuleTriggerCacher.Where(x => x.Value.Any(a => a == methodInformation.ToString())).ToList();

            foreach (var x in triggers)
            {
                await x.Key.DataBinder(methodInformation);
            }
        }
Exemplo n.º 17
0
 void appendCode(MethodInformation method, string code1, ref string code)
 {
     if (!string.IsNullOrEmpty(code1))
     {
         code1 = "\r\n" + code1;
         method.append(ref code, LeftSpaceLevel.one, code1);
         method.append(ref code, LeftSpaceLevel.one, "");
     }
 }
Exemplo n.º 18
0
        public override async Task DataBinder(MethodInformation method = null)
        {
            var l = await this.StartLoading();

            stVideoContainer.Refresh();
            stVideoContainer.Refresh();
            stVideoContainer.Refresh();
            l.EndLoading();
        }
Exemplo n.º 19
0
        protected override void HandleRefOutMethod(MethodInfo baseMethod, MethodInformation methodDescription)
        {
            var returnType = baseMethod.ReturnType;

            this.generatedDelegates.Add(MethodTemplates.GetAssemblyDelegate(
                                            baseMethod.ReturnType == typeof(void) ? "void" : TypeDissector.Create(returnType).SafeName,
                                            methodDescription.DelegateCast,
                                            baseMethod.GetParameters(this.Namespaces), baseMethod.IsUnsafeToMock()));
            this.Namespaces.Add(returnType.Namespace);
        }
Exemplo n.º 20
0
        public void ResolveMethodInformation_GoodSignature_ReturnsInformation()
        {
            MethodInformation information = _service.ResolveMethodInformation(typeof(RuntimeType), "MyMethod", new Type[] { typeof(string) });

            Assert.AreEqual("MyMethod", information.Method.Name);
            Assert.AreEqual(1, information.Parameters.Length);
            Assert.AreEqual("name", information.Parameters[0].Parameter.Name);
            Assert.AreEqual(1, information.Parameters[0].CustomAttributes.Length);
            Assert.AreEqual(1, information.CustomAttributes.Length);
        }
Exemplo n.º 21
0
        // java methods only have one return value
        // convention in raptor is to use the first parameter for that if needed
        private Boolean hasReturnValue(MethodInformation checkMi, String name)
        {
            Boolean hasReturn = false;

            if (Procedures[name].arg_names != null && Procedures[name].arg_names.Length > 0)
                if (checkMi.args_are_output[0])
                    hasReturn = true;

            return hasReturn;
        }
Exemplo n.º 22
0
        protected override MethodCompiler GetMethodCompiler(MethodInformation method)
        {
            CompilerOptions options = new CompilerOptions();

            options.DebugInfoService                = method.Method.GetDebugInfoService();
            options.LiteralEncodingStrategy         = this.LiteralEncodingStrategy;
            options.DynamicCallStrategy             = this.DynamicCallStrategy;
            options.DiscreteBindingEncodingStrategy = this.DiscreteBindingEncodingStrategy;
            return(new ClassMethodCompiler(this.Compiler.Parameters.Runtime, options));
        }
Exemplo n.º 23
0
        public override async Task DataBinder(MethodInformation method = null)
        {
            userSettings.IsVisible = this.UserIsLogedIn();

            if (this.UserIsLogedIn())
            {
                await Methods.AppSettings.ValidateStoragePermission();
            }
            await base.DataBinder(method);
        }
Exemplo n.º 24
0
        public static MethodInformation CompleteMethodInfo(Type target, MethodInformation methodInformation)
        {
            var method = target.GetMethod(methodInformation.Name);

            methodInformation.ReturnType  = method.ReturnType;
            methodInformation.Args        = method.GetParameters().Select(arg => arg.ParameterType).ToList();
            methodInformation.MethodAttrs = method.Attributes;

            return(methodInformation);
        }
        private void AddMethodsForClass(List <MethodInformation> methods, FieldInfo[] fieldInfos, List <string> enumValues)
        {
            foreach (FieldInfo fieldInfo in fieldInfos.Where(m => m.FieldType == typeof(Func <decimal?>) ||
                                                             m.CustomAttributes.Any(c => c.AttributeType.Name == "CalculationAttribute") ||
                                                             m.CustomAttributes.Any(c => c.AttributeType.Name == "FundingLineAttribute") ||
                                                             m.IsLiteral).ToList())
            {
                if (!fieldInfo.IsSpecialName)
                {
                    if (fieldInfo.IsLiteral)
                    {
                        enumValues.Add(fieldInfo.Name);
                        continue;
                    }

                    string entityId = null;

                    bool isCustom = false;
                    ApplyCalculationMetadata(fieldInfo, ref entityId, ref isCustom);
                    ApplyFundingLineMetadata(fieldInfo, ref entityId, ref isCustom);

                    (string fullReturnType, string directType, bool isNullable)returnDetails = ConvertTypeName(fieldInfo.FieldType);

                    MethodInformation methodInformation = new MethodInformation()
                    {
                        Name                 = fieldInfo.Name,
                        ReturnType           = returnDetails.fullReturnType,
                        ReturnTypeClass      = returnDetails.directType,
                        ReturnTypeIsNullable = returnDetails.isNullable,
                        EntityId             = entityId,
                        IsCustom             = isCustom
                    };

                    if (string.IsNullOrWhiteSpace(methodInformation.FriendlyName))
                    {
                        methodInformation.FriendlyName = GetAttributeProperty(fieldInfo.CustomAttributes, "Calculation", "Name");
                    }

                    if (string.IsNullOrWhiteSpace(methodInformation.FriendlyName))
                    {
                        methodInformation.FriendlyName = GetAttributeProperty(fieldInfo.CustomAttributes, "FundingLine", "Name");
                    }

                    if (string.IsNullOrWhiteSpace(methodInformation.Description))
                    {
                        methodInformation.Description = GetAttributeProperty(fieldInfo.CustomAttributes, "Description", "Description");
                    }

                    if (fieldInfo.GetCustomAttribute <System.ComponentModel.EditorBrowsableAttribute>()?.State != System.ComponentModel.EditorBrowsableState.Never)
                    {
                        methods.Add(methodInformation);
                    }
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// 执行select、insert、update、delete数据操作时被调用
        /// </summary>
        /// <param name="method">接口方法信息对象</param>
        /// <param name="dataOptType">数据操作类型select|insert|update|delete</param>
        /// <param name="sql">sql语句表达式</param>
        /// <param name="code">接口方法代码相关代码字符串</param>
        protected void ExecInterfaceMethodOfCodeStr_DataOpt(MethodInformation method, DataOptType dataOptType, string sql, ref string code)
        {
            StackTrace stackTrace = new StackTrace();
            Type       type       = stackTrace.GetFrame(1).GetMethod().DeclaringType;

            if (null == type.GetInterface("IDataInterface"))
            {
                e("调用该方法的类必须实例接口类 IDataInterface", ErrorLevels.severe);
                throw new Exception("调用该方法的类必须实例接口类 IDataInterface");
            }
            string sqlVarName = "sql";

            DynamicCodeChange dynamicCodeChange = new DynamicCodeChange();

            try
            {
                dynamicCodeChange.AnalyzeSql(method, dataOptType, sqlVarName, ref sql);
            }
            catch (Exception ex)
            {
                e(ex.ToString(), ErrorLevels.severe);
                throw ex;
            }

            code = dynamicCodeAutoCall.ExecReplaceForSqlByFieldName(sql, sqlVarName, method);

            string paraListVarName = "null";

            dynamicCodeAutoCall.DataProviderCode(sqlVarName, method, dataOptType, ref code, ref paraListVarName);
            if (string.IsNullOrEmpty(code) && string.IsNullOrEmpty(sql))
            {
                e("没有提供任何执行语句", ErrorLevels.severe);
                throw new Exception("没有提供任何执行语句");
            }

            string code1 = "";

            if (dataOptType == DataOptType.select ||
                dataOptType == DataOptType.count ||
                DataOptType.procedure == dataOptType)
            {
                code1 = dynamicCodeAutoCall.GetParametersBySqlParameter(sql, method, ref paraListVarName);
                appendCode(method, code1, ref code);

                dynamicCodeAutoCall.MadeExecuteSql(sqlVarName, paraListVarName, method, dataOptType, ref code);
            }
            else
            {
                code1 = dynamicCodeChange.GetParametersBySqlParameter(sql, sqlVarName, method, dataOptType, ref paraListVarName);
                appendCode(method, code1, ref code);
            }
        }
        public Task Parse(Step step, string stepExpression, GherkinParseResult parseResult, BuildProject buildProject)
        {
            if (buildProject.Build.Assembly.IsNullOrEmpty())
            {
                parseResult.AddError("No valid assembly to test", step.Location.Line, step.Location.Column);
            }
            else
            {
                byte[] assembly = buildProject.Build.Assembly;

                if (assembly == null)
                {
                    parseResult.AddError("No calculations available for this test", step.Location.Line, step.Location.Column);
                }
                else
                {
                    string[] matches = Regex.Split(step.Text, stepExpression, RegexOptions.IgnoreCase);

                    string calcName = matches[7];

                    string comparison = matches[9];

                    string value = matches[11];

                    MethodInformation calculation = FindCalculationMethod(assembly, calcName);

                    if (calculation == null)
                    {
                        parseResult.AddError($"Calculation: '{calcName}' was not found to test", step.Location.Line, step.Location.Column);
                    }

                    if (!ComparisonOperators.Values.Contains(comparison.ToLower()))
                    {
                        parseResult.AddError($"'{comparison}' is not a valid comparison", step.Location.Line, step.Location.Column);
                    }

                    if (!Decimal.TryParse(value, out var result))
                    {
                        parseResult.AddError($"'{value}' is not a valid decimal", step.Location.Line, step.Location.Column);
                    }

                    parseResult.StepActions.Add(new ThenCalculationValue
                    {
                        CalculationName = calcName,
                        Operator        = ComparisonOperators.FirstOrDefault(x => x.Value == comparison).Key,
                        Value           = value
                    });
                }
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 28
0
        public override string ExecuteInterfaceMethodCodeString(MethodInformation method)
        {
            string code = "";

            method.dataProviderNamespace = dataProviderNamespace;
            method.dataProviderClassName = dataProviderClassName;
            method.fields           = fields;
            method.fieldsType       = fieldsType;
            method.ResultExecMethod = ResultExecMethod;
            method.sqlExecType      = sqlExecType;
            ExecInterfaceMethodOfCodeStr_DataOpt(method, ((IDataInterface)this).dataOptType, sql, ref code);

            return(code);
        }
Exemplo n.º 29
0
        private void Analyzer(SyntaxNodeAnalysisContext context)
        {
            var method = new MethodInformation(
                "Parse",
                "System.Net.IPAddress.Parse(string)",
                args =>
            {
                parseMethodInfo.Value.Invoke(null, new[] { args[0].ToString() });
            }
                );
            var checker = new MethodChecker(context, Rule);

            checker.AnalyzeMethod(method);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Generates a method in ".Classes.ClassName[ class]" for each defined IronSmalltalk method.
        /// </summary>
        /// <param name="method">The newly created native method.</param>
        private void GenerateMethod(MethodInformation method)
        {
            MethodBuilder methodBuilder = this.TypeBuilder.DefineMethod(method.MethodName, MethodAttributes.Public | MethodAttributes.Static);

            // The lambda expression has been generated by the Expression Compiler. We just compile it into a native method.
            if (this.Compiler.NativeGenerator.DebugInfoGenerator == null)
            {
                method.LambdaExpression.CompileToMethod(methodBuilder);
            }
            else
            {
                method.LambdaExpression.CompileToMethod(methodBuilder, this.Compiler.NativeGenerator.DebugInfoGenerator);
            }
        }
        // This static function returns an array containing
        // information of all public methods of a COM object.
        // Note that the COM object must implement the IDispatch
        // interface in order to be usable in this function.
        public static MethodInformation[] GetMethodInformation(object com_obj)
        {
            IDispatch pDispatch = null;

            try
            {
                // Obtain the COM IDispatch interface from the input com_obj object.
                // Low-level-wise this causes a QueryInterface() to be performed on
                // com_obj to obtain the IDispatch interface from it.
                pDispatch = (IDispatch)com_obj;
            }
            catch (System.InvalidCastException ex)
            {
                // This means that the input com_obj
                // does not support the IDispatch
                // interface.
                File.AppendAllText("log.txt", ex.ToString());
                return null;
            }

            // Obtain the ITypeInfo interface from the object via its
            // IDispatch.GetTypeInfo() method.
            System.Runtime.InteropServices.ComTypes.ITypeInfo pTypeInfo = null;
            // Call the IDispatch.GetTypeInfo() to obtain an ITypeInfo interface
            // pointer from the com_obj.
            // Note that the first parameter must be 0 in order to
            // obtain the Type Info of the current object.
            pDispatch.GetTypeInfo
                (
                    0,
                    0,
                    out pTypeInfo
                );

            // If for some reason we are not able to obtain the
            // ITypeInfo interface from the IDispatch interface
            // of the COM object, we return immediately.
            if (pTypeInfo == null)
            {
                return null;
            }

            // Get the TYPEATTR (type attributes) of the object
            // via its ITypeInfo interface.
            IntPtr pTypeAttr = IntPtr.Zero;
            System.Runtime.InteropServices.ComTypes.TYPEATTR typeattr;
            // The TYPEATTR is returned via an IntPtr.
            pTypeInfo.GetTypeAttr(out pTypeAttr);
            // We must convert the IntPtr into the TYPEATTR structure
            // defined in the System.Runtime.InteropServices.ComTypes
            // namespace.
            typeattr = (System.Runtime.InteropServices.ComTypes.TYPEATTR)Marshal.PtrToStructure
                                                                             (
                                                                                 pTypeAttr,
                                                                                 typeof(System.Runtime.InteropServices.ComTypes.TYPEATTR)
                                                                             );
            // Release the resources related to the obtaining of the
            // COM TYPEATTR structure from an ITypeInfo interface.
            // From now onwards, we will only work with the
            // System.Runtime.InteropServices.ComTypes.TYPEATTR
            // structure.
            pTypeInfo.ReleaseTypeAttr(pTypeAttr);
            pTypeAttr = IntPtr.Zero;

            // The TYPEATTR.guid member indicates the default interface implemented
            // by the COM object.
            Guid defaultInterfaceGuid = typeattr.guid;

            MethodInformation[] method_information_array = new MethodInformation[typeattr.cFuncs];
            // The TYPEATTR.cFuncs member indicates the total number of methods
            // that the current COM object implements.
            for (int i = 0; i < (typeattr.cFuncs); i++)
            {
                // We loop through the number of methods.
                System.Runtime.InteropServices.ComTypes.FUNCDESC funcdesc;
                IntPtr pFuncDesc = IntPtr.Zero;
                string strName;
                string strDocumentation;
                int iHelpContext;
                string strHelpFile;

                // During each loop, we use the ITypeInfo.GetFuncDesc()
                // method to obtain a FUNCDESC structure which describes
                // the current method indexed by "i".
                pTypeInfo.GetFuncDesc(i, out pFuncDesc);
                // The FUNCDESC structure is returned as an IntPtr.
                // We need to convert it into a FUNCDESC structure
                // defined in the System.Runtime.InteropServices.ComTypes
                // namespace.
                funcdesc = (System.Runtime.InteropServices.ComTypes.FUNCDESC)Marshal.PtrToStructure
                                                                                 (
                                                                                     pFuncDesc,
                                                                                     typeof(System.Runtime.InteropServices.ComTypes.FUNCDESC)
                                                                                 );
                // The FUNCDESC.memid contains the member id of the current function
                // in the Type Info of the object.
                // Use the ITypeInfo.GetDocumentation() with reference to memid
                // to obtain information for this function.
                pTypeInfo.GetDocumentation
                    (
                        funcdesc.memid,
                        out strName,
                        out strDocumentation,
                        out iHelpContext,
                        out strHelpFile
                    );
                // Fill up the appropriate method_information_array element
                // with field information.
                method_information_array[i].m_strName = strName;
                method_information_array[i].m_strDocumentation = strDocumentation;

                if (funcdesc.invkind == System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_FUNC)
                {
                    method_information_array[i].m_method_type = MethodType.Method;
                }
                else if (funcdesc.invkind == System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYGET)
                {
                    method_information_array[i].m_method_type = MethodType.Property_Getter;
                }
                else if (funcdesc.invkind == System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT)
                {
                    method_information_array[i].m_method_type = MethodType.Property_Putter;
                }
                else if (funcdesc.invkind == System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF)
                {
                    method_information_array[i].m_method_type = MethodType.Property_PutRef;
                }

                // The ITypeInfo.ReleaseFuncDesc() must be called
                // to release the (unmanaged) memory of the FUNCDESC
                // returned in pFuncDesc (an IntPtr).
                pTypeInfo.ReleaseFuncDesc(pFuncDesc);
                pFuncDesc = IntPtr.Zero;
            }

            return method_information_array;
        }