示例#1
0
        public void Validation_FindAttributes()
        {
            var found = AttributeFinder.Find <ValidationAttribute>(typeof(BasicValidationObject));

            Assert.IsTrue(found.Count == 1);
            Assert.IsTrue(found.First().Value.Count == 4);
        }
示例#2
0
        public override bool Execute()
        {
            Console.WriteLine($"ApplicationPath: {ApplicationPath}");

            var finder       = new AttributeFinder();
            var assemblyPath = ApplicationPath;
            var foundType    = finder.FindAttribute(assemblyPath);

            Console.WriteLine(foundType);

            if (foundType != null)
            {
                var cacheGenerator = new CacheWarmupGenerator();

                var cacheResult = cacheGenerator.WarmupCache(assemblyPath, foundType);
                if (cacheResult != null)
                {
                    DcAssembly         = cacheResult.DcAssemblyFilePath;
                    ModelAssembly      = cacheResult.ModelAssemblyFilePath;
                    ModelCache         = cacheResult.ModelCacheFilePath;
                    ModulesVersionInfo = cacheResult.ModulesVersionInfoFilePath;

                    Console.WriteLine("Done");
                    return(true);
                }
            }

            return(false);
        }
示例#3
0
        public void Attribute_Filtering_All_NullFilter()
        {
            var dictionary = AttributeFinder.Find <ValidationAttribute>(typeof(FilteredObject));

            Assert.AreEqual(1, dictionary.Count);
            Assert.AreEqual(6, dictionary[typeof(FilteredObject)].First().Value.Count);
        }
