public ActionResult <ResultTypeStankins> Get(string id)
        {
            var ret = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath))).FirstOrDefault(it => string.Equals(it.Name, id));

            if (ret == null)
            {
                return(NotFound("could not find " + id));
            }
            return(ret);
        }
Exemple #2
0
 public void TestFindingAll()
 {
     ResultTypeStankins[] r = null;
     $"when find types in the assembly ".w(() =>
     {
         r = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath)));
     });
     $"can find data".w(() =>
     {
         r.Should().NotBeNull();
         r.Length.Should().BeGreaterThan(20);
     });
 }
        public bool CanInterpretString(string data)
        {
            var all   = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath)));
            var instr = SplitString(data);
            var name  = instr[0];

            ObjectType = all.FirstOrDefault(it =>
                                            string.Equals(it.Name, name, StringComparison.InvariantCultureIgnoreCase));
            if (ObjectType == null)
            {
                ObjectType = all.FirstOrDefault(it =>
                                                string.Equals(it.Type.FullName, name, StringComparison.InvariantCultureIgnoreCase)
                                                );
            }
            if (ObjectType == null)
            {
                valid.Add(new ValidationResult($"cannot find object {name}"));
                return(false);
            }

            if (instr.Length - 1 != ObjectType.ConstructorParam.Keys.Count)
            {
                valid.Add(new ValidationResultWarning(new ValidationResult($"for {name} constructor items length different:{instr.Length -1} {ObjectType.ConstructorParam.Keys.Count}")));
            }
            var keys = ObjectType.ConstructorParam.Keys;

            for (int i = 1; i < instr.Length; i++)
            {
                var first         = instr[i].IndexOf("=");
                var argumentName  = instr[i].Substring(0, first);
                var argumentValue = instr[i].Substring(first + 1);
                var key           = keys.FirstOrDefault(it =>
                                                        string.Equals(it, argumentName, StringComparison.InvariantCultureIgnoreCase));

                if (key == null)
                {
                    valid.Add(new ValidationResult($"key not found:{argumentName}"));
                }
                else
                {
                    ObjectType.ConstructorParam[key] = argumentValue;
                }
            }

            var warning = typeof(ValidationResultWarning).FullName;

            return(valid.Count(it => it.GetType().FullName != warning) == 0);
        }
        private Assembly LoadFile(string fileName)
        {
            var refs    = new List <MetadataReference>();
            var ourRefs = Assembly.GetEntryAssembly().GetReferencedAssemblies();

            foreach (var item in ourRefs)
            {
                var ass = Assembly.Load(item);
                refs.Add(MetadataReference.CreateFromFile(ass.Location));
            }
            refs.Add(MetadataReference.CreateFromFile(typeof(Attribute).Assembly.Location));
            //MetadataReference NetStandard = MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location);
            MetadataReference NetStandard = MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location);

            refs.Add(NetStandard);
            refs.Add(MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location));
            var refs1 = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath)))
                        .Select(it => it.Type.Assembly.Location)
                        .Distinct()
                        .Select(it => MetadataReference.CreateFromFile(it));

            refs.AddRange(refs1);
            refs.Add(MetadataReference.CreateFromFile(typeof(CtorDictionary).Assembly.Location));
            refs.Add(MetadataReference.CreateFromFile(typeof(MarshalByValueComponent).Assembly.Location));
            refs.Add(MetadataReference.CreateFromFile(typeof(System.Console).Assembly.Location));
            refs.Add(MetadataReference.CreateFromFile(typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly.Location));

            var g           = Guid.NewGuid().ToString("N");
            var compilation = CSharpCompilation.Create(g,
                                                       new[] { CSharpSyntaxTree.ParseText(File.ReadAllText(fileName)) },
                                                       refs,
                                                       new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var res = compilation.Emit(ms);

                if (!res.Success)
                {
                    string diag = string.Join(Environment.NewLine, res.Diagnostics.Select(it => it.ToString()));
                    File.AppendAllText(fileName, "/*" + diag + "*/");
                    return(null);
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(Assembly.Load(ms.ToArray()));
            }
        }
 public static Recipe[] RecipesFromBaseObjects()
 {
     if (recipesFromBaseObjects != null)
     {
         return(recipesFromBaseObjects);
     }
     lock (lockMe)
     {
         if (recipesFromBaseObjects != null)
         {
             return(recipesFromBaseObjects);
         }
         recipesFromBaseObjects = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath))).Select(it => new RecipeFromType(it)).ToArray();
         return(recipesFromBaseObjects);
     }
 }
        public ResultTypeStankins[] Get()
        {
            if (results == null)
            {
                lock (lockObj)
                {
                    if (results != null)
                    {
                        return(results);
                    }

                    results = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath)));
                }
            }

            return(results);
        }
