private static void setupShapefile(HttpContext context, Map m) { GeometryServices geometryServices = new GeometryServices(); string[] layernames = new[] { "Countries", "Rivers"/*, "Cities"*/ }; foreach (string s in layernames) { ShapeFileProvider shapeFile = new ShapeFileProvider(context.Server.MapPath(string.Format("~/App_Data/Shapefiles/{0}.shp", s)), geometryServices.DefaultGeometryFactory, geometryServices.CoordinateSystemFactory, false); shapeFile.IsSpatiallyIndexed = false; AppStateMonitoringFeatureProvider provider = new AppStateMonitoringFeatureProvider(shapeFile); GeoJsonGeometryStyle style = RandomStyle.RandomGeometryStyle(); /* include GeoJson styles */ style.IncludeAttributes = false; style.IncludeBBox = true; style.PreProcessGeometries = false; style.CoordinateNumberFormatString = "{0:F}"; GeometryLayer geometryLayer = new GeometryLayer(s, style, provider); geometryLayer.Features.IsSpatiallyIndexed = false; m.AddLayer(geometryLayer); provider.Open(); } }
public void Install(IWindsorContainer container, IConfigurationStore store) { var dependenciesAsAnonymousType = new { serverUrl = ConfigurationManager.AppSettings["serverUrl"], routes = RoutesProvider.GetDefaultRoutes() }; container.Register( Component.For<IProductControllerClient>() .ImplementedBy<ProductControllerClient>() .DependsOn(dependenciesAsAnonymousType) .LifeStyle.Transient, Component.For<IBasketControllerClient>() .ImplementedBy<BasketControllerClient>() .DependsOn(dependenciesAsAnonymousType) .LifeStyle.Transient, Component.For<IDeliveryAddressControllerClient>() .ImplementedBy<DeliveryAddressControllerClient>() .DependsOn(dependenciesAsAnonymousType) .LifeStyle.Transient, Component.For<IOrderControllerClient>() .ImplementedBy<OrderControllerClient>() .DependsOn(dependenciesAsAnonymousType) .LifeStyle.Transient, Component.For<IAuthenticationCookiePersister>() .ImplementedBy<AuthenticationCookiePersister>() .LifeStyle.Singleton ); }
public static MvcHtmlString RenderAuthWarnings(this HtmlHelper htmlHelper) { var appSettingsKeys = new[] { "googleAppID", "googleAppSecret", "facebookAppID", "facebookAppSecret", "twitterConsumerKey", "twitterConsumerSecret" }; var noValueForSetting = appSettingsKeys .Any(key => string.IsNullOrEmpty(ConfigurationManager.AppSettings[key])); var message = ""; if (noValueForSetting) { message = new HtmlTag("p") .Attr("style", "color: Red;") .Text("Not all key and secrets are filled in a configuration file.") .ToHtmlString(); } return new MvcHtmlString(message); }
public async void Create_Account_Untyped() { var client = await GetForceClient(); var account = new { Name = "New Account", Description = "New Account Description" }; var id = await client.Create("Account", account); Assert.IsNotNullOrEmpty(id); }
public IEventPersistence CreateEventPersistence() { var domainTypes = new[] { typeof (DomainEvent), typeof (AccommodationLeadCreated), typeof (AccommodationLeadApproved), typeof (UserCreated), typeof (AuthenticationCreated), typeof (AccommodationSupplierCreated) }; var connectionString = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString; return SqlEventPersistence.Create(connectionString, domainTypes); }
private static string GetAppsettings() { var appSettings = new { appSettings = new { resourceServerUrl = ConfigurationManager.AppSettings["resourceServerUrl"], identityServerUrl = ConfigurationManager.AppSettings["identityServerUrl"] } }; var json = JObject.FromObject(appSettings) .ToString(); json = RemoveWhitespace(json); return json; }
public object GetBoardData() { string gameFile = ConfigurationManager.AppSettings["GameDataFile"]; XElement root = XElement.Load(gameFile); var categories = from c in root.Element("categories").Elements("category") select new { title = c.Attribute("title").Value, questions = (from question in c.Element("questions").Elements("question") select new { q = question.Attribute("q").Value, a = question.Attribute("a").Value } ).ToArray() }; var result = new { Categories = categories.ToArray() }; return result; }
public void Configuration(IAppBuilder app) { var pathsToIgnore = new[] { "/authentication/**", "/authentication", }; app.Map("/api", site => { site.RequiresStatelessAuth(new SecureTokenValidator(ConfigurationManager.AppSettings["jwt_secret"]), new StatelessAuthOptions { IgnorePaths = pathsToIgnore, PassThroughUnauthorizedRequests = true }); site.UseNancy(); site.UseStageMarker(PipelineStage.MapHandler); }); }
/// <summary> /// 是否通过授权 /// </summary> /// <param name="actionContext">上下文</param> /// <returns>是否成功</returns> protected override bool IsAuthorized(HttpActionContext actionContext) { var requestQueryPairs = actionContext.Request.GetQueryNameValuePairs().ToDictionary(k => k.Key, v => v.Value); if (requestQueryPairs.Count == 0 || !requestQueryPairs.ContainsKey("timestamp") || !requestQueryPairs.ContainsKey("signature") || !requestQueryPairs.ContainsKey("nonce")) { return false; } string[] waitEncryptParamsArray = new[] { _wxToken, requestQueryPairs["timestamp"], requestQueryPairs["nonce"] }; string waitEncryptParamStr = string.Join("", waitEncryptParamsArray.OrderBy(m => m)); string encryptStr = HashAlgorithm.SHA1(waitEncryptParamStr); return encryptStr.ToLower().Equals(requestQueryPairs["signature"].ToLower()); }
public void SET_REALEC_DOCTYPES_Test() { string tableName = "EMPOWER.SET_REALEC_DOCTYPES"; using ( SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ExtraTestsConnectionString"])) { conn.Open(); var cmd = new SqlCommand(string.Format("SELECT * FROM {0}", tableName), conn); using (var dr = cmd.ExecuteReader(CommandBehavior.KeyInfo)) { var dt = new DataTable(tableName); dt.Load(dr); var actualColumns = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName); var expectedColumns = new[] { "REALEC_ENUM_VALUE", "DOC_TYPE_ID", "FINALVERSION", "FILEEXT", "DESCRIPTION", "EXCLUDEGDR" }; Assert.That(actualColumns, Is.EquivalentTo(expectedColumns)); } } }
private static void InitializeENode( bool useMockCommandStore = false, bool useMockEventStore = false, bool useMockPublishedVersionStore = false, bool useMockDomainEventPublisher = false, bool useMockApplicationMessagePublisher = false, bool useMockPublishableExceptionPublisher = false) { var setting = new ConfigurationSetting(ConfigurationManager.AppSettings["connectionString"]); var assemblies = new[] { Assembly.GetExecutingAssembly() }; _enodeConfiguration = ECommonConfiguration .Create() .UseAutofac() .RegisterCommonComponents() .UseLog4Net() .UseJsonNet() .RegisterUnhandledExceptionHandler() .CreateENode(setting) .RegisterENodeComponents() .UseCommandStore(useMockCommandStore) .UseEventStore(useMockEventStore) .UsePublishedVersionStore(useMockPublishedVersionStore) .RegisterBusinessComponents(assemblies) .InitializeBusinessAssemblies(assemblies) .UseEQueue(useMockDomainEventPublisher, useMockApplicationMessagePublisher, useMockPublishableExceptionPublisher) .StartEQueue(); _commandService = ObjectContainer.Resolve<ICommandService>(); _memoryCache = ObjectContainer.Resolve<IMemoryCache>(); _commandStore = ObjectContainer.Resolve<ICommandStore>(); _eventStore = ObjectContainer.Resolve<IEventStore>(); _publishedVersionStore = ObjectContainer.Resolve<IPublishedVersionStore>(); _domainEventPublisher = ObjectContainer.Resolve<IMessagePublisher<DomainEventStreamMessage>>(); _applicationMessagePublisher = ObjectContainer.Resolve<IMessagePublisher<IApplicationMessage>>(); _publishableExceptionPublisher = ObjectContainer.Resolve<IMessagePublisher<IPublishableException>>(); _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(typeof(BaseTest)); _logger.Info("ENode initialized."); }
public string[] ChangePassword(string CurrentPassword, string NewPassword, string ReNewPassword, string SessionId, string SessionValue) { var charLimitValidationMessage = new[] { "Password length must be minimum 7 character" }; var currentPasswordNotMatched = new[] {"Current password is not matching"}; var newAndRenewPasswordNotMatched = new[] { "Entred new password and renew pasword is not matching." }; var sessionOut= new []{"Session expired, please login again"}; var sessionId = LeaveRegisterUtils.DecryptPassword(SessionId); var sessionValue = LeaveRegisterUtils.DecryptPassword(SessionValue); var employeeId = DataBaseUtils.GetEmployeeId(ConnectionString, sessionId); return !DataBaseUtils.IsEmployeeLoggedIn(ConnectionString, sessionId, sessionValue) ? sessionOut : (!DataBaseUtils.IsPasswordMatches(ConnectionString, CurrentPassword, sessionId) ? currentPasswordNotMatched : ((!(NewPassword.Length > 6)) ? charLimitValidationMessage : ((NewPassword != ReNewPassword) ? newAndRenewPasswordNotMatched : DataBaseUtils.EmployeeSignUpOrChangePassword(ConnectionString, NewPassword, ReNewPassword, employeeId)))); }
protected void Application_Start() { UnityConfig.GetConfiguredContainer(); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var appData = Server.MapPath("~/App_Data"); if (!Directory.Exists(appData)) Directory.CreateDirectory(appData); var folders = new[] {"OrganisationsImgPath", "PlaylistImgPath", "UsersImgPath"}; foreach (var folder in folders) { var mapped = Server.MapPath(ConfigurationManager.AppSettings[folder]); if (!Directory.Exists(mapped)) Directory.CreateDirectory(mapped); } }
private static void ClearContentOfTables() { string connectionString = ConfigurationManager.ConnectionStrings["TasksConnectionString"].ConnectionString; Assert.IsFalse(connectionString == null); using (SqlConnection con = new SqlConnection(connectionString)) { string[] tblNames = new[] { "dbo.Task", "dbo.AuditLog", }; con.Open(); foreach (string tblName in tblNames) { using (var cmd = con.CreateCommand()) { cmd.CommandText = string.Format("delete from {0}", tblName); cmd.ExecuteNonQuery(); } } con.Close(); } }
internal override void Process(ProcessorArgs args) { Assert.ArgumentNotNull(args, "args"); var connectionStrings = args.ConnectionStringsConfig; var mongoConnectionStrings = new[] { "analytics", "tracking.live", "tracking.history", "tracking.contact", }; foreach (var name in mongoConnectionStrings) { if (args.AddedConnectionStrings.Contains(name)) { continue; } if (ConfigurationManager.ConnectionStrings[name] != null) { continue; } var addNode = connectionStrings.CreateElement("add"); addNode.SetAttribute("name", name); var db = Path.Combine(args.Server.MapPath("/").TrimEnd('\\'), name); db = db.Replace("\\\\", "\\").Replace("\\", "_").Replace(":", "").Replace(".", "_"); db = db.Length > 64 ? db.Substring(db.Length - 64) : db; // mongo db limit is 64 chars for db name addNode.SetAttribute("connectionString", string.Format("mongodb://localhost:27017/{0}", db)); connectionStrings.DocumentElement.AppendChild(addNode); args.AddedConnectionStrings.Add(name); } }
public static object CreateApplicationHost (Type hostType, string virtualDir, string physicalDir) { if (physicalDir == null) throw new NullReferenceException (); // Make sure physicalDir has file system semantics // and not uri semantics ( '\' and not '/' ). physicalDir = Path.GetFullPath (physicalDir); if (hostType == null) throw new ArgumentException ("hostType can't be null"); if (virtualDir == null) throw new ArgumentNullException ("virtualDir"); Evidence evidence = new Evidence (AppDomain.CurrentDomain.Evidence); // // Setup // AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = physicalDir; string webConfig = FindWebConfig (physicalDir); if (webConfig == null) webConfig = Path.Combine (physicalDir, DEFAULT_WEB_CONFIG_NAME); setup.ConfigurationFile = webConfig; setup.DisallowCodeDownload = true; string[] bindirPath = new string [1] { #if NET_2_0 Path.Combine (physicalDir, "bin") #else "bin" #endif }; string bindir; foreach (string dir in HttpApplication.BinDirs) { bindir = Path.Combine (physicalDir, dir); if (Directory.Exists (bindir)) { #if NET_2_0 bindirPath [0] = bindir; #else bindirPath [0] = dir; #endif break; } } setup.PrivateBinPath = BuildPrivateBinPath (physicalDir, bindirPath); setup.PrivateBinPathProbe = "*"; string dynamic_dir = null; string user = Environment.UserName; int tempDirTag = 0; string dirPrefix = String.Concat (user, "-temp-aspnet-"); for (int i = 0; ; i++){ string d = Path.Combine (Path.GetTempPath (), String.Concat (dirPrefix, i.ToString ("x"))); try { CreateDirectory (d); string stamp = Path.Combine (d, "stamp"); CreateDirectory (stamp); dynamic_dir = d; try { Directory.Delete (stamp); } catch (Exception) { // ignore } tempDirTag = i.GetHashCode (); break; } catch (UnauthorizedAccessException){ continue; } } // // Unique Domain ID // string domain_id = (virtualDir.GetHashCode () + 1 ^ physicalDir.GetHashCode () + 2 ^ tempDirTag).ToString ("x"); // This is used by mod_mono's fail-over support string domain_id_suffix = Environment.GetEnvironmentVariable ("__MONO_DOMAIN_ID_SUFFIX"); if (domain_id_suffix != null && domain_id_suffix.Length > 0) domain_id += domain_id_suffix; setup.ApplicationName = domain_id; setup.DynamicBase = dynamic_dir; setup.CachePath = dynamic_dir; string dynamic_base = setup.DynamicBase; if (CreateDirectory (dynamic_base) && (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") == null)) ClearDynamicBaseDirectory (dynamic_base); // // Create app domain // AppDomain appdomain; appdomain = AppDomain.CreateDomain (domain_id, evidence, setup); // // Populate with the AppDomain data keys expected, Mono only uses a // few, but third party apps might use others: // appdomain.SetData (".appDomain", "*"); int l = physicalDir.Length; if (physicalDir [l - 1] != Path.DirectorySeparatorChar) physicalDir += Path.DirectorySeparatorChar; appdomain.SetData (".appPath", physicalDir); appdomain.SetData (".appVPath", virtualDir); appdomain.SetData (".appId", domain_id); appdomain.SetData (".domainId", domain_id); appdomain.SetData (".hostingVirtualPath", virtualDir); appdomain.SetData (".hostingInstallDir", Path.GetDirectoryName (typeof (Object).Assembly.CodeBase)); #if NET_2_0 appdomain.SetData ("DataDirectory", Path.Combine (physicalDir, "App_Data")); #endif appdomain.SetData (MonoHostedDataKey, "yes"); #if NET_2_0 appdomain.DoCallBack (SetHostingEnvironment); #endif return appdomain.CreateInstanceAndUnwrap (hostType.Module.Assembly.FullName, hostType.FullName); }
public void ArgumentKeysCaseInsensitive() { const string xml = @"<?xml version='1.0' encoding='UTF-8' ?> <logging> <factoryAdapter type='CONSOLE'> <arg key='LeVel1' value='DEBUG' /> <arg key='LEVEL2' value='DEBUG' /> <arg key='level3' value='DEBUG' /> </factoryAdapter> </logging>"; StandaloneConfigurationReader reader = new StandaloneConfigurationReader( xml ); LogSetting setting = reader.GetSection( null ) as LogSetting; Assert.IsNotNull( setting ); Assert.AreEqual(3, setting.Properties.Count); var expectedValue = new[] { "DEBUG" }; CollectionAssert.AreEqual(expectedValue, setting.Properties.GetValues("level1")); CollectionAssert.AreEqual(expectedValue, setting.Properties.GetValues("level2")); CollectionAssert.AreEqual(expectedValue, setting.Properties.GetValues("LEVEL3")); //Assert.AreEqual( 1, setting.Properties.Count ); //Assert.AreEqual( 3, setting.Properties.GetValues("LeVeL").Length ); }
public static void RegisterRoutes(RouteCollection routes) { //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.ico/{*pathInfo}"); routes.IgnoreRoute("Scripts/{resource}"); routes.IgnoreRoute("Images/{*pathInfo}");//Handled by th binaryHandler routes.IgnoreRoute("{resource}/Images/{*pathInfo}");//Handled by th binaryHandler routes.IgnoreRoute("{resource}/images/{*pathInfo}");//Handled by th binaryHandler routes.IgnoreRoute("_Images/{*pathInfo}"); routes.IgnoreRoute("_Scripts/{*pathInfo}"); routes.IgnoreRoute("_Styles/{*pathInfo}"); //Route for serving Javascript from broker DB routes.MapRoute( "Javascript", "{language}/system/js/{*PageId}", new { controller = "Javascript", action = "Index" }, // Parameter defaults new { pageId = @"^(.*.js)?$", httpMethod = new HttpMethodConstraint("GET") } // Parameter constraints ); //routes.MapRoute( // "HomePage", // "{controller}/{action}", // new { controller = "Home", action="Index"}); routes.MapRoute( "PreviewPage", "{*PageId}", new { controller = "Page", action = "PreviewPage" }, // Parameter defaults new { httpMethod = new HttpMethodConstraint("POST") } // Parameter constraints ); routes.MapRoute("SiteSelector", "go", new { Controller = "SiteSelector", action="Index", language = "it_en" }); var pageDefaults = new { language = "it_en", controller = "Page", action = "Page", pageId = WebConfigurationManager.AppSettings["DefaultPage"], parameters = UrlParameter.Optional, }; //Route for serving partial views to booking engine (header/footer etc.) routes.MapRoute( "PartialView", "{language}/system/include/{Controller}/{Action}", pageDefaults, // Parameter defaults new { httpMethod = new HttpMethodConstraint("GET") } // Parameter constraints ); routes.MapRoute( "TridionPage", "{language}/{*pageId}", pageDefaults, // Parameter defaults new { pageId = @"^(.*(\.html|/))?$" } // Parameter constraints to only catch .html pages ); //General. For parameter use: http://localhost:1775/it_en/faq/detail?keywordUri=13-540-1024 routes.MapRoute( "General", "{language}/{controller}/{action}/{parameters}", pageDefaults ); routes.MapRoute( "Default", "{controller}/{action}"); }
private static void setupMsSqlSpatial(Map m) { string[] layernames = new[] {"Rivers", "Countries" /*, "Cities"*/ }; string sridstr = SridMap.DefaultInstance.Process(4326, ""); foreach (string lyrname in layernames) { string tbl = lyrname; AppStateMonitoringFeatureProvider provider = new AppStateMonitoringFeatureProvider( new MsSqlSpatialProvider( new GeometryServices()[sridstr], ConfigurationManager.ConnectionStrings["db"].ConnectionString, "st", "dbo", tbl, "oid", "Geometry") { DefaultProviderProperties = new ProviderPropertiesExpression( new ProviderPropertyExpression[] { new WithNoLockExpression(true) }) }); GeoJsonGeometryStyle style = new GeoJsonGeometryStyle(); switch (tbl) { case "Rivers": { StyleBrush brush = new SolidStyleBrush(StyleColor.Blue); StylePen pen = new StylePen(brush, 1); style.Enabled = true; style.EnableOutline = true; style.Line = pen; style.Fill = brush; break; } case "Countries": { StyleBrush brush = new SolidStyleBrush(new StyleColor(0, 0, 0, 255)); StylePen pen = new StylePen(brush, 2); style.Enabled = true; style.EnableOutline = true; style.Line = pen; style.Fill = new SolidStyleBrush(StyleColor.Green); break; } default: { style = RandomStyle.RandomGeometryStyle(); style.MaxVisible = 100000; break; } } /* include GeoJson styles */ style.IncludeAttributes = false; style.IncludeBBox = true; style.PreProcessGeometries = false; style.CoordinateNumberFormatString = "{0:F}"; GeometryLayer layer = new GeometryLayer(tbl, style, provider); layer.Features.IsSpatiallyIndexed = false; layer.AddProperty(AppStateMonitoringFeatureLayerProperties.AppStateMonitor, provider.Monitor); m.AddLayer(layer); } }
public async void Update_Account_BadField() { try { using (var httpClient = new HttpClient()) { var client = await GetForceClient(httpClient); var originalName = "New Account"; var newName = "New Account 2"; var account = new { Name = originalName, Description = "New Account Description" }; var id = await client.CreateAsync("Account", account); var updatedAccount = new { BadName = newName, Description = "New Account Description" }; await client.UpdateAsync("Account", id, updatedAccount); } } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } }
public async void Create_Account_Untyped_BadObject() { try { using (var httpClient = new HttpClient()) { var client = await GetForceClient(httpClient); var account = new { Name = "New Account", Description = "New Account Description" }; await client.CreateAsync("BadAccount", account); } } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } }
public IConfiguration OpenConfiguration(DotNetConfiguration.ConfigurationUserLevel userLevel) { DotNetConfiguration.Configuration configuration = DotNetConfiguration.ConfigurationManager.OpenExeConfiguration(userLevel); return configuration == null ? null : new ConfigurationWrapper(configuration); }