Exemple #1
0
 public ClassSemanticQuery(
     SemanticModel model,
     ClassInspector inspector)
 {
     this.model     = model;
     this.inspector = inspector;
 }
Exemple #2
0
        /// <summary>
        /// The inspect.
        /// </summary>
        /// <param name="targetObject">
        /// The target object.
        /// </param>
        /// <returns>
        /// The <see cref="ServiceDescriptor"/>.
        /// </returns>
        public ServiceDescriptor inspect(string targetObject)
        {
            try
            {
                Type serviceType = TypeLoader.LoadType(targetObject);
                if (!this.TryGenerateServiceFile(serviceType))
                {
                    return(null);
                }

                ServiceDescriptor descriptor = ClassInspector.inspectClass(ServicesToContracts[serviceType]);
                if (Log.isLogging(LoggingConstants.INFO))
                {
                    Log.log(LoggingConstants.INFO, "WCF Object handler has successfully inspected target service");
                }

                return(descriptor);
            }
            catch (Exception exception)
            {
                string message = exception.Message;
                if (string.IsNullOrWhiteSpace(message))
                {
                    message = "Unable to inspect WCF object with id " + targetObject;
                }

                if (Log.isLogging(LoggingConstants.ERROR))
                {
                    Log.log(LoggingConstants.ERROR, string.Format("{0} {1}", message, exception));
                }

                return(null);
            }
        }
Exemple #3
0
        public async Task Given_ParameterlessMethod_Then_NoAssignmentsAreFound()
        {
            // Arrange
            var text = @"
using System;

namespace RefactorClasses.Analysis.Test
{
    public static class Test
    {
        public static void Something()
        {
            Console.Out.WriteLine(""dswwww"");
        }
    }
}";

            var tree          = CSharpSyntaxTree.ParseText(text);
            var compilation   = TestHelpers.CreateCompilation(tree);
            var semanticModel = compilation.GetSemanticModel(tree);

            var classDeclaration = TestHelpers.FindFirstClassDeclaration(await tree.GetRootAsync());
            var classInspector   = new ClassInspector(classDeclaration);
            var mi = classInspector.FindMatchingMethods(m => m.Name.Equals("Something")).First();
            var methodSemanticQuery = mi.CreateSemanticQuery(semanticModel);

            // Act
            var assignments = methodSemanticQuery.FindAssignments();

            // Assert
            Assert.NotNull(assignments);
            Assert.Empty(assignments.Assignments);
            Assert.Empty(assignments.NotAssignedParameters);
        }
 public void InitializeTests()
 {
     _userInputRepoMock = new Mock <IUserInputRepository>();
     _userInputRepoMock
     .Setup(x => x.GetUserInput(It.IsAny <string>()))
     .Returns("");
     _inspector = new ClassInspector(_userInputRepoMock.Object);
 }
        public void MonoInspectType()
        {
            if (Framework.Detect() != FrameworkVersion.MONO)
            {
                return;
            }
            FieldInfo[] f = ClassInspector.InspectClass(
                typeof(System.Collections.Hashtable));

            int counter = 0;

            foreach (FieldInfo field in f)
            {
                if (field.Name.Equals("inUse"))
                {
                    counter++;
                }
                else if (field.Name.Equals("modificationCount"))
                {
                    counter++;
                }
                else if (field.Name.Equals("loadFactor"))
                {
                    counter++;
                }
                else if (field.Name.Equals("table"))
                {
                    counter++;
                }
                else if (field.Name.Equals("threshold"))
                {
                    counter++;
                }
                else if (field.Name.Equals("hashKeys"))
                {
                    counter++;
                }
                else if (field.Name.Equals("hashValues"))
                {
                    counter++;
                }
                else if (field.Name.Equals("hcpRef"))
                {
                    counter++;
                }
                else if (field.Name.Equals("comparerRef"))
                {
                    counter++;
                }
                else
                {
                    Assert.Fail("Field is not an expected one: " + field.Name);
                }
            }
            Assert.AreEqual(9, counter, "Number of fields is different from expected");
        }
Exemple #6
0
        public void Test1()
        {
            var tree = CSharpSyntaxTree.ParseText("void Something(int a, int b)", CSharpParseOptions.Default);
            int b    = 10;

            ClassDeclarationSyntax cc = null;
            var ci = ClassInspector.Create(cc);

            ci.FindMatchingConstructors(
                mi => true);
        }
