示例#1
0
        static void Game_OnGameLoad(EventArgs args)
        {
            Player = ObjectManager.Player;

            if (Player.ChampionName != ChampionName)
                return;

            try
            {
                InitializeSpells();

                InitializeSkinManager();

                InitializeLevelUpManager();

                InitializeMainMenu();

                InitializeAttachEvents();

                Game.PrintChat(string.Format("<font color='#fb762d'>DevFiora Loaded v{0}</font>", Assembly.GetExecutingAssembly().GetName().Version));

                assemblyUtil = new AssemblyUtil(Assembly.GetExecutingAssembly().GetName().Name);
                assemblyUtil.onGetVersionCompleted += AssemblyUtil_onGetVersionCompleted;
                assemblyUtil.GetLastVersionAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
示例#2
0
        static void Game_OnGameLoad(EventArgs args)
        {
            Player = ObjectManager.Player;

            if (!Player.ChampionName.ToLower().Contains(ChampionName))
                return;

            InitializeSpells();

            InitializeSkinManager();

            InitializeMainMenu();

            InitializeAttachEvents();

            //Game.PrintChat(string.Format("<font color='#F7A100'>DevLulu Loaded v{0}</font>", Assembly.GetExecutingAssembly().GetName().Version));

            assemblyUtil = new AssemblyUtil(Assembly.GetExecutingAssembly().GetName().Name);
            assemblyUtil.onGetVersionCompleted += AssemblyUtil_onGetVersionCompleted;
            assemblyUtil.GetLastVersionAsync();

            Game.PrintChat(string.Format("<font color='#FF0000'>DevLulu: THIS ASSEMBLY IS NOT FINISHED YET!!!</font>"));
        }
示例#3
0
        public MainWindowVM(IKernel kernel,
                            IEventAggregator eventAggregator,
                            ITwitchService twitchService,
                            IDialogService dialogService,
                            IDonationService donationService,
                            INavigationService navigationService,
                            ISearchService searchService,
                            IPreferencesService preferencesService,
                            IRuntimeDataService runtimeDataService,
                            IUpdateService updateService)
        {
            AssemblyUtil au = AssemblyUtil.Get;

            this.Title = au.GetProductName() + " " + au.GetAssemblyVersion().Trim();

            this._kernel             = kernel;
            this._eventAggregator    = eventAggregator;
            this._twitchService      = twitchService;
            this._dialogService      = dialogService;
            this._donationService    = donationService;
            this._navigationService  = navigationService;
            this._searchService      = searchService;
            this._preferencesService = preferencesService;
            this._runtimeDataService = runtimeDataService;
            this._updateService      = updateService;

            this._commandLockObject = new object();

            this._eventAggregator.GetEvent <ShowViewEvent>().Subscribe(this.ShowView);
            this._eventAggregator.GetEvent <IsAuthorizedChangedEvent>().Subscribe(this.IsAuthorizedChanged);
            this._eventAggregator.GetEvent <PreferencesSavedEvent>().Subscribe(this.PreferencesSaved);
            this._eventAggregator.GetEvent <VideosCountChangedEvent>().Subscribe(this.VideosCountChanged);
            this._eventAggregator.GetEvent <DownloadsCountChangedEvent>().Subscribe(this.DownloadsCountChanged);

            this._showDonationButton = this._preferencesService.CurrentPreferences.AppShowDonationButton;
        }
示例#4
0
        /// <summary>
        /// Initialize .NET Core generic host's app configuration
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <param name="args"></param>
        /// <param name="configureDelegate"></param>
        /// <param name="configEnvironmentPrefix"></param>
        /// <param name="configFilePrefix"></param>
        /// <returns></returns>
        public static IHostBuilder UseAppConfiguration(this IHostBuilder hostBuilder,
                                                       string[] args,
                                                       Action <HostBuilderContext, IConfigurationBuilder> configureDelegate = null,
                                                       string configEnvironmentPrefix = AppEnvPrefix,
                                                       string configFilePrefix        = ConfigFilePrefix)
        {
            if (configureDelegate == null)
            {
                hostBuilder.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
                {
                    configurationBuilder
                    .SetBasePath(GetContextCwd())
                    .AddJsonFile($"{configFilePrefix}.json", optional: true)
                    .AddJsonFile($"{configFilePrefix}.{hostBuilderContext.HostingEnvironment.EnvironmentName}.json",
                                 optional: true)
                    .AddEnvironmentVariables(prefix: configEnvironmentPrefix)
                    .AddCommandLine(args);

                    if (hostBuilderContext.HostingEnvironment.IsDevelopment())
                    {
                        var mainAssembly         = AssemblyUtil.GetMainAssembly();
                        var userSecretsAttribute = mainAssembly.GetCustomAttribute <UserSecretsIdAttribute>();
                        if (userSecretsAttribute != null)
                        {
                            configurationBuilder.AddUserSecrets(AssemblyUtil.GetMainAssembly());
                        }
                    }
                });
            }
            else
            {
                hostBuilder.ConfigureAppConfiguration(configureDelegate);
            }

            return(hostBuilder);
        }
示例#5
0
        private static void onGameLoad(EventArgs args)
        {
            try
            {
                Player = ObjectManager.Player;

                if (!Player.ChampionName.ToLower().Contains(ChampionName))
                {
                    return;
                }

                InitializeSpells();

                InitializeSkinManager();

                InitializeLevelUpManager();

                InitializeMainMenu();

                InitializeAttachEvents();

                Game.PrintChat(string.Format("<font color='#fb762d'>{0} Loaded v{1}</font>", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version));

                assemblyUtil = new AssemblyUtil(Assembly.GetExecutingAssembly().GetName().Name);
                assemblyUtil.onGetVersionCompleted += AssemblyUtil_onGetVersionCompleted;
                assemblyUtil.GetLastVersionAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                if (mustDebug)
                {
                    Game.PrintChat(ex.ToString());
                }
            }
        }
        protected override void OnOK(object sender, EventArgs args)
        {
            CustomItemSettings settings = new CustomItemSettings(HttpContext.Current);

            ICustomItemNamespaceProvider  namespaceProvider = AssemblyUtil.GetNamespaceProvider(settings.NamespaceProvider);
            ICustomItemFolderPathProvider filePathProvider  = AssemblyUtil.GetFilePathProvider(settings.FilepathProvider);

            CustomItemInformation customItemInformation = new CustomItemInformation(template, CustomItemNamespace.Value,
                                                                                    CustomItemFilePath.Value, filePathProvider, namespaceProvider);

            if (settings.AutoUpdate)
            {
                new CodeGenerator(customItemInformation, true, false, false, false).GenerateCode();
            }
            else
            {
                CodeGenerator codeGenerator = new CodeGenerator(customItemInformation,
                                                                GenerateBaseFile.Checked, GenerateInstanceFile.Checked, GenerateInterfaceFile.Checked, GenerateStaticFile.Checked);
                codeGenerator.GenerateCode();

                SheerResponse.Alert(codeGenerator.GenerationMessage, new string[0]);
            }
            base.OnOK(sender, args);
        }
        public HttpResponse GetPostsByPage(HttpRequest request, string language)
        {
            Console.WriteLine("Get Posts By Page");

            DirectoryInfo   postsDir = new DirectoryInfo(Path.Combine(AssemblyUtil.GetApplicationRoot(), "Resources", language, "blog"));
            List <FileInfo> files    = postsDir.GetFiles().ToList();

            files.Sort(CompareFile);

            string content = "";
            bool   first   = true;

            for (int i = 0; i < files.Count; i++)
            {
                FileInfo file = files[i];
                string   text = File.ReadAllText(file.FullName);
                if (text.Contains("!IGNORE"))
                {
                    continue;
                }

                if (!first)
                {
                    content += "<next>";
                }
                content += text;
                first    = false;
            }

            return(new HttpResponse()
            {
                ReasonPhrase = "",
                StatusCode = "200",
                ContentAsUTF8 = content
            });
        }
示例#8
0
 public static void ConfigurePostgreSql()
 {
     ConfigurePostgreSql(AssemblyUtil.GetAssemblies());
 }
示例#9
0
 public static void ConfigureSqlServer()
 {
     ConfigureSqlServer(AssemblyUtil.GetAssemblies());
 }
        public static void ProcessUnifiedHtmlFile(string htmlFile, bool darkMode, out string coverageHtml)
        {
            coverageHtml = AssemblyUtil.RunInAssemblyResolvingContext(() =>
            {
                // read [htmlFile] into memory

                var htmlFileContent = File.ReadAllText(htmlFile);

                var folder = Path.GetDirectoryName(htmlFile);

                // create and save doc util

                var doc = new HtmlDocument();

                doc.OptionFixNestedTags  = true;
                doc.OptionAutoCloseOnEnd = true;

                doc.LoadHtml(htmlFileContent);

                doc.DocumentNode.QuerySelectorAll(".footer").ToList().ForEach(x => x.SetAttributeValue("style", "display:none"));
                doc.DocumentNode.QuerySelectorAll(".container").ToList().ForEach(x => x.SetAttributeValue("style", "margin:0;padding:0;border:0"));
                doc.DocumentNode.QuerySelectorAll(".containerleft").ToList().ForEach(x => x.SetAttributeValue("style", "margin:0;padding:0;border:0"));
                doc.DocumentNode.QuerySelectorAll(".containerleft > h1 , .containerleft > p").ToList().ForEach(x => x.SetAttributeValue("style", "display:none"));

                // DOM changes

                var table     = doc.DocumentNode.QuerySelectorAll("table.overview").First();
                var tableRows = table.QuerySelectorAll("tr").ToArray();
                try { tableRows[0].SetAttributeValue("style", "display:none"); } catch { }
                try { tableRows[1].SetAttributeValue("style", "display:none"); } catch { }
                try { tableRows[10].SetAttributeValue("style", "display:none"); } catch { }
                try { tableRows[10].SetAttributeValue("style", "display:none"); } catch { }
                try { tableRows[11].SetAttributeValue("style", "display:none"); } catch { }
                try { tableRows[12].SetAttributeValue("style", "display:none"); } catch { }

                // TEXT changes
                var assemblyClassDelimiter = "!";
                var outerHtml           = doc.DocumentNode.OuterHtml;
                var htmlSb              = new StringBuilder(outerHtml);
                var assembliesSearch    = "var assemblies = [";
                var startIndex          = outerHtml.IndexOf(assembliesSearch) + assembliesSearch.Length - 1;
                var endIndex            = outerHtml.IndexOf("var historicCoverageExecutionTimes");
                var assembliesToReplace = outerHtml.Substring(startIndex, endIndex - startIndex);
                endIndex            = assembliesToReplace.LastIndexOf(']');
                assembliesToReplace = assembliesToReplace.Substring(0, endIndex + 1);
                var assemblies      = JArray.Parse(assembliesToReplace);
                foreach (JObject assembly in assemblies)
                {
                    var assemblyName = assembly["name"];
                    var classes      = assembly["classes"] as JArray;

                    var autoGeneratedRemovals = new List <JObject>();
                    foreach (JObject @class in classes)
                    {
                        var className = @class["name"].ToString();
                        if (className == "AutoGeneratedProgram")
                        {
                            autoGeneratedRemovals.Add(@class);
                        }
                        else
                        {
                            // simplify name
                            var lastIndexOfDotInName = className.LastIndexOf('.');
                            if (lastIndexOfDotInName != -1)
                            {
                                @class["name"] = className.Substring(lastIndexOfDotInName).Trim('.');
                            }

                            //mark with # and add the assembly name
                            var rp        = @class["rp"].ToString();
                            var htmlIndex = rp.IndexOf(".html");
                            @class["rp"]  = $"#{assemblyName}{assemblyClassDelimiter}{className + ".html" + rp.Substring(htmlIndex + 5)}";
                        }
                    }
                    foreach (var autoGeneratedRemoval in autoGeneratedRemovals)
                    {
                        classes.Remove(autoGeneratedRemoval);
                    }
                }
                var assembliesReplaced = assemblies.ToString();
                htmlSb.Replace(assembliesToReplace, assembliesReplaced);

                htmlSb.Replace(".table-fixed", ".table-fixed-ignore-me");

                htmlSb.Replace("</head>", $@"
					<style type=""text/css"">
						*, body {{ font-size: small; }}
						table td {{ white-space: nowrap; }}
						table.coverage {{ width:150px;height:13px }}
						body {{ padding-left:3px;padding-right:3px;padding-bottom:3px }}
						table,tr,th,td {{ border: 1px solid #3f3f46; font-size: small; }}
						a, a:hover {{ color: #0078D4; text-decoration: none; cursor: pointer; }}
						body {{ -webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none }}
						table.overview th, table.overview td {{ font-size: small; white-space: nowrap; word-break: normal; padding-left:10px;padding-right:10px; }}
						coverage-info div.customizebox div:nth-child(2) {{ opacity:0;font-size:1px;height:1px;padding:0;border:0;margin:0 }}
						coverage-info div.customizebox div:nth-child(2) * {{ opacity:0;font-size:1px;height:1px;padding:0;border:0;margin:0 }}
					</style>
					</head>
				"                );

                if (darkMode)
                {
                    htmlSb.Replace("</head>", $@"
						<style type=""text/css"">
							*, body {{ color: #f1f1f1 }}
							table.overview.table-fixed {{ border: 1px solid #3f3f46; }}
							body, html {{ scrollbar-arrow-color:#999;scrollbar-track-color:#3e3e42;scrollbar-face-color:#686868;scrollbar-shadow-color:#686868;scrollbar-highlight-color:#686868;scrollbar-3dlight-color:#686868;scrollbar-darkshadow-Color:#686868; }}
						</style>
						</head>
					"                    );
                }
                else
                {
                    htmlSb.Replace("</head>", $@"
						<style type=""text/css"">
							table.overview.table-fixed {{ border-width: 1px }}
						</style>
						</head>
					"                    );
                }

                htmlSb.Replace("</body>", $@"
					<script type=""text/javascript"">
						
						var htmlExtension = '.html';
						
						var eventListener = function (element, event, func) {{
							if (element.addEventListener)
								element.addEventListener(event, func, false);
							else if (element.attachEvent)
								element.attachEvent('on' + event, func);
							else
								element['on' + event] = func;
						}};

						var classes = {{}};
						
						Array.prototype.forEach.call(assemblies, function (assembly) {{
							setTimeout(function () {{
								Array.prototype.forEach.call(assembly.classes, function (classs) {{
									setTimeout(function () {{
										classs.assembly = assembly;
										classes[classs.rp] = classs;
									}});
								}});
							}});
						}});
						
						eventListener(document, 'click', function (event) {{
							
							var target = event.target;
							if (target.tagName.toLowerCase() !== 'a') return;
							
							var href = target.getAttribute('href');
							if (!href || href[0] !== '#') return;
							
							var htmlExtensionIndex = href.toLowerCase().indexOf(htmlExtension);
							if (htmlExtensionIndex === -1) return;
							
							if (event.preventDefault) event.preventDefault()
							if (event.stopPropagation) event.stopPropagation();
							
							var assemblyAndQualifiedClassName = href.substring(1, htmlExtensionIndex);
							var delimiterIndex = assemblyAndQualifiedClassName.indexOf('{assemblyClassDelimiter}');
							var assembly = assemblyAndQualifiedClassName.substring(0, delimiterIndex);
							var qualifiedClassName = assemblyAndQualifiedClassName.substring(delimiterIndex + 1);
							var fileLine = href.substring(htmlExtensionIndex + htmlExtension.length);
							
							if (fileLine.indexOf('#') !== -1)
								fileLine = fileLine.substring(fileLine.indexOf('#') + 1).replace('file', '').replace('line', '').split('_');
							else
								fileLine = ['0', '0'];
							
							window.external.OpenFile(assembly, qualifiedClassName, parseInt(fileLine[0]), parseInt(fileLine[1]));
							
							return false;
						}});
							
					</script>
					</body>
				"                );

                htmlSb.Replace("</head>", $@"
					<style type=""text/css"">
						table.overview.table-fixed.stripped > thead > tr > th:nth-of-type(4) > a:nth-of-type(2) {{ display: none; }}
					</style>
					</head>
				"                );

                if (darkMode)
                {
                    htmlSb.Replace("<body>", @"
						<body>
						<style>
							#divHeader {
								background-color: #252526;
							}
							table#headerTabs td {
								color: #969696;
								border-color:#969696;
							}
						</style>
					"                    );
                }
                else
                {
                    htmlSb.Replace("<body>", @"
						<body>
						<style>
							#divHeader {
								background-color: #ffffff;
							}
							table#headerTabs td {
								color: #3b3b3b;
								border-color: #3b3b3b;
							}
						</style>
					"                    );
                }

                htmlSb.Replace("<body>", @"
					<body oncontextmenu='return false;'>
					<style>
						
						table#headerTabs td {
							border-width:3px;
							padding: 3px;
							padding-left: 7px;
							padding-right: 7px;
						}
						table#headerTabs td.tab {
							cursor: pointer;
						}
						table#headerTabs td.active {
							border-bottom: 3px solid transparent;
							font-weight: bolder;
						}
						
					</style>
					<script>
					
						var body = document.getElementsByTagName('body')[0];
						body.style['padding-top'] = '50px';
					
						var tabs = [
							{ button: 'btnCoverage', content: 'coverage-info' }, 
							{ button: 'btnSummary', content: 'table-fixed' },
							{ button: 'btnRiskHotspots', content: 'risk-hotspots' },
						];
					
						var openTab = function (tabIndex) {
							for (var i = 0; i < tabs.length; i++) {
							
								var tab = tabs[i];
								if (!tab) continue;
							
								var button = document.getElementById(tab.button);
								if (!button) continue;
							
								var content = document.getElementsByTagName(tab.content)[0];
								if (!content) content = document.getElementsByClassName(tab.content)[0];
								if (!content) continue;
							
								if (i == tabIndex) {
									if (button.className.indexOf('active') == -1) button.className += ' active';
									content.style.display = 'block';
								} else {
									button.className = button.className.replace('active', '');
									content.style.display = 'none';
								}
							}
						};
					
						window.addEventListener('load', function() {
							openTab(0);
						});
					
					</script>
					<div id='divHeader' style='border-collapse:collapse;padding:0;padding-top:3px;margin:0;border:0;position:fixed;top:0;left:0;width:100%;z-index:100' cellpadding='0' cellspacing='0'>
						<table id='headerTabs' style='border-collapse:collapse;padding:0;margin:0;border:0' cellpadding='0' cellspacing='0'>
							<tr style='padding:0;margin:0;border:0;'>
								<td style='width:3px;white-space:no-wrap;padding-left:0;padding-right:0;border-left:0;border-top:0'>
								</td>
								<td id='btnCoverage' onclick='return openTab(0);' class='tab' style='width:1%;white-space:no-wrap;'>
									Coverage
								</td>
								<td id='btnSummary' onclick='return openTab(1);' class='tab' style='width:1%;white-space:no-wrap'>
									Summary
								</td>
								<td id='btnRiskHotspots' onclick='return openTab(2);' class='tab' style='width:1%;white-space:no-wrap'>
									Risk Hotspots
								</td>
								<td style='border-top:transparent;border-right:transparent;padding-top:0px' align='center'>
									<a href='#' onclick='return window.external.RateAndReview();' style='margin-right:7px'>Rate & Review</a>
									<a href='#' onclick='return window.external.LogIssueOrSuggestion();' style='margin-left:7px'>Log Issue/Suggestion</a>
								</td>
								<td style='width:1%;white-space:no-wrap;border-top:transparent;border-right:transparent;border-left:transparent;padding-top:0px'>
									<a href='#' onclick='return window.external.BuyMeACoffee();'>Buy me a coffee</a>
								</td>
							</tr>
						</table>
					</div>
				"                );

                htmlSb.Replace("branchCoverageAvailable = true", "branchCoverageAvailable = false");

                var html = string.Join(
                    Environment.NewLine,
                    htmlSb.ToString().Split('\r', '\n')
                    .Select(line =>
                {
                    // modify column widths

                    if (line.StartsWith(".column"))
                    {
                        line = $"{line.Substring(0, line.IndexOf('{')).Trim('{')} {{white-space: nowrap; width:1%;}}";
                    }

                    // modify coverage data

                    if (line.IndexOf(@"""name"":") != -1 && line.IndexOf(@"""rp"":") != -1 && line.IndexOf(@"""cl"":") != -1)
                    {
                        var lineJO = JObject.Parse(line.TrimEnd(','));
                        var name   = lineJO.Value <string>("name");

                        if (name.Equals("AutoGeneratedProgram"))
                        {
                            // output line

                            line = string.Empty;
                        }
                        else
                        {
                            // simplify name

                            var lastIndexOfDotInName = name.LastIndexOf('.');
                            if (lastIndexOfDotInName != -1)
                            {
                                lineJO["name"] = name.Substring(lastIndexOfDotInName).Trim('.');
                            }

                            // prefix the url with #

                            lineJO["rp"] = $"#{lineJO.Value<string>("rp")}";

                            // output line

                            line = $"{lineJO.ToString(Formatting.None)},";
                        }
                    }

                    // modify risk host spots data

                    if (line.IndexOf(@"""assembly"":") != -1 && line.IndexOf(@"""class"":") != -1 && line.IndexOf(@"""reportPath"":") != -1)
                    {
                        var lineJO = JObject.Parse($"{{ {line.TrimEnd(',')} }}");

                        // simplify class

                        var _class = lineJO.Value <string>("class");
                        var lastIndexOfDotInClass = _class.LastIndexOf('.');
                        if (lastIndexOfDotInClass != -1)
                        {
                            lineJO["class"] = _class.Substring(lastIndexOfDotInClass).Trim('.');
                        }

                        // prefix the urls with #

                        lineJO["reportPath"] = $"#{lineJO.Value<string>("reportPath")}";

                        // output line

                        line = $"{lineJO.ToString(Formatting.None).Trim('{', '}')},";
                    }

                    return(line);
                }));

                // save

                var resultHtmlFile = Path.Combine(folder, $"{Path.GetFileNameWithoutExtension(htmlFile)}-processed{Path.GetExtension(htmlFile)}");
                File.WriteAllText(resultHtmlFile, html);
                return(resultHtmlFile);
            });
        }
        /// <summary>
        /// Tries to load commands.
        /// </summary>
        /// <param name="commands">The commands.</param>
        /// <returns></returns>
        public override bool TryLoadCommands(out IEnumerable <TCommand> commands)
        {
            commands = null;

            var commandAssemblies = new List <Assembly>();

            if (m_AppServer.GetType().Assembly != this.GetType().Assembly)
            {
                commandAssemblies.Add(m_AppServer.GetType().Assembly);
            }

            string commandAssembly = m_AppServer.Config.Options.GetValue("commandAssembly");

            if (!string.IsNullOrEmpty(commandAssembly))
            {
                OnError("The configuration attribute 'commandAssembly' is not in used, please try to use the child node 'commandAssemblies' instead!");
                return(false);
            }


            if (m_AppServer.Config.CommandAssemblies != null && m_AppServer.Config.CommandAssemblies.Any())
            {
                try
                {
                    var definedAssemblies = AssemblyUtil.GetAssembliesFromStrings(m_AppServer.Config.CommandAssemblies.Select(a => a.Assembly).ToArray());

                    if (definedAssemblies.Any())
                    {
                        commandAssemblies.AddRange(definedAssemblies);
                    }
                }
                catch (Exception e)
                {
                    OnError(new Exception("Failed to load defined command assemblies!", e));
                    return(false);
                }
            }

            if (!commandAssemblies.Any())
            {
                commandAssemblies.Add(Assembly.GetEntryAssembly());
            }

            var outputCommands = new List <TCommand>();

            foreach (var assembly in commandAssemblies)
            {
                try
                {
                    outputCommands.AddRange(assembly.GetImplementedObjectsByInterface <TCommand>());
                }
                catch (Exception exc)
                {
                    OnError(new Exception(string.Format("Failed to get commands from the assembly {0}!", assembly.FullName), exc));
                    return(false);
                }
            }

            commands = outputCommands;

            return(true);
        }
		public AttributeBasedContainerBuilder()
		{
			assemblyUtil = new AssemblyUtil();
		}
示例#13
0
 public static string GetLibraryPath()
 {
     return(Path.Combine(AssemblyUtil.GetStartFolder(), "bin", "SplitScreenMe.Engine.dll"));
 }
示例#14
0
        /// <summary>
        /// 初始化Logic modules
        /// </summary>
        /// <remarks>
        /// 方法在 InitOnceServer_Step1() 里被调用
        /// </remarks>
        public void Initializationing()
        {
            var dependenceModules = new List <KeyValuePair <InitDependenceAttribute, ILogicModule> >();

            foreach (var type in AssemblyUtil.GetTypesByInterface(typeof(ILogicModule)))
            {
                if (type.IsInterface)
                {
                    continue;
                }

                string moduleId = string.Empty;

                try
                {
                    var obj    = Activator.CreateInstance(type);
                    var module = (ILogicModule)obj;
                    moduleId = module.ModuleId;

                    //  获得模块的初始化依赖
                    var dependances = type.GetCustomAttributes(typeof(InitDependenceAttribute), false);
                    if (dependances.Length > 0)
                    {
                        var dependance = dependances[0] as InitDependenceAttribute;
                        if (dependance != null)
                        {
                            dependenceModules.Add(
                                new KeyValuePair <InitDependenceAttribute, ILogicModule>(dependance, module));
                        }
                    }

                    //  忽略某些模块的初始化
                    var ignore = type.GetCustomAttributes(typeof(IgnoreInitializationAttribute), true);
                    if (ignore.Length > 0)
                    {
                        Logs.Info("Ignore {0} init.", moduleId);
                        continue;
                    }

                    //  一般逻辑模块会要求实现一个模块状态输出功能
                    if (type.GetInterface(typeof(IServerState).Name) != null)
                    {
                        ServerStateManager.Register((IServerState)obj);
                    }

                    Logs.Info("Craete module {0}", moduleId);

                    modules.Add(module);
                }
                catch (Exception ex)
                {
                    Logs.Error("LogicModule.CreateModule fail. ModuleName:{0} Type:{1}    ",
                               moduleId, type.Name, ex);
                }
            }

            foreach (var dp in dependenceModules)
            {
                modules.Remove(dp.Value);
            }

            while (dependenceModules.Count > 0)
            {
                bool isChange = false;
                foreach (var dp in dependenceModules.ToArray())
                {
                    int content = 0;
                    foreach (var moduleName in dp.Key.Dependences)
                    {
                        content += modules.Count(o => o.ModuleId == moduleName);
                    }

                    if (content == dp.Key.Dependences.Length)
                    {
                        //  满足依赖条件
                        modules.Add(dp.Value);
                        isChange = true;
                        dependenceModules.Remove(dp);
                    }
                }

                if (!isChange)
                {
                    string moduleName = string.Empty;
                    dependenceModules.ForEach(o => { moduleName += o.Value.ModuleId + ","; });
                    Logs.Error("模块依赖可能存在循环依赖问题,请检查以下模块:{0}", moduleName.TrimEnd(','));

                    modules.AddRange(dependenceModules.Select(o => o.Value).ToArray());
                    break;
                }
            }

            foreach (var module in modules)
            {
                try
                {
                    module.Initializationing();
                }
                catch (Exception ex)
                {
                    Logs.Error("LogicModule.Initializationing fail. moduleId:{0}", module.ModuleId, ex);
                }
            }
        }
示例#15
0
 public override void Invoke(CommandInvocationContext context)
 {
     base.Out.Object.Table(TableRecords.CreateModuleTableRecordList(false, AssemblyUtil.GetAssemblyModules(Assembly).ToArray()));
 }
        /// <summary>
        /// 统一注册MVC及服务程序集
        /// </summary>
        /// <param name="containerBuilder">容器生成器</param>
        /// <param name="param">参数</param>
        /// <returns>容器</returns>
        public static IContainer UnifiedRegisterAssemblysForMvc5(this ContainerBuilder containerBuilder, WebBuilderParam param)
        {
            var assemblyList = new List <Assembly>();

            foreach (BasicAssemblyInfo assembly in param.AssemblyControllers)
            {
                Assembly[] assemblies = AssemblyUtil.Load(assembly.Names);
                if (assemblies.IsNullOrLength0())
                {
                    return(null);
                }
                assemblyList.AddRange(assemblies);

                if (!assembly.InterceptedTypes.IsNullOrLength0())
                {
                    foreach (Type type in assembly.InterceptedTypes)
                    {
                        containerBuilder.RegisterType(type);
                    }
                }

                if (assembly.Intercepteds.IsNullOrLength0())
                {
                    containerBuilder.RegisterControllers(assemblies)
                    .PropertiesAutowired()
                    .AsImplementedInterfaces()
                    .Where(AutofacUtil.CanInject)
                    .AsSelf();
                }
                else
                {
                    containerBuilder.RegisterControllers(assemblies)
                    .PropertiesAutowired()
                    .AsImplementedInterfaces()
                    .AsSelf()
                    .InterceptedBy(assembly.Intercepteds)
                    .Where(AutofacUtil.CanInject)
                    .EnableClassInterceptors();
                }
            }

            if (param.RegisteringControllerAction != null)
            {
                param.RegisteringControllerAction();
            }

            IContainer container = containerBuilder.UnifiedRegisterAssemblys(param);

            //将MVC的控制器对象实例 交由autofac来创建
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            WebAutofacTool.MvcDependencyResolver = DependencyResolver.Current;
            Hzdtf.Autofac.Extend.Standard.AutofacTool.ResolveFunc = WebAutofacTool.GetMvcService;

            if (param.IsLoadAutoMapperConfig)
            {
                AutoMapperUtil.AutoRegisterConfig(assemblyList.ToArray());
            }

            return(container);
        }
 public static string GetLibraryPath()
 {
     return(Path.Combine(AssemblyUtil.GetStartFolder(), "bin", "Nucleus.Gaming.Coop.Api.dll"));
 }
示例#18
0
        internal static string FormatCdnUrl(Assembly assembly, string cdnPath)
        {
            AssemblyName name = new AssemblyName(assembly.FullName);

            return(string.Format(CultureInfo.InvariantCulture, cdnPath, new object[] { HttpUtility.UrlEncode(name.Name), HttpUtility.UrlEncode(name.Version.ToString(4)), HttpUtility.UrlEncode(AssemblyUtil.GetAssemblyFileVersion(assembly)) }));
        }
示例#19
0
        public WelcomeViewVM()
        {
            AssemblyUtil au = AssemblyUtil.Get;

            ProductName = au.GetProductName() + " " + au.GetAssemblyVersion().Trim();
        }
示例#20
0
        internal void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            Ice.Communicator ic = Communicator();
            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = ic.GetProperty("IceSSL.DefaultDir") ?? "";

            string        certStoreLocation = ic.GetProperty("IceSSL.CertStoreLocation") ?? "CurrentUser";
            StoreLocation storeLocation;

            if (certStoreLocation == "CurrentUser")
            {
                storeLocation = StoreLocation.CurrentUser;
            }
            else if (certStoreLocation == "LocalMachine")
            {
                storeLocation = StoreLocation.LocalMachine;
            }
            else
            {
                _logger.Warning($"Invalid IceSSL.CertStoreLocation value `{certStoreLocation}' adjusted to `CurrentUser'");
                storeLocation = StoreLocation.CurrentUser;
            }
            _useMachineContext = certStoreLocation == "LocalMachine";

            //
            // Protocols selects which protocols to enable, by default we only enable TLS1.0
            // TLS1.1 and TLS1.2 to avoid security issues with SSLv3
            //
            string[]? protocols = ic.GetPropertyAsList("IceSSL.Protocols");
            if (protocols != null)
            {
                _protocols = ParseProtocols(protocols);
            }
            else
            {
                _protocols = 0;
                foreach (int v in Enum.GetValues(typeof(SslProtocols)))
                {
                    if (v > (int)SslProtocols.Ssl3 && v != (int)SslProtocols.Default)
                    {
                        _protocols |= (SslProtocols)v;
                    }
                }
            }
            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = ic.GetPropertyAsInt("IceSSL.CheckCertName") > 0;

            //
            // VerifyDepthMax establishes the maximum length of a peer's certificate
            // chain, including the peer's certificate. A value of 0 means there is
            // no maximum.
            //
            _verifyDepthMax = ic.GetPropertyAsInt("IceSSL.VerifyDepthMax") ?? 3;

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = ic.GetPropertyAsInt("IceSSL.CheckCRL") ?? 0;

            //
            // Check for a certificate verifier.
            //
            string?certVerifierClass = ic.GetProperty("IceSSL.CertVerifier");

            if (certVerifierClass != null)
            {
                if (_verifier != null)
                {
                    throw new InvalidOperationException("IceSSL: certificate verifier already installed");
                }

                Type?cls = _facade.FindType(certVerifierClass);
                if (cls == null)
                {
                    throw new InvalidConfigurationException(
                              $"IceSSL: unable to load certificate verifier class `{certVerifierClass}'");
                }

                try
                {
                    _verifier = (ICertificateVerifier?)AssemblyUtil.CreateInstance(cls);
                }
                catch (Exception ex)
                {
                    throw new LoadException(
                              $"IceSSL: unable to instantiate certificate verifier class `{certVerifierClass}", ex);
                }
            }

            //
            // Check for a password callback.
            //
            string?passwordCallbackClass = ic.GetProperty("IceSSL.PasswordCallback");

            if (passwordCallbackClass != null)
            {
                if (_passwordCallback != null)
                {
                    throw new InvalidOperationException("IceSSL: password callback already installed");
                }

                Type?cls = _facade.FindType(passwordCallbackClass);
                if (cls == null)
                {
                    throw new InvalidConfigurationException(
                              $"IceSSL: unable to load password callback class `{passwordCallbackClass}'");
                }

                try
                {
                    _passwordCallback = (IPasswordCallback?)AssemblyUtil.CreateInstance(cls);
                }
                catch (Exception ex)
                {
                    throw new LoadException(
                              $"IceSSL: unable to load password callback class {passwordCallbackClass}", ex);
                }
            }

            //
            // If the user hasn't supplied a certificate collection, we need to examine
            // the property settings.
            //
            if (_certs == null)
            {
                //
                // If IceSSL.CertFile is defined, load a certificate from a file and
                // add it to the collection.
                //
                // TODO: tracing?
                _certs = new X509Certificate2Collection();
                string?      certFile    = ic.GetProperty("IceSSL.CertFile");
                string?      passwordStr = ic.GetProperty("IceSSL.Password");
                string?      findCert    = ic.GetProperty("IceSSL.FindCert");
                const string findPrefix  = "IceSSL.FindCert.";
                Dictionary <string, string> findCertProps = ic.GetProperties(forPrefix: findPrefix);

                if (certFile != null)
                {
                    if (!CheckPath(ref certFile))
                    {
                        throw new FileNotFoundException($"IceSSL: certificate file not found: `{certFile}'", certFile);
                    }

                    SecureString?password = null;
                    if (passwordStr != null)
                    {
                        password = CreateSecureString(passwordStr);
                    }
                    else if (_passwordCallback != null)
                    {
                        password = _passwordCallback.GetPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2    cert;
                        X509KeyStorageFlags importFlags;
                        if (_useMachineContext)
                        {
                            importFlags = X509KeyStorageFlags.MachineKeySet;
                        }
                        else
                        {
                            importFlags = X509KeyStorageFlags.UserKeySet;
                        }

                        if (password != null)
                        {
                            cert = new X509Certificate2(certFile, password, importFlags);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile, "", importFlags);
                        }
                        _certs.Add(cert);
                    }
                    catch (CryptographicException ex)
                    {
                        throw new InvalidConfigurationException(
                                  $"IceSSL: error while attempting to load certificate from `{certFile}'", ex);
                    }
                }
                else if (findCert != null)
                {
                    string certStore = ic.GetProperty("IceSSL.CertStore") ?? "My";
                    _certs.AddRange(FindCertificates("IceSSL.FindCert", storeLocation, certStore, findCert));
                    if (_certs.Count == 0)
                    {
                        throw new InvalidConfigurationException("IceSSL: no certificates found");
                    }
                }
                else if (findCertProps.Count > 0)
                {
                    //
                    // If IceSSL.FindCert.* properties are defined, add the selected certificates
                    // to the collection.
                    //
                    foreach (KeyValuePair <string, string> entry in findCertProps)
                    {
                        string name = entry.Key;
                        string val  = entry.Value;
                        if (val.Length > 0)
                        {
                            string        storeSpec = name.Substring(findPrefix.Length);
                            StoreLocation storeLoc  = 0;
                            StoreName     storeName = 0;
                            string?       sname     = null;
                            ParseStore(name, storeSpec, ref storeLoc, ref storeName, ref sname);
                            if (sname == null)
                            {
                                sname = storeName.ToString();
                            }
                            X509Certificate2Collection coll = FindCertificates(name, storeLoc, sname, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if (_certs.Count == 0)
                    {
                        throw new InvalidConfigurationException("IceSSL: no certificates found");
                    }
                }
            }

            if (_caCerts == null)
            {
                string?certAuthFile = ic.GetProperty("IceSSL.CAs");
                if (certAuthFile == null)
                {
                    certAuthFile = ic.GetProperty("IceSSL.CertAuthFile");
                }

                if (certAuthFile != null || (ic.GetPropertyAsInt("IceSSL.UsePlatformCAs") ?? 0) <= 0)
                {
                    _caCerts = new X509Certificate2Collection();
                }

                if (certAuthFile != null)
                {
                    if (!CheckPath(ref certAuthFile))
                    {
                        throw new FileNotFoundException("IceSSL: CA certificate file not found: `{certAuthFile}'",
                                                        certAuthFile);
                    }

                    try
                    {
                        using FileStream fs = File.OpenRead(certAuthFile);
                        byte[] data = new byte[fs.Length];
                        fs.Read(data, 0, data.Length);

                        string strbuf = "";
                        try
                        {
                            strbuf = System.Text.Encoding.UTF8.GetString(data);
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }

                        if (strbuf.Length == data.Length)
                        {
                            int  size, startpos, endpos = 0;
                            bool first = true;
                            while (true)
                            {
                                startpos = strbuf.IndexOf("-----BEGIN CERTIFICATE-----", endpos);
                                if (startpos != -1)
                                {
                                    endpos = strbuf.IndexOf("-----END CERTIFICATE-----", startpos);
                                    size   = endpos - startpos + "-----END CERTIFICATE-----".Length;
                                }
                                else if (first)
                                {
                                    startpos = 0;
                                    endpos   = strbuf.Length;
                                    size     = strbuf.Length;
                                }
                                else
                                {
                                    break;
                                }

                                byte[] cert = new byte[size];
                                Buffer.BlockCopy(data, startpos, cert, 0, size);
                                _caCerts !.Import(cert);
                                first = false;
                            }
                        }
                        else
                        {
                            _caCerts !.Import(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidConfigurationException(
                                  $"IceSSL: error while attempting to load CA certificate from {certAuthFile}", ex);
                    }
                }
            }
            _initialized = true;
        }
示例#21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("Title", typeof(string)));
            dt.Columns.Add(new DataColumn("ImageUrl", typeof(string)));
            DataRow         dr;
            IXPathNavigable navigable;
            // Selector: ClassName.ViewName.PlaceName.ProfileId.UserId
            Selector selector = new Selector(string.Empty, string.Empty, string.Empty, ProfileManager.GetProfileIdByUser().ToString(), Mediachase.IBN.Business.Security.UserID.ToString());

            // don't hide items for administrator
            if (Mediachase.IBN.Business.Security.IsUserInGroup(Mediachase.IBN.Business.InternalSecureGroups.Administrator))
            {
                navigable = XmlBuilder.GetCustomizationXml(null, StructureType.Navigation, selector);
            }
            else
            {
                navigable = XmlBuilder.GetXml(StructureType.Navigation, selector);
            }


            XPathNavigator tabs = navigable.CreateNavigator().SelectSingleNode("Navigation/Tabs");

            foreach (XPathNavigator tabItem in tabs.SelectChildren(string.Empty, string.Empty))
            {
                dr = dt.NewRow();
                string title = UtilHelper.GetResFileString(tabItem.GetAttribute("text", string.Empty));
                string id    = tabItem.GetAttribute("id", string.Empty);

                string enableHandler = tabItem.GetAttribute("enableHandler", string.Empty);
                if (!string.IsNullOrEmpty(enableHandler))
                {
                    ICommandEnableHandler enHandler = (ICommandEnableHandler)AssemblyUtil.LoadObject(enableHandler);
                    if (enHandler != null && !enHandler.IsEnable(sender, id))
                    {
                        continue;
                    }
                }

                string imageUrl = tabItem.GetAttribute("imageUrl", string.Empty);
                if (string.IsNullOrEmpty(imageUrl))
                {
                    imageUrl = "~/Images/ext/default/s.gif";
                }

                string type = tabItem.GetAttribute("contentType", string.Empty).ToLower();
                if (string.IsNullOrEmpty(type))
                {
                    type = "default";
                }

                string configUrl = tabItem.GetAttribute("configUrl", string.Empty);
                string checkUrl  = configUrl;
                if (checkUrl.IndexOf("?") >= 0)
                {
                    checkUrl = checkUrl.Substring(0, checkUrl.IndexOf("?"));
                }
                if (type.Equals("default") && string.IsNullOrEmpty(checkUrl))
                {
                    checkUrl  = "~/Apps/Shell/Pages/TreeSource.aspx";
                    configUrl = "~/Apps/Shell/Pages/TreeSource.aspx?tab=" + id;
                }

                if (File.Exists(Server.MapPath(checkUrl)))
                {
                    switch (type)
                    {
                    case "default":
                        ClientScript.RegisterStartupScript(this.Page, this.Page.GetType(), Guid.NewGuid().ToString("N"), string.Format("leftTemplate_AddMenuTab('{0}', '{1}', '{2}');", id, title, ResolveClientUrl(configUrl)), true);
                        break;

                    case "custom":
                        break;

                    default:
                        break;
                    }
                }

                dr["Title"]    = title;
                dr["ImageUrl"] = imageUrl;
                dt.Rows.Add(dr);
            }
            TabItems.DataSource = dt.DefaultView;
            TabItems.DataBind();

            RegisterScripts();

            //Register navigation commands
            string             profileId = ProfileManager.GetProfileIdByUser().ToString();
            string             userId    = Mediachase.IBN.Business.Security.UserID.ToString();
            IList <XmlCommand> list      = XmlCommand.GetListNavigationCommands("", "", "", profileId, userId);
            CommandManager     cm        = CommandManager.GetCurrent(this.Page);

            foreach (XmlCommand cmd in list)
            {
                cm.AddCommand("", "", "", profileId, userId, cmd.CommandName);
            }
        }
示例#22
0
 public MapperBuilder RegisterAssemblies()
 {
     _options.AddRegisterAssemblies(AssemblyUtil.GetAssemblies().ToArray());
     return(this);
 }
示例#23
0
        public HandlerDataEngine(GameHandlerMetadata metadata, string jsCode)
        {
            this.metadata = metadata;
            this.jsCode   = jsCode;

            string   tempPath = GameManager.GetTempFolder(metadata.GameID);
            Assembly platform = Assembly.GetExecutingAssembly();

            Evidence evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Untrusted));

            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Write, tempPath));
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, metadata.RootDirectory));
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, AssemblyUtil.GetStartFolder()));
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            AppDomainSetup setup = new AppDomainSetup {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };

            domain = AppDomain.CreateDomain("JSENGINE", evidence, setup, permissionSet);

            string enginePath = GetLibraryPath();

            byte[] engineData = File.ReadAllBytes(enginePath);
            domain.Load(engineData);

            ObjectHandle jsobj = domain.CreateInstance("SplitScreenMe.Engine", "SplitScreenMe.Engine.AppDomainEngine");

            jsEngine = jsobj.Unwrap();
            // TODO: strong typing on dynamic object (cache the fields/use reflection)
        }
示例#24
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <JwtSettings>(Configuration.GetSection("Jwt"));
            var jwtSettings = Configuration.GetSection("Jwt").Get <JwtSettings>();

            var dataAssemblyName = typeof(DatabaseContext).Assembly.GetName().Name;

            services.AddDbContext <DatabaseContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("SmarterAsp"),
                                                                         x => x.MigrationsAssembly(dataAssemblyName)));

            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(1d);
                options.Lockout.MaxFailedAccessAttempts = 5;
            })
            .AddEntityFrameworkStores <DatabaseContext>()
            .AddDefaultTokenProviders();

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddControllers();

            services.AddMvc(options => options.Filters.Add(new DefaultExceptionFilterAttribute()));

            services.AddLoggingSerilog();

            services.AddAutoMapper(AssemblyUtil.GetCurrentAssemblies());

            services.AddDependencyResolver();

            services.AddHealthChecks();

            services.AddApiVersioning(config =>
            {
                config.DefaultApiVersion = new ApiVersion(1, 0);
                config.AssumeDefaultVersionWhenUnspecified = true;
                config.ReportApiVersions = true;
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "Bearer utilizado para autenticação"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        Array.Empty <string>()
                    }
                });
            });

            services.AddTransient <IConfigureOptions <SwaggerGenOptions>, ConfigureSwaggerOptions>();

            services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            });

            services.AddAuth(jwtSettings);
        }
