Exemplo n.º 1
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>";
                }
            }
        }
        /// <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();
                }
            }
        }
Exemplo 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();
                }
            }
        }
        private void CreateWebSiteConfig(SPFeatureReceiverProperties properties)
        {
            try
            {
                if (webApp != null)
                {
                    WebSiteControllerConfig config = null;
                    lock (createlock)
                    {
                        config = webApp.GetChild <WebSiteControllerConfig>(WebSiteControllerConfig.OBJECTNAME);
                        if (config == null)
                        {
                            WebSiteControllerConfig settings = new WebSiteControllerConfig(webApp, Guid.NewGuid());
                            settings.Update();
                        }
                    }

                    webApp.Update();
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                //ex.ToString();
            }
        }
Exemplo n.º 5
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"]))
            {
                _guid = new Guid(Request.QueryString["guid"]);
            }

            if (!String.IsNullOrEmpty(Request.QueryString["Source"]))
            {
                _source = Request.QueryString["Source"];
            }

            if (this.Page.Request["__EVENTTARGET"] == RibbonPostbackId)
            {
                _event = this.Page.Request["__EVENTARGUMENT"];
            }

            _modulename = this.moduleTextBox.Text;
            _assembly   = this.assemblyTextbox.Text;

            if (_event == "GoModules")
            {
                GoBack();
            }

            if (_guid != Guid.Empty)
            {
                _module = WebSiteControllerConfig.GetModule(SPContext.Current.Site.WebApplication, _guid);

                if (!IsPostBack)
                {
                    this.moduleTextBox.Text      = _module.GetType().FullName;
                    this.moduleTextBox.Enabled   = false;
                    this.assemblyTextbox.Text    = _module.GetType().AssemblyQualifiedName;
                    this.assemblyTextbox.Enabled = false;

                    this.LoadRules();
                }

                if (_event == "Delete")
                {
                    DeleteModule();
                }

                if (_event == "Rules")
                {
                    CreateRule();
                }
            }
            else
            {
                if (_event == "Save")
                {
                    SaveModule();
                }
            }
            SPContext.Current.Web.AllowUnsafeUpdates = false;
        }
        /// <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();
            }
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
        public GateKeeperSettings Load()
        {
            GateKeeperSettings config = null;
            GateKeeperModule   module = new GateKeeperModule();

            HttpContext current = HttpContext.Current;
            HttpRequest request = current.Request;

            string currUrl  = current.Request.Url.ToString();
            string basePath = currUrl.Substring(0, currUrl.IndexOf(current.Request.Url.Host) + current.Request.Url.Host.Length);
            Uri    url      = new Uri(basePath);

            List <WebSiteControllerRule> rules = WebSiteControllerConfig.GetRulesForSiteCollection(url, module.RuleType);

            foreach (WebSiteControllerRule rule in rules)
            {
                //string props = rule.Properties.ToString();

                if (rule.Properties.ContainsKey("GateKeeper"))
                {
                    if (config == null)
                    {
                        try
                        {
                            string gateconfig = rule.Properties["GateKeeper"].ToString();
                            config       = new JavaScriptSerializer().Deserialize <GateKeeperSettings>(Encryption.Decrypt(gateconfig));
                            config._guid = rule.Id;
                            break;
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                            //throw;
                        }
                    }
                }
            }
            if (config != null)
            {
                return(config);
            }
            else
            {
                return(new GateKeeperSettings());
            }
        }
Exemplo n.º 9
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);
            }
        }