Exemple #7
0
        public static string outputDirectory = @"/home/myr/_repo/spindll/spindll/_testOutputs/";                //xubuntu
        // const string outputDirectory = @"C:\_repo\spindll\_testOutputs\";        //40

        public static void ExtractAndWrite(string[] args)
        {
            try {
                var source = "";

                // source = @"C:\_repo\spindll\bin\Debug\netcoreapp3.0\spindll.dll";											//40
                // source = @"D:\_repo\spindll\bin\Debug\netcoreapp3.0\spindll.dll";											//tower - spindll
                // source = @"D:\_repo\f5saver\f5saver.api\F5Saver.Common\bin\Debug\netstandard2.0\F5Saver.Common.dll";			//tower - f5saver
                source = @"/home/myr/_repo/spindll/spindll/bin/Debug/netcoreapp3.0/spindll.dll";                                                                                //xubuntu
                // source = @"/home/myr/_repo/f5saver/f5saver.api/F5Saver.Common/bin/Debug/netstandard2.0/F5Saver.Common.dll";	//xubuntu

                if (args.Any())
                {
                    source = args[0];
                    Console.WriteLine($"loading From: {source}");
                    outputDirectory = args[1];
                }

                var types = ClassInspector.LoadDll(source).ToList();

                var models = extractModels(types);

                //convert types to System
                var CSharpIn           = new LanguagePair(LanguageEnum.CSharp, LanguageEnum.System);
                var TypeScriptOut      = new LanguagePair(LanguageEnum.System, LanguageEnum.TypeScript);
                var languageDictionary = new LanguageMappingDictionary(CSharpIn, TypeScriptOut);
                var inDict             = languageDictionary[CSharpIn];
                var outDict            = languageDictionary.LanguageDictionary[TypeScriptOut];

                // fill out intermediary types
                models.ForEach(model => {
                    model.Properties.ForEach(prop => {
                        convertProperty(ref prop, inDict, outDict);
                    });
                });

                var definedClasses = models.Select(m => m.ModelName).ToList();

                // build typescript class as string
                var modelClassStrings = models
                                        .ToDictionary(m => m.ModelName, m => buildClassString(m, definedClasses));


                foreach (var kvp in modelClassStrings)
                {
                    var filename = kvp.Key + ".ts";
                    WriteStringToFile(filename, kvp.Value);
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString())
            }
        }
        public void GetFieldInfoFromType_IdentityPropertyIsNullable_ShouldThrowException()
        {
            //Act
            Action act = () =>
                         _inspector.GetFieldInfoFromType(typeof(NullableIdTestClass));

            //Assert
            act
            .Should()
            .ThrowExactly <InvalidInputException>()
            .WithMessage(
                ClassInspector.InvalidInputExceptionNullableIdProperty("Id")
                );
        }
Exemple #9
0
        public async Task Test1()
        {
            // Arrange
            var text = @"
using System;

namespace RefactorClasses.Analysis.Test
{
    [StateMachine(ContextType = typeof(ContextBase), StateType = typeof(StateBase), TriggerType = (typeof(TriggerBase)))]
    [StateMachine(""c"")]
    [StateMachine(""d"")]
    public class StateMachineImpl
    {

    }

    public class TriggerBase { }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public sealed class StateMachineAttribute : Attribute
    {
        public Type StateType { get; set; }

        public Type TriggerType { get; set; }

        public Type ContextType { get; set; }
    }
}";

            var tree             = CSharpSyntaxTree.ParseText(text);
            var compilation      = TestHelpers.CreateCompilation(tree);
            var semanticModel    = compilation.GetSemanticModel(tree);
            var classDeclaration = TestHelpers.FindFirstClassDeclaration(await tree.GetRootAsync());

            var classInspector    = new ClassInspector(classDeclaration);
            var semanticInspector = classInspector.CreateSemanticQuery(semanticModel);

            if (semanticInspector.TryFindFirstAttributeMatching("StateMachineAttribute", out var atData))
            {
                int a = 10;
                // parse named arguments looking for types - some of them might need to be
                // generated, some might be already present
            }

            // Act

            // Assert
        }
        public void GetFieldInfoFromType_UserProvidesInvalidIdPropertyName_ShouldThrowException()
        {
            //Assemble
            var invalidProperty = "not a real property";

            _userInputRepoMock
            .Setup(x => x.GetUserInput(ClassInspector.NoIdPropertyMessage))
            .Returns(invalidProperty);

            //Act
            Action act = () =>
                         _inspector.GetFieldInfoFromType(typeof(MissingIdTestClass));

            //Assert
            act.
            Should()
            .ThrowExactly <InvalidInputException>()
            .WithMessage(ClassInspector.InvalidInputExceptionIdProperty(
                             invalidProperty
                             ));
        }
        public void GetFieldInfoFromType_UserSpecifiesIdentityPropertyAsNullable_ShouldThrowException()
        {
            //Assemble
            var idProperty = "NullableIntProperty";

            _userInputRepoMock
            .Setup(x => x.GetUserInput(ClassInspector.NoIdPropertyMessage))
            .Returns(idProperty);

            //Act
            Action act = () =>
                         _inspector.GetFieldInfoFromType(typeof(MissingIdTestClass));

            //Assert
            act.
            Should()
            .ThrowExactly <InvalidInputException>()
            .WithMessage(
                ClassInspector.InvalidInputExceptionNullableIdProperty(
                    idProperty
                    )
                );
        }