Exemple #7
0
        public void TestCreation(Type t, params string[] arguments)
        {
            FindAssembliesToExecute f = null;
            ResultTypeStankins      r = null;

            $"when find types in the assembly {t.Assembly.FullName}".w(() =>
            {
                f = new FindAssembliesToExecute(t.Assembly);
            });
            $"can find {t.Name}".w(() =>
            {
                r = f.FindTypes().FirstOrDefault(it => it.Type == t);
                r.Should().NotBeNull();
            });
            $"and can construct {t.Name}".w(() =>
            {
                var b = r.Create(arguments);
                b.GetType().Should().Be(t);
            });
        }
Exemple #8
0
        public void TestSimpleAll()
        {
            ResultTypeStankins[] rs  = null;
            RecipeFromType[]     rec = null;
            $"when finding all references".w(() => {
                rs = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath)));
            });
            $"then it should construct RecipeFromType".w(() =>
            {
                rec = rs.Select(it => new RecipeFromType(it)).ToArray();
            });
            $"and should have all kind of recipes".w(() =>
            {
                rec.Count(it => it.WhatToList.Value == WhatToList.Filters).Should().BeGreaterThan(1);

                rec.Count(it => it.WhatToList.Value == WhatToList.Receivers).Should().BeGreaterThan(1);

                rec.Count(it => it.WhatToList.Value == WhatToList.Senders).Should().BeGreaterThan(1);
                rec.Count(it => it.WhatToList.Value == WhatToList.Transformers).Should().BeGreaterThan(1);
            });
        }