示例#4
0
        public void Attribute_Filtering_DataValidation()
        {
            var dictionary = AttributeFinder.Find <ValidationAttribute>(typeof(FilteredObject), (x) => x is DataValidationAttribute);

            Assert.AreEqual(1, dictionary.Count);
            Assert.AreEqual(4, dictionary[typeof(FilteredObject)].First().Value.Count);
        }
        public override bool Execute()
        {
            Log.LogMessage($"ApplicationPath: {ApplicationPath}");
            Log.LogMessage($"Mode: {Mode}");

            if (Mode == "InProcess")
            {
                var finder       = new AttributeFinder();
                var assemblyPath = ApplicationPath;
                var foundType    = finder.FindAttribute(assemblyPath);

                Console.WriteLine(foundType);

                if (foundType != null)
                {
                    var cacheGenerator = new CacheWarmupGenerator();

                    var cacheResult = cacheGenerator.WarmupCache(assemblyPath, foundType.ApplicationType, foundType.FactoryType);
                    if (cacheResult != null)
                    {
                        DcAssembly         = cacheResult.DcAssemblyFilePath;
                        ModelAssembly      = cacheResult.ModelAssemblyFilePath;
                        ModelCache         = cacheResult.ModelCacheFilePath;
                        ModulesVersionInfo = cacheResult.ModulesVersionInfoFilePath;

                        Console.WriteLine("Done");
                        return(true);
                    }
                }
            }

            if (Mode == "OutOfProcess")
            {
                if (string.IsNullOrEmpty(CliPath))
                {
                    CliPath = Path.Combine(Path.GetDirectoryName(ApplicationPath), "Scissors.Xaf.CacheWarmup.Generators.Cli");
                }

                using (var process = new Process())
                {
                    process.StartInfo = new ProcessStartInfo(CliPath, ApplicationPath)
                    {
                        RedirectStandardOutput = true,
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        CreateNoWindow         = true,
                        UseShellExecute        = false,
                        WorkingDirectory       = Path.GetDirectoryName(ApplicationPath)
                    };
                    process.OutputDataReceived += (s, e) => Log.LogMessage(e.Data);
                    if (process.Start())
                    {
                        process.WaitForExit(10000);
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#6
0
        public void Init()
        {
            //Log.DebugLog("entered Init", "Init()");
            try
            {
                if (MyAPIGateway.CubeBuilder == null || MyAPIGateway.Entities == null || MyAPIGateway.Multiplayer == null || MyAPIGateway.Parallel == null ||
                    MyAPIGateway.Players == null || MyAPIGateway.Session == null || MyAPIGateway.TerminalActionsHelper == null || MyAPIGateway.Utilities == null)
                {
                    return;
                }

                if (!MyAPIGateway.Multiplayer.IsServer && MyAPIGateway.Session.Player == null)
                {
                    return;
                }

                Globals.WorldClosed = false;
                Log.DebugLog("World: " + MyAPIGateway.Session.Name + ", Path: " + MyAPIGateway.Session.CurrentPath, Logger.severity.INFO);
                AttributeFinder.InvokeMethodsWithAttribute <OnWorldLoad>();
                MyAPIGateway.Entities.OnCloseAll += UnloadData;

                if (!MyAPIGateway.Multiplayer.MultiplayerActive)
                {
                    Log.AlwaysLog("Single player, running server scripts", Logger.severity.INFO);
                    RegisterScripts_Server();
                }
                else if (MyAPIGateway.Multiplayer.IsServer)
                {
                    Log.AlwaysLog("This is the server, running server scripts", Logger.severity.INFO);
                    RegisterScripts_Server();
                }
                else
                {
                    Log.AlwaysLog("Client, running client scripts only", Logger.severity.INFO);
                }

                if (!CheckFinalBuildConstant("IS_OFFICIAL"))
                {
                    Log.AlwaysLog("Space Engineers build is UNOFFICIAL; this build is not supported. Version: " + MyFinalBuildConstants.APP_VERSION_STRING, Logger.severity.WARNING);
                }
                else if (CheckFinalBuildConstant("IS_DEBUG"))
                {
                    Log.AlwaysLog("Space Engineers build is DEBUG; this build is not supported. Version: " + MyFinalBuildConstants.APP_VERSION_STRING, Logger.severity.WARNING);
                }
                else
                {
                    Log.AlwaysLog("Space Engineers version: " + MyFinalBuildConstants.APP_VERSION_STRING, Logger.severity.INFO);
                }

                Logger.DebugNotify("ARMS DEBUG build loaded", 10000, Logger.severity.INFO);

                ManagerStatus = Status.Initialized;
            }
            catch (Exception ex)
            {
                Log.AlwaysLog("Failed to Init(): " + ex, Logger.severity.FATAL);
                ManagerStatus = Status.Terminated;
            }
        }
示例#7
0
        public void Validation_FindAttributesWithNestedList()
        {
            var found = AttributeFinder.Find <ValidationAttribute>(typeof(NestedListValidationObject));

            Assert.IsTrue(found.Count == 2);
            Assert.IsTrue(found[typeof(NestedListValidationObject)].Count == 2);
            Assert.IsTrue(found[typeof(BasicValidationObject)].Count == 4);
        }
示例#8
0
        private void Start()
        {
            RegisterScripts_ClientAndServer();

            // create script for each entity
            HashSet <IMyEntity> allEntities = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(allEntities);

            //Log.DebugLog("Adding all entities", "Init()");
            foreach (IMyEntity entity in allEntities)
            {
                AddEntity(entity);
            }

            MyAPIGateway.Entities.OnEntityAdd += Entities_OnEntityAdd;
            ManagerStatus = Status.Started;

            if (!ServerSettings.GetSetting <bool>(ServerSettings.SettingName.bAllowAutopilot))
            {
                Log.AlwaysLog("Disabling autopilot blocks", Logger.severity.INFO);
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Cockpit), "Autopilot-Block_Large")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Cockpit), "Autopilot-Block_Small")).Enabled = false;
            }
            if (!ServerSettings.GetSetting <bool>(ServerSettings.SettingName.bAllowGuidedMissile))
            {
                Log.AlwaysLog("Disabling guided missile blocks", Logger.severity.INFO);
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_SmallMissileLauncher), "Souper_R12VP_Launcher")).Enabled       = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_SmallMissileLauncher), "Souper_R8EA_Launcher")).Enabled        = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_SmallMissileLauncher), "Souper_B3MP_Launcher")).Enabled        = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_LargeMissileTurret), "Souper_Missile_Defense_Turret")).Enabled = false;
            }
            if (!ServerSettings.GetSetting <bool>(ServerSettings.SettingName.bAllowHacker))
            {
                Log.AlwaysLog("Disabling hacker blocks", Logger.severity.INFO);
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_LandingGear), "ARMS_SmallHackerBlock")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_LandingGear), "ARMS_LargeHackerBlock")).Enabled = false;
            }
            if (!ServerSettings.GetSetting <bool>(ServerSettings.SettingName.bAllowRadar))
            {
                Log.AlwaysLog("Disabling radar blocks", Logger.severity.INFO);
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Beacon), "LargeBlockRadarRynAR")).Enabled   = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Beacon), "SmallBlockRadarRynAR")).Enabled   = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Beacon), "Radar_A_Large_Souper07")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Beacon), "Radar_A_Small_Souper07")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_RadioAntenna), "PhasedArrayRadar_Large_Souper07")).Enabled       = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_RadioAntenna), "PhasedArrayRadar_Small_Souper07")).Enabled       = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_RadioAntenna), "PhasedArrayRadarOffset_Large_Souper07")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_RadioAntenna), "PhasedArrayRadarOffset_Small_Souper07")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Beacon), "AWACSRadarLarge_JnSm")).Enabled        = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_Beacon), "AWACSRadarSmall_JnSm")).Enabled        = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_RadioAntenna), "AP_Radar_Jammer_Large")).Enabled = false;
                MyDefinitionManager.Static.GetCubeBlockDefinition(new SerializableDefinitionId(typeof(MyObjectBuilder_RadioAntenna), "AP_Radar_Jammer_Small")).Enabled = false;
            }

            AttributeFinder.InvokeMethodsWithAttribute <AfterArmsInit>();
        }