示例#25
0
        /// <summary>
        /// 加载静态配置文件
        /// </summary>
        /// <param name="reLoad">
        /// 是否重新加载
        /// 如果reload = true,则不管之前是否加载过配置文件,都重新进行一次加载
        /// 否则会验证之前是否加载过,如果加载过则不再进行加载
        /// </param>
        public static void LoadData(bool reLoad = false)
        {
            if (!reLoad && isLoadData)
            {
                return;
            }

            var configTypes = AssemblyUtil.GetTypesByAttribute(typeof(StaticXmlConfigRootAttribute));

            foreach (var type in configTypes)
            {
                var rootAttribute = (StaticXmlConfigRootAttribute)type.GetCustomAttributes(typeof(StaticXmlConfigRootAttribute), true)[0];
                if (string.IsNullOrEmpty(rootAttribute.FileName))
                {
                    Logs.Error("Static config class:'{0}' not define file", type.Name);
                    continue;
                }
                var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootAttribute.FileName);

                var xmlDoc = GetXml(fileName);
                if (xmlDoc == null)
                {
                    continue;
                }

                //  xml的根结点
                var rootName = string.IsNullOrEmpty(rootAttribute.RootName) ? type.Name : rootAttribute.RootName;
                Logs.Info("Load static config node:{0}", rootName);

                foreach (var pro in type.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.SetProperty | BindingFlags.GetProperty))
                {
                    //  获得读取xml结点名字
                    var    attribute = pro.GetAttribute <XmlConfigAttribute>();
                    string nodeName  = attribute == null ? pro.Name : attribute.Name;

                    if (pro.PropertyType == typeof(string))
                    {
                        var node = xmlDoc.SelectSingleNode(string.Format("root/{0}/{1}", rootName, nodeName));
                        if (node != null)
                        {
                            var value = node.InnerText.Trim();
                            pro.SetValue(null, value, null);
                        }
                    }
                    else if (pro.PropertyType == typeof(int))
                    {
                        var node = xmlDoc.SelectSingleNode(string.Format("root/{0}/{1}", rootName, nodeName));
                        if (node != null)
                        {
                            var str = node.InnerText.Trim();
                            int value;
                            if (int.TryParse(str, out value))
                            {
                                pro.SetValue(null, value, null);
                            }
                        }
                    }
                    else if (pro.PropertyType == typeof(long))
                    {
                        var node = xmlDoc.SelectSingleNode(string.Format("root/{0}/{1}", rootName, nodeName));
                        if (node != null)
                        {
                            var  str = node.InnerText.Trim();
                            long value;
                            if (long.TryParse(str, out value))
                            {
                                pro.SetValue(null, value, null);
                            }
                        }
                    }
                    else if (pro.PropertyType == typeof(bool))
                    {
                        var node = xmlDoc.SelectSingleNode(string.Format("root/{0}/{1}", rootName, nodeName));
                        if (node != null)
                        {
                            var  str = node.InnerText.Trim();
                            bool value;
                            if (bool.TryParse(str, out value))
                            {
                                pro.SetValue(null, value, null);
                            }
                        }
                    }
                    else if (pro.PropertyType == typeof(double))
                    {
                        var node = xmlDoc.SelectSingleNode(string.Format("root/{0}/{1}", rootName, nodeName));
                        if (node != null)
                        {
                            var    str = node.InnerText.Trim();
                            double value;
                            if (double.TryParse(str, out value))
                            {
                                pro.SetValue(null, value, null);
                            }
                        }
                    }
                    else if (pro.PropertyType.IsArray)
                    {
                        //  获得数组对应的类型
                        var elementType = pro.PropertyType.GetElementType();

                        if (elementType == typeof(string))
                        {
                            var nodes = xmlDoc.SelectNodes(string.Format("root/{0}/{1}", rootName, nodeName));
                            if (nodes != null)
                            {
                                var values = new List <string>();
                                foreach (XmlNode node in nodes)
                                {
                                    values.Add(node.InnerText.Trim());
                                }

                                pro.SetValue(null, values.ToArray(), null);
                            }
                        }
                        else if (elementType == typeof(int))
                        {
                            var nodes = xmlDoc.SelectNodes(string.Format("root/{0}/{1}", rootName, nodeName));
                            if (nodes != null)
                            {
                                var values = new List <int>();

                                foreach (XmlNode node in nodes)
                                {
                                    var str = node.InnerText.Trim();
                                    int value;
                                    if (int.TryParse(str, out value))
                                    {
                                        values.Add(value);
                                    }
                                }

                                pro.SetValue(null, values.ToArray(), null);
                            }
                        }
                        else if (elementType == typeof(long))
                        {
                            var nodes = xmlDoc.SelectNodes(string.Format("root/{0}/{1}", rootName, nodeName));
                            if (nodes != null)
                            {
                                var values = new List <long>();

                                foreach (XmlNode node in nodes)
                                {
                                    var  str = node.InnerText.Trim();
                                    long value;
                                    if (long.TryParse(str, out value))
                                    {
                                        values.Add(value);
                                    }
                                }

                                pro.SetValue(null, values.ToArray(), null);
                            }
                        }
                        else if (elementType == typeof(bool))
                        {
                            var nodes = xmlDoc.SelectNodes(string.Format("root/{0}/{1}", rootName, nodeName));
                            if (nodes != null)
                            {
                                var values = new List <bool>();

                                foreach (XmlNode node in nodes)
                                {
                                    var  str = node.InnerText.Trim();
                                    bool value;
                                    if (bool.TryParse(str, out value))
                                    {
                                        values.Add(value);
                                    }
                                }

                                pro.SetValue(null, values.ToArray(), null);
                            }
                        }
                        else if (elementType == typeof(double))
                        {
                            var nodes = xmlDoc.SelectNodes(string.Format("root/{0}/{1}", rootName, nodeName));
                            if (nodes != null)
                            {
                                var values = new List <double>();

                                foreach (XmlNode node in nodes)
                                {
                                    var    str = node.InnerText.Trim();
                                    double value;
                                    if (double.TryParse(str, out value))
                                    {
                                        values.Add(value);
                                    }
                                }

                                pro.SetValue(null, values.ToArray(), null);
                            }
                        }
                        else if (elementType.IsClass && !elementType.IsValueType)
                        {
                            var nodes = xmlDoc.SelectNodes(string.Format("root/{0}/{1}", rootName, nodeName));

                            if (nodes == null)
                            {
                                continue;
                            }

                            var xml = new StringBuilder("<?xml version=\"1.0\"?>");
                            xml.AppendFormat("<ArrayOf{0}>", elementType.Name);
                            foreach (XmlNode node in nodes)
                            {
                                xml.Append(node.OuterXml);
                            }

                            xml.Replace(string.Format("<{0}>", pro.Name), string.Format("<{0}>", elementType.Name));
                            xml.Replace(string.Format("</{0}>", pro.Name), string.Format("</{0}>", elementType.Name));
                            xml.AppendFormat("</ArrayOf{0}>", elementType.Name);

                            var obj = xml.ToString().XmlDeserialize(pro.PropertyType);
                            if (obj != null)
                            {
                                pro.SetValue(null, obj, null);
                            }
                        }
                    }
                    else
                    {
                        //  是对象,需要重新加载
                        if (pro.PropertyType.IsClass)
                        {
                            var node = xmlDoc.SelectSingleNode(string.Format("root/{0}/{1}", rootName, nodeName));

                            if (node == null)
                            {
                                continue;
                            }

                            var xml = new StringBuilder("<?xml version=\"1.0\"?>");
                            xml.Append(node.OuterXml);
                            xml.Replace(string.Format("<{0}>", pro.Name), string.Format("<{0}>", pro.PropertyType.Name));
                            xml.Replace(string.Format("</{0}>", pro.Name), string.Format("</{0}>", pro.PropertyType.Name));

                            var obj = xml.ToString().XmlDeserialize(pro.PropertyType);
                            if (obj != null)
                            {
                                pro.SetValue(null, obj, null);
                            }
                        }
                    }
                }
            }

            isLoadData = true;
        }
