Exemplo n.º 1
0
        public static T GetSection <T>(string sectionName, string virtualPath) where T : ConfigurationSection
        {
            T section = WebConfigurationManager.GetSection(sectionName, virtualPath) as T;

            if (section == null)
            {
                throw new ConfigurationErrorsException(
                          Format.Current(
                              Strings.WebConfigurationManager_SectionNotFoundInPath_Format,
                              sectionName,
                              virtualPath));
            }

            return(section);
        }
Exemplo n.º 2
0
        public virtual void Initialize()
        {
            ApplicationServices.FrameworkAppName = "REPORTS XZEDI SERVICES";
            ApplicationServices.Version          = "8.7.4.42";
            ApplicationServices.JqmVersion       = "1.4.6";
            ApplicationServices.HostVersion      = "1.2.4.0";
            CompilationSection compilation = ((CompilationSection)(WebConfigurationManager.GetSection("system.web/compilation")));
            bool releaseMode = !(compilation.Debug);

            AquariumExtenderBase.EnableMinifiedScript = releaseMode;
            AquariumExtenderBase.EnableCombinedScript = releaseMode;
            ApplicationServices.EnableMinifiedCss     = releaseMode;
            ApplicationServices.EnableCombinedCss     = releaseMode;
            BlobFactoryConfig.Initialize();
        }
Exemplo n.º 3
0
        protected internal override void Render(HtmlTextWriter writer)
        {
            XhtmlConformanceSection xhtml = WebConfigurationManager.GetSection("system.web/xhtmlConformance") as XhtmlConformanceSection;

            if (xhtml != null && xhtml.Mode == XhtmlConformanceMode.Legacy)
            {
                base.Render(writer);
            }
            else
            {
                writer.WriteBeginTag(TagName);
                RenderAttributes(writer);
                writer.Write("/>");
            }
        }
    void context_Error(object sender, EventArgs e)
    {
        var error = HttpContext.Current.Server.GetLastError() as HttpException;

        if (error.GetHttpCode() == 404)
        {
            //use web.config to find where we need to redirect
            var config = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors");
            context.Response.StatusCode = 404;

            string requestedUrl    = HttpContext.Current.Request.RawUrl;
            string urlToRedirectTo = config.Errors["404"].Redirect;
            HttpContext.Current.Server.Transfer(urlToRedirectTo + "&errorPath=" + requestedUrl);
        }
    }
Exemplo n.º 5
0
        public virtual void Initialize()
        {
            ApplicationServices.FrameworkAppName = "ARHuman";
            ApplicationServices.Version          = "8.9.4.139";
            ApplicationServices.JqmVersion       = "1.4.6";
            ApplicationServices.HostVersion      = "1.2.5.0";
            var compilation = ((CompilationSection)(WebConfigurationManager.GetSection("system.web/compilation")));
            var releaseMode = !compilation.Debug;

            AquariumExtenderBase.EnableMinifiedScript = releaseMode;
            AquariumExtenderBase.EnableCombinedScript = releaseMode;
            ApplicationServices.EnableMinifiedCss     = releaseMode;
            ApplicationServices.EnableCombinedCss     = releaseMode;
            BlobFactoryConfig.Initialize();
        }
Exemplo n.º 6
0
 internal static RazorWebSectionGroup GetRazorSection(string virtualPath)
 {
     // Get the individual sections (we can only use GetSection in medium trust) and then reconstruct the section group
     return(new RazorWebSectionGroup()
     {
         Host = (HostSection)WebConfigurationManager.GetSection(
             HostSection.SectionName,
             virtualPath
             ),
         Pages = (RazorPagesSection)WebConfigurationManager.GetSection(
             RazorPagesSection.SectionName,
             virtualPath
             )
     });
 }