Exemplo n.º 10
0
        private List <SemanticUrl> CheckForManagedUrl(SPSite site, Uri url)
        {
            List <SemanticUrl> entries = new List <SemanticUrl>();

            System.Collections.Generic.List <WebSiteControllerRule> Allrules = WebSiteControllerConfig.GetRulesForSiteCollection(new Uri(site.Url), typeof(SemanticModule).FullName);
            List <WebSiteControllerRule> rules = new List <WebSiteControllerRule>();

            foreach (WebSiteControllerRule arule in Allrules)
            {
                if (arule.RuleType == typeof(SemanticModule).FullName && arule.Properties.ContainsKey("OriginalUrl"))
                {
                    string original = arule.Properties["OriginalUrl"].ToString().ToLower();
                    string _lurl    = url.AbsolutePath.ToString().ToLower();
                    if ((original == _lurl) || (original.EndsWith(_lurl)))
                    {
                        string org = arule.Url;
                        if (org.EndsWith("/"))
                        {
                            org = org.TrimEnd(new char[1] {
                                '/'
                            });
                        }
                        if ((org != SPContext.Current.Site.Url) && (org != SPContext.Current.Web.Url))
                        {
                            SemanticUrl sem = new SemanticUrl();
                            sem.OriginalUrl = arule.Properties["OriginalUrl"].ToString().ToLower();
                            sem.Semantic    = arule.Url;
                            sem.Id          = arule.Id;
                            sem.Disabled    = arule.IsDisabled;
                            entries.Add(sem);
                        }
                    }
                }
            }
            entries.Sort(SemanticUrl.UrlComparison);
            return(entries);
        }
Exemplo n.º 11
0
        private void CreateWorkItem(string url)
        {
            Guid siteId = SPContext.Current.Site.ID;
            Guid webId  = SPContext.Current.Web.ID;

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append(url + ";");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            builder.Append(String.Format("{0}:{1};", "OriginalUrl", _url));

            string full = builder.ToString();

            SemanticModule           mod  = new SemanticModule();
            IWebSiteControllerModule imod = null;// WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);

            while (imod == null)
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    imod = WebSiteControllerConfig.GetModule(SPContext.Current.Site.WebApplication, mod.RuleType);
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }
            }


            int item = -1;

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

                SPJobDefinitionCollection jobs = SPContext.Current.Site.WebApplication.JobDefinitions;

                foreach (SPJobDefinition job in jobs)
                {
                    if (job.Name == WebSiteControllerRuleWorkItem.WorkItemJobDisplayName)
                    {
                        try
                        {
                            DateTime next = job.Schedule.NextOccurrence(job.LastRunTime);
                            _seconds      = next.Second;
                            break;
                        }
                        catch (Exception ex)
                        {
                            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                            //ex.ToString();
                        }
                    }
                }
            });
        }