Exemple #12
0
        public async Task Given_MethodWithSimpleVariableAssignment_Then_AssignmentIsFound()
        {
            // Arrange
            var text = @"
using System;

namespace RefactorClasses.Analysis.Test
{
    public class Test1
    {
        public void MyMethod(int a, int b)
        {
            int u = 0;
            u = b;
        }
    }
}";

            var tree          = CSharpSyntaxTree.ParseText(text);
            var compilation   = TestHelpers.CreateCompilation(tree);
            var semanticModel = compilation.GetSemanticModel(tree);

            var classDeclaration = TestHelpers.FindFirstClassDeclaration(await tree.GetRootAsync());
            var classInspector   = new ClassInspector(classDeclaration);
            var mi = classInspector.FindMatchingMethods(m => m.Name.Equals("MyMethod")).First();
            var methodSemanticQuery = mi.CreateSemanticQuery(semanticModel);

            // Act
            var assignments = methodSemanticQuery.FindAssignments();

            // Assert
            Assert.Equal(1, assignments.Assignments.Count);
            Assert.Equal(1, assignments.Assignments.First().ParameterIdx);

            Assert.Equal(1, assignments.NotAssignedParameters.Count);
            Assert.Equal(0, assignments.NotAssignedParameters.First().ParameterIdx);
        }
        public void NETInspectType()
        {
            if (Framework.Detect() != FrameworkVersion.NET11 ||
                Framework.Detect() != FrameworkVersion.NET10)
            {
                return;
            }
            FieldInfo[] f = ClassInspector.InspectClass(
                typeof(System.Collections.Hashtable));

            int counter = 0;

            foreach (FieldInfo field in f)
            {
                if (field.Name.Equals("buckets"))
                {
                    counter++;
                }
                else if (field.Name.Equals("count"))
                {
                    counter++;
                }
                else if (field.Name.Equals("occupancy"))
                {
                    counter++;
                }
                else if (field.Name.Equals("loadsize"))
                {
                    counter++;
                }
                else if (field.Name.Equals("loadFactor"))
                {
                    counter++;
                }
                else if (field.Name.Equals("version"))
                {
                    counter++;
                }
                else if (field.Name.Equals("keys"))
                {
                    counter++;
                }
                else if (field.Name.Equals("values"))
                {
                    counter++;
                }
                else if (field.Name.Equals("_hcp"))
                {
                    counter++;
                }
                else if (field.Name.Equals("_comparer"))
                {
                    counter++;
                }
                else if (field.Name.Equals("m_siInfo"))
                {
                    counter++;
                }
                else
                {
                    Assert.Fail("Field is not an expected one: " + field.Name);
                }
            }
            Assert.AreEqual(11, counter, "Number of fields is different from expected");
        }