示例#26
0
        private static void onGameLoad(EventArgs args)
        {
            try
            {
                Player = ObjectManager.Player;

                if (!Player.ChampionName.Equals(ChampionName, StringComparison.CurrentCultureIgnoreCase))
                    return;

                InitializeSpells();

                InitializeSkinManager();

                InitializeLevelUpManager();

                InitializeMainMenu();

                InitializeAttachEvents();

                Game.PrintChat(string.Format("<font color='#fb762d'>DevKogMaw Loaded v{0}</font>", Assembly.GetExecutingAssembly().GetName().Version));

                assemblyUtil = new AssemblyUtil(Assembly.GetExecutingAssembly().GetName().Name);
                assemblyUtil.onGetVersionCompleted += AssemblyUtil_onGetVersionCompleted;
                assemblyUtil.GetLastVersionAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                if (mustDebug)
                    Game.PrintChat(ex.Message);
            }
        }
        internal static Assembly GetAssembly(string xamlNamespace)
        {
            var attr = _global.GetValue((t) => t.XamlNamespace == xamlNamespace);

            return(attr == null ? null : AssemblyUtil.Get(attr.AssemblyName));
        }
示例#28
0
        public void ConfigureServices(IServiceCollection services)
        {
            var dataAssemblyName = typeof(DatabaseContext).Assembly.GetName().Name;

            services.AddDbContext <DatabaseContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("SmarterAsp"),
                                                                         x => x.MigrationsAssembly(dataAssemblyName)));

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddControllers();

            services.AddMvc(options => options.Filters.Add(new DefaultExceptionFilterAttribute()));

            services.AddLoggingSerilog();

            services.AddAutoMapper(AssemblyUtil.GetCurrentAssemblies());

            services.AddDependencyResolver();

            services.AddHealthChecks();

            services.AddApiVersioning(config =>
            {
                config.DefaultApiVersion = new ApiVersion(1, 0);
                config.AssumeDefaultVersionWhenUnspecified = true;
                config.ReportApiVersions = true;
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "Bearer utilizado para autenticação"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        Array.Empty <string>()
                    }
                });
            });

            services.AddTransient <IConfigureOptions <SwaggerGenOptions>, ConfigureSwaggerOptions>();

            services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            });

            //Token JWT
            var key = Encoding.ASCII.GetBytes("CdWiH4fu7byjWwzgIzRa9PGHM7WdhpZr0F0_3a-F71LdGu-BSw0ZVOOLw5quQgD080b7eK1sJqg3jaRU9hwtfPyAZG9STaMPg4DdmQlmi6EUbcSjdBeKmTdGCZ8wkEltDWj1p51otfaWrdxICzCFZ6bVvjTzdWI-dQXMFCIXACP-aN1cAL1JewNbFetnAkA9c9Z3hgJLmGYQTC3LUkvVAQXxm4J_RRE7v5kWKbn0BPziJQF-_sedgHrIP0zpsHU7g1Ztch0tLwIu7NiXe3-gCrWVLhe2tUB6IkxLjD3eMEXNdUI2uy6Croa_sXyX6lT4npYJnJ1lChSZwiFqUgK_");

            //Authentication
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddControllers();
        }
        /// <summary>
        /// 为WebApi2统一注册MVC及服务程序集
        /// WebApi2用于MVC5以上
        /// </summary>
        /// <param name="containerBuilder">容器生成器</param>
        /// <param name="param">参数</param>
        /// <returns>容器</returns>
        public static IContainer UnifiedRegisterAssemblysForWebApi2(this ContainerBuilder containerBuilder, HttpConfiguration configuration, WebBuilderParam param)
        {
            foreach (BasicAssemblyInfo assembly in param.AssemblyControllers)
            {
                Assembly[] assemblies = AssemblyUtil.Load(assembly.Names);
                if (assemblies.IsNullOrLength0())
                {
                    return(null);
                }

                if (!assembly.InterceptedTypes.IsNullOrLength0())
                {
                    foreach (Type type in assembly.InterceptedTypes)
                    {
                        containerBuilder.RegisterType(type);
                    }
                }

                if (assembly.Intercepteds.IsNullOrLength0())
                {
                    containerBuilder.RegisterApiControllers(assemblies)
                    .PropertiesAutowired()
                    .AsImplementedInterfaces()
                    .Where(AutofacUtil.CanInject)
                    .AsSelf();   //注册api容器的实现

                    containerBuilder.RegisterControllers(assemblies)
                    .PropertiesAutowired()
                    .AsImplementedInterfaces()
                    .Where(AutofacUtil.CanInject)
                    .AsSelf();
                }
                else
                {
                    containerBuilder.RegisterApiControllers(assemblies)
                    .PropertiesAutowired()
                    .AsImplementedInterfaces()
                    .AsSelf()
                    .InterceptedBy(assembly.InterceptedTypes)
                    .Where(AutofacUtil.CanInject)
                    .EnableClassInterceptors();   //注册api容器的实现

                    containerBuilder.RegisterControllers(assemblies)
                    .PropertiesAutowired()
                    .AsImplementedInterfaces()
                    .AsSelf()
                    .InterceptedBy(assembly.InterceptedTypes)
                    .Where(AutofacUtil.CanInject)
                    .EnableClassInterceptors();
                }
            }

            if (param.RegisteringControllerAction != null)
            {
                param.RegisteringControllerAction();
            }

            IContainer container = containerBuilder.UnifiedRegisterAssemblys(param);

            //将MVC的控制器对象实例 交由autofac来创建
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            WebAutofacTool.HttpDependencyResolver = configuration.DependencyResolver;
            AutofacTool.ResolveFunc = WebAutofacTool.GetHttpService;

            return(container);
        }