Exemplo n.º 12
0
        private void CheckUrlOnZones(SPSite site, Uri curl, out Uri url, out bool isControlled, string RuleType)
        {
            Uri zoneUri = curl;

            isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, zoneUri, RuleType);
            UriBuilder builder = new UriBuilder(curl);

            if (!isControlled)
            {
                try
                {
                    zoneUri      = site.WebApplication.GetResponseUri(SPUrlZone.Default);
                    builder.Host = zoneUri.Host;
                    builder.Port = zoneUri.Port;
                    isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, builder.Uri, RuleType);
                    zoneUri      = builder.Uri;
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            if (!isControlled)
            {
                try
                {
                    zoneUri      = site.WebApplication.GetResponseUri(SPUrlZone.Internet);
                    builder.Host = zoneUri.Host;
                    builder.Port = zoneUri.Port;
                    isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, builder.Uri, RuleType);
                    zoneUri      = builder.Uri;
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            if (!isControlled)
            {
                try
                {
                    zoneUri      = site.WebApplication.GetResponseUri(SPUrlZone.Extranet);
                    builder.Host = zoneUri.Host;
                    builder.Port = zoneUri.Port;
                    isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, builder.Uri, RuleType);
                    zoneUri      = builder.Uri;
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            if (!isControlled)
            {
                try
                {
                    zoneUri      = site.WebApplication.GetResponseUri(SPUrlZone.Intranet);
                    builder.Host = zoneUri.Host;
                    builder.Port = zoneUri.Port;
                    isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, builder.Uri, RuleType);
                    zoneUri      = builder.Uri;
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            if (!isControlled)
            {
                try
                {
                    zoneUri      = site.WebApplication.GetResponseUri(SPUrlZone.Custom);
                    builder.Host = zoneUri.Host;
                    builder.Port = zoneUri.Port;
                    isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, builder.Uri, RuleType);
                    zoneUri      = builder.Uri;
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            if (!isControlled)
            {
                Uri altZone = null;
                foreach (SPAlternateUrl altUrl in site.WebApplication.AlternateUrls)
                {
                    if (altUrl.UrlZone == site.Zone)
                    {
                        altZone = altUrl.Uri;
                        break;
                    }
                }

                if (altZone != null)
                {
                    builder.Host = zoneUri.Host;
                    builder.Port = zoneUri.Port;
                    isControlled = WebSiteControllerConfig.IsPageControlled(site.WebApplication, builder.Uri, RuleType);
                    zoneUri      = builder.Uri;
                }
            }
            url = zoneUri;
        }
Exemplo n.º 13
0
        private List <SemanticUrl> CheckSemantics(string _url)
        {
            SemanticModule     module  = new SemanticModule();
            List <SemanticUrl> entries = new List <SemanticUrl>();

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

            try
            {
                bool   isControlled = false;
                SPSite site         = new SPSite(url.OriginalString);
                CheckUrlOnZones(site, url, out url, out isControlled, module.RuleType);

                if (isControlled)
                {
                    System.Collections.Generic.List <WebSiteControllerRule> Allrules = WebSiteControllerConfig.GetRulesForSiteCollection(new Uri(site.Url), module.RuleType);
                    List <WebSiteControllerRule> rules = new List <WebSiteControllerRule>();

                    foreach (WebSiteControllerRule arule in Allrules)
                    {
                        if (arule.RuleType == module.RuleType && arule.Properties.ContainsKey("OriginalUrl"))
                        {
                            string original = arule.Properties["OriginalUrl"].ToString().ToLower();
                            string _lurl    = _url.ToString().ToLower();
                            if ((original == _lurl) || (original.EndsWith(_lurl)))
                            {
                                string org = arule.Url;
                                if (org.EndsWith("/"))
                                {
                                    org = org.TrimEnd(new char[1] {
                                        '/'
                                    });
                                }
                                //if ((org != SPContext.Current.Site.Url) && (org != SPContext.Current.Web.Url))
                                //{
                                SemanticUrl sem = new SemanticUrl();
                                sem.OriginalUrl = arule.Properties["OriginalUrl"].ToString().ToLower();
                                sem.Semantic    = arule.Url;
                                sem.Id          = arule.Id;
                                sem.Disabled    = arule.IsDisabled;
                                entries.Add(sem);
                                //}
                            }
                        }
                    }

                    if (entries.Count > 0)
                    {
                        entries.Sort(SemanticUrl.UrlComparison);
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return(entries);
        }
Exemplo n.º 14
0
        private void LoadRules()
        {
            string url = Site.Url;

            if (!url.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                url += "/";
            }

            TableRow headerRow = this.entriesTable.Rows[0];

            this.entriesTable.Rows.Clear();
            this.entriesTable.Rows.Add(headerRow);

            foreach (WebSiteControllerRule rule in WebSiteControllerConfig.GetRulesForSiteCollection(new Uri(url), _module.RuleType))
            {
                TableRow  row  = new TableRow();
                TableCell cell = new TableCell();
                cell.CssClass = "ms-descriptionText";
                cell.Text     = rule.ShortRuleType;
                row.Cells.Add(cell);
                cell          = new TableCell();
                cell.CssClass = "ms-descriptionText";
                HyperLink link = new HyperLink();
                link.NavigateUrl = "/_layouts/Hemrika/ManageWebSiteModuleRule.aspx?guid=" + rule.Id + "&ruletype=" + rule.RuleType + "&Source=/_layouts/Hemrika/ManageWebSiteModules.aspx?guid=" + _module.Id.ToString();
                link.Text        = rule.Url.ToString();
                cell.Controls.Add(link);
                row.Cells.Add(cell);
                cell          = new TableCell();
                cell.CssClass = "ms-descriptionText";
                cell.Text     = String.IsNullOrEmpty(rule.Principal) ? "&nbsp" : rule.Principal;
                row.Cells.Add(cell);
                cell          = new TableCell();
                cell.CssClass = "ms-descriptionText";
                cell.Style.Add("text-align", "center");
                cell.Text = rule.PrincipalType.ToString();
                row.Cells.Add(cell);
                cell = new TableCell();
                CheckBox cb = new CheckBox();
                cb.Enabled = false;
                cb.Checked = rule.IsDisabled;
                cell.Controls.Add(cb);
                cell.HorizontalAlign = HorizontalAlign.Center;
                row.Cells.Add(cell);
                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;
                cb         = new CheckBox();
                cb.Enabled = false;
                cb.Checked = rule.AppliesToSsl;
                cell.Controls.Add(cb);
                row.Cells.Add(cell);
                cell          = new TableCell();
                cell.CssClass = "ms-descriptionText";
                cell.Style.Add("text-align", "center");
                cell.Text = rule.Sequence.ToString(CultureInfo.InvariantCulture);
                row.Cells.Add(cell);
                cell = new TableCell();
                Literal literal = new Literal();
                if (rule.Properties.Count > 0)
                {
                    cell.CssClass = "ms-descriptionText";
                    StringBuilder sb = new StringBuilder();
                    foreach (DictionaryEntry property in rule.Properties)
                    {
                        sb.Append(_module.GetFriendlyName(property.Key.ToString()) + ": " + property.Value.ToString() + "<br/>");
                    }

                    literal.Text = sb.ToString();
                }
                else
                {
                    literal.Text = "None";
                }

                cell.Controls.Add(literal);
                row.Cells.Add(cell);
                this.entriesTable.Rows.Add(row);
            }
        }
        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(string url)
        {
            Guid siteId = SPContext.Current.Site.ID;
            Guid webId  = SPContext.Current.Web.ID;

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append(SPContext.Current.Web.ServerRelativeUrl + ";");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            builder.Append(String.Format("{0}:{1};", "OriginalUrl", url));

            string full = builder.ToString();

            SemanticModule           mod  = new SemanticModule();
            IWebSiteControllerModule imod = null;// WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);

            while (imod == null)
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    imod = WebSiteControllerConfig.GetModule(SPContext.Current.Site.WebApplication, mod.RuleType);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }


            int item = -1;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        imod.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 { };
                }
            });
        }
Exemplo n.º 17
0
        private void CreateWorkItem(SPWeb web)//, HttpStatusCode code)
        {
            Guid siteId = web.Site.ID;
            Guid webId  = web.ID;

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append("/;");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            string value = new JavaScriptSerializer().Serialize(this);

            builder.Append(String.Format("{0}:{1};", "GateKeeper", Encryption.Encrypt(value)));
            //builder.Append(value);

            string full = builder.ToString();

            GateKeeperModule         mod  = new GateKeeperModule();
            IWebSiteControllerModule imod = null;  //WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);

            while (imod == null)
            {
                try
                {
                    imod = WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                System.Threading.Thread.Sleep(1000);
            }

            Guid itemGuid = _guid;
            int  item     = 0;

            if (itemGuid.Equals(Guid.Empty))
            {
                itemGuid = mod.Id;
                item     = -1;
            }
            else
            {
                item = 2;
            }

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        itemGuid,
                        Guid.Empty,
                        site.SystemAccount.ID,
                        null,
                        builder.ToString(),
                        Guid.Empty
                        );
                }
            });
        }