示例#9
0
    public void Process()
    {
        attributeFinder = new AttributeFinder(Method);
        if (!attributeFinder.Found)
        {
            return;
        }
        Method.ThrowIfIsAsync();

        FoundUsageInType();
        ContinueProcessing();
    }
    public void Process()
    {
        attributeFinder = new AttributeFinder(Method);
        if (!attributeFinder.Found)
        {
            return;
        }
        Method.ThrowIfIsAsync();

        FoundUsageInType();
        ContinueProcessing();
    }
示例#11
0
        public BaseImageRepository(IMongoClientContext mongoClientContext)
        {
            mongoClient   = mongoClientContext.getContext();
            mongoDatabase = mongoClientContext.getDatabase();
            string collection = AttributeFinder.GetAttributeValue <T, MongoTable, string>(z => z.Name);

            if (String.IsNullOrEmpty(collection))
            {
                throw new Exception(Errors.UNDEFINED_COLLECTION);
            }

            Items = mongoDatabase.GetCollection <T>(collection);
        }
示例#12
0
        public void Attribute_Filtering_DataValidation_Pipeline_Stage()
        {
            var filter = new Func <Attribute, bool>((x) =>
            {
                var datavalidationAttribute = x as DataValidationAttribute;
                if (datavalidationAttribute != null)
                {
                    return(datavalidationAttribute.Pipeline == "Simple" && datavalidationAttribute.Stage == "BeforeSave");
                }
                return(false);
            });

            var dictionary = AttributeFinder.Find <ValidationAttribute>(typeof(FilteredObject), filter);

            Assert.AreEqual(1, dictionary.Count);
            Assert.AreEqual(1, dictionary[typeof(FilteredObject)].First().Value.Count);
        }
示例#13
0
        public void Validation_FindsCorrectAmountOfValidators()
        {
            var dictionary = new Dictionary <object, object>();

            dictionary.Add("Hello", "Goodbye");

            var attributes = AttributeFinder.Find <ValidationAttribute>(typeof(PipelineStageTestModel));

            Assert.AreEqual(6, attributes[typeof(PipelineStageTestModel)].First().Value.Count);

            attributes = AttributeFinder.Find <ValidationAttribute>(typeof(PipelineStageTestModel), false, false, null);
            Assert.AreEqual(6, attributes[typeof(PipelineStageTestModel)].First().Value.Count);

            attributes = AttributeFinder.Find <ValidationAttribute>(typeof(PipelineStateTestModelDerived), false, false, null);
            Assert.AreEqual(2, attributes[typeof(PipelineStateTestModelDerived)].First().Value.Count);

            attributes = AttributeFinder.Find <ValidationAttribute>(typeof(PipelineStateTestModelDerived), false, false, null);
            Assert.AreEqual(8, attributes[typeof(PipelineStateTestModelDerived)].First().Value.Count);

            var a = (typeof(PipelineStateTestModelDerived)).GetCustomAttributes(false);
        }