Exemplo n.º 7
0
        public void Init(HttpApplication app)
        {
            originalFormsAuthenticationModule = new System.Web.Security.FormsAuthenticationModule();
            var t = originalFormsAuthenticationModule.GetType();

            originalFormsAuthenticationModuleOnEnter = t.GetMethod("OnEnter", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(Object), typeof(EventArgs) }, null);
            originalFormsAuthenticationModuleOnLeave = t.GetMethod("OnLeave", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(Object), typeof(EventArgs) }, null);
            if (originalFormsAuthenticationModuleOnEnter == null || originalFormsAuthenticationModuleOnLeave == null)
            {
                throw new Exception("Unable to get all required FormsAuthenticationModule entrypoints using reflection.");
            }
            app.AuthenticateRequest += (source, e) =>
            {
                formsAuthenticationEnabled = false;
                var context = ((HttpApplication)source).Context;
                config = WebConfigurationManager.GetSection(FormsAuthConfigurationSection.ConfigurationSectionName, context.Request.Path) as FormsAuthConfigurationSection;
                if (config == null || !config.FormsAuthenticationEnabled)
                {
                    return;
                }
                if (!IsFormsAuthEnabled(context))
                {
                    return;
                }
                formsAuthenticationEnabled = true;
                originalFormsAuthenticationModuleOnEnter.Invoke(originalFormsAuthenticationModule, new [] { source, e });
            };
            app.PostAuthenticateRequest += (source, e) =>
            {
                var context = ((HttpApplication)source).Context;
                if (!formsAuthenticationEnabled && context.User == null && config != null && config.WindowsAuthenticationEnabled)
                {
                    var iisIdentity = context.Request.LogonUserIdentity;
                    if (iisIdentity != null)
                    {
                        context.User = iisIdentity.IsAnonymous ? new WindowsPrincipal(WindowsIdentity.GetAnonymous()) : new WindowsPrincipal(iisIdentity);
                    }
                }
            };
            app.EndRequest += (source, e) =>
            {
                if (!formsAuthenticationEnabled)
                {
                    return;
                }
                originalFormsAuthenticationModuleOnLeave.Invoke(originalFormsAuthenticationModule, new [] { source, e });
            };
        }
        /// <summary>
        /// System.Configuration.Provider.ProviderBase.Initialize Method
        /// </summary>
        public override void Initialize(string name, NameValueCollection config)
        {
            // Initialize values from web.config.
            if (config == null)
            {
                throw new ArgumentNullException("config", Properties.Resources.ErrArgumentNull);
            }

            if (string.IsNullOrEmpty(name))
            {
                name = Properties.Resources.SessionStoreProviderDefaultName;
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", Properties.Resources.SessionStoreProviderDefaultDescription);
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            m_applicationName = PgMembershipProvider.GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);

            // Get connection string.
            m_connectionString = PgMembershipProvider.GetConnectionString(config["connectionStringName"]);

            // Get <sessionState> configuration element.
            m_config = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

            // Should automatic session garbage collection be turned on?
            bool enableExpiredSessionAutoDeletion = Convert.ToBoolean(PgMembershipProvider.GetConfigValue(config["enableExpiredSessionAutoDeletion"], "false"), CultureInfo.InvariantCulture);

            if (!enableExpiredSessionAutoDeletion)
            {
                return;
            }

            m_enableExpireCallback = Convert.ToBoolean(PgMembershipProvider.GetConfigValue(config["enableSessionExpireCallback"], "false"), CultureInfo.InvariantCulture);

            // Load session garbage collection configuration and setup garbage collection interval timer
            double expiredSessionAutoDeletionInterval = Convert.ToDouble(PgMembershipProvider.GetConfigValue(config["expiredSessionAutoDeletionInterval"], "1800000"), CultureInfo.InvariantCulture); //default: 30 minutes

            m_expiredSessionDeletionTimer           = new System.Timers.Timer(expiredSessionAutoDeletionInterval);
            m_expiredSessionDeletionTimer.Elapsed  += new System.Timers.ElapsedEventHandler(ExpiredSessionDeletionTimer_Elapsed);
            m_expiredSessionDeletionTimer.Enabled   = true;
            m_expiredSessionDeletionTimer.AutoReset = true;
        }