Exemplo n.º 18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            lbl_url.InnerText = "Semantic Url : " + SPContext.Current.Site.Url + "/";

            if (!String.IsNullOrEmpty(Request.QueryString["List"]))
            {
                _List = Request.QueryString["List"];
            }

            if (!String.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                _ID = Request.QueryString["ID"];
            }

            if (!String.IsNullOrEmpty(_List) && !String.IsNullOrEmpty(_ID))
            {
                _Guid = new Guid(_List);
                _list = SPContext.Current.Web.Lists[_Guid];

                if (_list != null)
                {
                    _url = _list.GetItemById(int.Parse(_ID)).File.ServerRelativeUrl;
                }
            }

            gridSemantic.RowDataBound += new GridViewRowEventHandler(gridSemantic_RowDataBound);

            lbl_error.Visible            = false;
            pnl_wait.Attributes["style"] = "display:none;";

            if (!IsPostBack)
            {
                SemanticModule module = new SemanticModule();


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

                try
                {
                    bool   isControlled = false;
                    SPSite site         = new SPSite(url.OriginalString);
                    CheckUrlOnZones(site, url, out url, out isControlled, module.RuleType);

                    //if (WebSiteControllerConfig.IsPageControlled(url, module.RuleType))
                    if (isControlled)
                    {
                        List <SemanticUrl> entries = new List <SemanticUrl>();

                        //SPSite site = new SPSite(url.OriginalString);

                        System.Collections.Generic.List <WebSiteControllerRule> Allrules = WebSiteControllerConfig.GetRulesForSiteCollection(new Uri(site.Url), module.RuleType);
                        List <WebSiteControllerRule> rules = new List <WebSiteControllerRule>();

                        foreach (WebSiteControllerRule arule in Allrules)
                        {
                            if (arule.RuleType == module.RuleType && arule.Properties.ContainsKey("OriginalUrl"))
                            {
                                string original = arule.Properties["OriginalUrl"].ToString().ToLower();
                                string _lurl    = _url.ToString().ToLower();
                                if ((original == _lurl))// || (original.EndsWith(_lurl)))
                                {
                                    string org = arule.Url;
                                    if (org.EndsWith("/"))
                                    {
                                        org = org.TrimEnd(new char[1] {
                                            '/'
                                        });
                                    }
                                    //if ((org != SPContext.Current.Site.Url) && (org != SPContext.Current.Web.Url))
                                    //{
                                    SemanticUrl sem = new SemanticUrl();
                                    sem.OriginalUrl = arule.Properties["OriginalUrl"].ToString().ToLower();
                                    sem.Semantic    = arule.Url;
                                    sem.Id          = arule.Id;
                                    sem.Disabled    = arule.IsDisabled;
                                    entries.Add(sem);
                                    //}
                                }
                            }
                        }

                        if (entries.Count > 0)
                        {
                            entries.Sort(SemanticUrl.UrlComparison);
                            gridSemantic.DataSource = entries;
                            gridSemantic.DataBind();
                            //Response.Write(rules.Count.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
            else
            {
                pnl_wait.Attributes["style"] = "";
            }
        }
Exemplo n.º 19
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; };
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event to initialize the page.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;

            if (!String.IsNullOrEmpty(Request.QueryString["guid"]))
            {
                _guid = new Guid(Request.QueryString["guid"]);
            }

            if (!String.IsNullOrEmpty(Request.QueryString["ruletype"]))
            {
                _ruletype = Request.QueryString["ruletype"];
            }


            if (!String.IsNullOrEmpty(Request.QueryString["Source"]))
            {
                _source = Request.QueryString["Source"];
            }

            if (this.Page.Request["__EVENTTARGET"] == RibbonPostbackId)
            {
                _event = this.Page.Request["__EVENTARGUMENT"];
            }

            if (_event == "GoModules")
            {
                GoBack();
            }

            if (!string.IsNullOrEmpty(_ruletype))
            {
                _module = WebSiteControllerConfig.GetModule(SPContext.Current.Site.WebApplication, _ruletype);
            }

            try
            {
                if (_module != null)
                {
                    if (!String.IsNullOrEmpty(_module.Control))
                    {
                        WebSiteControllerRuleControl control = (WebSiteControllerRuleControl)Page.LoadControl(_module.Control);
                        control.ID = "moduleControl";
                        if (control.SimpleView)
                        {
                            _SimpleView = control.SimpleView;

                            ControlCollection controls = this.defaultPlaceHolder.Controls;
                            foreach (Control ctrl in controls)
                            {
                                ctrl.Visible = false;
                            }
                        }

                        this.propertiesPlaceholder.Controls.Add(control);
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            SPContext.Current.Web.AllowUnsafeUpdates = false;
        }
Exemplo n.º 21
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);
            }
        }
Exemplo n.º 22
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;
                 * }
                 */
            }
        }