示例#14
0
        static void Main(string[] args)
        {
            var finder       = new AttributeFinder();
            var assemblyPath = @"C:\F\github\how-to-precache-an-xaf-winforms-application\src\PreCacheDemo.Win\bin\Debug\PreCacheDemo.Win.exe";
            var foundType    = finder.FindAttribute(assemblyPath);

            Console.WriteLine(foundType);

            if (foundType != null)
            {
                var cacheGenerator = new CacheWarmupGenerator();

                var cacheResult = cacheGenerator.WarmupCache(assemblyPath, foundType);
                if (cacheResult != null)
                {
                }
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }
示例#15
0
        static void Main(string[] args)
        {
            var finder       = new AttributeFinder();
            var assemblyPath = args[0];
            var mode         = Mode.OutOfProcess;
            var foundType    = finder.FindAttribute(assemblyPath, mode);

            Console.WriteLine(foundType);

            if (foundType != null)
            {
                var cacheGenerator = new CacheWarmupGenerator();

                var cacheResult = cacheGenerator.WarmupCache(assemblyPath, foundType.ApplicationType, foundType.FactoryType, mode);
                if (cacheResult != null)
                {
                }
            }

            Console.WriteLine("Done");
        }
示例#16
0
        protected override void UnloadData()
        {
            base.UnloadData();
            if (MyAPIGateway.Entities != null)
            {
                MyAPIGateway.Entities.OnEntityAdd -= Entities_OnEntityAdd;
                MyAPIGateway.Entities.OnCloseAll  -= UnloadData;
            }

            if (!Globals.WorldClosed)
            {
                MainLock.MainThread_ReleaseExclusive();
                try
                {
                    AttributeFinder.InvokeMethodsWithAttribute <OnWorldClose>();
                }
                catch (Exception ex)
                {
                    // if world is closed by X button, expect an exception
                    Log.AlwaysLog("Exception while unloading: " + ex, Logger.severity.ERROR);
                }
                Globals.WorldClosed = true;
                Profiler.Write();
            }

            // in case SE doesn't clean up properly, clear all fields
            foreach (FieldInfo field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (!field.IsLiteral && !field.IsInitOnly)
                {
                    field.SetValue(this, null);
                }
            }

            ManagerStatus = Status.Terminated;
        }
        public void ValidationLoader_Loads_Derived_Validators_Via_Loader()
        {
            var result = AttributeFinder.Find <ValidationAttribute>(typeof(ValidationLoaderDerived));

            Assert.AreEqual(2, result[typeof(ValidationLoaderDerived)].First().Value.Count());
        }
示例#18
0
 public override void SaveData()
 {
     AttributeFinder.InvokeMethodsWithAttribute <OnWorldSave>();
 }
        static void Main(string[] args)
        {
            var assemblyPath = args[0];

            Console.WriteLine($"ARGUMENTS: '{assemblyPath}'");
            var assemblyDirectory = Path.GetDirectoryName(assemblyPath);

            Console.WriteLine($"AssemblyDirectory: '{assemblyDirectory}'");

            Console.WriteLine("Clean All old asserts");

            foreach (var file in Directory.EnumerateFiles(Path.GetDirectoryName(typeof(Program).Assembly.Location)))
            {
                if (file == typeof(Program).Assembly.Location)
                {
                    continue;
                }
                if (File.Exists(file))
                {
                    Console.WriteLine($"Deleting: {file}");
                    File.Delete(file);
                }
            }

            AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs e) =>
            {
                Console.WriteLine($"AssemblyResolve: {e.Name}");
                var assemblyName = e.Name.Split(',').First();
                var aPath        = Path.Combine(assemblyDirectory, assemblyName + ".dll");
                Console.WriteLine($"New AssemblyPath: '{aPath}'");
                if (File.Exists(aPath))
                {
                    Console.WriteLine($"New AssemblyPath exists!: '{aPath}'");
                    var loadedAssembly = Assembly.LoadFile(aPath);
                    Console.WriteLine($"New Assembly?: '{loadedAssembly}'");
                    return(loadedAssembly);
                }

                return(null);
            };

            var finder = new AttributeFinder();

            Console.WriteLine($"Loading Assembly: {assemblyPath}");
            var assembly = Assembly.LoadFile(assemblyPath);

            Console.WriteLine($"Loaded Assembly: {assembly.GetName().FullName}");
            Console.WriteLine($"Try To Find Type");
            var foundType = finder.FindAttribute(assembly);

            Console.WriteLine($"Found-Type: '{foundType}'");

            if (foundType != null)
            {
                var cacheGenerator = new CacheWarmupGenerator();

                var cacheResult = cacheGenerator.WarmupCache(assembly, foundType.ApplicationType, foundType.FactoryType);
                if (cacheResult != null)
                {
                    CopyFile(cacheResult.DcAssemblyFilePath, assemblyDirectory);
                    CopyFile(cacheResult.ModelAssemblyFilePath, assemblyDirectory);
                    CopyFile(cacheResult.ModelCacheFilePath, assemblyDirectory);
                    CopyFile(cacheResult.ModulesVersionInfoFilePath, assemblyDirectory);
                }
            }

            Console.WriteLine("Done");
        }