Exemplo n.º 9
0
        public ActionResult LogOn(LogOn model, string returnUrl)
        {
            IUsersRepository usersRepository = new UsersRepository(db);
            IRolesRepository rolesRepository = new RolesRepository(db);

            if (ModelState.IsValid)
            {
                if (usersRepository.ValidateUser(model.UserName, model.Password))
                {
                    string[] roles    = rolesRepository.GetRoleNamesByUsername(model.UserName);
                    string   userData = String.Join(", ", roles);

                    User user = usersRepository.GetUserByUsername(model.UserName);

                    userData += "|" + user.UserPK;

                    double sessionMinutes = ((SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState")).Timeout.TotalMinutes;

                    FormsAuthenticationTicket fAuthTicket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(sessionMinutes), model.RememberMe, userData, FormsAuthentication.FormsCookiePath);
                    string     hashCookies = FormsAuthentication.Encrypt(fAuthTicket);
                    HttpCookie cookie      = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
                    Response.Cookies.Add(cookie);

                    IUserActivitiesRepository userActivitiesRepository = new UserActivitiesRepository(db);

                    UserActivity userActivity = UserActivityView.LogUserActivity(user.UserPK, "Ulazak u sustav.", DateTime.Now);

                    userActivitiesRepository.Add(userActivity);
                    userActivitiesRepository.SaveChanges();

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "ToDoList"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Kriva kombinacija korisničkog imena i lozinke.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 10
0
        private void InitializeUserIdentity(string username)
        {
            string             authenticationType;
            AuthenticationMode authenticationMode = ((AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication")).Mode;

            switch (authenticationMode)
            {
            case AuthenticationMode.Forms:
                authenticationType = authenticationMode.ToString();
                break;

            default:
                throw new UnsupportedAuthenticationType();
            }
            identity = new GenericIdentity(username, authenticationType);
        }
Exemplo n.º 11
0
        public void Initialize()
        {
            // seems like IIS re-creates this object every time a session-requiring request is made
            // we don't want to overwrite the providers list if it's already populated
            // Providers is a class variable so it will persist
            if (Providers != null)
            {
                return;
            }

            var stateConfig = WebConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;

            Providers = stateConfig.StateConnectionString.Split(';').Select(StateServer.FromAddress).ToArray();

            Log.Info("Initialized HeartbeatPartitionProvider with {0} provider(s)", Providers.Length);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates the authentication header.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="date">The date.</param>
        /// <param name="querystring">The querystring.</param>
        /// <param name="routingUrl">The routing URL.</param>
        /// <example>
        /// <code>
        /// 2015-10-27 20:21:47.5215 RESTAPIWrapperClinet DEBUG  Client side token mxPc48qN5MVe2ZVOU4DdlaQklAt39Ac6rRbtJRr/16s=
        /// 2015-10-27 20:21:47.5675 RESTAPIWrapperClinet DEBUG  请求 GET URL:http://localhost:3956//api/Employee/?BirthDate=0001%2f1%2f1+0%3a00%3a00&ContactID=0&CurrentFlag=False&HireDate=0001%2f1%2f1+0%3a00%3a00&ModifiedDate=0001%2f1%2f1+0%3a00%3a00&pageIndex=1&pageSize=5&rowguid=00000000-0000-0000-0000-000000000000&SalariedFlag=False&SickLeaveHours=0&VacationHours=0  结果:True
        /// </code>
        /// </example>
        private void CreateAuthenticationHeader(HttpClient client, string date, string querystring, string routingUrl, HttpMethod httpMethod)
        {
            string message = string.Join("\n", httpMethod.Method, date, routingUrl.ToLower(), querystring);

            Hashtable remoteDataSource =
                (Hashtable)WebConfigurationManager.GetSection(this.Section);
            string password = (string)remoteDataSource["password"];

            string token = HashManager.ComputeHash(password, message);

            //log.DebugFormat("Client side token {0}", token);
            client.DefaultRequestHeaders.Remove("Authentication");
            client.DefaultRequestHeaders.Remove("Timestamp");
            client.DefaultRequestHeaders.Add("Authentication", string.Format("{0}:{1}", password, token));
            client.DefaultRequestHeaders.Add("Timestamp", date);
        }
Exemplo n.º 13
0
        public static XmlElement RootElement()
        {
            XmlElement xe = WebConfigurationManager.GetSection(Constants.ConfigRootName) as XmlElement;

            if (xe == null)
            {
                throw new MissingRootTagException();
            }

            if (xe.Name != Constants.ConfigRootName)
            {
                throw new UnknownRootTagException(xe.Name);
            }

            return(xe);
        }
Exemplo n.º 14
0
        public static ReportInitializerSection GetReportInitializerSection()
        {
            //var section = WebConfigurationManager.GetSection("Nat.WebReportManager/ReportInitializer") as ReportInitializerSection;
            //var section = WebConfiguration == null ? WebConfigurationManager.GetSection("Nat.WebReportManager/ReportInitializer") as ReportInitializerSection : WebConfiguration.GetSection("Nat.WebReportManager/ReportInitializer") as ReportInitializerSection;
            var WebConfiguration = ((IWebConfiguration)SpecificInstances.DbFactory).WebConfiguration;
            var section          = WebConfiguration == null
             ? WebConfigurationManager.GetSection("Nat.WebReportManager/ReportInitializer") as ReportInitializerSection
            : WebConfiguration.GetSection("Nat.WebReportManager/ReportInitializer")
                                   as ReportInitializerSection;

            if (section == null)
            {
                throw new Exception("Config not containt ReportInitializer section");
            }
            return(section);
        }
Exemplo n.º 15
0
        public void Init(HttpApplication app)
        {
            this.app = app;
            app.PostMapRequestHandler += OnEnter;
            app.EndRequest            += OnLeave;

            AnonymousIdentificationSection anonymousConfig =
                (AnonymousIdentificationSection)WebConfigurationManager.GetSection("system.web/anonymousIdentification");

            if (anonymousConfig == null)
            {
                return;
            }

            anonymousCookieName = anonymousConfig.CookieName;
        }
Exemplo n.º 16
0
        public static ConfigurationSection Read(string section)
        {
            ConfigurationSection config = null;

            try {
                if (!reading)
                {
                    reading = true;
                    config  = WebConfigurationManager.GetSection(section) as ConfigurationSection;
                    reading = false;
                }
            } catch (Exception) {
                // Error("Fehler beim lesen der Konfiguration.", ex);
            }
            return(config);
        }
Exemplo n.º 17
0
        public override void Initialize(string name, NameValueCollection config)
        {
            this.config = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            if (String.IsNullOrEmpty(name))
            {
                name = "Session Server handler";
            }
            RemotingConfiguration.Configure(null);
            string cons = null, proto = null, server = null, port = null;

            GetConData(out proto, out server, out port);
            cons        = String.Format("{0}://{1}:{2}/StateServer", proto, server, port);
            stateServer = Activator.GetObject(typeof(RemoteStateServer), cons) as RemoteStateServer;

            base.Initialize(name, config);
        }
Exemplo n.º 18
0
        private static JSObject loadTemplate(Context context, JSObject args)
        {
            string templateName = args.GetField("0").ToString();
            var    sect         = (WebConfigurationManager.GetSection("templates") as Html.TemplateElementCollection)[templateName];

            templateName = sect.Path ?? templateName;
            templateName = validatePath(templateName);
            string templateText = "";
            var    file         = new FileStream(templateName, FileMode.Open, FileAccess.Read);

            templateText = new StreamReader(file).ReadToEnd();
            file.Close();
            var template = NiL.WBE.Html.HtmlPage.Parse(templateText);

            return(TypeProxy.Proxy(template));
        }
Exemplo n.º 19
0
        private static ISchedulerProvider CreateSchedulerProvider()
        {
            var section  = (Hashtable)WebConfigurationManager.GetSection("crystalQuartz/provider");
            var type     = Type.GetType(section["Type"].ToString());
            var provider = Activator.CreateInstance(type);

            foreach (string property in section.Keys)
            {
                if (property != "Type")
                {
                    provider.GetType().GetProperty(property).SetValue(provider, section[property], new object[] { });
                }
            }
            _schedulerProvider = (ISchedulerProvider)provider;
            return((ISchedulerProvider)provider);
        }
Exemplo n.º 20
0
        private MailService()
        {
            db     = new ClimbingContext();
            client = new SmtpClient();
            SmtpSection sect      = (SmtpSection)WebConfigurationManager.GetSection("system.net/mailSettings/smtp");
            string      emailFrom = WebConfigurationManager.AppSettings["emailFrom"];

            adFrom      = new MailAddress(emailFrom, sect.From);
            client.Host = sect.Network.Host;
            client.UseDefaultCredentials = sect.Network.DefaultCredentials;
            if (!client.UseDefaultCredentials)
            {
                client.Credentials = new NetworkCredential(sect.Network.UserName, sect.Network.Password);
            }
            client.EnableSsl = sect.Network.EnableSsl;
        }
        public IEnumerable <SelectListItem> GetTestLinksOld()
        {
            var section = WebConfigurationManager.GetSection("wopiHostSettings/sampleUrls") as Hashtable;
            var rv      = new List <SelectListItem>();

            foreach (DictionaryEntry item in section)
            {
                rv.Add(new SelectListItem
                {
                    Selected = false,
                    Text     = item.Value.ToString(),
                    Value    = item.Value.ToString()
                });
            }
            return(rv);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureCacheAdapter"/> class.
        /// </summary>
        /// <param name="name">The name of the region</param>
        /// <param name="serializationProvider"></param>
        public AzureCacheAdapter(string name)
        {
            _serializationProvider = MrCMSApplication.Get <ISerializationProvider>();
            //validate the params
            if (string.IsNullOrEmpty(name))
            {
                Log.Info("No region name specified for cache region. Using default name of 'nhibernate'");
                name = "nhibernate";
            }
            MrCMSConfigSection mrCMSSection = WebConfigurationManager.GetSection("mrcms") as MrCMSConfigSection;

            _webCache = AzureCacheFactory.Instance.GetCache(mrCMSSection == null ? "default" : mrCMSSection.CacheName);
            _name     = StripNonAlphaNumeric(name);

            //configure the cache region based on the configured settings and any relevant nhibernate settings
        }
        /// <summary>
        /// Retrieves IIS bindings, used to figure out the scheme and port the host is running on
        /// </summary>
        /// <returns></returns>
        private static IEnumerable <KeyValuePair <string, string> > GetBindings()
        {
            // Get the sites section from the AppPool.config
            var sitesSection = WebConfigurationManager.GetSection(HostingEnvironment.SiteName, HostingEnvironment.ApplicationVirtualPath, "system.applicationHost/sites");

            return((from s in sitesSection.GetCollection()
                    where (string)s["name"] == HostingEnvironment.SiteName
                    from b in s.GetCollection("bindings")
                    select new
            {
                Protocol = (string)b["protocol"],
                BindingInfo = (string)b["bindingInformation"]
            })
                   .Where(b => b.Protocol.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                   .Select(b => new KeyValuePair <string, string>(b.Protocol, b.BindingInfo.Split(':')[1])));
        }
Exemplo n.º 24
0
        public ActionResult UploadSize()
        {
            DisableAjaxRequestCachingInInternetExplorer();

            var runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");

            // Approx 100 Kb (for page content) size has been deducted because the maxRequestLength proprty is the page size,
            // not only the file upload size. Size in MB
            var maxRequestLength = (runTime.MaxRequestLength - 100) / 1024;

            TempData["maxRequestLength"] = maxRequestLength;

            var data = RenderPartialViewToString(ControllerContext, "Error/UploadSize", null);

            return(Json(new { modalView = data }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 25
0
        public void GetSection_1()
        {
            object sect1 = WebConfigurationManager.GetSection("system.web/clientTarget");
            object sect2 = WebConfigurationManager.GetSection("system.web/clientTarget");

            Assert.AreEqual(sect1, sect2, "A1");

            sect1 = WebConfigurationManager.GetSection("foo");
            Assert.IsNull(sect1);

            sect1 = WebConfigurationManager.GetSection("appSettings");
            Assert.IsNotNull(sect1, "A2");

            sect1 = WebConfigurationManager.GetSection("connectionStrings");
            Assert.IsNotNull(sect1, "A3");
        }
Exemplo n.º 26
0
        public static void Initialize()
        {
            if (initialized)
            {
                return;
            }

            lock (locker) {
                if (initialized)
                {
                    return;
                }

                AuthenticationSection            section = (AuthenticationSection)WebConfigurationManager.GetSection(authConfigPath);
                FormsAuthenticationConfiguration config  = section.Forms;

                cookieName        = config.Name;
                Timeout           = config.Timeout;
                timeout           = (int)config.Timeout.TotalMinutes;
                cookiePath        = config.Path;
                protection        = config.Protection;
                requireSSL        = config.RequireSSL;
                slidingExpiration = config.SlidingExpiration;
                cookie_domain     = config.Domain;
                cookie_mode       = config.Cookieless;
                cookies_supported = true;                 /* XXX ? */
                if (!String.IsNullOrEmpty(default_url))
                {
                    default_url = MapUrl(default_url);
                }
                else
                {
                    default_url = MapUrl(config.DefaultUrl);
                }
                enable_crossapp_redirects = config.EnableCrossAppRedirects;
                if (!String.IsNullOrEmpty(login_url))
                {
                    login_url = MapUrl(login_url);
                }
                else
                {
                    login_url = MapUrl(config.LoginUrl);
                }

                initialized = true;
            }
        }
        static SelectelStorageTransform()
        {
            try
            {
                var section = (StorageConfigurationSection)WebConfigurationManager.GetSection("storage");

                if (section == null)
                {
                    throw new Exception("Storage section not found.");
                }

                if (section.Appenders.Count == 0)
                {
                    throw new Exception("Appenders not found.");
                }

                foreach (AppenderConfigurationElement a in section.Appenders)
                {
                    var url = string.IsNullOrEmpty(a.AppendSecure) ? a.Append : a.AppendSecure;
                    if (url.StartsWith("~"))
                    {
                        throw new Exception("Only absolute cdn path supported. Can not use " + url);
                    }

                    appenders[a.Extensions + "|"] = url.TrimEnd('/') + "/";
                }

                foreach (HandlerConfigurationElement h in section.Handlers)
                {
                    if (h.Type.Equals(typeof(SelectelStorage)) && h.Name == "cdn")
                    {
                        _authPwd   = h.HandlerProperties["authPwd"].Value;
                        _authUser  = h.HandlerProperties["authUser"].Value;
                        _container = h.HandlerProperties["container"].Value;
                        _subDir    = h.HandlerProperties["subdir"].Value;

                        successInitialized = true;

                        break;
                    }
                }
            }
            catch (Exception fatal)
            {
                log.Fatal(fatal);
            }
        }
Exemplo n.º 28
0
        private string EncodePassword(string password, MembershipPasswordFormat passwordFormat, string salt)
        {
            byte [] password_bytes;
            byte [] salt_bytes;

            switch (passwordFormat)
            {
            case MembershipPasswordFormat.Clear:
                return(password);

            case MembershipPasswordFormat.Hashed:
                password_bytes = Encoding.Unicode.GetBytes(password);
                salt_bytes     = Convert.FromBase64String(salt);

                byte [] hashBytes = new byte [salt_bytes.Length + password_bytes.Length];

                Buffer.BlockCopy(salt_bytes, 0, hashBytes, 0, salt_bytes.Length);
                Buffer.BlockCopy(password_bytes, 0, hashBytes, salt_bytes.Length, password_bytes.Length);

                MembershipSection section  = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
                string            alg_type = section.HashAlgorithmType;
                if (alg_type == "")
                {
                    MachineKeySection keysection = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");
                    alg_type = keysection.Validation.ToString();
                }
                using (HashAlgorithm hash = HashAlgorithm.Create(alg_type)) {
                    hash.TransformFinalBlock(hashBytes, 0, hashBytes.Length);
                    return(Convert.ToBase64String(hash.Hash));
                }

            case MembershipPasswordFormat.Encrypted:
                password_bytes = Encoding.Unicode.GetBytes(password);
                salt_bytes     = Convert.FromBase64String(salt);

                byte [] buf = new byte [password_bytes.Length + salt_bytes.Length];

                Array.Copy(salt_bytes, 0, buf, 0, salt_bytes.Length);
                Array.Copy(password_bytes, 0, buf, salt_bytes.Length, password_bytes.Length);

                return(Convert.ToBase64String(EncryptPassword(buf)));

            default:
                /* not reached.. */
                return(null);
            }
        }
Exemplo n.º 29
0
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
            //Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty is the page size, not only the file upload size
            int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

            //This code is used to check the request length of the page and if the request length is greater than
            //MaxRequestLength then retrun to the same page with extra query string value action=exception

            HttpContext context = ((HttpApplication)sender).Context;

            if (context.Request.ContentLength > maxRequestLength)
            {
                IServiceProvider  provider      = (IServiceProvider)context;
                HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

                // Check if body contains data
                if (workerRequest.HasEntityBody())
                {
                    // get the total body length
                    int requestLength = workerRequest.GetTotalEntityBodyLength();
                    // Get the initial bytes loaded
                    int initialBytes = 0;
                    if (workerRequest.GetPreloadedEntityBody() != null)
                    {
                        initialBytes = workerRequest.GetPreloadedEntityBody().Length;
                    }
                    if (!workerRequest.IsEntireEntityBodyIsPreloaded())
                    {
                        byte[] buffer = new byte[512000];
                        // Set the received bytes to initial bytes before start reading
                        int receivedBytes = initialBytes;
                        while (requestLength - receivedBytes >= initialBytes)
                        {
                            // Read another set of bytes
                            initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);

                            // Update the received bytes
                            receivedBytes += initialBytes;
                        }
                        initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
                    }
                }
                // Redirect the user to the same page with querystring action=exception.
                context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a description of the service hosted.
        /// </summary>
        /// <param name="implementedContracts">
        /// The <see cref="IDictionary&lt;TKey,TValue&gt;"/> with key pairs of
        /// type (string, <see cref="ContractDescription"/>) that contains the
        /// keyed-contracts of the hosted service that have been implemented.
        /// </param>
        /// <returns>A <see cref="ServiceDescription"/> of the hosted service.</returns>
        protected override ServiceDescription CreateDescription(out IDictionary <string, ContractDescription> implementedContracts)
        {
            try
            {
                Type domainServiceType         = this._domainServiceDescription.DomainServiceType;
                ServiceDescription serviceDesc = ServiceDescription.GetService(domainServiceType);

                implementedContracts = new Dictionary <string, ContractDescription>();

                DomainServicesSection config = (DomainServicesSection)WebConfigurationManager.GetSection("system.serviceModel/domainServices");
                if (config == null)
                {
                    // Make sure we have a config instance, as that's where we put our default configuration. If we don't do this, our
                    // binary endpoint won't be used when someone doesn't have a <domainServices/> section in their web.config.
                    config = new DomainServicesSection();
                    config.InitializeDefaultInternal();
                }

                foreach (ProviderSettings provider in config.Endpoints)
                {
                    DomainServiceEndpointFactory endpointFactory = DomainServiceHost.CreateEndpointFactoryInstance(provider);
                    foreach (ServiceEndpoint endpoint in endpointFactory.CreateEndpoints(this._domainServiceDescription, this))
                    {
                        string contractName = endpoint.Contract.ConfigurationName;

                        ContractDescription contract;
                        if (implementedContracts.TryGetValue(contractName, out contract) && contract != endpoint.Contract)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resource.DomainServiceHost_DuplicateContractName, contract.ConfigurationName));
                        }

                        // Register the contract.
                        implementedContracts[endpoint.Contract.ConfigurationName] = endpoint.Contract;

                        // Register the endpoint.
                        serviceDesc.Endpoints.Add(endpoint);
                    }
                }

                return(serviceDesc);
            }
            catch (Exception ex)
            {
                DiagnosticUtility.ServiceException(ex);
                throw;
            }
        }