Exemplo n.º 23
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));
            }
        }
Exemplo n.º 24
0
        private void CreateErrorWorkItem(SPWeb web, HttpStatusCode code)
        {
            try
            {
                Guid siteId = web.Site.ID;
                Guid webId  = web.ID;

                bool disabled = false;
                WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
                bool   appliesToSSL = true;
                int    sequence     = 1;
                String pricipal     = string.Empty;

                StringBuilder builder = new StringBuilder();
                builder.Append("Error/" + code.ToString() + ".aspx;");
                builder.Append(disabled.ToString() + ";");
                builder.Append(appliesToSSL.ToString() + ";");
                builder.Append(sequence.ToString() + ";");
                builder.Append(principalType.ToString() + ";");
                builder.Append(pricipal + ";");
                builder.Append("#");

                builder.Append(String.Format("{0}:{1};", "ErrorPage", "Error/" + code.ToString() + ".aspx;"));
                builder.Append(String.Format("{0}:{1};", "ErrorCode", ((int)code).ToString()));


                string full = builder.ToString();

                ErrorModule mod = new ErrorModule();
                IWebSiteControllerModule imod = null;  //WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);

                while (imod == null)
                {
                    System.Threading.Thread.Sleep(1000);
                    try
                    {
                        imod = WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);
                    }
                    catch (Exception ex)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                        //ex.ToString();
                    }
                }

                //Guid itemGuid = new Guid("17A3219B-049F-4056-9566-37590122BE8E");
                int item = -1;

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

                try
                {
                    WebSiteControllerRuleWorkItem WebSiteControllerModuleJob = new WebSiteControllerRuleWorkItem(WebSiteControllerRuleWorkItem.WorkItemJobDisplayName + code.ToString(), web.Site.WebApplication);
                    SPOneTimeSchedule             oneTimeSchedule            = new SPOneTimeSchedule(DateTime.Now);

                    WebSiteControllerModuleJob.Schedule = oneTimeSchedule;
                    WebSiteControllerModuleJob.Update();
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                    //ex.ToString();
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }
        }
        private void CreateWorkItem(SPWeb web, string pagename, string url)
        {
            Guid siteId = web.Site.ID;
            Guid webId  = web.ID;

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

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append(url + ";");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            if (url.EndsWith("/"))
            {
                builder.Append(String.Format("{0}:{1};", "OriginalUrl", url + pagename + ".aspx"));
            }
            else
            {
                builder.Append(String.Format("{0}:{1};", "OriginalUrl", url + ".aspx"));
            }


            string full = builder.ToString();

            SemanticModule           mod  = new SemanticModule();
            IWebSiteControllerModule imod = null;

            while (imod == null)
            {
                try
                {
                    imod = WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                System.Threading.Thread.Sleep(1000);
            }


            int item = -1;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        imod.Id,
                        Guid.Empty,
                        site.SystemAccount.ID,
                        null,
                        builder.ToString(),
                        Guid.Empty
                        );
                }
            });
        }