示例#20
0
        public string InitSession()
        {
            HttpStatusCode httpStatus;

            // No idea why from time to time the login fails.  It does
            // not appear that it is a failed login, but instead
            // strava is ignoring the post and is just re-rendering the
            // login page.  - must have something to do with the authenticity token or something.
            var loggedIn = false;

            for (var tryCount = 0; tryCount < 3; tryCount++)
            {
                this._cookieHolder = new CookieContainer();
                var loginPage = this.HttpGet("https://www.strava.com/login", out httpStatus);

                if (httpStatus != HttpStatusCode.OK)
                {
                    return("Unable to contact the Strava server.");
                }

                // Attempt to parse the table.
                var loader = new HtmlAgilityPack.HtmlDocument();
                loader.LoadHtml(loginPage);

                AttributeFinder finder = (doc, name) =>
                {
                    var element = (from n in doc.DocumentNode.Descendants("input") where n.GetAttributeValue("name", string.Empty) == name select n).FirstOrDefault();

                    if (element == null)
                    {
                        return(string.Empty);
                    }

                    var attb = element.Attributes.FirstOrDefault(f => f.Name == "value");

                    if (attb == null)
                    {
                        return(string.Empty);
                    }

                    return(attb.Value);
                };

                var authTok = finder(loader, "authenticity_token");
                var utf8    = finder(loader, "utf8");

                var loginResultPage = this.HttpPost(
                    "https://www.strava.com/session",
                    string.Format(
                        "email={0}&password={1}&authenticity_token={2}&utf8=%E2%9C%93",
                        HttpUtility.HtmlEncode(this._userName),
                        HttpUtility.HtmlEncode(this._password),
                        authTok),
                    out httpStatus);

                if (httpStatus != HttpStatusCode.OK)
                {
                    return("Unable to contact the Strava server.");
                }

                loader = new HtmlAgilityPack.HtmlDocument();
                loader.LoadHtml(loginResultPage);

                var htmlObj = loader.DocumentNode.Descendants("html").FirstOrDefault();

                if (htmlObj == null)
                {
                    return("Unexpected result returned from Strava Server");
                }

                if (htmlObj.GetAttributeValue("class", string.Empty).Split(' ').Any(a => a.ToLower() == "logged-in"))
                {
                    loggedIn = true;
                    break;
                }

                // Not logged in.
                // Need to see if an 'alert-message' exists.
                htmlObj = (from n in loader.DocumentNode.Descendants("div") where n.GetAttributeValue("class", string.Empty) == "alert-message" select n).FirstOrDefault();

                if (htmlObj != null &&
                    htmlObj.InnerHtml.ToLower().Contains("did not match"))
                {
                    // If this exists, the error is wrong pwd.
                    break;
                }

                if (htmlObj != null &&
                    htmlObj.InnerHtml.ToLower().Contains("expired"))
                {
                    // Session expired... loop around again.
                    // Is this a .net thing?  I'm creating a new cookie container...whatever, I
                    // guess this hack seems to work by looping and just trying again.
                }
            }

            if (!loggedIn)
            {
                return("The login details provider do not appear to be valid.");
            }

            // We're now logged in.

            // Next, we need to be sure we have a valid API token.
            this._auth = new StaticAuthentication(this._apiKey);
            var athlete = new AthleteClient(this._auth);

            try
            {
                var details = athlete.GetAthlete();

                if (details == null ||
                    details.Email == null ||
                    details.Email.ToLower() != this._userName.ToLower())
                {
                    return("The API key is not associated to the same Strava account as the user name provided.");
                }
            }
            catch
            {
                return("The API key provided does not appear to be valid");
            }


            return(string.Empty);
        }