/// <summary>
        /// Raises the <see cref="E:Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            if (!String.IsNullOrEmpty(Request.QueryString["guid"]) && !IsPostBack)
            {
                WebSiteControllerRule rule = WebSiteControllerConfig.GetRule(this.Page.Request.QueryString["guid"]);
                this.OriginalUrlTextBox.Text = rule.Properties["OriginalUrl"].ToString();
                //this.SemanticUrlTextBox.Text = rule.Properties["SemanticUrl"].ToString();
            }
            //TODO Button Dialog Update
            else
            {
                try
                {
                    SubscriptionModule module = new SubscriptionModule();
                    Uri url = new Uri(this.Page.Request.QueryString["Source"].ToString());

                    if (WebSiteControllerConfig.IsPageControlled(url, module.RuleType))
                    {
                        System.Collections.Generic.List <WebSiteControllerRule> rules = WebSiteControllerConfig.GetRulesForPage(SPContext.Current.Site.WebApplication, url, module.RuleType);
                        WebSiteControllerRule rule = rules[rules.Count - 1];
                        this.OriginalUrlTextBox.Text = rule.Properties["OriginalUrl"].ToString();
                        //this.SemanticUrlTextBox.Text = rule.Properties["SemanticUrl"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
        }
Esempio n. 2
0
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            pnl_wait.Attributes["style"] = "";
            SemanticModule mod = new SemanticModule();

            Uri baseUri = new Uri(SPContext.Current.Site.Url, UriKind.RelativeOrAbsolute);
            Uri url     = new Uri(baseUri, tbx_url.Text); ////WebSiteControllerModule.GetFullUrl(application.Context);

            if (!WebSiteControllerConfig.HasRule(SPContext.Current.Site.WebApplication, url, mod.RuleType))
            {
                CreateWorkItem(tbx_url.Text);
                System.Threading.Thread.Sleep((_seconds * 1000));
                SPUtility.Redirect(Request.RawUrl, (SPRedirectFlags.DoNotEncodeUrl | SPRedirectFlags.Trusted), HttpContext.Current);
            }
            else
            {
                WebSiteControllerRule rule = WebSiteControllerConfig.GetRule(SPContext.Current.Site.WebApplication, url, mod.RuleType);
                lbl_error.Visible = true;

                if (rule != null && rule.Properties.ContainsKey("OriginalUrl"))
                {
                    lbl_error.InnerHtml = "This url is alreay in use by <a target=\"_blank\" href=\"" + rule.Properties["OriginalUrl"].ToString() + "\" >" + rule.Properties["OriginalUrl"].ToString() + "</a>";
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Raises the <see cref="E:Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            if (!String.IsNullOrEmpty(Request.QueryString["guid"]) && !IsPostBack)
            {
                WebSiteControllerRule rule = WebSiteControllerConfig.GetRule(this.Page.Request.QueryString["guid"]);
                this.tbx_LicenseDomain.Text = rule.Properties["LicenseDomain"].ToString();
                this.txb_LicenseFile.Text   = rule.Properties["LicenseFile"].ToString();
            }
            //TODO Button Dialog Update
            else
            {
                try
                {
                    LicenseModule module = new LicenseModule();
                    Uri           url    = new Uri(this.Page.Request.QueryString["Source"].ToString());

                    if (WebSiteControllerConfig.IsPageControlled(url, module.RuleType))
                    {
                        System.Collections.Generic.List <WebSiteControllerRule> rules = WebSiteControllerConfig.GetRulesForPage(SPAdministrationWebApplication.Local, url, module.RuleType);
                        WebSiteControllerRule rule = rules[rules.Count - 1];
                        this.tbx_LicenseDomain.Text = rule.Properties["LicenseDomain"].ToString();
                        this.txb_LicenseFile.Text   = rule.Properties["LicenseFile"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
        }
        /// <summary>
        /// Sets the inital values of controls
        /// </summary>
        /// <param name="e">Event arguments</param>
        protected override void OnLoad(EventArgs e)
        {
            this.webAppUrlLabel.Text = this.Site.Url + "/";

            if (_guid != Guid.Empty)
            {
                if (!IsPostBack)
                {
                    this._rule = WebSiteControllerConfig.GetRule(SPContext.Current.Site.WebApplication, _guid);

                    this.pageTextBox.Text             = this._rule.Page;
                    this.disabledCheckBox.Checked     = this._rule.IsDisabled;
                    this.appliesToSslCheckBox.Checked = this._rule.AppliesToSsl;
                    this.sequenceTextBox.Text         = this._rule.Sequence.ToString(CultureInfo.CurrentCulture);
                    this.principalTextBox.Text        = this._rule.Principal;
                    if (!String.IsNullOrEmpty(this._rule.Principal))
                    {
                        this.principalTypeSection.Visible = true;
                        if (this._rule.PrincipalType == WebSiteControllerPrincipalType.User)
                        {
                            this.principalTypeList.SelectedValue = "User";
                        }
                        else
                        {
                            this.principalTypeList.SelectedValue = "Group";
                        }
                    }

                    //this.ruleTypeLabel.Text = this.rule.ShortRuleType;
                }
            }
            else
            {
                //this.pageTextBox.Text = this._rule.Page.Replace(this.Site.Url + "/", String.Empty);
                this.appliesToSslCheckBox.Checked = true;
                this.sequenceTextBox.Text         = WebSiteControllerConfig.Rules.Count.ToString(CultureInfo.CurrentCulture);
                //this.ruleTypeLabel.Text = _ruletype;
            }

            /*
             * if (_SimpleView)
             * {
             *  ControlCollection controls = this.propertiesPlaceholder.Controls;
             *  foreach (Control ctrl in controls)
             *  {
             *      ctrl.Visible = false;
             *  }
             * }
             */
            if (_event == "Save")
            {
                SaveRule();
            }

            if (_event == "Delete")
            {
                DeleteRule();
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Binds to selected row and sends the id cell (0) to
        /// Utils.DeleteEntry for deletion based in the entryID
        /// </summary>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            pnl_wait.Attributes["style"] = "";
            Button      btn    = (Button)sender;
            GridViewRow grdRow = (GridViewRow)btn.Parent.Parent;

            Guid id = new Guid(grdRow.Cells[0].Text);

            SPSite site = SPContext.Current.Site;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                try
                {
                    Guid siteId = site.ID;
                    Guid webId  = SPContext.Current.Web.ID;
                    int itemId  = SPContext.Current.ItemId;

                    WebSiteControllerRule rule = WebSiteControllerConfig.GetRule(site.WebApplication, id);

                    using (SPSite wsite = new SPSite(siteId))
                    {
                        site.AddWorkItem(
                            Guid.NewGuid(),
                            DateTime.Now.ToUniversalTime(),
                            WebSiteControllerRuleWorkItem.WorkItemTypeId,
                            webId,
                            siteId,
                            itemId,
                            true,
                            rule.Id,
                            Guid.Empty,
                            site.SystemAccount.ID,
                            null,
                            string.Empty,
                            Guid.Empty
                            );
                    }

                    /*
                     * rule.Delete();
                     * rule.Unprovision();
                     * rule.Uncache();
                     */
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }
            });

            Response.Redirect(Request.RawUrl, true);
        }
Esempio n. 6
0
        void WebSiteControllerModule_OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            LanguageModule module = new LanguageModule();

            application = sender as HttpApplication;
            Uri url = WebSiteControllerModule.GetFullUrl(application.Context);

            string host_ip = application.Request.UserHostAddress;

            if (WebSiteControllerConfig.IsPageControlled(url, module.RuleType))
            {
                System.Collections.Generic.List <WebSiteControllerRule> rules = WebSiteControllerConfig.GetRulesForPage(SPContext.Current.Site.WebApplication, url, module.RuleType);
                WebSiteControllerRule rule = rules[rules.Count - 1];
                string OriginalUrl         = rule.Properties["OriginalUrl"].ToString();

                string httpsAdjustedUrl = rule.Url;
                if (url.ToString().StartsWith("https:", StringComparison.InvariantCultureIgnoreCase))
                {
                    httpsAdjustedUrl = httpsAdjustedUrl.Replace("http", "https");
                }

                Match match = new Regex(httpsAdjustedUrl).Match(url.ToString());
                if (match.Groups.Count > 1)
                {
                    string[] matches = new string[match.Groups.Count - 1];
                    for (int i = 1; i < match.Groups.Count; i++)
                    {
                        matches[i - 1] = match.Groups[i].Value;
                    }

                    OriginalUrl = String.Format(OriginalUrl, matches);
                }

                application.Context.RewritePath(OriginalUrl);
            }
            else
            {
                //String NewRule = this.Rewrite(url);
                //WebSiteControllerConfig.AddRule()
                //Forward against the new Rule
                //this.application.Context.RewritePath(NewRule);
            }
        }
Esempio n. 7
0
        private void GetFileContents(bool authenticated, Stream stream, HttpContext context, SPSite site, SPWeb web)
        {
            SPFile file = null;

            try
            {
                file = web.GetFile(this.VirtualPath);
            }
            catch { };

            if (file != null && file.Exists)
            {
                try
                {
                    byte[] binFile = null;
                    string content = string.Empty;

                    if (file.InDocumentLibrary)
                    {
                        SPListItem listItem = file.ListItemAllFields;

                        int  versionId  = 0;
                        bool versioning = file.DocumentLibrary.EnableVersioning;
                        SPFileVersionCollection versions = null;

                        if (versioning)
                        {
                            if (versioning && !authenticated && file.Level != SPFileLevel.Published && file.MajorVersion > 0)
                            {
                                versions = file.Versions;

                                try
                                {
                                    foreach (SPFileVersion version in versions)
                                    {
                                        if (version.Level == SPFileLevel.Published)
                                        {
                                            if (versionId <= version.ID)
                                            {
                                                versionId = version.ID;
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }

                        string url = file.ServerRelativeUrl;

                        NameValueCollection queryString = context.Request.QueryString;
                        StringBuilder       builder     = new StringBuilder();
                        bool NoKeys = !queryString.HasKeys();

                        if (versionId > 0)
                        {
                            bool NoVersion = true;

                            foreach (string key in queryString.AllKeys)
                            {
                                if (key != null)
                                {
                                    //NoKeys = false;
                                    var value = queryString[key];
                                    if (key != "PageVersion")
                                    {
                                        builder.Append((NoKeys) ? "?" : "&" + key + "=" + value);
                                    }
                                    else
                                    {
                                        NoVersion = false;
                                    }
                                }
                            }

                            if (NoVersion)
                            {
                                builder.Append((NoKeys) ? "?" : "&");
                                builder.Append("PageVersion=" + versionId.ToString());
                                url = context.Request.Url.AbsolutePath + builder.ToString();
                                context.RewritePath(url);
                            }
                        }

                        /*
                         * else if (file.MajorVersion > 0 && !authenticated)
                         * {
                         *  int count = versions.Count;
                         *
                         *  for (int i = count; i > 0; i--)
                         *  {
                         *      try
                         *      {
                         *          if (versions[i].Level == SPFileLevel.Published)
                         *          {
                         *              builder.Append((NoKeys) ? "?" : "&");
                         *              builder.Append("PageVersion=" + versions[i].ID.ToString());
                         *              url = context.Request.Url.AbsolutePath + builder.ToString();
                         *              context.RewritePath(url);
                         *              break;
                         *          }
                         *      }
                         *      catch { };
                         *
                         *  }
                         * }
                         */

                        if (versionId == 0 && !authenticated && versioning && file.Level != SPFileLevel.Published)// && !(file.MajorVersion > 0))
                        {
                            WebSiteControllerRule rule = WebSiteControllerConfig.GetRule("ErrorCode", "403");
                            string page = rule.Properties["ErrorPage"].ToString();
                            context.Response.Redirect("~/" + page + "?aspxerrorpath=" + url, false);
                        }

                        if (listItem != null)
                        {
                            PublishingPageDesignFieldValue value = null;
                            SPFile pageLayoutFile = null;
                            SPWeb  rootWeb        = null;
                            try
                            {
                                if (listItem.Fields.Contains(BuildFieldId.PublishingPageDesign))
                                {
                                    value = listItem[BuildFieldId.PublishingPageDesign] as PublishingPageDesignFieldValue;
                                }
                                if (value != null)
                                {
                                    rootWeb = site.RootWeb;

                                    if (rootWeb.ServerRelativeUrl != "/")
                                    {
                                        string rootsite = SPContext.Current.Site.RootWeb.Url.Replace(SPContext.Current.Site.ServerRelativeUrl, string.Empty);
                                        site    = new SPSite(rootsite);
                                        rootWeb = site.OpenWeb();
                                    }

                                    pageLayoutFile = rootWeb.GetFile(value.Id);

                                    if (pageLayoutFile != null && !pageLayoutFile.Exists)
                                    {
                                        pageLayoutFile = rootWeb.GetFile(value.Url);
                                    }
                                }
                            }
                            catch { };


                            if (pageLayoutFile != null && pageLayoutFile.Exists)
                            {
                                if (pageLayoutFile.Item.HasPublishedVersion && (rootWeb != null && rootWeb.Exists))
                                {
                                    string slayout = rootWeb.GetFileAsString(pageLayoutFile.Url);
                                    binFile = Encoding.ASCII.GetBytes(slayout);

                                    //binFile = pageLayoutFile.OpenBinary();
                                }
                                else
                                {
                                    throw (new HttpException((int)HttpStatusCode.Forbidden, this.VirtualPath));
                                }
                            }
                            else
                            {
                                string sfile = web.GetFileAsString(file.Url);
                                binFile = Encoding.ASCII.GetBytes(sfile);

                                //binFile = file.OpenBinary();
                            }
                        }
                        else
                        {
                            throw (new HttpException((int)HttpStatusCode.Gone, this.VirtualPath));
                        }
                    }
                    else
                    {
                        binFile = file.OpenBinary();
                    }
                    //}
                    //else
                    //{
                    //    throw (new HttpException((int)HttpStatusCode.Forbidden, ""));
                    //}

                    if (binFile != null && binFile.Length > 0)
                    {
                        MemoryStream m      = new MemoryStream(binFile);
                        StreamReader reader = new StreamReader(m);
                        content = reader.ReadToEnd();
                        reader.Close();
                        //m.Close();

                        StreamWriter writer = new StreamWriter(stream);

                        writer.Write(content);
                        writer.Flush();
                        stream.Seek(0, SeekOrigin.Begin);
                    }
                }
                catch (HttpException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    throw (new HttpException((int)HttpStatusCode.NotImplemented, ""));
                }
                finally
                {
                }
            }
            else
            {
                throw (new HttpException((int)HttpStatusCode.NotFound, this.VirtualPath));
            }
        }
        public string GetCallbackResult()
        {
            SPListItem listItem = SPContext.Current.ListItem;

            try
            {
                if ((listItem != null) && (listItem.File != null))
                {
                    SPFolder folder = SPContext.Current.Web.RootFolder;
                    List <WebSiteControllerRule> rules;
                    string url = SPContext.Current.Site.Url + "/";
                    WebSiteControllerRule homepage = null;

                    if (!SPContext.Current.Web.IsRootWeb)
                    {
                        url = url.TrimEnd(new char[1] {
                            '/'
                        });
                        url += SPContext.Current.Web.ServerRelativeUrl;
                    }

                    rules = WebSiteControllerConfig.GetRulesForPage(SPContext.Current.Site.WebApplication, new Uri(url));

                    foreach (WebSiteControllerRule rule in rules)
                    {
                        if (rule.Url == url)
                        {
                            homepage = rule;
                            break;
                        }
                        else
                        {
                            if (rule.Url == string.Empty)
                            {
                                try
                                {
                                    //if (string.IsNullOrEmpty(rule.ShortRuleType))
                                    //{
                                    rule.Delete();
                                    //}
                                }
                                catch (Exception ex)
                                {
                                    ex.ToString();
                                }
                            }
                        }
                    }

                    if (homepage != null)
                    {
                        CreateWorkItem(homepage, listItem.File.ServerRelativeUrl);
                    }
                    else
                    {
                        CreateWorkItem(listItem.File.ServerRelativeUrl);
                    }


                    folder.WelcomePage = listItem.File.Url;
                    folder.Update();
                }
            }
            catch (SPException exception)
            {
                base.SetGenericErrorMessage(exception);
            }

            try
            {
                SPContext.Current.Web.Title = SPContext.Current.ListItem.Title;
                SPContext.Current.Web.Update();
            }
            catch (SPException exception)
            {
                base.SetGenericErrorMessage(exception);
            }

            base.RefreshPageState();
            return(base.BuildReturnValue("HomePage has been set"));
        }
        private void CreateWorkItem(WebSiteControllerRule rule, string url)
        {
            Guid siteId = SPContext.Current.Site.ID;
            Guid webId  = SPContext.Current.Web.ID;

            if (url.StartsWith("/"))
            {
                url = url.TrimStart('/');
            }

            StringBuilder builder = new StringBuilder();

            builder.Append(SPContext.Current.Web.ServerRelativeUrl + ";");
            builder.Append(rule.IsDisabled.ToString() + ";");
            builder.Append(rule.AppliesToSsl.ToString() + ";");
            builder.Append(rule.Sequence.ToString() + ";");
            builder.Append(rule.PrincipalType + ";");
            builder.Append(rule.Principal + ";");
            builder.Append("#");
            builder.Append(String.Format("{0}:{1};", "OriginalUrl", "/" + url));

            int item = 2;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        rule.Id,
                        Guid.Empty,
                        site.SystemAccount.ID,
                        null,
                        builder.ToString(),
                        Guid.Empty
                        );
                }
            });

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteId))//, SPUserToken.SystemAccount))
                {
                    try
                    {
                        WebSiteControllerRuleWorkItem WebSiteControllerModuleJob = new WebSiteControllerRuleWorkItem(WebSiteControllerRuleWorkItem.WorkItemJobDisplayName + "HomePage", site.WebApplication);
                        SPOneTimeSchedule oneTimeSchedule = new SPOneTimeSchedule(DateTime.Now);

                        WebSiteControllerModuleJob.Schedule = oneTimeSchedule;
                        WebSiteControllerModuleJob.Update();
                    }
                    catch { };
                }
            });
        }
Esempio n. 10
0
        private void ProcessRequest(Object sender, EventArgs e)
        {
            //SemanticModule module = new SemanticModule();
            application = sender as HttpApplication;
            HttpContext context = application.Context;

            Uri url = WebSiteControllerModule.GetFullUrl(application.Context);

            if (url == null || url.AbsoluteUri.EndsWith("null"))
            {
                return;
            }

            /*
             * else
             * {
             *  if (url.DnsSafeHost == "clubcloud.kampong.nl")
             *  {
             *      System.UriBuilder builder = new UriBuilder(url);
             *      builder.Host = "kampong.clubcloud.nl";
             *      string newurl = builder.ToString();
             *
             *      try
             *      {
             *          context.RewritePath(builder.ToString());
             *      }
             *      catch(Exception ex)
             *      {
             *          ex.ToString();
             *          //context.Response.Redirect(builder.ToString());
             *      }
             *
             *  }
             * }
             */

            GateKeeperSettings gatekeeper = new GateKeeperSettings();

            gatekeeper = gatekeeper.Load();

            if (url.OriginalString.ToLower().Contains(gatekeeper.HoneyPotPath.ToLower()) && !string.IsNullOrEmpty(gatekeeper.HoneyPotPath))
            {
                return;
            }


            if (url.OriginalString.ToLower().Contains("_layouts") || url.OriginalString.ToLower().Contains("_login") || url.OriginalString.ToLower().Contains("_vti_bin") || url.OriginalString.ToLower().Contains("_catalogs") || url.OriginalString.ToLower().Contains("_windows") || url.OriginalString.ToLower().Contains("_forms") || url.OriginalString.ToLower().Contains("_trust"))
            {
                return;
            }


            try
            {
                bool handled = false;

                #region Controlled
                bool isControlled = false;

                using (SPSite site = new SPSite(url.OriginalString))
                {
                    CheckUrlOnZones(site, url, out url, out isControlled);
                }

                if (isControlled)
                {
                    using (SPSite site = new SPSite(url.OriginalString))
                    {
                        System.Collections.Generic.List <WebSiteControllerRule> rules = WebSiteControllerConfig.GetRulesForPage(site.WebApplication, url, this.RuleType);
                        WebSiteControllerRule rule = null;

                        foreach (WebSiteControllerRule arule in rules)
                        {
                            if (arule.RuleType == this.RuleType && arule.Properties.ContainsKey("OriginalUrl"))
                            {
                                if (arule.Url.ToLower() == url.ToString().ToLower() && !arule.IsDisabled)
                                {
                                    rule = arule;
                                    break;
                                }
                            }
                        }

                        if (rule != null)
                        {
                            //WebSiteControllerRule rule = rules[rules.Count - 1];
                            string OriginalUrl = rule.Properties["OriginalUrl"].ToString();

                            string httpsAdjustedUrl = rule.Url;
                            if (url.ToString().StartsWith("https:", StringComparison.InvariantCultureIgnoreCase))
                            {
                                httpsAdjustedUrl = httpsAdjustedUrl.Replace("http", "https");
                            }

                            Match match = new Regex(httpsAdjustedUrl).Match(url.ToString());
                            if (match.Groups.Count > 1)
                            {
                                string[] matches = new string[match.Groups.Count - 1];
                                for (int i = 1; i < match.Groups.Count; i++)
                                {
                                    matches[i - 1] = match.Groups[i].Value;
                                }

                                OriginalUrl = String.Format(OriginalUrl, matches);
                            }


                            if (OriginalUrl.IndexOf(".aspx") >= 1)
                            {
                                if (CheckIfExists(OriginalUrl, url))
                                {
                                    application.Context.RewritePath("~/" + welcomepage);
                                }
                                else
                                {
                                    application.Server.ClearError();
                                    application.Response.StatusCode = (int)HttpStatusCode.NotFound;
                                    throw (new HttpException((int)HttpStatusCode.NotFound, ""));
                                }
                            }

                            //application.Context.RewritePath("~/" + OriginalUrl);
                            handled = true;
                        }
                        else
                        {
                            handled = false;
                        }
                    }
                }

                #endregion

                if (!handled)
                {
                    if (!application.Context.Request.Url.LocalPath.Contains("."))
                    {
                        //if (url.LocalPath.IndexOf(".aspx") >= 1)
                        //{
                        if (CheckIfExists(url.AbsolutePath, url))
                        {
                            if (islist)
                            {
                                //SPBasePermissions locked = (SPBasePermissions.ViewListItems | SPBasePermissions.Open | SPBasePermissions.ViewPages | SPBasePermissions.UseClientIntegration);
                                //SPBasePermissions permission = site.OpenWeb().AnonymousPermMask64;

                                //if ((locked != permission) || context.User.Identity.IsAuthenticated)
                                //{
                                application.Context.Response.Redirect("~/" + welcomepage, false);
                                //}
                                //else
                                //{
                                //    application.Server.ClearError();
                                //    application.Response.StatusCode = (int)HttpStatusCode.NotFound;
                                //    throw (new HttpException((int)HttpStatusCode.NotFound, ""));
                                //}
                            }
                            else
                            {
                                if (isweb)
                                {
                                    try
                                    {
                                        //application.Context.RewritePath("~/" + site.RootWeb.RootFolder.WelcomePage);

                                        //SPWeb cweb = SPContext.Current.Web;
                                        //SPFolder croot = cweb.RootFolder;
                                        //string cwelcome = croot.WelcomePage;
                                        //SPSecurity.RunWithElevatedPrivileges(delegate()
                                        //{
                                        using (SPSite site = new SPSite(url.OriginalString))
                                        {
                                            using (SPWeb web = site.OpenWeb())
                                            {
                                                SPFolder root        = web.RootFolder;
                                                string   welcomepage = string.Empty;
                                                if (root.Exists)
                                                {
                                                    welcomepage = root.WelcomePage;
                                                }
                                                else
                                                {
                                                    welcomepage = web.RootFolder.WelcomePage;
                                                }
                                                if (issubcollection)
                                                {
                                                    welcomepage = SPUtility.ConcatUrls(web.ServerRelativeUrl, welcomepage);
                                                }
                                                application.Context.RewritePath("~/" + welcomepage);
                                            }
                                        }
                                        //});
                                    }
                                    catch (Exception ex)
                                    {
                                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                                        application.Context.RewritePath("~/" + welcomepage);
                                    }
                                }
                                else
                                {
                                    application.Context.RewritePath("~/" + welcomepage);
                                }
                            }
                        }
                        else
                        {
                            //TODO Catch SharePoint Designer requests.
                            if (SPContext.Current == null)
                            {
                                string useragent = application.Request.UserAgent;
                                if (useragent == "Microsoft Office Protocol Discovery")
                                {
                                    return;
                                }

                                application.Server.ClearError();
                                application.Response.StatusCode = (int)HttpStatusCode.NotFound;
                                throw (new HttpException((int)HttpStatusCode.NotFound, ""));
                                //return;
                            }
                            else
                            {
                                application.Server.ClearError();
                                application.Response.StatusCode = (int)HttpStatusCode.NotFound;
                                throw (new HttpException((int)HttpStatusCode.NotFound, ""));
                            }
                        }
                        //}
                    }
                    else
                    {
                        if (url.LocalPath.IndexOf(".aspx") >= 1)
                        {
                            if (!CheckIfExists(url.AbsolutePath, url))
                            {
                                application.Server.ClearError();
                                application.Response.StatusCode = (int)HttpStatusCode.NotFound;
                                throw (new HttpException((int)HttpStatusCode.NotFound, ""));
                            }
                            else
                            {
                                if ((url.AbsolutePath != welcomepage) && (url.AbsolutePath != "/" + welcomepage))
                                {
                                    application.Context.RewritePath("~/" + welcomepage, true);
                                }
                            }
                        }

                        /*
                         * else
                         * {
                         *  if (url.IsFile)
                         *  {
                         *      application.Server.ClearError();
                         *      application.Response.StatusCode = (int)HttpStatusCode.NotFound;
                         *      throw (new HttpException((int)HttpStatusCode.NotFound, ""));
                         *  }
                         * }
                         */
                    }
                }
            }

            catch (HttpException)
            {
                throw;
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                application.Server.ClearError();
                application.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                WebSiteControllerRule rule = WebSiteControllerConfig.GetRule("ErrorCode", "400");
                string page = rule.Properties["ErrorPage"].ToString();
                context.Response.Redirect("/" + page + "?aspxerrorpath=" + url, false);
            }
            finally
            {
            }
            //HttpContext context = application.Context;

            if (((context != null) && (context.Request != null)) && ((context.Request.Browser != null) && (context.Request.Browser.Adapters != null)))
            {
                string fullName = typeof(HtmlForm).FullName;

                if (!context.Request.Browser.Adapters.Contains(fullName))
                {
                    context.Request.Browser.Adapters[fullName] = typeof(WebSiteAdapter).AssemblyQualifiedName;
                }

                /*
                 * fullName = typeof(Page).FullName;
                 * if (!context.Request.Browser.Adapters.Contains(fullName))
                 * {
                 *  context.Request.Browser.Adapters[fullName] = typeof(WebSitePage).AssemblyQualifiedName;
                 * }
                 */
            }
        }
Esempio n. 11
0
        private void ProcessStatus(object sender, EventArgs e, bool IsError)
        {
            //ErrorModule module = new ErrorModule();

            application = sender as HttpApplication;
            bool   act  = false;
            string page = "";
            WebSiteControllerRule rule = null;

            /*
             * if (application.Context.User == null || application.Context.User.Identity.IsAuthenticated)
             * {
             *  return;
             * }
             */

            string AccessDeniedType      = string.Empty;
            string CatchAccessDeniedName = string.Empty;

            if (application.Context.Items.Contains("CatchAccessDeniedType"))
            {
                AccessDeniedType = application.Context.Items["CatchAccessDeniedType"].ToString();
            }

            if (application.Context.Items.Contains("CatchAccessDeniedName"))
            {
                CatchAccessDeniedName = application.Context.Items["CatchAccessDeniedName"].ToString();
            }

            string statuscode = "200";

            if (!String.IsNullOrEmpty(AccessDeniedType) && !String.IsNullOrEmpty(CatchAccessDeniedName))
            {
                if ((application.Context.User == null) || (!application.Context.User.Identity.IsAuthenticated))
                {
                    rule = WebSiteControllerConfig.GetRule("ErrorCode", "403");
                }
            }
            else
            {
                statuscode = application.Response.StatusCode.ToString();
            }

            try
            {
                rule = WebSiteControllerConfig.GetRule("ErrorCode", statuscode);
            }
            catch (Exception ex) { ex.ToString(); };

            if (rule != null && !rule.IsDisabled)// && IsError)
            {
                page = rule.Properties["ErrorPage"].ToString();
                act  = true;
            }


            if (act)
            {
                HandleError(page);
            }
        }
Esempio n. 12
0
        void WebSiteControllerModule_OnAuthenticateRequest(object sender, EventArgs e)
        {
            try
            {
                application = sender as HttpApplication;

                string absolutePath = application.Request.Url.AbsolutePath.ToLower();
                if (absolutePath.Contains(".dll") ||
                    absolutePath.Contains(".asmx") ||
                    absolutePath.Contains(".svc") ||
                    absolutePath.Contains("favicon.ico"))
                {
                    return;
                }

                if (application != null)
                {
                    string AccessDeniedType      = string.Empty;
                    string CatchAccessDeniedName = string.Empty;
                    WebSiteControllerRule rule   = null;
                    bool   act  = false;
                    string page = "";

                    if (application.Context.Items.Contains("CatchAccessDeniedType"))
                    {
                        AccessDeniedType = application.Context.Items["CatchAccessDeniedType"].ToString();
                    }

                    if (application.Context.Items.Contains("CatchAccessDeniedName"))
                    {
                        CatchAccessDeniedName = application.Context.Items["CatchAccessDeniedName"].ToString();
                    }

                    try
                    {
                        if (!String.IsNullOrEmpty(AccessDeniedType) && !String.IsNullOrEmpty(CatchAccessDeniedName))
                        {
                            if ((application.Context.User == null) || (!application.Context.User.Identity.IsAuthenticated))
                            {
                                rule = WebSiteControllerConfig.GetRule("ErrorCode", "403");
                            }
                        }
                    }
                    catch (Exception ex) { ex.ToString(); };

                    if (rule != null && !rule.IsDisabled)// && IsError)
                    {
                        page = rule.Properties["ErrorPage"].ToString();
                        act  = true;
                    }

                    if (act)
                    {
                        HandleError(page);
                    }

                    /*
                     * if (!application.Request.IsAuthenticated)
                     * {
                     *  application.Server.ClearError();
                     *  application.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                     *  throw (new HttpException((int)HttpStatusCode.Forbidden, ""));
                     * }
                     */
                    /*
                     * if (application.Response.StatusCode == (int)HttpStatusCode.Forbidden)
                     * {
                     *  string result = "Forbidden";
                     * }
                     */
                }
            }
            catch { return; };
        }