Exemple #9
0
        private static void Main(string[] args)
        {
            ResultTypeStankins[] refs = FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath)));

            CtorDictionaryGeneric <ResultTypeStankins> commands = new CtorDictionaryGeneric <ResultTypeStankins>();

            Action <ResultTypeStankins> createItem = (t) =>
            {
                if (commands.ContainsKey(t.Name))
                {
                    System.Console.WriteLine($"key exists : {t.Name}");
                }
                else
                {
                    commands.Add(t.Name, t);
                }
            };

            foreach (ResultTypeStankins item in refs)
            {
                createItem(item);
            }


            CommandLineApplication app = new CommandLineApplication
            {
                Name = "Stankins.Console"
            };
            string versionString = Assembly.GetEntryAssembly()
                                   .GetCustomAttribute <AssemblyInformationalVersionAttribute>()
                                   .InformationalVersion
                                   .ToString();



            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", app.Name + "v" + versionString, app.Name + "v" + versionString);
            app.ExtendedHelpText = ExtendedHelpText();
            //app.Command("list", (command) =>
            //{
            //    command.Description = "List all supported objects";
            //    command.HelpOption("-?|- h|--help");


            //    command.OnExecute(() =>
            //    {
            //        var all = commands.Select(it => it.Key.ToString()).ToList();
            //        all.Sort();
            //        all.ForEach(it => System.Console.WriteLine(it));

            //        return 0;
            //    });

            //});
            app.Command("recipes", (command) =>
            {
                command.Description   = "execute/list recipes already in system";
                CommandOption list    = command.Option("-l|--list", "list recipes", CommandOptionType.NoValue);
                CommandOption execute = command.Option("-e|--execute", "execute recipe", CommandOptionType.SingleValue);
                command.OnExecute(async() =>
                {
                    if (list.HasValue())
                    {
                        List <Recipe> recipes = RecipeFromString.RecipesFromFolder().ToList();
                        recipes.Sort((a, b) => a.Name.CompareTo(b.Name));
                        foreach (Recipe item in recipes)
                        {
                            System.Console.WriteLine($"Stankins.Console recipes -e {item.Name}");
                        }
                        return(0);
                    }
                    if (execute.HasValue())
                    {
                        string recipeString     = execute.Value();
                        RecipeFromString recipe = RecipeFromString.FindRecipe(recipeString);
                        if (recipe == null)
                        {
                            System.Console.Error.WriteLine($"can not found {recipeString}");
                            return(0);//maybe return error?
                        }
                        await recipe.TransformData(null);
                        return(0);
                    }

                    command.ShowHelp();
                    return(0);
                });
            });
            app.Command("list", (command) =>
            {
                string names = string.Join(',', Enum.GetNames(typeof(WhatToList)));

                command.Description = "Explain arguments  for supported objects - could be " + names;

                command.HelpOption("-?|-h|--help");
                CommandOption optWhat = command.Option("-what", "what to list", CommandOptionType.SingleValue);



                command.OnExecute(() =>
                {
                    if (!optWhat.HasValue())
                    {
                        System.Console.WriteLine("please add -what " + names);
                        return(-1);
                    }
                    WhatToList val = (WhatToList)(int)Enum.Parse(typeof(WhatToList), optWhat.Value(), true);

                    List <ResultTypeStankins> all = commands.Select(it => it.Value).ToList();

                    List <ResultTypeStankins> find = all.Where(it => val == (val & it.FromType())).ToList();
                    find.Sort((a, b) => a.Name.CompareTo(b.Name));

                    WriteLines(find.ToArray());


                    System.Console.WriteLine("");
                    System.Console.WriteLine("!for often used  commands , see -h option");
                    return(0);
                });
            });

            app.Command("files", (command) =>
            {
                command.Description = "Execute file ";
                command.HelpOption("-?|-h|--help");
                CommandOption opt = command.Option("-f", "execute file ", CommandOptionType.MultipleValue);
                command.OnExecute(async() =>
                {
                    if (!opt.HasValue())
                    {
                        System.Console.WriteLine("please add -f fileName");
                        return(0);
                    }
                    int lenValuesCount = opt.Values.Count;
                    for (int i = 0; i < lenValuesCount; i++)
                    {
                        string fileName = opt.Values[i];
                        System.Console.WriteLine($"executing {fileName}");
                        string text = await File.ReadAllTextAsync(fileName);
                        var r       = new RecipeFromString(text);
                        await r.TransformData(null);
                    }
                    return(0);
                });
            });
            app.Command("cron", (command) =>
            {
                command.Description = "Execute CRON file uninterrupted ";
                command.HelpOption("-?|-h|--help");
                CommandOption opt = command.Option("-d", "directory with cron files", CommandOptionType.SingleValue);
                command.OnExecute(async() =>
                {
                    if (!opt.HasValue())
                    {
                        System.Console.WriteLine("please add -d directoryname");
                        return(0);
                    }
                    var dir   = opt.Value();
                    var r     = new RunCRONFiles(dir);
                    var ct    = new CancellationTokenSource();
                    var token = ct.Token;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    r.StartAsync(token);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    System.Console.WriteLine("press any key to shutdown");
                    var s = System.Console.ReadKey();
                    ct.Cancel();
                    await Task.Delay(3000);
                    return(0);
                });
            });
            app.Command("execute", (command) =>
            {
                command.Description = "Execute multiple ";
                command.HelpOption("-?|-h|--help");
                CommandOption opt        = command.Option("-o", "execute object", CommandOptionType.MultipleValue);
                CommandOption argObjects = command.Option("-a", "arguments for the object", CommandOptionType.MultipleValue);
                //var locationArgument = command.Argument("[location]", "The object to execute -see list command ", true);

                command.OnExecute(async() =>
                {
                    if (!opt.HasValue())
                    {
                        System.Console.WriteLine("see list command for objects");
                        return(0);
                    }


                    int argNr          = 0;
                    int lenValuesCount = opt.Values.Count;
                    for (int i = 0; i < lenValuesCount; i++)
                    {
                        string item = opt.Values[i].ToLowerInvariant();
                        if (!commands.ContainsKey(item))
                        {
                            System.Console.WriteLine($"not an existing object {item} - please see list command");
                            return(-1);
                        }

                        argNr += commands[item].ConstructorParam.Count;
                    }

                    if (argNr != argObjects.Values.Count)
                    {
                        System.Console.WriteLine($"not equal nr args -a {lenValuesCount} with  nr args for objects {argNr} - please see list command");

                        return(-1);
                    }


                    IBaseObject last = null;
                    IDataToSent data = null;
                    argNr            = 0;
                    for (int value = 0; value < lenValuesCount; value++)
                    {
                        string item            = opt.Values[value].ToLowerInvariant();
                        ResultTypeStankins cmd = commands[item];
                        object[] ctorArgs      = null;
                        if (cmd.ConstructorParam.Count > 0)
                        {
                            ctorArgs = new object[cmd.ConstructorParam.Count];
                            int i    = 0;
                            do
                            {
                                string item1 = argObjects.Values[argNr];

                                ctorArgs[i] = item1;
                                i++;
                                argNr++;
                            } while (i < cmd.ConstructorParam.Count);
                        }

                        last = cmd.Create(ctorArgs);
                        data = await last.TransformData(data);
                    }


                    ISenderToOutput output = last as ISenderToOutput;
                    if (output != null)
                    {
                        System.Console.WriteLine("exporting default output ?");
                        //TODO: add option for this
                        SenderOutputToFolder sender = new SenderOutputToFolder("", true);
                        data = await sender.TransformData(data);
                    }
                    else
                    {
                        System.Console.WriteLine("exporting all tables to csv ? ");
                        //TODO: add option for this
                        //await new SenderAllTablesToFileCSV("").TransformData(data);
                    }

                    return(0);
                });
            }
                        );

            if (args?.Length < 1)
            {
                app.ShowRootCommandFullNameAndVersion();
                app.ShowHint();

                return;
            }

            app.Execute(args);
        }
 public ActionResult <ResultTypeStankins[]> Get()
 {
     return(FindAssembliesToExecute.AddReferences(new FindAssembliesToExecute(null).FromType(typeof(RecipeFromFilePath))));
 }