示例#30
0
 public static void RegisterBasicDispatcher(this ContainerBuilder builder, Func <Assembly, bool> isKnownAssembly = null)
 {
     builder.RegisterType <CommandDispatcher>().As <ICommandDispatcher>();
     builder.RegisterMessageHandlers(AssemblyUtil.LoadAllKnownAssemblies(isKnownAssembly));
 }
示例#31
0
        /// <summary>
        /// Setups the appServer instance
        /// </summary>
        /// <param name="rootConfig">The root config.</param>
        /// <param name="config">The socket server instance config.</param>
        /// <param name="socketServerFactory">The socket server factory.</param>
        /// <param name="requestFilterFactory">The request filter factory.</param>
        /// <returns></returns>
        protected virtual bool Setup(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory, IRequestFilterFactory <TRequestInfo> requestFilterFactory)
        {
            if (rootConfig == null)
            {
                throw new ArgumentNullException("rootConfig");
            }

            RootConfig = rootConfig;

            if (!m_ThreadPoolConfigured)
            {
                if (!TheadPoolEx.ResetThreadPool(rootConfig.MaxWorkingThreads >= 0 ? rootConfig.MaxWorkingThreads : new Nullable <int>(),
                                                 rootConfig.MaxCompletionPortThreads >= 0 ? rootConfig.MaxCompletionPortThreads : new Nullable <int>(),
                                                 rootConfig.MinWorkingThreads >= 0 ? rootConfig.MinWorkingThreads : new Nullable <int>(),
                                                 rootConfig.MinCompletionPortThreads >= 0 ? rootConfig.MinCompletionPortThreads : new Nullable <int>()))
                {
                    return(false);
                }

                m_ThreadPoolConfigured = true;
            }

            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (!(config is ServerConfig))
            {
                //Use config plain model directly to avoid extra object casting in runtime
                var newConfig = new ServerConfig();
                config.CopyPropertiesTo(newConfig);
                config = newConfig;
            }

            Config = config;

            m_SocketServerFactory = socketServerFactory;

            SetupLogger();

            if (!SetupSecurity(config))
            {
                return(false);
            }

            if (!SetupListeners(config))
            {
                if (Logger.IsErrorEnabled)
                {
                    Logger.Error("Invalid config ip/port");
                }

                return(false);
            }

            if (!SetupRequestFilterFactory(config, requestFilterFactory))
            {
                return(false);
            }

            m_CommandLoaders = new List <ICommandLoader>
            {
                new ReflectCommandLoader()
            };

            if (Config.EnableDynamicCommand)
            {
                ICommandLoader dynamicCommandLoader;

                try
                {
                    dynamicCommandLoader = AssemblyUtil.CreateInstance <ICommandLoader>("SuperSocket.Dlr.DynamicCommandLoader, SuperSocket.Dlr");
                }
                catch (Exception e)
                {
                    if (Logger.IsErrorEnabled)
                    {
                        Logger.Error("The file SuperSocket.Dlr is required for dynamic command support!", e);
                    }

                    return(false);
                }

                m_CommandLoaders.Add(dynamicCommandLoader);
            }

            if (!SetupCommands(m_CommandDict))
            {
                return(false);
            }

            return(SetupSocketServer());
        }
        public override void SaveValue(string cUid, string key, object value)
        {
            string uid = GetKey(cUid, key);

            CustomPageEntity cpe = Mediachase.IBN.Business.WidgetEngine.CustomPageManager.GetCustomPage(pageUid, profileId, userId);

            if (cpe == null)
            {
                throw new ArgumentException(string.Format("Page not found for pageUid: {0} profileId: {1} userId: {2}", pageUid, profileId, userId));
            }

            XmlDocument doc = new XmlDocument();

            if (String.IsNullOrEmpty(cpe.PropertyJsonData))
            {
                doc.AppendChild(doc.CreateElement("ControlProperties"));
                cpe.PropertyJsonData = doc.OuterXml;
            }
            else
            {
                doc.LoadXml(cpe.PropertyJsonData);
            }

            XmlNode controlNode = doc.DocumentElement.SelectSingleNode(cUid);

            if (controlNode == null)
            {
                controlNode = doc.CreateElement(cUid);
                doc.DocumentElement.AppendChild(controlNode);
            }

            XmlNode keyNode = controlNode.SelectSingleNode(key);

            if (keyNode == null)
            {
                keyNode = doc.CreateElement(key);
                controlNode.AppendChild(keyNode);
            }

            if (value == null)
            {
                keyNode.InnerText = ControlProperties._nullValueKey;
            }
            else if (value is string && string.Empty == ((string)value))
            {
                keyNode.InnerText = string.Empty;
            }
            else
            {
                // Step 1. Object to XmlSerializedItem
                string typeName = null;

                if (value.GetType().IsGenericType)
                {
                    typeName = AssemblyUtil.GetTypeString(value.GetType().FullName, value.GetType().Assembly.GetName().Name);
                }
                else
                {
                    typeName = AssemblyUtil.GetTypeString(value.GetType().ToString(), value.GetType().Assembly.GetName().Name);
                }

                XmlSerializedItem item = new XmlSerializedItem(typeName, McXmlSerializer.GetString(value.GetType(), value));

                // Step 2. XmlSerializedItem to string
                keyNode.InnerText = McXmlSerializer.GetString <XmlSerializedItem>(item);
            }

            //todo: to debug
            Mediachase.IBN.Business.WidgetEngine.CustomPageManager.UpdateCustomPageProperty(pageUid, doc.OuterXml, profileId, userId);
        }