Exemplo n.º 26
0
        private void CreateWorkItem(SPWebEventProperties properties, string pagename, string url)
        {
            Guid siteId = properties.SiteId;
            Guid webId  = properties.WebId;

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append(properties.Web.ServerRelativeUrl + url + ";");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            builder.Append(String.Format("{0}:{1};", "OriginalUrl", properties.Web.ServerRelativeUrl + pagename));

            string full = builder.ToString();

            IWebSiteControllerModule imod = null;
            SPSite parentsite             = new SPSite(properties.SiteId);

            while (imod == null)
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    imod = WebSiteControllerConfig.GetModule(parentsite.WebApplication, "Hemrika.SharePoint.WebSite.Modules.SemanticModule.SemanticModule");
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            int item = -1;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        imod.Id,
                        Guid.Empty,
                        site.SystemAccount.ID,
                        null,
                        builder.ToString(),
                        Guid.Empty
                        );
                }
            });
        }
        private void CreateWorkItem(SPWeb web, string pagename, string url)
        {
            Guid siteId = web.Site.ID;
            Guid webId  = web.ID;
            //string url = properties.ServerRelativeUrl;

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

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append(url + ";");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            //builder.Append(String.Format("{0}:{1};", "OriginalUrl", url));
            //string full = builder.ToString();

            if (url.EndsWith("/"))
            {
                if (!pagename.EndsWith(".aspx"))
                {
                    builder.Append(String.Format("{0}:{1};", "OriginalUrl", pagename + ".aspx"));
                }
                else
                {
                    builder.Append(String.Format("{0}:{1};", "OriginalUrl", pagename));
                }
            }
            else
            {
                if (!url.EndsWith(".aspx"))
                {
                    builder.Append(String.Format("{0}:{1};", "OriginalUrl", url + pagename + ".aspx"));
                }
                else
                {
                    builder.Append(String.Format("{0}:{1};", "OriginalUrl", url + pagename));
                }
            }

            string full = builder.ToString();

            //Guid itemGuid = new Guid("386577D9-0777-4AD3-A90A-C240D8B0A49E");
            SemanticModule           mod  = new SemanticModule();
            IWebSiteControllerModule imod = null;// WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);

            while (imod == null)
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    imod = WebSiteControllerConfig.GetModule(web.Site.WebApplication, mod.RuleType);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }


            int item = -1;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        imod.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 { };
                }

                /*
                 * if (SPContext.Current != null)
                 * {
                 *  SPJobDefinitionCollection jobs = SPContext.Current.Site.WebApplication.JobDefinitions;
                 *
                 *  int _seconds = 0;
                 *
                 *  foreach (SPJobDefinition job in jobs)
                 *  {
                 *      if (job.Name == WebSiteControllerRuleWorkItem.WorkItemJobDisplayName)
                 *      {
                 *          DateTime next = job.Schedule.NextOccurrence(job.LastRunTime);
                 *          _seconds = next.Second;
                 *          break;
                 *      }
                 *  }
                 * }
                 */
            });

            /*
             * SPSecurity.RunWithElevatedPrivileges(() =>
             * {
             *  using (SPSite site = new SPSite(siteId))
             *  {
             *      site.AddWorkItem(
             *          Guid.NewGuid(),
             *          DateTime.Now.ToUniversalTime(),
             *          WebSiteControllerRuleWorkItem.WorkItemTypeId,
             *          webId,
             *          siteId,
             *          item,
             *          true,
             *          imod.Id,
             *          Guid.Empty,
             *          site.SystemAccount.ID,
             *          null,
             *          builder.ToString(),
             *          Guid.Empty
             *          );
             *
             *      try
             *      {
             *
             *          WebSiteControllerRuleWorkItem WebSiteControllerModuleJob = new WebSiteControllerRuleWorkItem(WebSiteControllerRuleWorkItem.WorkItemJobDisplayName + "HomePage", site.WebApplication);
             *          SPOneTimeSchedule oneTimeSchedule = new SPOneTimeSchedule(DateTime.Now);
             *
             *          WebSiteControllerModuleJob.Schedule = oneTimeSchedule;
             *          WebSiteControllerModuleJob.Update();
             *      }
             *      catch (Exception ex)
             *      {
             *          SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
             *          //ex.ToString();
             *      }
             *
             *  }
             *
             *  SPJobDefinitionCollection jobs = SPContext.Current.Site.WebApplication.JobDefinitions;
             *
             *  int _seconds = 0;
             *
             *  foreach (SPJobDefinition job in jobs)
             *  {
             *      if (job.Name == WebSiteControllerRuleWorkItem.WorkItemJobDisplayName)
             *      {
             *          DateTime next = job.Schedule.NextOccurrence(job.LastRunTime);
             *          _seconds = next.Second;
             *          break;
             *      }
             *  }
             * });
             */
        }