public virtual bool IsAccessibleToUser(HttpContext context, SiteMapNode node) { if (context == null) { throw new ArgumentNullException("context"); } if (node == null) { throw new ArgumentNullException("node"); } if (!SecurityTrimmingEnabled) { return(true); } /* The node is accessible (according to msdn2) if: * * 1. The Roles exists on node and the current user is in at least one of the specified roles. * * 2. The current thread has an associated WindowsIdentity that has file access to the requested URL and * the URL is located within the directory structure for the application. * * 3. The current user is authorized specifically for the requested URL in the authorization element for * the current application and the URL is located within the directory structure for the application. */ /* 1. */ IList roles = node.Roles; if (roles != null && roles.Count > 0) { foreach (string rolename in roles) { if (rolename == "*" || context.User.IsInRole(rolename)) { return(true); } } } /* 2. */ /* XXX */ /* 3. */ string url = node.Url; if (!String.IsNullOrEmpty(url)) { // TODO check url is located within the current application if (VirtualPathUtility.IsAppRelative(url) || !VirtualPathUtility.IsAbsolute(url)) { url = VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), url); } AuthorizationSection config = (AuthorizationSection)WebConfigurationManager.GetSection( "system.web/authorization", url); if (config != null) { return(config.IsValidUser(context.User, context.Request.HttpMethod)); } } return(false); }
public static FriendLinkSection GetSection() { return((FriendLinkSection)WebConfigurationManager.GetSection("system.web/friendlink")); }
public static Logger GetLogger() { if (_logger != null) { return(_logger); } NameValueCollection appSettings = WebConfigurationManager.GetSection("appSettings") as NameValueCollection; String loggingLevel = null; if (appSettings != null) { loggingLevel = appSettings["resin.log-level"]; } if ("".Equals(loggingLevel)) { loggingLevel = null; } if (_logger == null && !"None".Equals(loggingLevel, StringComparison.OrdinalIgnoreCase)) { try { if (!EventLog.SourceExists(LOG_SOURCE)) { EventLog.CreateEventSource(LOG_SOURCE, "Application"); } EventLogEntryType logLevel; if ("Information".Equals(loggingLevel, StringComparison.OrdinalIgnoreCase)) { logLevel = EventLogEntryType.Information; } else if ("Error".Equals(loggingLevel, StringComparison.OrdinalIgnoreCase)) { logLevel = EventLogEntryType.Error; } else if ("Warning".Equals(loggingLevel, StringComparison.OrdinalIgnoreCase)) { logLevel = EventLogEntryType.Warning; } else { logLevel = EventLogEntryType.Error; } EventLog log = new EventLog(); log.Log = "Application"; log.Source = LOG_SOURCE; String message = String.Format("Initializing logging at {0} logging level", loggingLevel); log.WriteEntry(message, EventLogEntryType.Information); Trace.TraceInformation(message); _logger = new Logger(log, logLevel); } catch (Exception e) { Trace.TraceError(e.Message + '\n' + e.StackTrace); //security does not allow to write create source or use EventLog } } if (_logger == null) { _logger = new NoopLogger(); } return(_logger); }
private void context_EndRequest(object sender, EventArgs e) { HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; // // Check for the X-Send headers // string filePath = response.Headers.Get("X-Sendfile"); if (filePath == null) { filePath = response.Headers.Get("X-Accel-Redirect"); } if (filePath != null) { // // Determine the file path and ready the response // if (ConfigurationManager.AppSettings["XSendDir"] != null) { filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath); // if there is a base path set (file will be located above this) } else if (ConfigurationManager.AppSettings["XAccelLocation"] != null) { filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]); } response.Clear(); // Clears output buffer response.Headers.Remove("X-Sendfile"); // Remove unwanted headers response.Headers.Remove("X-Accel-Redirect"); // // Set the cache policy // if (ConfigurationManager.AppSettings["XSendCache"] == null) { response.Cache.SetCacheability(HttpCacheability.NoCache); } else if (ConfigurationManager.AppSettings["XSendCache"] == "Public") { response.Cache.SetCacheability(HttpCacheability.Public); } else { response.Cache.SetCacheability(HttpCacheability.Private); } // // Get the file information and set headers appropriately // if (!FileUtil.FileExists(filePath)) { throw new HttpException(404, "File_does_not_exist"); } if (filePath[filePath.Length - 1] == '.') { throw new HttpException(404, "File_does_not_exist"); } FileInfo file = new FileInfo(filePath); response.Cache.SetLastModified(file.LastWriteTimeUtc); response.Headers.Remove("Content-Length"); DateTime dateTime = new DateTime(file.LastWriteTime.Year, file.LastWriteTime.Month, file.LastWriteTime.Day, file.LastWriteTime.Hour, file.LastWriteTime.Minute, file.LastWriteTime.Second, 0); DateTime now = DateTime.Now; string range = request.Headers["Range"]; // // Call into .net static file handler to do the heavy lifting for us // Massive hacks. Should work for all version of .net // // http://dotnetinside.com/framework/v2.0.50727/System.Web/StaticFileHandler // http://typedescriptor.net/browse/types/7243-System.Web.StaticFileHandler // http://stackoverflow.com/questions/7829478/how-to-execute-a-private-static-method-with-optional-parameters-via-reflection // // var genEtag = typeof(System.Web.StaticFileHandler).GetMethod("GenerateETag", BindingFlags.Static | BindingFlags.NonPublic); string etag = genEtag.Invoke(obj: null, parameters: new object[] { HttpContext.Current, dateTime, now }); var rangeRequest = typeof(System.Web.StaticFileHandler).GetMethod("ProcessRangeRequest", BindingFlags.Static | BindingFlags.NonPublic); if (StringUtil.StringStartsWithIgnoreCase(range, "bytes") && rangeRequest.Invoke(obj: null, parameters: new object[] { HttpContext.Current, filePath, file.Length, range, etag, dateTime })) { return; } response.AddHeader("Content-Length", file.Length.ToString()); response.AppendHeader("Accept-Ranges", "bytes"); response.Cache.SetIgnoreRangeRequests(); // // Check if we want to detect the mime type of the current content // if (ConfigurationManager.AppSettings["XSendMime"] == null) { Microsoft.Web.Administration.ConfigurationSection staticContentSection = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent"); Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); var mt = staticContentCollection.Where( a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower() ).FirstOrDefault(); if (mt != null) { response.ContentType = mt.GetAttributeValue("mimeType").ToString(); } else { response.ContentType = "application/octet-stream"; } } // // Set a content disposition if it is not already set by the application // if (response.Headers["Content-Disposition"] == null) { response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name); } // // Send the file without loading it into memory // response.TransmitFile(file.FullName); } }
static void Main(string[] args) { string inputStr = String.Empty; string option = String.Empty; // Define a regular expression to allow only // alphanumeric inputs that are at most 20 character // long. For instance "/iii:". Regex rex = new Regex(@"[^\/w]{1,20}:"); // Parse the user's input. if (args.Length < 1) { // No option entered. Console.Write("Input parameter missing."); return; } else { // Get the user's option. inputStr = args[0].ToLower(); if (!(rex.Match(inputStr)).Success) { // Wrong option format used. Console.Write("Input parameter format not allowed."); return; } } // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration( "/aspnetTest"); // Get the <system.web> group. SystemWebSectionGroup systemWeb = (SystemWebSectionGroup)configuration.GetSectionGroup("system.web"); // </Snippet1> try { switch (inputStr) { case "/anonymous:": // <Snippet2> // Get the anonymousIdentification section. AnonymousIdentificationSection anonymousIdentification = systemWeb.AnonymousIdentification; // Read section information. info = anonymousIdentification.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet2> Console.Write(msg); break; case "/authentication:": // <Snippet3> // Get the authentication section. AuthenticationSection authentication = systemWeb.Authentication; // Read section information. info = authentication.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet3> Console.Write(msg); break; case "/authorization:": // <Snippet4> // Get the authorization section. AuthorizationSection authorization = systemWeb.Authorization; // Read section information. info = authorization.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet4> Console.Write(msg); break; case "/compilation:": // <Snippet5> // Get the compilation section. CompilationSection compilation = systemWeb.Compilation; // Read section information. info = compilation.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet5> Console.Write(msg); break; case "/customerrors:": // <Snippet6> // Get the customerrors section. CustomErrorsSection customerrors = systemWeb.CustomErrors; // Read section information. info = customerrors.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet6> Console.Write(msg); break; case "/globalization:": // <Snippet7> // Get the globalization section. GlobalizationSection globalization = systemWeb.Globalization; // Read section information. info = globalization.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet7> Console.Write(msg); break; case "/httpcookies:": // <Snippet8> // Get the httpCookies section. HttpCookiesSection httpCookies = systemWeb.HttpCookies; // Read section information. info = httpCookies.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet8> Console.Write(msg); break; case "/httphandlers:": // <Snippet9> // Get the httpHandlers section. HttpHandlersSection httpHandlers = systemWeb.HttpHandlers; // Read section information. info = httpHandlers.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet9> Console.Write(msg); break; case "/httpmodules:": // <Snippet10> // Get the httpModules section. HttpModulesSection httpModules = systemWeb.HttpModules; // Read section information. info = httpModules.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet10> Console.Write(msg); break; case "/httpruntime:": // <Snippet11> // Get the httpRuntime section. HttpRuntimeSection httpRuntime = systemWeb.HttpRuntime; // Read section information. info = httpRuntime.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet11> Console.Write(msg); break; case "/identity:": // <Snippet12> // Get the identity section. IdentitySection identity = systemWeb.Identity; // Read section information. info = identity.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet12> Console.Write(msg); break; case "/machinekey:": // <Snippet13> // Get the machineKey section. MachineKeySection machineKey = systemWeb.MachineKey; // Read section information. info = machineKey.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet13> Console.Write(msg); break; case "/membership:": // <Snippet14> // Get the membership section. MembershipSection membership = systemWeb.Membership; // Read section information. info = membership.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet14> Console.Write(msg); break; case "/pages:": // <Snippet15> // Get the pages section. PagesSection pages = systemWeb.Pages; // Read section information. info = pages.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet15> Console.Write(msg); break; case "/processModel:": // <Snippet16> // Get the processModel section. ProcessModelSection processModel = systemWeb.ProcessModel; // Read section information. info = processModel.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet16> Console.Write(msg); break; case "/profile:": // <Snippet17> // Get the profile section. ProfileSection profile = systemWeb.Profile; // Read section information. info = profile.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet17> Console.Write(msg); break; case "/roleManager:": // <Snippet18> // Get the roleManager section. RoleManagerSection roleManager = systemWeb.RoleManager; // Read section information. info = roleManager.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet18> Console.Write(msg); break; case "/securityPolicy:": // <Snippet19> // Get the securityPolicy section. SecurityPolicySection securityPolicy = systemWeb.SecurityPolicy; // Read section information. info = securityPolicy.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet19> Console.Write(msg); break; case "/sessionState:": // <Snippet20> // Get the sessionState section. SessionStateSection sessionState = systemWeb.SessionState; // Read section information. info = sessionState.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet20> Console.Write(msg); break; case "/sitemap:": // <Snippet21> // Get the siteMap section. SiteMapSection siteMap = systemWeb.SiteMap; // Read section information. info = siteMap.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet21> Console.Write(msg); break; case "/trace:": // <Snippet22> // Get the trace section. TraceSection trace = systemWeb.Trace; // Read section information. info = trace.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet22> Console.Write(msg); break; case "/trust:": // <Snippet23> // Get the trust section. TrustSection trust = systemWeb.Trust; // Read section information. info = trust.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet23> Console.Write(msg); break; case "/browserCaps:": // <Snippet24> // Get the browserCaps section. DefaultSection browserCaps = systemWeb.BrowserCaps; // Read section information. info = browserCaps.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet24> Console.Write(msg); break; case "/clientTarget:": // <Snippet25> // Get the clientTarget section. ClientTargetSection clientTarget = systemWeb.ClientTarget; // Read section information. info = clientTarget.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet25> Console.Write(msg); break; case "/deployment:": // <Snippet26> // Get the deployment section. DeploymentSection deployment = systemWeb.Deployment; // Read section information. info = deployment.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet26> Console.Write(msg); break; case "/deviceFilters:": // <Snippet27> // Get the deviceFilters section. DefaultSection deviceFilters = systemWeb.DeviceFilters; // Read section information. info = deviceFilters.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet27> Console.Write(msg); break; case "/healthMonitoring:": // <Snippet28> // Get the healthMonitoring section. HealthMonitoringSection healthMonitoring = systemWeb.HealthMonitoring; // Read section information. info = healthMonitoring.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet28> Console.Write(msg); break; case "/hostingEnvironment:": // <Snippet29> // Get the hostingEnvironment section. HostingEnvironmentSection hostingEnvironment = systemWeb.HostingEnvironment; // Read section information. info = hostingEnvironment.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet29> Console.Write(msg); break; case "/mobileControls:": // <Snippet30> // Get the mobileControls section. ConfigurationSection mobileControls = systemWeb.MobileControls; // Read section information. info = mobileControls.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet30> Console.Write(msg); break; case "/protocols:": // <Snippet31> // Get the protocols section. DefaultSection protocols = systemWeb.Protocols; // Read section information. info = protocols.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet31> Console.Write(msg); break; case "/urlMappings:": // <Snippet32> // Get the urlMappings section. UrlMappingsSection urlMappings = systemWeb.UrlMappings; // Read section information. info = urlMappings.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet32> Console.Write(msg); break; case "/webControls:": // <Snippet33> // Get the webControls section. WebControlsSection webControls = systemWeb.WebControls; // Read section information. info = webControls.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet33> Console.Write(msg); break; case "/webParts:": // <Snippet34> // Get the webParts section. WebPartsSection webParts = systemWeb.WebParts; // Read section information. info = webParts.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet34> Console.Write(msg); break; case "/webServices:": // <Snippet35> // Get the webServices section. WebServicesSection webServices = systemWeb.WebServices; // Read section information. info = webServices.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet35> Console.Write(msg); break; case "/XhtmlConformance:": // <Snippet36> // Get the xhtmlConformance section. XhtmlConformanceSection xhtmlConformance = systemWeb.XhtmlConformance; // Read section information. info = xhtmlConformance.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); msg = String.Format( "Name: {0}\nDeclared: {1}\nType: {2}\n", name, declared, type); // </Snippet36> Console.Write(msg); break; case "/all:": StringBuilder allSections = new StringBuilder(); ConfigurationSectionGroup systemWebGroup = configuration.GetSectionGroup("system.web"); int i = 0; foreach (ConfigurationSection section in systemWebGroup.Sections) { i += 1; info = section.SectionInformation; name = info.SectionName; type = info.Type; declared = info.IsDeclared.ToString(); if (i < 10) { msg = String.Format( "{0})Name: {1}\nDeclared: {2}\nType: {3}\n", i.ToString(), name, declared, type); } else { msg = String.Format( "{0})Name: {1}\nDeclared: {2}\nType: {3}\n", i.ToString(), name, declared, type); } allSections.AppendLine(msg); } // Console.WriteLine(systemWebGroup.Name); // Console.WriteLine(systemWebGroup.SectionGroupName); Console.Write(allSections.ToString()); break; default: // Option is not allowed.. Console.Write("Input not allowed."); break; } } catch (ArgumentException e) { // Never display this. Use it for // debugging purposes. msg = e.ToString(); } }
public ActionResult Generate(string Format, int SortBy, int Size = 0) { Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~"); int paradeSize = Convert.ToInt32(webConfigApp.AppSettings.Settings["ParadeSize"].Value.ToString()); int paradeRecords = Convert.ToInt32(webConfigApp.AppSettings.Settings["ParadeRecords"].Value.ToString()); if (paradeSize != Size && Size > 0) { paradeSize = Size; webConfigApp.AppSettings.Settings["ParadeSize"].Value = paradeSize.ToString(); } List <Person> people = new List <Person>(); var query = db.People.AsQueryable(); if (SortBy == 0) { query = query.OrderBy(x => x.id); } if (SortBy == 1) { query = query.OrderBy(x => x.First_Name); } if (SortBy == 2) { query = query.OrderByDescending(x => x.First_Name); } if (SortBy == 3) { query = query.OrderBy(x => x.First_Name).ThenBy(x => x.Last_Name).ThenBy(x => x.Middle_Name); } if (SortBy == 4) { query = query.OrderByDescending(x => x.First_Name).ThenBy(x => x.Last_Name).ThenBy(x => x.Middle_Name); } people = query.Skip(paradeRecords).Take(paradeSize).ToList(); int count = people.Count; webConfigApp.AppSettings.Settings["ParadeRecords"].Value = (count + paradeRecords).ToString(); webConfigApp.Save(); if (Format == "xlsx") { string[] columns = { "First_Name", "Middle_Name", "Last_Name", "Taluko", "District", "Date_of_Birth", "Medical_History" }; byte[] filecontent = Helpers.ExcelExportHelper.ExportExcel(people, "Parade", true, columns); return(File(filecontent, Helpers.ExcelExportHelper.ExcelContentType, "Parade_" + DateTime.Now.Date + ".xlsx")); } if (Format == "pdf") { DataTable dataTable = Helpers.ExcelExportHelper.ListToDataTable(people); MemoryStream PDFData = Helpers.PDFExportHelper.CreatedPdf(dataTable); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.Charset = string.Empty; Response.Cache.SetCacheability(HttpCacheability.Public); Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Parade_" + DateTime.Now + ".pdf", DateTime.Now.Ticks.ToString().Substring(0, 6))); Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.End(); } return(RedirectToAction("Index")); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected new void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e); cMsg = (Mensajes.msgBox) this.Master.FindControl("MsgBox1"); if (Context.Request.IsAuthenticated) { // retrieve user's identity from httpcontext user FormsIdentity ident = (FormsIdentity)Context.User.Identity; string perfil = ident.Ticket.UserData; if (perfil == "0") { Response.Redirect("~/Configuracion/Inicio.aspx?Permiso=NO"); return; } PermisoSegunPerfil = perfil == "3"; Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); Ulises5000Configuration.ToolsUlises5000Section UlisesTools = Ulises5000Configuration.ToolsUlises5000Section.Instance; UlisesToolsVersion = UlisesTools; } //ServicioCD40.NoTransaction(); // Las actuaciones sobre la base de datos se realizarán inmediatamente, independientemente de TransactionTimeout if (CallbackCompletado == null) { CallbackCompletado = new AsyncCallback(OnCallBackCompleted); } if (!IsPostBack) { BtAceptar_ConfirmButtonExtender.ConfirmText = (string)GetGlobalResourceObject("Espaniol", "AceptarCambios"); BtCancelar_ConfirmButtonExtender.ConfirmText = (string)GetGlobalResourceObject("Espaniol", "CancelarCambios"); IndexListBox1 = -1; //Mostrar grabación ED137 sólo para Nouakchott (Version==1) if (UlisesToolsVersion.Tools["GrabacionRecursoRadio"] == null) { TblRecorders.Visible = false; } //Se lee la variable de sesión idsistema Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); KeyValueConfigurationElement s = config.AppSettings.Settings["Sistema"]; Session["idsistema"] = s.Value; CargaDDLGrabadores(); BtNuevo.Visible = PermisoSegunPerfil; MuestraDatos(DameDatos()); } else { LblIp1Existente.Visible = LblIp2Existente.Visible = false; //if (Request.Form["eliminaelemento"] == "1") //El usuario elige eliminar el elemento //{ // Request.Form["eliminaelemento"].Replace("1", "0"); // EliminarElemento(); //} //if (Request.Form["cancelparam"] == "1") //El usuario elige no guardar los cambios //{ // Request.Form["cancelparam"].Replace("1", "0"); // CancelarCambios(); //} //if (Request.Form["aceptparam"] == "1") //El usuario elige guardar los cambios //{ // Request.Form["aceptparam"].Replace("1", "0"); // GuardarCambios(); //} if (Session["idsistema"] == null) { //Si la variable de sesión idsistema es nula, se vuelve a recuperar Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); KeyValueConfigurationElement s = config.AppSettings.Settings["Sistema"]; Session["idsistema"] = s.Value; } if (datos == null) { DameDatos(); } } }
public static void Main() { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration( "/aspnet"); // Get the section. AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection( "system.web/authentication"); // Get the users collection. FormsAuthenticationUserCollection formsAuthenticationUsers = authenticationSection.Forms.Credentials.Users; // </Snippet1> // <Snippet2> // </Snippet2> // <Snippet3> // Define the user name. string name = "userName"; // Define the encrypted password. string password = "******"; // Create a new FormsAuthenticationUser object. FormsAuthenticationUser newformsAuthenticationUser = new FormsAuthenticationUser(name, password); // </Snippet3> // <Snippet4> // Using the Password property. // Get current password. string currentPassword = formsAuthenticationUsers[0].Password; // Set a SHA1 encrypted password. formsAuthenticationUsers[0].Password = "******"; // </Snippet4> // <Snippet5> // Using the Name property. // Get current name. string currentName = formsAuthenticationUsers[0].Name; // Set a new name. formsAuthenticationUsers[0].Name = "userName"; // </Snippet5> }
/// <summary> /// 初始化提供程序。 (从 ProviderBase 继承。) /// </summary> /// <remarks>初始化提供程序。 (从 ProviderBase 继承。)</remarks> /// <param name="name">该提供程序的友好名称。</param> /// <param name="config">名称/值对的集合,表示在配置中为该提供程序指定的、提供程序特定的属性。</param> public override void Initialize(string name, NameValueCollection config) { Debug.WriteLine("初始化", "SessionStore.Initialize"); //验证配置对象无效。 if (config == null) throw new ArgumentNullException("config"); //重写基类初始化。 base.Initialize(name, config); //获取虚拟路径。 string appName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; //打开配置文件。 Configuration cfg = WebConfigurationManager.OpenWebConfiguration(appName); //获取会话状态配置对象。 this.SessionStateConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState"); //获取配置节点集合。 NameValueCollection nvc = (NameValueCollection)ConfigurationManager.AppSettings; //获取配置会话中心IP地址。 this.SessionCenterServiceIPAddresse = nvc.Get("SessionCenterServiceIPAddresse"); if (string.IsNullOrEmpty(this.SessionCenterServiceIPAddresse)) this.SessionCenterServiceIPAddresse = DefaultSessionCenterServiceIPAddresse; //获取配置会话中心端口。 this.SessionCenterServicePort = Convert.ToInt32(nvc.Get("SessionCenterServicePort")); if (this.SessionCenterServicePort <= 0) this.SessionCenterServicePort = DefaultSessionCenterServicePort; //获取配置SSL证书路径。 this.SessionCenterServiceSSLCertificatePath = nvc.Get("SessionCenterServiceSSLCertificatePath"); //获取配置SSL证书名称。 this.SessionCenterServiceSSLCertificate = nvc.Get("SessionCenterServiceSSLCertificate"); //获取配置文件字符编码。 /* string ed = nvc.Get("SessionCenterServiceEncoding"); if (string.IsNullOrEmpty(ed)) { this.Encoding = System.Text.Encoding.UTF8; } else { this.Encoding = System.Text.Encoding.GetEncoding(ed); } */ //获取配置文件安全连接会话中心验证内容。 this.SessionCenterSecureConnectionContent = nvc.Get("SessionCenterSecureConnectionContent"); //获取配置文件会话传输通道空闲超时时间。 string ChannelIdleTimeout = nvc.Get("SessionTransferChannelIdleTimeout"); if (!string.IsNullOrEmpty(ChannelIdleTimeout) && Convert.ToInt32(ChannelIdleTimeout) > 0) { this.SessionTransferChannelIdleTimeout = Convert.ToInt32(ChannelIdleTimeout); } //初始化SSL证书列表。 if (this.certificates == null && this.certificate == null) { //验证使用文件或设置使用证书名称加载证书。 if (!string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificatePath) && string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificate)) { //加载SSL文件。 //验证是否使用证书密码。 if (string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificatePassword)) //使用没有密码的证书文件。 this.certificate = new X509Certificate2(this.SessionCenterServiceSSLCertificatePath); else //使用有密码的证书文件。 this.certificate = new X509Certificate2(this.SessionCenterServiceSSLCertificatePath, this.SessionCenterServiceSSLCertificatePassword); Debug.WriteLine("连接时创建SSL证书信息完成将证书添加进证书容器", "SessionStore.Initialize"); this.certificates = new X509CertificateCollection(); this.certificates.Add(this.certificate); } else if (string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificatePath) && !string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificate)) { //加载SSL文件。 //验证是否使用证书密码。 if (string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificatePassword)) { X509Store store = null; X509Certificate2Collection certs = null; //检索证书。 foreach (string item in EnumExpand.EnumToList(typeof(StoreName))) { try { //创建证书列表。 store = new X509Store(((StoreName)Enum.Parse(typeof(StoreName), item))); store.Open(OpenFlags.ReadOnly); //检索证书。 certs = store.Certificates.Find(X509FindType.FindBySubjectName, this.SessionCenterServiceSSLCertificate, false); //验证检索到的证书。 if (certs.Count > 0) { //验证是否使用证书密码。 if (string.IsNullOrEmpty(this.SessionCenterServiceSSLCertificatePassword)) { //使用没有密码的证书。 this.certificate = new X509Certificate(certs[0].RawData); } else { //使用有密码的证书。 this.certificate = new X509Certificate(certs[0].RawData, this.SessionCenterServiceSSLCertificatePassword); } this.certificates = new X509CertificateCollection(); this.certificates.Add(this.certificate); Debug.WriteLine("连接时创建SSL证书信息完成将证书添加进证书容器", "SessionStore.Initialize"); //找到指定名称的证书退出。 break; } } finally { //释放证书资源。 if (store != null) { store.Close(); store = null; } } } } } } // Debug.WriteLine("初始化创建一条连接通道[SessionCenterServiceIPAddresse:" + this.SessionCenterServiceIPAddresse + ",SessionCenterServicePort:" + this.SessionCenterServicePort.ToString() + ",SessionTransferChannelIdleTimeout:" + this.SessionTransferChannelIdleTimeout.ToString() + ",SessionCenterServiceSSLCertificatePath:" + (this.SessionCenterServiceSSLCertificatePath == null ? "" : this.SessionCenterServiceSSLCertificatePath) + ",SessionCenterServiceSSLCertificate:" + (this.SessionCenterServiceSSLCertificate == null ? "" : this.SessionCenterServiceSSLCertificate) + "]", "SessionStore.Initialize"); //初始化通道管理对象。 this.ChannelManager = new SessionTransferChannelManager(this); //初始化通道连接。 this.ChannelManager.Connection(); //验证初始化通道连接到会话中心是否正常。 if (!this.ChannelManager.IsConnected) { throw new Exception("没有连接到全局会话中心初始化错误!"); } Debug.WriteLine("初始化完成[SessionCenterServiceIPAddresse:" + this.SessionCenterServiceIPAddresse + ",SessionCenterServicePort:" + this.SessionCenterServicePort.ToString() + ",SessionCenterCurrentDateTime:" + this.SessionCenterCurrentDateTime.ToString() + "]", "SessionStore.Initialize"); }
protected override void RenderAttributes(HtmlTextWriter w) { /* Need to always render: method, action and id */ string action; string customAction = Attributes ["action"]; Page page = Page; HttpRequest req = page != null ? page.RequestInternal : null; #if !TARGET_J2EE if (String.IsNullOrEmpty(customAction)) { string file_path = req != null ? req.ClientFilePath : null; string current_path = req != null ? req.CurrentExecutionFilePath : null; if (file_path == null) { action = Action; } else if (file_path == current_path) { // Just the filename will do action = UrlUtils.GetFile(file_path); } else { // Fun. We need to make cookieless sessions work, so no // absolute paths here. bool cookieless; SessionStateSection sec = WebConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection; cookieless = sec != null ? sec.Cookieless == HttpCookieMode.UseUri: false; string appVPath = HttpRuntime.AppDomainAppVirtualPath; int appVPathLen = appVPath.Length; if (appVPathLen > 1) { if (cookieless) { if (StrUtils.StartsWith(file_path, appVPath, true)) { file_path = file_path.Substring(appVPathLen + 1); } } else if (StrUtils.StartsWith(current_path, appVPath, true)) { current_path = current_path.Substring(appVPathLen + 1); } } if (cookieless) { Uri current_uri = new Uri("http://host" + current_path); Uri fp_uri = new Uri("http://host" + file_path); action = fp_uri.MakeRelative(current_uri); } else { action = current_path; } } } else { action = customAction; } if (req != null) { action += req.QueryStringRaw; } #else // Allow the page to transform action to a portlet action url if (String.IsNullOrEmpty(customAction)) { string queryString = req.QueryStringRaw; action = CreateActionUrl(VirtualPathUtility.ToAppRelative(req.CurrentExecutionFilePath) + (string.IsNullOrEmpty(queryString) ? string.Empty : "?" + queryString)); } else { action = customAction; } #endif if (req != null) { XhtmlConformanceSection xhtml = WebConfigurationManager.GetSection("system.web/xhtmlConformance") as XhtmlConformanceSection; if (xhtml == null || xhtml.Mode != XhtmlConformanceMode.Strict) #if NET_4_0 { if (RenderingCompatibilityLessThan40) #endif { // LAMESPEC: MSDN says the 'name' attribute is rendered only in // Legacy mode, this is not true. w.WriteAttribute("name", Name); } } w.WriteAttribute("method", Method); if (String.IsNullOrEmpty(customAction)) { w.WriteAttribute("action", action, true); } /* * This is a hack that guarantees the ID is set properly for HtmlControl to * render it later on. As ugly as it is, we use it here because of the way * the ID, ClientID and UniqueID properties work internally in our Control * code. * * Fixes bug #82596 */ if (ID == null) { #pragma warning disable 219 string client = ClientID; #pragma warning restore 219 } string submit = page != null?page.GetSubmitStatements() : null; if (!String.IsNullOrEmpty(submit)) { Attributes.Remove("onsubmit"); w.WriteAttribute("onsubmit", submit); } /* enctype and target should not be written if * they are empty */ string enctype = Enctype; if (!String.IsNullOrEmpty(enctype)) { w.WriteAttribute("enctype", enctype); } string target = Target; if (!String.IsNullOrEmpty(target)) { w.WriteAttribute("target", target); } string defaultbutton = DefaultButton; if (!String.IsNullOrEmpty(defaultbutton)) { Control c = FindControl(defaultbutton); if (c == null || !(c is IButtonControl)) throw new InvalidOperationException(String.Format("The DefaultButton of '{0}' must be the ID of a control of type IButtonControl.", ID)); } if (page != null && DetermineRenderUplevel()) { w.WriteAttribute( "onkeypress", "javascript:return " + page.WebFormScriptReference + ".WebForm_FireDefaultButton(event, '" + c.ClientID + "')"); } } /* Now remove them from the hash so the base * RenderAttributes can do all the rest */ Attributes.Remove("method"); Attributes.Remove("enctype"); Attributes.Remove("target"); base.RenderAttributes(w); }
public static object GetSection(string section) { return(WebConfigurationManager.GetWebApplicationSection(section)); }
static Roles() { config = (RoleManagerSection)WebConfigurationManager.GetSection("system.web/roleManager"); }
/// <summary> /// Handles the URL Rewriting for the application /// </summary> /// <param name="context">Http context</param> public static void BeginRequest(HttpContext context) { try { string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ? context.Request.ApplicationPath.Length : 0); string[] args = path.Split(new char[] { '/' }).Subset(1); if (args.Length > 0) { int pos = 0; // Ensure database if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null) { context.Response.Redirect("~/manager", false); context.Response.EndClean(); } // Check for culture prefix if (Cultures.ContainsKey(args[0])) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = Cultures[args[0]]; pos = 1; } else { var def = (GlobalizationSection)WebConfigurationManager.GetSection("system.web/globalization"); if (def != null && !String.IsNullOrWhiteSpace(def.Culture) && !def.Culture.StartsWith("auto:")) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(def.UICulture); } } // Check for hostname extension. This feature can't be combined with culture prefixes if (pos == 0) { var segments = context.Request.RawUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segments.Length > 0) { var hostExt = context.Request.Url.Host + "/" + segments[0]; if (HostNames.ContainsKey(hostExt)) { RequestedSite = new ExtendedHostName() { HostName = context.Request.Url.Host, Extension = segments[0], SiteTree = HostNames[hostExt] }; if (segments[0] == args[0]) { pos = 1; // If this was the last argument, add an empty one if (args.Length == 1) { args = args.Concat(new string[] { "" }).ToArray(); } } } } } var handled = false; // Find the correct request handler foreach (var hr in Application.Current.Handlers) { if (hr.UrlPrefix.ToLower() == args[pos].ToLower()) { if (hr.Id != "PERMALINK" || !Config.PrefixlessPermalinks) { // Don't execute permalink routing in passive mode if ((hr.Id != "PERMALINK" && hr.Id != "STARTPAGE") || !Config.PassiveMode) { // Execute the handler hr.Handler.HandleRequest(context, args.Subset(pos + 1)); handled = true; break; } } } } if (!handled && args[pos].ToLower() == "res.ashx") { Application.Current.Resources.HandleRequest(context, args.Subset(pos + 1)); handled = true; } // If no handler was found and we are using prefixless permalinks, // route traffic to the permalink handler. if (!Config.PassiveMode) { if (!handled && Config.PrefixlessPermalinks && args[pos].ToLower() != "manager" && String.IsNullOrEmpty(context.Request["permalink"])) { var handler = Application.Current.Handlers["PERMALINK"]; handler.HandleRequest(context, args.Subset(pos)); } } } } catch (ThreadAbortException) { // We simply swallow this exception as we don't want unhandled // exceptions flying around causing the app pool to die. } catch (Exception e) { // One catch to rule them all, and in the log file bind them. Application.Current.LogProvider.Error("WebPiranha.BeginRequest", "Unhandled exception", e); context.Response.StatusCode = 500; context.Response.EndClean(); } }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "SessionSQLServerHandler"; } if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Mono SQL Session Store Provider"); } ApplicationName = HostingEnvironment.ApplicationVirtualPath; base.Initialize(name, config); sessionConfig = WebConfigurationManager.GetWebApplicationSection("system.web/sessionState") as SessionStateSection; connectionString = sessionConfig.SqlConnectionString; string dbProviderName; if (String.IsNullOrEmpty(connectionString) || String.Compare(connectionString, SessionStateSection.DefaultSqlConnectionString, StringComparison.Ordinal) == 0) { connectionString = "Data Source=|DataDirectory|/ASPState.sqlite;Version=3"; dbProviderName = defaultDbFactoryTypeName; } else { string[] parts = connectionString.Split(';'); var newCS = new List <string> (); dbProviderName = null; bool allowDb = sessionConfig.AllowCustomSqlDatabase; foreach (string p in parts) { if (p.Trim().Length == 0) { continue; } if (p.StartsWith("DbProviderName", StringComparison.OrdinalIgnoreCase)) { int idx = p.IndexOf('='); if (idx < 0) { throw new ProviderException("Invalid format for the 'DbProviderName' connection string parameter. Expected 'DbProviderName = value'."); } dbProviderName = p.Substring(idx + 1); continue; } if (!allowDb) { string tmp = p.Trim(); if (tmp.StartsWith("database", StringComparison.OrdinalIgnoreCase) || tmp.StartsWith("initial catalog", StringComparison.OrdinalIgnoreCase)) { throw new ProviderException("Specifying a custom database is not allowed. Set the allowCustomSqlDatabase attribute of the <system.web/sessionState> section to 'true' in order to use a custom database name."); } } newCS.Add(p); } connectionString = String.Join(";", newCS.ToArray()); if (String.IsNullOrEmpty(dbProviderName)) { dbProviderName = defaultDbFactoryTypeName; } } Exception typeException = null; try { providerFactoryType = Type.GetType(dbProviderName, true); } catch (Exception ex) { typeException = ex; providerFactoryType = null; } if (providerFactoryType == null) { throw new ProviderException("Unable to find database provider factory type.", typeException); } sqlCommandTimeout = (int)sessionConfig.SqlCommandTimeout.TotalSeconds; }
public static string GetSqlServerConnectionString() { bool flag1 = HttpContext.Current.Request.ApplicationPath == "/"; return(WebConfigurationManager.OpenWebConfiguration("/Lesktop").ConnectionStrings.ConnectionStrings["Lesktop_ConnectString"].ConnectionString); }
/// <summary> /// Reverting Web.config changes made for the DocuSign Feature on deactivation /// </summary> /// <param name="properties"></param> public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { spSite = (SPSite)properties.Feature.Parent; spWeb = spSite.OpenWeb(); webApp = spWeb.Site.WebApplication; spWebService = SPWebService.ContentService; Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name); string configFilePath = config.FilePath; doc = new XmlDocument(); XmlNode nodeTrust = null; XmlNode nodeEnableSessionState = null; doc.Load(configFilePath); nodeServiceModel = doc.SelectSingleNode("configuration/system.serviceModel"); nodeSmtpServer = doc.SelectSingleNode("configuration/appSettings/add[@key='smtpServer']"); nodeUserName = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignUserName']"); nodePassword = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignPassword']"); nodeTrust = doc.SelectSingleNode("configuration/system.web/trust"); nodeEnableSessionState = doc.SelectSingleNode("configuration/system.web/pages"); //int count=0; if (webApp != null) { // Set the enableSessionState attribute to false if (nodeEnableSessionState != null) { XmlAttribute attributeEnableSessionState = nodeEnableSessionState.Attributes["enableSessionState"]; if (attributeEnableSessionState != null) { attributeEnableSessionState.Value = "false"; } } // Set the level attribute to WSS_Minimal if (nodeTrust != null) { XmlAttribute attributeLevel = nodeTrust.Attributes["level"]; if (attributeLevel != null) { attributeLevel.Value = "WSS_Minimal"; } } // Remove serviceModel node - DocuSign Webservice info if (nodeServiceModel != null) { nodeServiceModel.ParentNode.RemoveChild(nodeServiceModel); } //Remove smtpServer node if (nodeSmtpServer != null) { nodeSmtpServer.ParentNode.RemoveChild(nodeSmtpServer); } //Remove Password node if (nodePassword != null) { nodePassword.ParentNode.RemoveChild(nodePassword); } // Remove UserName node if (nodeUserName != null) { nodeUserName.ParentNode.RemoveChild(nodeUserName); } doc.Save(configFilePath); // Apply the config modifications to the application } }
static void Main(string[] args) { try { // Set the path of the config file. string configPath = ""; // Get the Web application configuration object. Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath); // Get the section-related object. SecurityPolicySection configSection = (SecurityPolicySection)config.GetSection("system.web/securityPolicy"); // Display title and info. Console.WriteLine("ASP.NET Configuration Info"); Console.WriteLine(); // Display Config details. Console.WriteLine("File Path: {0}", config.FilePath); Console.WriteLine("Section Path: {0}", configSection.SectionInformation.Name); // Display the number of trust levels. Console.WriteLine("TrustLevels Collection Count: {0}", configSection.TrustLevels.Count); // <Snippet2> // Display elements of the TrustLevels collection property. for (int i = 0; i < configSection.TrustLevels.Count; i++) { Console.WriteLine(); Console.WriteLine("TrustLevel {0}:", i); Console.WriteLine("Name: {0}", configSection.TrustLevels.Get(i).Name); Console.WriteLine("Type: {0}", configSection.TrustLevels.Get(i).PolicyFile); } // Add a TrustLevel element to the configuration file. configSection.TrustLevels.Add(new TrustLevel("myTrust", "mytrust.config")); // </Snippet2> // Update if not locked. if (!configSection.SectionInformation.IsLocked) { config.Save(); Console.WriteLine("** Configuration updated."); } else { Console.WriteLine("** Could not update; section is locked."); } } catch (Exception e) { // Unknown error. Console.WriteLine(e.ToString()); } // Display and wait Console.ReadLine(); }
/// <summary> /// Make modifications to the web.config when the feature is activated. /// </summary> /// <param name="properties"></param> public override void FeatureActivated(SPFeatureReceiverProperties properties) { spSite = (SPSite)properties.Feature.Parent; spWeb = spSite.OpenWeb(); spWebService = SPWebService.ContentService; Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name); string smtpServer = string.Empty; string configFilePath = config.FilePath; doc = new XmlDocument(); doc.Load(configFilePath); AppSettingsSection appSettings = config.AppSettings; if (appSettings.ElementInformation.IsPresent) { nodeSmtpServer = doc.SelectSingleNode("configuration/appSettings/add[@key='smtpServer']"); nodeUserName = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignUserName']"); nodePassword = doc.SelectSingleNode("configuration/appSettings/add[@key='docuSignPassword']"); // Add smtpServer to web.config file if (nodeSmtpServer == null) { ModifyWebConfigData("add[@key='SMTPServer']", "configuration/appSettings", "<add key='smtpServer' value='" + SMTP_SERVER + "' />"); } // Add DocuSign Service user Credentials to web.config file if (nodeUserName == null) { ModifyWebConfigData("add[@key='userName']", "configuration/appSettings", "<add key='docuSignUserName' value='" + DOCUSIGN_USERNAME + "' />"); } // Add Profiles to web.config file if (nodePassword == null) { ModifyWebConfigData("add[@key='password']", "configuration/appSettings", "<add key='docuSignPassword' value='" + DOCUSIGN_PASSWORD + "' />"); } } else { ModifyWebConfigData("add[@key='SMTPServer']", "configuration", "<appSettings><add key='smtpServer' value='" + SMTP_SERVER + "' /><add key='docuSignUserName' value='" + DOCUSIGN_USERNAME + "' /><add key='docuSignPassword' value='" + DOCUSIGN_PASSWORD + "' /></appSettings>"); } nodeServiceModel = doc.SelectSingleNode("configuration/system.serviceModel"); // Add ServiceModel to web.config file if (nodeServiceModel == null) { ModifyWebConfigData("ServiceModel", "configuration", GetServiceModelTag()); } XmlNode nodeTrust = null; XmlNode nodeEnableSessionState = null; nodeTrust = doc.SelectSingleNode("configuration/system.web/trust"); nodeEnableSessionState = doc.SelectSingleNode("configuration/system.web/pages"); if (nodeEnableSessionState != null) { XmlAttribute attributeEnableSessionState = nodeEnableSessionState.Attributes["enableSessionState"]; if (attributeEnableSessionState != null) { attributeEnableSessionState.Value = "true"; } } // Set the level attribute to WSS_Minimal if (nodeTrust != null) { XmlAttribute attributeLevel = nodeTrust.Attributes["level"]; if (attributeLevel != null) { attributeLevel.Value = "Full"; } } doc.Save(configFilePath); ModifyWebConfigData("add[@name='Session']", "configuration/system.web/httpModules", "<add name='Session' type='System.Web.SessionState.SessionStateModule' />"); spWebService.Update(); spWebService.ApplyWebConfigModifications(); }
public void Init(HttpApplication app) { config = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState"); ProviderSettings settings; switch (config.Mode) { case SessionStateMode.Custom: settings = config.Providers [config.CustomProvider]; if (settings == null) { throw new HttpException(String.Format("Cannot find '{0}' provider.", config.CustomProvider)); } break; case SessionStateMode.Off: return; case SessionStateMode.InProc: settings = new ProviderSettings(null, typeof(SessionInProcHandler).AssemblyQualifiedName); break; case SessionStateMode.SQLServer: settings = new ProviderSettings(null, typeof(SessionSQLServerHandler).AssemblyQualifiedName); break; case SessionStateMode.StateServer: settings = new ProviderSettings(null, typeof(SessionStateServerHandler).AssemblyQualifiedName); break; default: throw new NotImplementedException(String.Format("The mode '{0}' is not implemented.", config.Mode)); } handler = (SessionStateStoreProviderBase)ProvidersHelper.InstantiateProvider(settings, typeof(SessionStateStoreProviderBase)); if (String.IsNullOrEmpty(config.SessionIDManagerType)) { idManager = new SessionIDManager(); } else { Type idManagerType = HttpApplication.LoadType(config.SessionIDManagerType, true); idManager = (ISessionIDManager)Activator.CreateInstance(idManagerType); } try { idManager.Initialize(); } catch (Exception ex) { throw new HttpException("Failed to initialize session ID manager.", ex); } supportsExpiration = handler.SetItemExpireCallback(OnSessionExpired); HttpRuntimeSection runtime = HttpRuntime.Section; executionTimeout = runtime.ExecutionTimeout; //executionTimeoutMS = executionTimeout.Milliseconds; this.app = app; app.BeginRequest += new EventHandler(OnBeginRequest); app.AcquireRequestState += new EventHandler(OnAcquireRequestState); app.ReleaseRequestState += new EventHandler(OnReleaseRequestState); app.EndRequest += new EventHandler(OnEndRequest); }
protected virtual CassetteConfigurationSection GetConfigurationSection() { return((WebConfigurationManager.GetSection("cassette") as CassetteConfigurationSection) ?? new CassetteConfigurationSection()); }
public List <ElementItemInfo> GetProperties( string sectionName, string elementName, int index, string virtualPath, string site, string locationSubPath, string server) { List <ElementItemInfo> elementItemList = new List <ElementItemInfo>(); Configuration config = WebConfigurationManager.OpenWebConfiguration( virtualPath, site, locationSubPath, server); ConfigurationSection cs = config.GetSection(sectionName); Type sectionType = cs.GetType(); System.Reflection.PropertyInfo reflectionElement = sectionType.GetProperty(elementName); Object elementObject = reflectionElement.GetValue(cs, null); Type elementType = elementObject.GetType(); System.Reflection.PropertyInfo reflectionProperty = elementType.GetProperty("Count"); int elementCount = reflectionProperty == null ? 0 : Convert.ToInt32( reflectionProperty.GetValue(elementObject, null)); if (elementCount > 0) { int i = 0; ConfigurationElementCollection elementItems = elementObject as ConfigurationElementCollection; foreach (ConfigurationElement elementItem in elementItems) { if (i == index) { elementObject = elementItem; } i++; } } Type reflectionItemType = elementObject.GetType(); PropertyInfo[] elementProperties = reflectionItemType.GetProperties(); foreach (System.Reflection.PropertyInfo rpi in elementProperties) { if (rpi.Name != "SectionInformation" && rpi.Name != "LockAttributes" && rpi.Name != "LockAllAttributesExcept" && rpi.Name != "LockElements" && rpi.Name != "LockAllElementsExcept" && rpi.Name != "LockItem" && rpi.Name != "Item" && rpi.Name != "ElementInformation" && rpi.Name != "CurrentConfiguration") { ElementItemInfo eii = new ElementItemInfo(); eii.Name = rpi.Name; eii.TypeName = rpi.PropertyType.ToString(); string uniqueID = rpi.Name + index.ToString(); eii.UniqueID = uniqueID.Replace("/", ""); ParameterInfo[] indexParms = rpi.GetIndexParameters(); if (rpi.PropertyType == typeof(IList) || rpi.PropertyType == typeof(ICollection) || indexParms.Length > 0) { eii.Value = "List"; } else { object propertyValue = rpi.GetValue(elementObject, null); eii.Value = propertyValue == null ? "" : propertyValue.ToString(); } elementItemList.Add(eii); } } return(elementItemList); }
static SDKConfig() { Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); IList keys = config.AppSettings.Settings.AllKeys; if (keys.Contains("acpsdk.signCert.path")) { signCertPath = config.AppSettings.Settings["acpsdk.signCert.path"].Value; //功能:读取配置文件获取签名证书路径 } if (keys.Contains("acpsdk.signCert.pwd")) { signCertPwd = config.AppSettings.Settings["acpsdk.signCert.pwd"].Value;//功能:读取配置文件获取签名证书密码 } if (keys.Contains("acpsdk.validateCert.dir")) { validateCertDir = config.AppSettings.Settings["acpsdk.validateCert.dir"].Value;//功能:读取配置文件获取验签目录 } if (keys.Contains("acpsdk.encryptCert.path")) { encryptCert = config.AppSettings.Settings["acpsdk.encryptCert.path"].Value; //功能:加密公钥证书路径 } if (keys.Contains("acpsdk.cardRequestUrl")) { cardRequestUrl = config.AppSettings.Settings["acpsdk.cardRequestUrl"].Value; //功能:有卡交易路径; } if (keys.Contains("acpsdk.appRequestUrl")) { appRequestUrl = config.AppSettings.Settings["acpsdk.appRequestUrl"].Value; //功能:appj交易路径; } if (keys.Contains("acpsdk.singleQueryUrl")) { singleQueryUrl = config.AppSettings.Settings["acpsdk.singleQueryUrl"].Value; //功能:读取配置文件获取交易查询地址 } if (keys.Contains("acpsdk.fileTransUrl")) { fileTransUrl = config.AppSettings.Settings["acpsdk.fileTransUrl"].Value; //功能:读取配置文件获取文件传输类交易地址 } if (keys.Contains("acpsdk.frontTransUrl")) { frontTransUrl = config.AppSettings.Settings["acpsdk.frontTransUrl"].Value; //功能:读取配置文件获取前台交易地址 } if (keys.Contains("acpsdk.backTransUrl")) { backTransUrl = config.AppSettings.Settings["acpsdk.backTransUrl"].Value;//功能:读取配置文件获取后台交易地址 } if (keys.Contains("acpsdk.batTransUrl")) { batTransUrl = config.AppSettings.Settings["acpsdk.batTransUrl"].Value;//功能:读取配批量交易地址 } if (keys.Contains("acpsdk.frontUrl")) { frontUrl = config.AppSettings.Settings["acpsdk.frontUrl"].Value;//功能:读取配置文件获取前台通知地址 } if (keys.Contains("acpsdk.backUrl")) { backUrl = config.AppSettings.Settings["acpsdk.backUrl"].Value;//功能:读取配置文件获取前台通知地址 } if (keys.Contains("acpsdk.jf.cardRequestUrl")) { jfCardRequestUrl = config.AppSettings.Settings["acpsdk.jf.cardRequestUrl"].Value; //功能:缴费产品有卡交易路径; } if (keys.Contains("acpsdk.jf.appRequestUrl")) { jfAppRequestUrl = config.AppSettings.Settings["acpsdk.jf.appRequestUrl"].Value; //功能:缴费产品app交易路径; } if (keys.Contains("acpsdk.jf.singleQueryUrl")) { jfSingleQueryUrl = config.AppSettings.Settings["acpsdk.jf.singleQueryUrl"].Value; //功能:读取配置文件获取缴费产品交易查询地址 } if (keys.Contains("acpsdk.jf.frontTransUrl")) { jfFrontTransUrl = config.AppSettings.Settings["acpsdk.jf.frontTransUrl"].Value; //功能:读取配置文件获取缴费产品前台交易地址 } if (keys.Contains("acpsdk.jf.backTransUrl")) { jfBackTransUrl = config.AppSettings.Settings["acpsdk.jf.backTransUrl"].Value;//功能:读取配置文件获取缴费产品后台交易地址 } if (keys.Contains("acpsdk.ifValidateRemoteCert")) { ifValidateRemoteCert = config.AppSettings.Settings["acpsdk.ifValidateRemoteCert"].Value;//功能:是否验证后台https证书 } if (keys.Contains("acpsdk.ifValidateCNName")) { ifValidateCNName = config.AppSettings.Settings["acpsdk.ifValidateCNName"].Value;//功能:是否验证证书cn } if (keys.Contains("acpsdk.middleCert.path")) { middleCertPath = config.AppSettings.Settings["acpsdk.middleCert.path"].Value;//功能:中级证书路径 } if (keys.Contains("acpsdk.rootCert.path")) { rootCertPath = config.AppSettings.Settings["acpsdk.rootCert.path"].Value;//功能:根证书路径 } if (keys.Contains("acpsdk.secureKey")) { secureKey = config.AppSettings.Settings["acpsdk.secureKey"].Value;//功能:散列方式签名密钥 } if (keys.Contains("acpsdk.signMethod")) { signMethod = config.AppSettings.Settings["acpsdk.signMethod"].Value;//功能:设置signMethod } if (keys.Contains("acpsdk.version")) { version = config.AppSettings.Settings["acpsdk.version"].Value;//功能:设置signMethod } }
/// <summary> /// /// </summary> /// <param name="configFilePath">Config 配置文件路径</param> public Config(string configFilePath) { this.WebConfig = WebConfigurationManager.OpenWebConfiguration(configFilePath); }
private void init() { try { NameValueCollection appSettings = WebConfigurationManager.GetSection("appSettings") as NameValueCollection; _log = Logger.GetLogger(); String servers = appSettings["resin.servers"]; if ("".Equals(servers)) { servers = "127.0.0.1:6800"; _log.Info("application setting 'resin.servers' is not specified. Using '{0}'", servers); Trace.TraceInformation("application setting 'resin.servers' is not specified. Using '{0}'", servers); } else { _log.Info("Setting servers to '{0}'", servers); Trace.TraceInformation("Setting servers to '{0}'", servers); } if (!String.IsNullOrEmpty(appSettings["resin.session-cookie"])) { _sessionCookieName = appSettings["resin.session-cookie"]; } if (!String.IsNullOrEmpty(appSettings["resin.ssl-session-cookie"])) { _sslSessionCookieName = appSettings["resin.ssl-session-cookie"]; } if ("false".Equals(appSettings["resin.sticky-sessions"], StringComparison.OrdinalIgnoreCase)) { _isStickySessions = false; } _log.Info("Setting sticky sessions to {0}", _isStickySessions); if (!String.IsNullOrEmpty(appSettings["resin.session-url-prefix"])) { _sessionUrlPrefix = appSettings["resin.session-url-prefix"]; } if (!String.IsNullOrEmpty(appSettings["resin.alternate-session-url-prefix"])) { _sessionUrlPrefix = appSettings["resin.alternate-session-url-prefix"]; } int loadBalanceConnectTimeout = 5 * 1000; if (!String.IsNullOrEmpty(appSettings["resin.load-balance-connect-timeout"])) { loadBalanceConnectTimeout = ParseTime("resin.load-balance-connect-timeout", appSettings["resin.load-balance-connect-timeout"]); } int loadBalanceIdleTime = 5 * 1000; if (!String.IsNullOrEmpty(appSettings["resin.load-balance-idle-time"])) { loadBalanceIdleTime = ParseTime("resin.load-balance-idle-time", appSettings["resin.load-balance-idle-time"]); } int loadBalanceRecoverTime = 15 * 1000; if (!String.IsNullOrEmpty(appSettings["resin.load-balance-recover-time"])) { loadBalanceRecoverTime = ParseTime("resin.load-balance-recover-time", appSettings["resin.load-balance-recover-time"]); } int loadBalanceSocketTimeout = 665 * 1000; if (!String.IsNullOrEmpty(appSettings["resin.load-balance-socket-timeout"])) { loadBalanceSocketTimeout = ParseTime("resin.load-balance-socket-timeout", appSettings["resin.load-balance-socket-timeout"]); } int keepaliveTimeout = 15 * 1000; if (!String.IsNullOrEmpty(appSettings["resin.keepalive-timeout"])) { keepaliveTimeout = ParseTime("resin.keepalive-timeout", appSettings["resin.keepalive-timeout"]); } int socketTimeout = 65 * 1000; if (!String.IsNullOrEmpty(appSettings["resin.socket-timeout"])) { socketTimeout = ParseTime("resin.socket-timeout", appSettings["resin.socket-timeout"]); } _isDebug = "true".Equals(appSettings["resin.debug"], StringComparison.OrdinalIgnoreCase); if (_isDebug) { Trace.TraceInformation("Setting debug to true"); } _isCauchoStatusEnabled = !"false".Equals(appSettings["resin.caucho-status"], StringComparison.OrdinalIgnoreCase); _loadBalancer = new LoadBalancer(servers, loadBalanceConnectTimeout, loadBalanceIdleTime, loadBalanceRecoverTime, loadBalanceSocketTimeout, keepaliveTimeout, socketTimeout, _isDebug); } catch (ConfigurationException e) { _e = e; } catch (FormatException e) { _e = new ConfigurationException(e.Message, e); } }
public override void Initialize(string name, NameValueCollection config) { // // Initialize values from web.config. // if (config == null) { throw new ArgumentNullException("config"); } if (name == null || name.Length == 0) { name = "MongoMember"; } if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "MongoDB Membership provider"); } // Initialize the abstract base class. base.Initialize(name, config); ApplicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); pWriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true")); string temp_format = config["passwordFormat"]; if (temp_format == null) { temp_format = "Hashed"; } switch (temp_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } string conectionStr = string.IsNullOrWhiteSpace(Mongo.ConnectionString) ? ConfigurationManager.ConnectionStrings[config["connectionStringName"]].ConnectionString : Mongo.ConnectionString; if (string.IsNullOrWhiteSpace(conectionStr)) { throw new ProviderException("ConnectionStringName string cannot be blank."); } Db = Mongo.Create(conectionStr); // Get encryption and decryption key information from the configuration. var cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (machineKey.ValidationKey.Contains("AutoGenerate")) { if (PasswordFormat != MembershipPasswordFormat.Clear) { throw new ProviderException("Hashed or Encrypted passwords are not supported with auto-generated keys."); } } }
static void Main(string[] args) { try { // Set the path of the config file. string configPath = ""; // Get the Web application configuration object. Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath); // Get the section related object. CompilationSection configSection = (CompilationSection)config.GetSection("system.web/compilation"); // Display title and info. Console.WriteLine("ASP.NET Configuration Info"); Console.WriteLine(); // Display Config details. Console.WriteLine("File Path: {0}", config.FilePath); Console.WriteLine("Section Path: {0}", configSection.SectionInformation.Name); // Create a new assembly reference. AssemblyInfo myAssembly = new AssemblyInfo("MyAssembly, Version=1.0.0000.0, " + "Culture=neutral, Public KeyToken=b03f5f7f11d50a3a"); // Add an assembly to the configuration. configSection.Assemblies.Add(myAssembly); // Add a second assembly reference. AssemblyInfo myAssembly2 = new AssemblyInfo("MyAssembly2"); configSection.Assemblies.Add(myAssembly2); // Assembly Collection int i = 1; int j = 1; foreach (AssemblyInfo assemblyItem in configSection.Assemblies) { Console.WriteLine(); Console.WriteLine("Assemblies {0} Details:", i); Console.WriteLine("Type: {0}", assemblyItem.ElementInformation.Type); Console.WriteLine("Source: {0}", assemblyItem.ElementInformation.Source); Console.WriteLine("LineNumber: {0}", assemblyItem.ElementInformation.LineNumber); Console.WriteLine("Properties Count: {0}", assemblyItem.ElementInformation.Properties.Count); j = 1; foreach (PropertyInformation propertyItem in assemblyItem.ElementInformation.Properties) { Console.WriteLine("Property {0} Name: {1}", j, propertyItem.Name); Console.WriteLine("Property {0} Value: {1}", j, propertyItem.Value); j++; } i++; } // Remove an assembly. configSection.Assemblies.Remove("MyAssembly, Version=1.0.0000.0, " + "Culture=neutral, Public KeyToken=b03f5f7f11d50a3a"); // Remove an assembly. configSection.Assemblies.RemoveAt(configSection.Assemblies.Count - 1); // Update if not locked. if (!configSection.SectionInformation.IsLocked) { config.Save(); Console.WriteLine("** Configuration updated."); } else { Console.WriteLine("** Could not update, section is locked."); } } catch (Exception e) { // Unknown error. Console.WriteLine(e.ToString()); } // Display and wait. Console.ReadLine(); }
static ProfileManager() { config = (ProfileSection)WebConfigurationManager.GetSection("system.web/profile"); }
public static void Main() { // <Snippet1> // Get the Web application configuration. Configuration configuration = WebConfigurationManager.OpenWebConfiguration( "/aspnetTest"); // Get the section. CustomErrorsSection customErrors = (CustomErrorsSection)configuration.GetSection( "system.web/customErrors"); // Get the collection. CustomErrorCollection customErrorsCollection = customErrors.Errors; // </Snippet1> // <Snippet2> // Create a new error object. // Does not exist anymore. // CustomError newcustomError = new CustomError(); // </Snippet2> // <Snippet3> // Create a new error object. CustomError newcustomError2 = new CustomError(404, "customerror404.htm"); // </Snippet3> // <Snippet4> // Get first errorr Redirect. CustomError currentError0 = customErrorsCollection[0]; string currentRedirect = currentError0.Redirect; // Set first error Redirect. currentError0.Redirect = "customError404.htm"; // </Snippet4> // <Snippet5> // Get second error StatusCode. CustomError currentError1 = customErrorsCollection[1]; int currentStatusCode = currentError1.StatusCode; // Set the second error StatusCode. currentError1.StatusCode = 404; // </Snippet5> }
public static void Main() { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the external Authentication section. AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection( "system.web/authentication"); // Get the external Forms section . FormsAuthenticationConfiguration formsAuthentication = authenticationSection.Forms; //</Snippet1> // <Snippet2> // Create a new FormsAuthentication object. FormsAuthenticationConfiguration newformsAuthentication = new FormsAuthenticationConfiguration(); // </Snippet2> // <Snippet3> // Get the current LoginUrl. string currentLoginUrl = formsAuthentication.LoginUrl; // Set the LoginUrl. formsAuthentication.LoginUrl = "newLoginUrl"; // </Snippet3> // <Snippet4> // Get current DefaultUrl. string currentDefaultUrl = formsAuthentication.DefaultUrl; // Set current DefaultUrl. formsAuthentication.DefaultUrl = "newDefaultUrl"; // </Snippet4> // <Snippet5> // Get current Cookieless. System.Web.HttpCookieMode currentCookieless = formsAuthentication.Cookieless; // Set current Cookieless. formsAuthentication.Cookieless = HttpCookieMode.AutoDetect; // </Snippet5> // <Snippet6> // Get the current Domain. string currentDomain = formsAuthentication.Domain; // Set the current Domain formsAuthentication.Domain = "newDomain"; // </Snippet6> // <Snippet7> // Get the current SlidingExpiration. bool currentSlidingExpiration = formsAuthentication.SlidingExpiration; // Set the SlidingExpiration. formsAuthentication.SlidingExpiration = false; // </Snippet7> // <Snippet8> // Get the current EnableCrossAppRedirects. bool currentEnableCrossAppRedirects = formsAuthentication.EnableCrossAppRedirects; // Set the EnableCrossAppRedirects. formsAuthentication.EnableCrossAppRedirects = false; // </Snippet8> // <Snippet9> // Get the current Path. string currentPath = formsAuthentication.Path; // Set the Path property. formsAuthentication.Path = "newPath"; // </Snippet9> // <Snippet10> // Get the current Timeout. System.TimeSpan currentTimeout = formsAuthentication.Timeout; // Set the Timeout. formsAuthentication.Timeout = System.TimeSpan.FromMinutes(10); // </Snippet10> // <Snippet11> // Get the current Protection. FormsProtectionEnum currentProtection = formsAuthentication.Protection; // Set the Protection property. formsAuthentication.Protection = FormsProtectionEnum.All; // </Snippet11> // <Snippet12> // Get the current RequireSSL. bool currentRequireSSL = formsAuthentication.RequireSSL; // Set the RequireSSL property value. formsAuthentication.RequireSSL = true; // </Snippet12> // <Snippet13> // Get the current Name property value. string currentName = formsAuthentication.Name; // Set the Name property value. formsAuthentication.Name = "newName"; // </Snippet13> // <Snippet14> // Get the current Credentials. FormsAuthenticationCredentials currentCredentials = formsAuthentication.Credentials; StringBuilder credentials = new StringBuilder(); // Get all the credentials. for (System.Int32 i = 0; i < currentCredentials.Users.Count; i++) { credentials.Append("Name: " + currentCredentials.Users[i].Name + " Password: " + currentCredentials.Users[i].Password); credentials.Append(Environment.NewLine); } // </Snippet14> }
protected void Page_Load(object sender, EventArgs e) { var umbracoVersion = IO.Container.Resolve <IUmbracoVersion>(); bool storePresent; IO.Container.Resolve <ICMSInstaller>().InstallStarterkit("demo", out storePresent); var admin = User.GetUser(0); var configuration = WebConfigurationManager.OpenWebConfiguration("~"); // change UmbracoMembershipProvider to this: // <add name="UmbracoMembershipProvider" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" type="umbraco.providers.members.UmbracoMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Customers" passwordFormat="Hashed" /> var systemWeb = configuration.SectionGroups["system.web"]; var membershipSection = (MembershipSection)systemWeb.Sections["membership"]; var umbracoMembershipProvider = membershipSection.Providers["UmbracoMembershipProvider"]; if (umbracoMembershipProvider.Parameters["defaultMemberTypeAlias"] != "Customers") { if (umbracoMembershipProvider.Parameters.Get("minRequiredPasswordLength") == null) { umbracoMembershipProvider.Parameters.Add("minRequiredPasswordLength", "4"); } if (umbracoMembershipProvider.Parameters.Get("minRequiredNonalphanumericCharacters") == null) { umbracoMembershipProvider.Parameters.Add("minRequiredNonalphanumericCharacters", "0"); } umbracoMembershipProvider.Parameters.Set("defaultMemberTypeAlias", "Customers"); } // add profile to system.web, or add new fields if they are not there yet var profileSection = (ProfileSection)systemWeb.Sections["profile"]; if (profileSection.DefaultProvider != "UmbracoMemberProfileProvider") { profileSection.DefaultProvider = "UmbracoMemberProfileProvider"; profileSection.Enabled = true; profileSection.AutomaticSaveEnabled = false; // <profile defaultProvider="UmbracoMemberProfileProvider" enabled="true" automaticSaveEnabled="false"> // <providers> // <clear /> // <add name="UmbracoMemberProfileProvider" type="umbraco.providers.members.UmbracoProfileProvider, umbraco.providers" /> // </providers> // <properties> // <clear /> // <add name="customerFirstName" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // <add name="customerLastName" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // <add name="customerStreet" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // <add name="customerStreetNumber" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // <add name="customerZipCode" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // <add name="customerCity" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // <add name="customerCountry" allowAnonymous="false" provider="UmbracoMemberProfileProvider" type="System.String" /> // </properties> //</profile> var providerSettings = new ProviderSettings { Name = "UmbracoMemberProfileProvider", Type = "umbraco.providers.members.UmbracoProfileProvider, umbraco.providers" }; profileSection.Providers.Add(providerSettings); profileSection.PropertySettings.Clear(); var customerFirstName = new ProfilePropertySettings("customerFirstName", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerFirstName); var customerLastName = new ProfilePropertySettings("customerLastName", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerLastName); var customerStreet = new ProfilePropertySettings("customerStreet", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerStreet); var customerStreetNumber = new ProfilePropertySettings("customerStreetNumber", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerStreetNumber); var customerZipCode = new ProfilePropertySettings("customerZipCode", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerZipCode); var customerCity = new ProfilePropertySettings("customerCity", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerCity); var customerCountry = new ProfilePropertySettings("customerCountry", false, SerializationMode.String, "UmbracoMemberProfileProvider", string.Empty, "System.String", false, string.Empty); profileSection.PropertySettings.Add(customerCountry); } configuration.Save(); // generate new membertype based on properties above // add them to both customer profile and order var customersType = MemberType.GetByAlias("Customers"); if (customersType == null) { try { customersType = MemberType.MakeNew(admin, "Customers"); } catch { Log.Instance.LogError("Umbraco Failed to create 'Customers' MemberType"); // Umbraco bug with SQLCE + MemberType.MakeNew requires this catch, membertype will not be created... } } var uwbsOrdersType = DocumentType.GetByAlias(Order.NodeAlias); if (customersType != null && uwbsOrdersType != null) { var customerTab = uwbsOrdersType.getVirtualTabs.FirstOrDefault(x => x.Caption.ToLowerInvariant() == "customer"); var customerTabId = customerTab == null?uwbsOrdersType.AddVirtualTab("Customer") : customerTab.Id; var shippingTab = uwbsOrdersType.getVirtualTabs.FirstOrDefault(x => x.Caption.ToLowerInvariant() == "shipping"); var shippingTabId = shippingTab == null?uwbsOrdersType.AddVirtualTab("Shipping") : shippingTab.Id; // todo V7 version! var stringDataType = umbracoVersion.GetDataTypeDefinition("Umbraco.Textbox", new Guid("0cc0eba1-9960-42c9-bf9b-60e150b429ae")); var stringDataTypeDef = new DataTypeDefinition(stringDataType.Id); var textboxMultipleDataType = umbracoVersion.GetDataTypeDefinition("Umbraco.TextboxMultiple", new Guid("c6bac0dd-4ab9-45b1-8e30-e4b619ee5da3")); var textboxMultipleDataTypeDef = new DataTypeDefinition(textboxMultipleDataType.Id); foreach (var propertyKey in profileSection.PropertySettings.AllKeys) { customersType.AddPropertyType(stringDataTypeDef, propertyKey, "#" + UppercaseFirstCharacter(propertyKey)); if (uwbsOrdersType.PropertyTypes.All(x => x.Alias.ToLowerInvariant() != propertyKey.ToLowerInvariant())) { var property = uwbsOrdersType.AddPropertyType(stringDataTypeDef, propertyKey, "#" + UppercaseFirstCharacter(propertyKey)); var propertyShippingKey = propertyKey.Replace("customer", "shipping"); var shippingProperty = uwbsOrdersType.AddPropertyType(stringDataTypeDef, propertyShippingKey, "#" + UppercaseFirstCharacter(propertyShippingKey)); property.TabId = customerTabId; shippingProperty.TabId = shippingTabId; } } customersType.Save(); // todo V7 version! var extraMessageProperty = uwbsOrdersType.AddPropertyType(textboxMultipleDataTypeDef, "extraMessage", "#ExtraMessage"); extraMessageProperty.TabId = customerTabId; uwbsOrdersType.Save(); } // create membergroup "customers", as set in the UmbracoMembershipProvider -> defaultMemberTypeAlias if (MemberGroup.GetByName("Customers") == null) { MemberGroup.MakeNew("Customers", admin); } Document.RePublishAll(); library.RefreshContent(); }