示例#33
0
 //
 // Obtain the type for a name.
 //
 public System.Type findType(string name)
 {
     return(AssemblyUtil.findType(_instance, name));
 }
示例#34
0
        internal static bool UpdaterCheck(out String errorMessage)
        {
            errorMessage = String.Empty;
            String actualVersion = AssemblyUtil.GetExternalAssemblyVersion(ConstantUtil.ApplicationExecutionPath(), ConstantUtil.dtPadUpdater);

            WebClient webClient = null;

            String repository = ConstantUtil.repository;

            #if ReleaseFE
            repository = ConstantUtil.repositoryFE;
            #endif

            try
            {
                webClient = ProxyUtil.InitWebClientProxy();
                String finalVersion = webClient.DownloadString(String.Format("{0}dtpadupdater-lastversion.log", repository));

                if (actualVersion != finalVersion)
                {
                    if (FileUtil.IsFileInUse("DtPadUpdater.exe"))
                    {
                        errorMessage = String.Format("DtPadUpdater.exe {0}", LanguageUtil.GetCurrentLanguageString("InUse", className));
                        return(false);
                    }

                    try
                    {
                        Directory.CreateDirectory("UpdateBackup");
                        Directory.CreateDirectory("UpdateTemp");

                        File.Copy("DtPadUpdater.exe", Path.Combine("UpdateBackup", "DtPadUpdater.exe"));

                        webClient.DownloadFile(String.Format("{0}dtpadupdater-repository/DtPadUpdater.exe", repository), Path.Combine("UpdateTemp", "DtPadUpdater.exe"));

                        File.Delete("DtPadUpdater.exe");
                        File.Move(Path.Combine("UpdateTemp", "DtPadUpdater.exe"), "DtPadUpdater.exe");

                        Directory.Delete("UpdateBackup", true);
                        Directory.Delete("UpdateTemp", true);
                    }
                    catch (Exception)
                    {
                        File.Delete("DtPadUpdater.exe");
                        File.Move(Path.Combine("UpdateBackup", "DtPadUpdater.exe"), "DtPadUpdater.exe");

                        Directory.Delete("UpdateBackup", true);
                        Directory.Delete("UpdateTemp", true);

                        errorMessage = LanguageUtil.GetCurrentLanguageString("ErrorDownloadingUpdater", className);
                        return(false);
                    }
                }
            }
            catch (WebException)
            {
                errorMessage = LanguageUtil.GetCurrentLanguageString("ErrorConnection", className);
                return(false);
            }
            finally
            {
                if (webClient != null)
                {
                    webClient.Dispose();
                }
            }

            return(true);
        }