Exemple #14
0
        public async Task Test2()
        {
            // Arrange
            var text = @"
using System;
using System.Threading.Tasks;

namespace RefactorClasses.Analysis.Test
{
    [StateMachine(ContextType = typeof(ContextBase), StateType = typeof(StateBase), TriggerType = (typeof(TriggerBase)))]
    public class StateMachineImpl
    {
        public void DoSomething(
            int a,
            Test1 testClass, string fdeee)
        {
        }

        public async Task<int> TaskMethodReturningSomething(int a, float b)
        {
            return 10;
        }

        public System.Threading.Tasks.Task AsyncOperationsSupport(int a, float b)
        {
            return Task.CompletedTask;
        }

        public async Task TaskMethod(int a, float b)
        {
            return;
        }

        public async Task TaskMethodWithArrays(int[] a, float[] b)
        {
            return;
        }

        public async Task TaskMethodWithTuples((int, float) a, float[] b)
        {
            return;
        }

        private void PrintSomething() {}
    }

    public class TriggerBase { }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public sealed class StateMachineAttribute : Attribute
    {
        public Type StateType { get; set; }

        public Type TriggerType { get; set; }

        public Type ContextType { get; set; }
    }
}";

            var tree             = CSharpSyntaxTree.ParseText(text);
            var compilation      = TestHelpers.CreateCompilation(tree);
            var semanticModel    = compilation.GetSemanticModel(tree);
            var classDeclaration = TestHelpers.FindFirstClassDeclaration(await tree.GetRootAsync());

            var classInspector    = new ClassInspector(classDeclaration);
            var semanticInspector = classInspector.CreateSemanticQuery(semanticModel);

            bool foundAttribute = semanticInspector.TryFindFirstAttributeMatching(
                "StateMachineAttribute", out var atData);
            var triggerType = atData
                              ?.NamedArguments
                              .FirstOrDefault(kvp => kvp.Key.Equals("TriggerType"));

            if (triggerType == null)
            {
                return;
            }

            var methods = classInspector.FindMatchingMethods(
                mi => mi.Check(m => m.IsPublic() && !m.IsStatic()).Passed);

            foreach (var method in methods)
            {
                var msq          = method.CreateSemanticQuery(semanticModel);
                var returnType   = msq.GetReturnType();
                var isTaskReturn = IsTask(returnType.Symbol);

                var parameters = method.Parameters.Select(par => par.Type).ToList();

                // TODO: will throw if array
                var triggerTypeName = triggerType.Value.Value.Value as INamedTypeSymbol;
                if (triggerTypeName == null)
                {
                    return;
                }

                var recordBuilder = new RecordBuilder(method.Name)
                                    .AddModifiers(Modifiers.Public)
                                    .AddBaseTypes(GeneratorHelper.Identifier(triggerTypeName.Name))
                                    .AddProperties(
                    method.Parameters
                    .Select(p => (p.Type, p.Name)).ToArray());

                if (isTaskReturn.Value.IsTask())
                {
                    var boolTcs = GeneratorHelper.GenericName(
                        "TaskCompletionSource",
                        Types.Bool);

                    var initializer = ExpressionGenerationHelper.CreateObject(boolTcs);
                    recordBuilder.AddField(boolTcs, "result", initializer);

                    var resolveMethod = new MethodBuilder(GH.IdentifierToken("Resolve"))
                                        .Body(new BodyBuilder()
                                              .AddVoidMemberInvocation(
                                                  GH.Identifier("result"),
                                                  GH.Identifier("TrySetResult"),
                                                  SF.Argument(GH.Identifier("true")))
                                              .Build())
                                        .Build();

                    var cancelMethod = new MethodBuilder(GH.IdentifierToken("Cancel"))
                                       .Body(new BodyBuilder()
                                             .AddVoidMemberInvocation(
                                                 GH.Identifier("result"),
                                                 GH.Identifier("TrySetCanceled"))
                                             .Build())
                                       .Build();

                    var rejectMethod = new MethodBuilder(GH.IdentifierToken("Cancel"))
                                       .AddParameter(GH.Identifier("Exception"), GH.IdentifierToken("exc"))
                                       .Body(new BodyBuilder()
                                             .AddVoidMemberInvocation(
                                                 GH.Identifier("result"),
                                                 GH.Identifier("TrySetException"),
                                                 SF.Argument(GH.Identifier("exc")))
                                             .Build())
                                       .Build();

                    recordBuilder.AddMethod(resolveMethod);
                    recordBuilder.AddMethod(cancelMethod);
                    recordBuilder.AddMethod(rejectMethod);

                    int ddddd = 0;
                }
                else if (isTaskReturn.Value.IsTypedTask(out var taskType))
                {
                    var typedTcs = GeneratorHelper.GenericName(
                        "TaskCompletionSource",
                        GeneratorHelper.Identifier(taskType.Name));

                    var initializer = ExpressionGenerationHelper.CreateObject(typedTcs);
                    recordBuilder.AddField(typedTcs, "result", initializer);
                }

                var record = recordBuilder.Build();

                // TODO: if task is returned -> generate TaskCompletionSource
                // and matching methods

                var rs = record.ToString();

                int a = 10;
            }

            // Act

            // Assert

            IsTaskResult?IsTask(ISymbol symbol)
            {
                var namedSymbol = symbol as INamedTypeSymbol;

                if (namedSymbol == null)
                {
                    return(null);
                }

                if (namedSymbol.Name == "Task" &&
                    namedSymbol?.ContainingNamespace?.ToString() == "System.Threading.Tasks")
                {
                    var firstTypeArg = namedSymbol.TypeArguments.FirstOrDefault();
                    if (firstTypeArg != null)
                    {
                        return(IsTaskResult.TypedTask(firstTypeArg));
                    }
                    else
                    {
                        return(IsTaskResult.Task());
                    }
                }

                return(IsTaskResult.NotATask());
            }

            //var tcs = new TaskCompletionSource<int>();
            //tcs.TrySetException()
        }