private void setupUser(int ID) { _id = ID; using (IRecordsReader dr = SqlHelper.ExecuteReader( "Select userNoConsole, userDisabled, userType,startStructureID, startMediaId, userName,userLogin,userEmail,userDefaultPermissions, userLanguage, defaultToLiveEditing from umbracoUser where id = @id", SqlHelper.CreateParameter("@id", ID))) { if (dr.Read()) { _userNoConsole = dr.GetBoolean("usernoconsole"); _userDisabled = dr.GetBoolean("userDisabled"); _name = dr.GetString("userName"); _loginname = dr.GetString("userLogin"); _email = dr.GetString("userEmail"); _language = dr.GetString("userLanguage"); _startnodeid = dr.GetInt("startStructureID"); if (!dr.IsNull("startMediaId")) { _startmediaid = dr.GetInt("startMediaID"); } _usertype = UserType.GetUserType(dr.GetShort("UserType")); _defaultToLiveEditing = dr.GetBoolean("defaultToLiveEditing"); } else { throw new ArgumentException("No User exists with ID " + ID.ToString()); } } _isInitialized = true; }
/// <summary> /// This function shows all version history for each current node /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvCurVer_RowDataBound(object sender, GridViewRowEventArgs e) { // Set Text for no versions to show if (e.Row.RowType.Equals(DataControlRowType.EmptyDataRow)) { Label lblNoVersionsToShow = (Label)e.Row.FindControl("lblNoVersionsToShow"); lblNoVersionsToShow.Text = getDictionaryItem("versions_Label_NoLogsToShow") + " '" + dtpckrDateFrom.DateTime.ToShortDateString() + "'"; } if (e.Row.RowType == DataControlRowType.DataRow) { Label lblNodeId = (Label)e.Row.FindControl("lblNodeId"); Literal ltrlHistVer = (Literal)e.Row.FindControl("ltrlHistVer"); using (IRecordsReader dr = SqlHelper.ExecuteReader(GetSQLHistoryVersions(), SqlHelper.CreateParameter("@nodeId", int.Parse(lblNodeId.Text)))) { while (dr.Read()) { ltrlHistVer.Text += dr.GetString("text") + " <small>(Created: " + dr.GetDateTime("updateDate").ToShortDateString() + " " + dr.GetDateTime("updateDate").ToShortTimeString() + ") "; if (dr.GetBoolean("published")) { ltrlHistVer.Text += "(<span style='color: green;'>published</span>)"; } if (dr.GetBoolean("newest")) { ltrlHistVer.Text += "(<span style='color: navy;'>newest</span>)"; } ltrlHistVer.Text += "</small><br />"; } } } }
internal DocTypeProperty BuildProperty(IRecordsReader reader) { var p = new DocTypeProperty { Alias = reader.GetAlias(), Description = reader.GetDescription(), Id = reader.GetId(), Mandatory = reader.GetBoolean("Mandatory"), Name = reader.GetName(), RegularExpression = reader.GetString("RegularExpression"), ControlId = reader.GetGuid("ControlId") }; switch (reader.GetDbType()) { case "Date": p.DatabaseType = typeof(DateTime); break; case "Integer": p.DatabaseType = typeof(int); break; case "Ntext": case "Nvarchar": p.DatabaseType = typeof(string); break; default: p.DatabaseType = typeof(object); break; } return(p); }
public PropertyType(int id) { using (IRecordsReader dr = SqlHelper.ExecuteReader( "Select mandatory, DataTypeId, tabId, ContentTypeId, sortOrder, alias, name, validationRegExp, description from cmsPropertyType where id=@id", SqlHelper.CreateParameter("@id", id))) { if (!dr.Read()) { throw new ArgumentException("Propertytype with id: " + id + " doesnt exist!"); } _mandatory = dr.GetBoolean("mandatory"); _id = id; if (!dr.IsNull("tabId")) { _tabId = dr.GetInt("tabId"); } _sortOrder = dr.GetInt("sortOrder"); _alias = dr.GetString("alias"); _name = dr.GetString("Name"); _validationRegExp = dr.GetString("validationRegExp"); _DataTypeId = dr.GetInt("DataTypeId"); _contenttypeid = dr.GetInt("contentTypeId"); _description = dr.GetString("description"); } }
public static Workflow CreateFromDataReader(IRecordsReader reader) { Workflow wf = new Workflow(); wf.Id = reader.GetGuid("id"); wf.Name = reader.GetString("name"); wf.Form = reader.GetGuid("form"); wf.SortOrder = reader.GetInt("sortorder"); wf.Active = reader.GetBoolean("active"); if (!reader.IsNull("executesOn")) { wf.ExecutesOn = (FormState)System.Enum.ToObject(typeof(FormState), reader.GetInt("executesOn")); } //if the type is null or does not exist in the collection, we should not initialize the workflow if (!reader.IsNull("type") && Umbraco.Forms.Core.Providers.WorkflowTypeProviderCollection.Instance.ContainsProvider(reader.GetGuid("type"))) { wf.Type = Umbraco.Forms.Core.Providers.WorkflowTypeProviderCollection.Instance.GetProviderInstance(reader.GetGuid("type")); } else { wf.Active = false; } wf.Settings = new Dictionary <string, string>(); return(wf); }
public List <object> GetRecordFieldValues(RecordField rf) { string sql = string.Format("SELECT * FROM UFRecordData{0} where [Key] = @key ORDER BY Id ASC", rf.DataTypeAlias); List <object> l = new List <object>(); IRecordsReader rr = sqlHelper.ExecuteReader(sql, sqlHelper.CreateParameter("@key", rf.Key)); while (rr.Read()) { switch (rf.DataType) { case FieldDataType.String: case FieldDataType.LongString: l.Add(rr.GetString("Value")); break; case FieldDataType.Integer: l.Add(rr.GetInt("Value")); break; case FieldDataType.DateTime: l.Add(rr.GetDateTime("Value")); break; case FieldDataType.Bit: l.Add(rr.GetBoolean("Value")); break; } } rr.Dispose(); return(l); }
private void PopulateMacroInfo(IRecordsReader dr) { _useInEditor = dr.GetBoolean("macroUseInEditor"); _refreshRate = dr.GetInt("macroRefreshRate"); _alias = dr.GetString("macroAlias"); _id = dr.GetInt("id"); _name = dr.GetString("macroName"); _assembly = dr.GetString("macroScriptAssembly"); _type = dr.GetString("macroScriptType"); _xslt = dr.GetString("macroXSLT"); _scriptingFile = dr.GetString("macroPython"); _cacheByPage = dr.GetBoolean("macroCacheByPage"); _cachePersonalized = dr.GetBoolean("macroCachePersonalized"); _renderContent = !dr.GetBoolean("macroDontRender"); }
private void PopulateFromReader(IRecordsReader dr) { this._id = dr.GetInt("id"); this._dual = dr.GetBoolean("dual"); //this._parentObjectType = dr.GetGuid("parentObjectType"); //this._childObjectType = dr.GetGuid("childObjectType"); this._name = dr.GetString("name"); this._alias = dr.GetString("alias"); }
//public CmsNode GetNodeById(Guid uniqueId) //{ // CmsNode cmsNode; // var id = SqlHelper.ExecuteScalar<int>("SELECT id FROM umbracoNode WHERE uniqueID = @uniqueId", SqlHelper.CreateParameter("@uniqueId", uniqueId)); // using (IRecordsReader dr = SqlHelper.ExecuteReader(m_SQLSingle, // SqlHelper.CreateParameter("@id", id))) // { // if (dr.Read() || dr.IsNull("uniqueID")) // { // cmsNode = new CmsNode // { // UniqueId = dr.GetGuid("uniqueID"), // NodeObjectType = dr.GetGuid("nodeObjectType"), // ContentTypeId = dr.GetInt("contentTypeId"), // Level = dr.GetShort("level"), // Path = dr.GetString("path"), // ParentId = dr.GetInt("parentId"), // Text = dr.GetString("text"), // SortOrder = dr.GetInt("sortOrder"), // UserId = dr.GetInt("nodeUser"), // CreateDate = dr.GetDateTime("createDate"), // IsTrashed = dr.GetBoolean("trashed") // }; // } // else // { // throw new ArgumentException(string.Format("No node exists with id '{0}' ({1})", id, uniqueId)); // } // } // return cmsNode; //} public IEnumerable <T> GetNodesByIds <T>(Guid[] uniqueIds) where T : CmsNode, new() { var cmsNodes = new List <T>(); // TODO: parameterize this the "right" way to prevent future sql injection var strUIds = string.Format("'{0}'", string.Join("','", uniqueIds)); var ids = new List <int>(); using (IRecordsReader reader = SqlHelper.ExecuteReader(string.Format("SELECT id FROM umbracoNode WHERE uniqueID in ({0})", strUIds))) { while (reader.Read()) { ids.Add(reader.GetInt("id")); } } var strIds = string.Join(",", ids); using (IRecordsReader dr = SqlHelper.ExecuteReader(string.Format(m_SQMultiple, strIds))) { while (dr.Read()) { cmsNodes.Add(new T { UniqueId = dr.GetGuid("uniqueID"), NodeObjectType = dr.GetGuid("nodeObjectType"), ContentTypeId = dr.GetInt("contentTypeId"), Level = dr.GetShort("level"), Path = dr.GetString("path"), ParentId = dr.GetInt("parentId"), Text = dr.GetString("text"), SortOrder = dr.GetInt("sortOrder"), UserId = dr.GetInt("nodeUser"), CreateDate = dr.GetDateTime("createDate"), IsTrashed = dr.GetBoolean("trashed") }); } } if (typeof(T) == typeof(DocType)) { // Fill out property data foreach (var node in cmsNodes) { var docType = node as DocType; if (docType != null) { docType.Properties = GetPropertyTypes(node).ToList(); } } } return(cmsNodes); }
private void PopulateTaskFromReader(IRecordsReader dr) { _id = dr.GetInt("id"); Type = new TaskType((int)dr.GetByte("taskTypeId")); Node = new CMSNode(dr.GetInt("nodeId")); ParentUser = User.GetUser(dr.GetInt("parentUserId")); User = User.GetUser(dr.GetInt("userId")); Date = dr.GetDateTime("DateTime"); Comment = dr.GetString("comment"); Closed = dr.GetBoolean("closed"); }
protected void PopulateDocumentTypeNodeFromReader(IRecordsReader dr) { if (!dr.IsNull("templateNodeId")) { _templateIds.Add(dr.GetInt("templateNodeId")); if (!dr.IsNull("IsDefault")) { if (dr.GetBoolean("IsDefault")) { _defaultTemplate = dr.GetInt("templateNodeId"); } } } }
public static FieldCondition CreateFromDataReader(IRecordsReader reader) { FieldCondition fc = Create(); fc.Id = reader.GetGuid("id"); fc.Field = reader.GetGuid("Field"); fc.Enabled = reader.GetBoolean("Enabled"); fc.ActionType = (FieldConditionActionType)System.Enum.Parse(typeof(FieldConditionActionType), reader.GetInt("ActionType").ToString()); fc.LogicType = (FieldConditionLogicType)System.Enum.Parse(typeof(FieldConditionLogicType), reader.GetInt("LogicType").ToString()); fc.Rules = new List <FieldConditionRule>(); return(fc); }
/// <summary> /// Read all ApplicationTree data and store it in cache. /// </summary> private static void Cache() { //don't query the database if the cache is not null if (HttpRuntime.Cache[CACHE_KEY] == null) { lock (m_Locker) { if (HttpRuntime.Cache[CACHE_KEY] == null) { List <ApplicationTree> list = new List <ApplicationTree>(); using (IRecordsReader dr = SqlHelper.ExecuteReader(@"Select treeSilent, treeInitialize, treeSortOrder, appAlias, treeAlias, treeTitle, treeIconClosed, treeIconOpen, treeHandlerAssembly, treeHandlerType, action from umbracoAppTree order by treeSortOrder")) { while (dr.Read()) { list.Add(new ApplicationTree( dr.GetBoolean("treeSilent"), dr.GetBoolean("treeInitialize"), dr.GetByte("treeSortOrder"), dr.GetString("appAlias"), dr.GetString("treeAlias"), dr.GetString("treeTitle"), dr.GetString("treeIconClosed"), dr.GetString("treeIconOpen"), dr.GetString("treeHandlerAssembly"), dr.GetString("treeHandlerType"), dr.GetString("action"))); } } AppTrees = list; } } } }
private void setup() { using (IRecordsReader dr = SqlHelper.ExecuteReader("select macro, macroPropertyHidden, macroPropertyType, macroPropertySortOrder, macroPropertyAlias, macroPropertyName from cmsMacroProperty where id = @id", SqlHelper.CreateParameter("@id", _id))) { if (dr.Read()) { m_macro = new Macro(dr.GetInt("macro")); _public = dr.GetBoolean("macroPropertyHidden"); _sortOrder = (int)dr.GetByte("macroPropertySortOrder"); _alias = dr.GetString("macroPropertyAlias"); _name = dr.GetString("macroPropertyName"); _type = new MacroPropertyType(dr.GetShort("macroPropertyType")); } else { throw new ArgumentException("No macro property found for the id specified"); } } }
protected void PopulateMediaFromReader(IRecordsReader dr) { var hc = dr.GetInt("children") > 0; SetupMediaForTree(dr.GetGuid("uniqueId") , dr.GetShort("level") , dr.GetInt("parentId") , dr.GetInt("nodeUser") , dr.GetString("path") , dr.GetString("text") , dr.GetDateTime("createDate") , dr.GetString("icon") , hc , dr.GetString("alias") , dr.GetString("thumbnail") , dr.GetString("description") , null , dr.GetInt("contentTypeId") , dr.GetBoolean("isContainer")); }
private void Initialize(int id) { IRecordsReader dr = SqlHelper.ExecuteReader( "select id, uninstalled, upgradeId, installDate, userId, package, versionMajor, versionMinor, versionPatch from umbracoInstalledPackages where id = @id", SqlHelper.CreateParameter("@id", id)); if (dr.Read()) { Id = id; Uninstalled = dr.GetBoolean("uninstalled"); UpgradeId = dr.GetInt("upgradeId"); InstallDate = dr.GetDateTime("installDate"); User = User.GetUser(dr.GetInt("userId")); PackageId = dr.GetGuid("package"); VersionMajor = dr.GetInt("versionMajor"); VersionMinor = dr.GetInt("versionMinor"); VersionPatch = dr.GetInt("versionPatch"); } dr.Close(); }
public static Form CreateFromDataReader(IRecordsReader reader) { Form form = Create(); form.Id = reader.GetGuid("id"); form.Pages = new List <Page>(); form.Name = reader.GetString("name"); form.Created = reader.GetDateTime("created"); form.MessageOnSubmit = reader.GetString("MessageOnSubmit"); form.GoToPageOnSubmit = reader.GetInt("GotoPageOnSubmit"); form.ShowValidationSummary = reader.GetBoolean("ShowValidationSummary"); form.HideFieldValidation = reader.GetBoolean("HideFieldValidation"); form.RequiredErrorMessage = reader.GetString("RequiredErrorMessage"); form.InvalidErrorMessage = reader.GetString("InvalidErrorMessage"); form.ManualApproval = reader.GetBoolean("ManualApproval"); form.Archived = reader.GetBoolean("Archived"); form.StoreRecordsLocally = reader.GetBoolean("StoreRecordsLocally"); if (!reader.IsNull("DataSource")) { form.DataSource = reader.GetGuid("DataSource"); } if (!reader.IsNull("FieldIndicationType")) { form.FieldIndicationType = (FormFieldIndication)System.Enum.Parse(typeof(FormFieldIndication), reader.GetInt("FieldIndicationType").ToString()); form.Indicator = reader.GetString("Indicator"); } if (!reader.IsNull("DisableDefaultStylesheet")) { form.DisableDefaultStylesheet = reader.GetBoolean("DisableDefaultStylesheet"); } //check for xpath setting //Umbraco.Forms.Migration.Data.Storage.SettingsStorage ss = new Umbraco.Forms.Migration.Data.Storage.SettingsStorage(); //string set = ss.GetSetting(form.Id, "XPathOnSubmit"); //if (!string.IsNullOrEmpty(set)) // form.XPathOnSubmit = set; //ss.Dispose(); return(form); }
protected void PopulateCMSNodeFromReader(IRecordsReader dr) { // testing purposes only > original umbraco data hasn't any unique values ;) // And we need to have a newParent in order to create a new node .. // Should automatically add an unique value if no exists (or throw a decent exception) if (dr.IsNull("uniqueID")) { _uniqueID = Guid.NewGuid(); } else { _uniqueID = dr.GetGuid("uniqueID"); } _nodeObjectType = dr.GetGuid("nodeObjectType"); _level = dr.GetShort("level"); _path = dr.GetString("path"); _parentid = dr.GetInt("parentId"); _text = dr.GetString("text"); _sortOrder = dr.GetInt("sortOrder"); _userId = dr.GetInt("nodeUser"); _createDate = dr.GetDateTime("createDate"); _isTrashed = dr.GetBoolean("trashed"); }
public static Field CreateFromDataReader(IRecordsReader reader) { Field f = Create(); f.Id = reader.GetGuid("id"); f.Values = new List <object>(); f.PreValues = new List <PreValue>(); f.Caption = reader.GetString("caption"); f.ToolTip = reader.GetString("tooltip"); f.RequiredErrorMessage = reader.GetString("RequiredErrorMessage"); f.InvalidErrorMessage = reader.GetString("InvalidErrorMessage"); f.DataSourceFieldKey = reader.GetObject("DataSourceField"); f.FieldSet = reader.GetGuid("fieldset"); f.Form = reader.GetGuid("form"); f.Mandatory = reader.GetBoolean("mandatory"); f.RegEx = reader.GetString("regex"); f.SortOrder = reader.GetInt("sortOrder"); f.FieldsetIndex = reader.GetInt("FieldsetIndex"); f.PageIndex = reader.GetInt("PageIndex"); f.FieldTypeId = reader.GetGuid("fieldType"); Type _t = Umbraco.Forms.Core.Providers.FieldTypeProviderCollection.Instance.GetProvider(f.FieldTypeId).GetType(); f.FieldType = (Umbraco.Forms.Core.FieldType)Activator.CreateInstance(_t); f.Settings = new List <Umbraco.Forms.Migration.Data.Storage.Setting <string, string> >(); return(f); }
public static List <UrlTrackerModel> GetUrlTrackerEntries(int?maximumRows, int?startRowIndex, string sortExpression = "", bool _404 = false, bool include410Gone = false, bool showAutoEntries = true, bool showCustomEntries = true, bool showRegexEntries = true, string keyword = "", bool onlyForcedRedirects = false) { List <UrlTrackerModel> urlTrackerEntries = new List <UrlTrackerModel>(); int intKeyword = 0; string query = "SELECT * FROM icUrlTracker WHERE Is404 = @is404 AND RedirectHttpCode != @redirectHttpCode"; if (onlyForcedRedirects) { query = string.Concat(query, " AND ForceRedirect = 1"); } if (!string.IsNullOrEmpty(keyword)) { query = string.Concat(query, " AND (OldUrl LIKE @keyword OR OldUrlQueryString LIKE @keyword OR OldRegex LIKE @keyword OR RedirectUrl LIKE @keyword OR Notes LIKE @keyword"); if (int.TryParse(keyword, out intKeyword)) { query = string.Concat(query, " OR RedirectNodeId = @intKeyword"); } query = string.Concat(query, ")"); } List <IParameter> parameters = new List <IParameter> { _sqlHelper.CreateParameter("is404", _404 ? 1 : 0), _sqlHelper.CreateParameter("redirectHttpCode", include410Gone ? 0 : 410) }; if (!string.IsNullOrEmpty(keyword)) { parameters.Add(_sqlHelper.CreateParameter("keyword", "%" + keyword + "%")); } if (intKeyword != 0) { parameters.Add(_sqlHelper.CreateParameter("intKeyword", intKeyword)); } using (IRecordsReader reader = _sqlHelper.ExecuteReader(query, parameters.ToArray())) { while (reader.Read()) { urlTrackerEntries.Add(new UrlTrackerModel(reader.GetInt("Id"), reader.GetString("OldUrl"), reader.GetString("OldUrlQueryString"), reader.GetString("OldRegex"), reader.GetInt("RedirectRootNodeId"), reader.Get <int?>("RedirectNodeId"), reader.GetString("RedirectUrl"), reader.GetInt("RedirectHttpCode"), reader.GetBoolean("RedirectPassThroughQueryString"), reader.GetBoolean("ForceRedirect"), reader.GetString("Notes"), reader.GetBoolean("Is404"), reader.GetString("Referrer"), reader.GetDateTime("Inserted"))); } } urlTrackerEntries = urlTrackerEntries.Where(x => x.RedirectNodeIsPublished).ToList(); if (!showAutoEntries || !showCustomEntries || !showRegexEntries || !string.IsNullOrEmpty(keyword)) { IEnumerable <UrlTrackerModel> filteredUrlTrackerEntries = urlTrackerEntries; if (!showAutoEntries) { filteredUrlTrackerEntries = filteredUrlTrackerEntries.Where(x => x.ViewType != UrlTrackerViewTypes.Auto); } if (!showCustomEntries) { filteredUrlTrackerEntries = filteredUrlTrackerEntries.Where(x => x.ViewType != UrlTrackerViewTypes.Custom || (showRegexEntries ? string.IsNullOrEmpty(x.OldUrl) : false)); } if (!showRegexEntries) { filteredUrlTrackerEntries = filteredUrlTrackerEntries.Where(x => !string.IsNullOrEmpty(x.OldUrl)); } //if (!string.IsNullOrEmpty(keyword)) //{ // filteredUrlTrackerEntries = filteredUrlTrackerEntries.Where(x => // (x.CalculatedOldUrl != null && x.CalculatedOldUrl.ToLower().Contains(keyword)) || // (x.CalculatedRedirectUrl != null && x.CalculatedRedirectUrl.ToLower().Contains(keyword)) || // (x.OldRegex != null && x.OldRegex.ToLower().Contains(keyword)) || // (x.Notes != null && x.Notes.ToLower().Contains(keyword)) // ); //} urlTrackerEntries = filteredUrlTrackerEntries.ToList(); } if (!string.IsNullOrEmpty(sortExpression)) { string sortBy = sortExpression; bool isDescending = false; if (sortExpression.ToLowerInvariant().EndsWith(" desc")) { sortBy = sortExpression.Substring(0, sortExpression.Length - " desc".Length); isDescending = true; } switch (sortBy) { case "RedirectRootNodeName": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.RedirectRootNodeName) : urlTrackerEntries.OrderBy(x => x.RedirectRootNodeName)).ToList(); break; case "CalculatedOldUrl": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.CalculatedOldUrl) : urlTrackerEntries.OrderBy(x => x.CalculatedOldUrl)).ToList(); break; case "CalculatedRedirectUrl": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.CalculatedRedirectUrl) : urlTrackerEntries.OrderBy(x => x.CalculatedRedirectUrl)).ToList(); break; case "RedirectHttpCode": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.RedirectHttpCode) : urlTrackerEntries.OrderBy(x => x.RedirectHttpCode)).ToList(); break; case "Referrer": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.Referrer) : urlTrackerEntries.OrderBy(x => x.Referrer)).ToList(); break; case "NotFoundCount": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.NotFoundCount) : urlTrackerEntries.OrderBy(x => x.NotFoundCount)).ToList(); break; case "Notes": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.Notes) : urlTrackerEntries.OrderBy(x => x.Notes)).ToList(); break; case "Inserted": urlTrackerEntries = (isDescending ? urlTrackerEntries.OrderByDescending(x => x.Inserted) : urlTrackerEntries.OrderBy(x => x.Inserted)).ToList(); break; } } if (startRowIndex.HasValue) { urlTrackerEntries = urlTrackerEntries.Skip(startRowIndex.Value).ToList(); } if (maximumRows.HasValue) { urlTrackerEntries = urlTrackerEntries.Take(maximumRows.Value).ToList(); } return(urlTrackerEntries); }
private static void UrlTrackerDo(bool ignoreHttpStatusCode = false) { HttpContext context = HttpContext.Current; HttpRequest request = context.Request; HttpResponse response = context.Response; if (!string.IsNullOrEmpty(request.QueryString[UrlTrackerSettings.HttpModuleCheck])) { response.Clear(); response.Write(UrlTrackerSettings.HttpModuleCheck); response.StatusCode = 200; response.End(); return; } LoggingHelper.LogInformation("UrlTracker HttpModule | PostReleaseRequestState start"); if (UrlTrackerSettings.IsDisabled) { LoggingHelper.LogInformation("UrlTracker HttpModule | UrlTracker is disabled by config"); return; } string url = request.RawUrl; if (url.StartsWith("/")) { url = url.Substring(1); } LoggingHelper.LogInformation("UrlTracker HttpModule | Incoming URL is: {0}", url); if (_urlTrackerInstalled && (response.StatusCode == (int)HttpStatusCode.NotFound || ignoreHttpStatusCode)) { if (response.StatusCode == (int)HttpStatusCode.NotFound) { LoggingHelper.LogInformation("UrlTracker HttpModule | Response statusCode is 404, continue URL matching"); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Checking for forced redirects (AcquireRequestState), continue URL matching"); } string urlWithoutQueryString = url; if (InfoCaster.Umbraco.UrlTracker.Helpers.UmbracoHelper.IsReservedPathOrUrl(url)) { LoggingHelper.LogInformation("UrlTracker HttpModule | URL is an umbraco reserved path or url, ignore request"); return; } bool urlHasQueryString = request.QueryString.HasKeys() && url.Contains('?'); if (urlHasQueryString) { urlWithoutQueryString = url.Substring(0, url.IndexOf('?')); } string shortestUrl = UrlTrackerHelper.ResolveShortestUrl(urlWithoutQueryString); int rootNodeId = -1; List <UrlTrackerDomain> domains = UmbracoHelper.GetDomains(); if (domains.Any()) { string fullRawUrl; string previousFullRawUrlTest; string fullRawUrlTest; fullRawUrl = previousFullRawUrlTest = fullRawUrlTest = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Host, request.RawUrl); UrlTrackerDomain urlTrackerDomain; do { if (previousFullRawUrlTest.EndsWith("/")) { urlTrackerDomain = domains.FirstOrDefault(x => x.UrlWithDomain == fullRawUrlTest); if (urlTrackerDomain != null) { rootNodeId = urlTrackerDomain.NodeId; urlWithoutQueryString = fullRawUrl.Replace(fullRawUrlTest, string.Empty); if (urlWithoutQueryString.StartsWith("/")) { urlWithoutQueryString = urlWithoutQueryString.Substring(1); } break; } } previousFullRawUrlTest = fullRawUrlTest; fullRawUrlTest = fullRawUrlTest.Substring(0, fullRawUrlTest.Length - 1); }while (fullRawUrlTest.Length > 0); } if (rootNodeId == -1) { rootNodeId = -1; List <INode> children = new Node(rootNodeId).ChildrenAsList; if (children != null && children.Any()) { rootNodeId = children.First().Id; } } LoggingHelper.LogInformation("UrlTracker HttpModule | Current request's rootNodeId: {0}", rootNodeId); string redirectUrl = null; int? redirectHttpCode = null; bool redirectPassThroughQueryString = true; // Normal matching string query = "SELECT * FROM icUrlTracker WHERE Is404 = 0 AND ForceRedirect = @forceRedirect AND (RedirectRootNodeId = @redirectRootNodeId OR RedirectRootNodeId IS NULL) AND (OldUrl = @url OR OldUrl = @shortestUrl) ORDER BY OldUrlQueryString DESC"; using (IRecordsReader reader = _sqlHelper.ExecuteReader(query, _sqlHelper.CreateParameter("forceRedirect", ignoreHttpStatusCode ? "1" : "0"), _sqlHelper.CreateParameter("redirectRootNodeId", rootNodeId), _sqlHelper.CreateParameter("url", urlWithoutQueryString), _sqlHelper.CreateParameter("shortestUrl", shortestUrl))) { while (reader.Read()) { LoggingHelper.LogInformation("UrlTracker HttpModule | URL match found"); if (!reader.IsNull("RedirectNodeId")) { int redirectNodeId = reader.GetInt("RedirectNodeId"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node id: {0}", redirectNodeId); Node n = new Node(redirectNodeId); if (n != null && n.Name != null && n.Id > 0) { string tempUrl = UmbracoHelper.GetUrl(redirectNodeId); redirectUrl = tempUrl.StartsWith("http") ? tempUrl : string.Format("{0}://{1}{2}{3}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port != 80 ? string.Concat(":", HttpContext.Current.Request.Url.Port) : string.Empty, tempUrl); if (redirectUrl.StartsWith("http")) { Uri redirectUri = new Uri(redirectUrl); string pathAndQuery = Uri.UnescapeDataString(redirectUri.PathAndQuery); redirectUrl = pathAndQuery.StartsWith("/") && pathAndQuery != "/" ? pathAndQuery.Substring(1) : pathAndQuery; } LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node is invalid; node is null, name is null or id <= 0"); continue; } } else if (!reader.IsNull("RedirectUrl")) { redirectUrl = reader.GetString("RedirectUrl"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } redirectPassThroughQueryString = reader.GetBoolean("RedirectPassThroughQueryString"); LoggingHelper.LogInformation("UrlTracker HttpModule | PassThroughQueryString is {0}", redirectPassThroughQueryString ? "enabled" : "disabled"); NameValueCollection oldUrlQueryString = null; if (!reader.IsNull("OldUrlQueryString")) { oldUrlQueryString = HttpUtility.ParseQueryString(reader.GetString("OldUrlQueryString")); LoggingHelper.LogInformation("UrlTracker HttpModule | Old URL query string set to: {0}", oldUrlQueryString.ToQueryString()); } if ((urlHasQueryString || oldUrlQueryString != null) && (oldUrlQueryString != null && !request.QueryString.CollectionEquals(oldUrlQueryString))) { LoggingHelper.LogInformation("UrlTracker HttpModule | Aborting; query strings don't match"); continue; } redirectHttpCode = reader.GetInt("RedirectHttpCode"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect http code set to: {0}", redirectHttpCode); break; } } if (!redirectHttpCode.HasValue) { // Regex matching query = "SELECT * FROM icUrlTracker WHERE Is404 = 0 AND ForceRedirect = @forceRedirect AND RedirectRootNodeId = @redirectRootNodeId AND OldRegex IS NOT NULL ORDER BY Inserted DESC"; using (IRecordsReader reader = _sqlHelper.ExecuteReader(query, _sqlHelper.CreateParameter("forceRedirect", ignoreHttpStatusCode ? "1" : "0"), _sqlHelper.CreateParameter("redirectRootNodeId", rootNodeId))) { Regex regex; while (reader.Read()) { regex = new Regex(reader.GetString("OldRegex")); if (regex.IsMatch(url)) { LoggingHelper.LogInformation("UrlTracker HttpModule | Regex match found"); if (!reader.IsNull("RedirectNodeId")) { int redirectNodeId = reader.GetInt("RedirectNodeId"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node id: {0}", redirectNodeId); Node n = new Node(redirectNodeId); if (n != null && n.Name != null && n.Id > 0) { redirectUrl = UmbracoHelper.GetUrl(redirectNodeId); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node is invalid; node is null, name is null or id <= 0"); } } else if (!reader.IsNull("RedirectUrl")) { redirectUrl = reader.GetString("RedirectUrl"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); if (_capturingGroupsRegex.IsMatch(redirectUrl)) { LoggingHelper.LogInformation("UrlTracker HttpModule | Found regex capturing groups in the redirect url"); redirectUrl = regex.Replace(url, redirectUrl); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url changed to: {0} (because of regex capturing groups)", redirectUrl); } } redirectPassThroughQueryString = reader.GetBoolean("RedirectPassThroughQueryString"); LoggingHelper.LogInformation("UrlTracker HttpModule | PassThroughQueryString is enabled"); redirectHttpCode = reader.GetInt("RedirectHttpCode"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect http code set to: {0}", redirectHttpCode); } } } } if (redirectHttpCode.HasValue) { response.Clear(); response.StatusCode = redirectHttpCode.Value; LoggingHelper.LogInformation("UrlTracker HttpModule | Response statuscode set to: {0}", response.StatusCode); if (!string.IsNullOrEmpty(redirectUrl)) { if (redirectUrl == "/") { redirectUrl = string.Empty; } Uri redirectUri = new Uri(redirectUrl.StartsWith("http") ? redirectUrl : string.Format("{0}://{1}{2}/{3}", request.Url.Scheme, request.Url.Host, request.Url.Port != 80 ? string.Concat(":", request.Url.Port) : string.Empty, redirectUrl)); if (redirectPassThroughQueryString) { NameValueCollection redirectQueryString = HttpUtility.ParseQueryString(redirectUri.Query); NameValueCollection newQueryString = HttpUtility.ParseQueryString(request.Url.Query); if (redirectQueryString.HasKeys()) { newQueryString = newQueryString.Merge(redirectQueryString); } string pathAndQuery = Uri.UnescapeDataString(redirectUri.PathAndQuery); redirectUri = new Uri(string.Format("{0}://{1}{2}/{3}{4}", redirectUri.Scheme, redirectUri.Host, redirectUri.Port != 80 ? string.Concat(":", redirectUri.Port) : string.Empty, pathAndQuery.Contains('?') ? pathAndQuery.Substring(0, pathAndQuery.IndexOf('?')) : pathAndQuery.StartsWith("/") ? pathAndQuery.Substring(1) : pathAndQuery, newQueryString.HasKeys() ? string.Concat("?", newQueryString.ToQueryString()) : string.Empty)); } response.RedirectLocation = redirectUri.ToString(); LoggingHelper.LogInformation("UrlTracker HttpModule | Response redirectlocation set to: {0}", response.RedirectLocation); } response.End(); } else if (!ignoreHttpStatusCode) { // Log 404 if (!UrlTrackerSettings.IsNotFoundTrackingDisabled && !UrlTrackerSettings.NotFoundUrlsToIgnore.Contains(urlWithoutQueryString) && !UmbracoHelper.IsReservedPathOrUrl(urlWithoutQueryString) && request.Headers["X-UrlTracker-Ignore404"] != "1") { bool ignoreNotFoundBasedOnRegexPatterns = false; foreach (Regex regexNotFoundUrlToIgnore in UrlTrackerSettings.RegexNotFoundUrlsToIgnore) { if (regexNotFoundUrlToIgnore.IsMatch(urlWithoutQueryString)) { ignoreNotFoundBasedOnRegexPatterns = true; break; } } if (!ignoreNotFoundBasedOnRegexPatterns) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, logging as 404 not found"); query = "INSERT INTO icUrlTracker (OldUrl, RedirectRootNodeId, "; if (urlHasQueryString) { query += "OldUrlQueryString, "; } query += "Is404, Referrer) VALUES (@oldUrl, @redirectRootNodeId, "; if (urlHasQueryString) { query += "@oldUrlQueryString, "; } query += "1, @referrer)"; _sqlHelper.ExecuteNonQuery(query, _sqlHelper.CreateParameter("oldUrl", urlWithoutQueryString), _sqlHelper.CreateParameter("redirectRootNodeId", rootNodeId), _sqlHelper.CreateParameter("oldUrlQueryString", request.QueryString.ToString()), _sqlHelper.CreateParameter("referrer", request.UrlReferrer != null && !request.UrlReferrer.ToString().Contains(UrlTrackerSettings.ReferrerToIgnore) ? (object)request.UrlReferrer.ToString() : DBNull.Value)); } } if (UrlTrackerSettings.IsNotFoundTrackingDisabled) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found and not found (404) tracking is disabled"); } if (UrlTrackerSettings.NotFoundUrlsToIgnore.Contains(urlWithoutQueryString)) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, url is configured to be ignored: {0}", urlWithoutQueryString); } else if (UmbracoHelper.IsReservedPathOrUrl(urlWithoutQueryString)) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, url is ignored because it's an umbraco reserved URL or path: {0}", urlWithoutQueryString); } else if (request.Headers["X-UrlTracker-Ignore404"] == "1") { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, url is ignored because the 'X-UrlTracker-Ignore404' header was set to '1'. URL: {0}", urlWithoutQueryString); } } } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Response statuscode is not 404, UrlTracker won't do anything"); } LoggingHelper.LogInformation("UrlTracker HttpModule | PostReleaseRequestState end"); }
protected void PopulateContentTypeNodeFromReader(IRecordsReader dr) { _alias = dr.GetString("Alias"); _iconurl = dr.GetString("icon"); _isContainerContentType = dr.GetBoolean("isContainer"); _allowAtRoot = dr.GetBoolean("allowAtRoot"); if (!dr.IsNull("thumbnail")) _thumbnail = dr.GetString("thumbnail"); if (!dr.IsNull("description")) _description = dr.GetString("description"); }
static void UrlTrackerDo(string callingEventName, bool ignoreHttpStatusCode = false) { HttpContext context = HttpContext.Current; HttpRequest request = context.Request; HttpResponse response = context.Response; if (!string.IsNullOrEmpty(request.QueryString[UrlTrackerSettings.HttpModuleCheck])) { response.Clear(); response.Write(UrlTrackerSettings.HttpModuleCheck); response.StatusCode = 200; response.End(); return; } LoggingHelper.LogInformation("UrlTracker HttpModule | {0} start", callingEventName); if (UrlTrackerSettings.IsDisabled) { LoggingHelper.LogInformation("UrlTracker HttpModule | UrlTracker is disabled by config"); return; } string url = request.RawUrl; if (url.StartsWith("/") && url != "/") { url = url.Substring(1); } LoggingHelper.LogInformation("UrlTracker HttpModule | Incoming URL is: {0}", url); if (_urlTrackerInstalled && (response.StatusCode == (int)HttpStatusCode.NotFound || ignoreHttpStatusCode)) { if (response.StatusCode == (int)HttpStatusCode.NotFound) { LoggingHelper.LogInformation("UrlTracker HttpModule | Response statusCode is 404, continue URL matching"); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Checking for forced redirects (AcquireRequestState), continue URL matching"); } string urlWithoutQueryString = url; if (InfoCaster.Umbraco.UrlTracker.Helpers.UmbracoHelper.IsReservedPathOrUrl(url)) { LoggingHelper.LogInformation("UrlTracker HttpModule | URL is an umbraco reserved path or url, ignore request"); return; } //bool urlHasQueryString = request.QueryString.HasKeys() && url.Contains('?'); bool urlHasQueryString = url.Contains('?'); // invalid querystring (?xxx) without = sign must also be stripped... if (urlHasQueryString) { urlWithoutQueryString = url.Substring(0, url.IndexOf('?')); } string shortestUrl = UrlTrackerHelper.ResolveShortestUrl(urlWithoutQueryString); int rootNodeId = -1; List <UrlTrackerDomain> domains = UmbracoHelper.GetDomains(); if (domains.Any()) { string fullRawUrl; string previousFullRawUrlTest; string fullRawUrlTest; fullRawUrl = previousFullRawUrlTest = fullRawUrlTest = string.Format("{0}{1}{2}{3}", request.Url.Scheme, Uri.SchemeDelimiter, request.Url.Host, request.RawUrl); UrlTrackerDomain urlTrackerDomain; do { if (previousFullRawUrlTest.EndsWith("/")) { urlTrackerDomain = domains.FirstOrDefault(x => (x.UrlWithDomain == fullRawUrlTest) || (x.UrlWithDomain == fullRawUrlTest + "/")); if (urlTrackerDomain != null) { rootNodeId = urlTrackerDomain.NodeId; urlWithoutQueryString = fullRawUrl.Replace(fullRawUrlTest, string.Empty); if (urlWithoutQueryString.StartsWith("/")) { urlWithoutQueryString = urlWithoutQueryString.Substring(1); } if (urlWithoutQueryString.EndsWith("/")) { urlWithoutQueryString = urlWithoutQueryString.Substring(0, urlWithoutQueryString.Length - 1); } break; } } previousFullRawUrlTest = fullRawUrlTest; fullRawUrlTest = fullRawUrlTest.Substring(0, fullRawUrlTest.Length - 1); }while (fullRawUrlTest.Length > 0); } if (rootNodeId == -1) { List <INode> children = new Node(rootNodeId).ChildrenAsList; if (children != null && children.Any()) { rootNodeId = children.First().Id; } } else { var rootUrl = "/"; try { rootUrl = new Node(rootNodeId).Url; } catch (ArgumentNullException) { // could not get full url for path, so we keep / as the root... (no other way to check, happens for favicon.ico for example) } var rootFolder = rootUrl != @"/" ? new Uri(HttpContext.Current.Request.Url, rootUrl).AbsolutePath.TrimStart('/') : string.Empty; if (shortestUrl.StartsWith(rootFolder, StringComparison.OrdinalIgnoreCase)) { shortestUrl = shortestUrl.Substring(rootFolder.Length); } } LoggingHelper.LogInformation("UrlTracker HttpModule | Current request's rootNodeId: {0}", rootNodeId); string redirectUrl = null; int? redirectHttpCode = null; bool redirectPassThroughQueryString = true; if (!ignoreHttpStatusCode) { // Normal matching (database) LoadUrlTrackerMatchesFromDatabase(request, urlWithoutQueryString, urlHasQueryString, shortestUrl, rootNodeId, ref redirectUrl, ref redirectHttpCode, ref redirectPassThroughQueryString); } else { // Forced matching (cache) LoadUrlTrackerMatchesFromCache(request, urlWithoutQueryString, urlHasQueryString, shortestUrl, rootNodeId, ref redirectUrl, ref redirectHttpCode, ref redirectPassThroughQueryString); } string query; if (!redirectHttpCode.HasValue) { if (!ignoreHttpStatusCode) { // Normal matching (database) // Regex matching query = "SELECT * FROM icUrlTracker WHERE Is404 = 0 AND ForceRedirect = @forceRedirect AND (RedirectRootNodeId = @redirectRootNodeId OR RedirectRootNodeId = -1) AND OldRegex IS NOT NULL ORDER BY Inserted DESC"; using (IRecordsReader reader = _sqlHelper.ExecuteReader(query, _sqlHelper.CreateParameter("forceRedirect", ignoreHttpStatusCode ? 1 : 0), _sqlHelper.CreateParameter("redirectRootNodeId", rootNodeId))) { Regex regex; while (reader.Read()) { regex = new Regex(reader.GetString("OldRegex")); if (regex.IsMatch(url)) { LoggingHelper.LogInformation("UrlTracker HttpModule | Regex match found"); if (!reader.IsNull("RedirectNodeId")) { int redirectNodeId = reader.GetInt("RedirectNodeId"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node id: {0}", redirectNodeId); Node n = new Node(redirectNodeId); if (n != null && n.Name != null && n.Id > 0) { redirectUrl = UmbracoHelper.GetUrl(redirectNodeId); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node is invalid; node is null, name is null or id <= 0"); } } else if (!reader.IsNull("RedirectUrl")) { redirectUrl = reader.GetString("RedirectUrl"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); if (_capturingGroupsRegex.IsMatch(redirectUrl)) { LoggingHelper.LogInformation("UrlTracker HttpModule | Found regex capturing groups in the redirect url"); redirectUrl = regex.Replace(url, redirectUrl); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url changed to: {0} (because of regex capturing groups)", redirectUrl); } } redirectPassThroughQueryString = reader.GetBoolean("RedirectPassThroughQueryString"); LoggingHelper.LogInformation("UrlTracker HttpModule | PassThroughQueryString is enabled"); redirectHttpCode = reader.GetInt("RedirectHttpCode"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect http code set to: {0}", redirectHttpCode); } } } } else { // Forced matching (cache) List <UrlTrackerModel> forcedRedirects = UrlTrackerRepository.GetForcedRedirects().Where(x => !string.IsNullOrEmpty(x.OldRegex)).ToList(); if (forcedRedirects == null || !forcedRedirects.Any()) { return; } foreach (var match in forcedRedirects.Select(x => new { UrlTrackerModel = x, Regex = new Regex(x.OldRegex) }).Where(x => x.Regex.IsMatch(url))) { LoggingHelper.LogInformation("UrlTracker HttpModule | Regex match found"); if (match.UrlTrackerModel.RedirectNodeId.HasValue) { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node id: {0}", match.UrlTrackerModel.RedirectNodeId.Value); Node n = new Node(match.UrlTrackerModel.RedirectNodeId.Value); if (n != null && n.Name != null && n.Id > 0) { redirectUrl = UmbracoHelper.GetUrl(match.UrlTrackerModel.RedirectNodeId.Value); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node is invalid; node is null, name is null or id <= 0"); } } else if (!string.IsNullOrEmpty(match.UrlTrackerModel.RedirectUrl)) { redirectUrl = match.UrlTrackerModel.RedirectUrl; LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); if (_capturingGroupsRegex.IsMatch(redirectUrl)) { LoggingHelper.LogInformation("UrlTracker HttpModule | Found regex capturing groups in the redirect url"); redirectUrl = match.Regex.Replace(url, redirectUrl); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url changed to: {0} (because of regex capturing groups)", redirectUrl); } } redirectPassThroughQueryString = match.UrlTrackerModel.RedirectPassThroughQueryString; LoggingHelper.LogInformation("UrlTracker HttpModule | PassThroughQueryString is enabled"); redirectHttpCode = match.UrlTrackerModel.RedirectHttpCode; LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect http code set to: {0}", redirectHttpCode); } } } if (redirectHttpCode.HasValue) { string redirectLocation = string.Empty; if (!string.IsNullOrEmpty(redirectUrl)) { if (redirectUrl == "/") { redirectUrl = string.Empty; } Uri redirectUri = new Uri(redirectUrl.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ? redirectUrl : string.Format("{0}{1}{2}{3}/{4}", request.Url.Scheme, Uri.SchemeDelimiter, request.Url.Host, request.Url.Port != 80 && UrlTrackerSettings.AppendPortNumber ? string.Concat(":", request.Url.Port) : string.Empty, redirectUrl.StartsWith("/") ? redirectUrl.Substring(1) : redirectUrl)); if (redirectPassThroughQueryString) { NameValueCollection redirectQueryString = HttpUtility.ParseQueryString(redirectUri.Query); NameValueCollection newQueryString = HttpUtility.ParseQueryString(request.Url.Query); if (redirectQueryString.HasKeys()) { newQueryString = newQueryString.Merge(redirectQueryString); } string pathAndQuery = Uri.UnescapeDataString(redirectUri.PathAndQuery) + redirectUri.Fragment; redirectUri = new Uri(string.Format("{0}{1}{2}{3}/{4}{5}", redirectUri.Scheme, Uri.SchemeDelimiter, redirectUri.Host, redirectUri.Port != 80 && UrlTrackerSettings.AppendPortNumber ? string.Concat(":", redirectUri.Port) : string.Empty, pathAndQuery.Contains('?') ? pathAndQuery.Substring(0, pathAndQuery.IndexOf('?')) : pathAndQuery.StartsWith("/") ? pathAndQuery.Substring(1) : pathAndQuery, newQueryString.HasKeys() ? string.Concat("?", newQueryString.ToQueryString()) : string.Empty)); } if (redirectUri == new Uri(string.Format("{0}{1}{2}{3}/{4}", request.Url.Scheme, Uri.SchemeDelimiter, request.Url.Host, request.Url.Port != 80 && UrlTrackerSettings.AppendPortNumber ? string.Concat(":", request.Url.Port) : string.Empty, request.RawUrl.StartsWith("/") ? request.RawUrl.Substring(1) : request.RawUrl))) { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect URL is the same as Request.RawUrl; don't redirect"); return; } if (request.Url.Host.Equals(redirectUri.Host, StringComparison.OrdinalIgnoreCase)) { redirectLocation = redirectUri.PathAndQuery + redirectUri.Fragment; } else { redirectLocation = redirectUri.AbsoluteUri; } LoggingHelper.LogInformation("UrlTracker HttpModule | Response redirectlocation set to: {0}", redirectLocation); } response.Clear(); response.StatusCode = redirectHttpCode.Value; LoggingHelper.LogInformation("UrlTracker HttpModule | Response statuscode set to: {0}", response.StatusCode); if (!string.IsNullOrEmpty(redirectLocation)) { response.RedirectLocation = redirectLocation; } response.End(); } else if (!ignoreHttpStatusCode) { // Log 404 if (!UrlTrackerSettings.IsNotFoundTrackingDisabled && !UrlTrackerSettings.NotFoundUrlsToIgnore.Contains(urlWithoutQueryString) && !UmbracoHelper.IsReservedPathOrUrl(urlWithoutQueryString) && request.Headers["X-UrlTracker-Ignore404"] != "1") { bool ignoreNotFoundBasedOnRegexPatterns = false; foreach (Regex regexNotFoundUrlToIgnore in UrlTrackerSettings.RegexNotFoundUrlsToIgnore) { if (regexNotFoundUrlToIgnore.IsMatch(urlWithoutQueryString)) { ignoreNotFoundBasedOnRegexPatterns = true; break; } } if (!ignoreNotFoundBasedOnRegexPatterns) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, logging as 404 not found"); query = "INSERT INTO icUrlTracker (OldUrl, RedirectRootNodeId, "; if (urlHasQueryString) { query += "OldUrlQueryString, "; } query += "Is404, Referrer) VALUES (@oldUrl, @redirectRootNodeId, "; if (urlHasQueryString) { query += "@oldUrlQueryString, "; } query += "1, @referrer)"; _sqlHelper.ExecuteNonQuery(query, _sqlHelper.CreateParameter("oldUrl", urlWithoutQueryString), _sqlHelper.CreateParameter("redirectRootNodeId", rootNodeId), _sqlHelper.CreateParameter("oldUrlQueryString", request.QueryString.ToString()), _sqlHelper.CreateParameter("referrer", request.UrlReferrer != null && !request.UrlReferrer.ToString().Contains(UrlTrackerSettings.ReferrerToIgnore) ? (object)request.UrlReferrer.ToString() : DBNull.Value)); } } if (UrlTrackerSettings.IsNotFoundTrackingDisabled) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found and not found (404) tracking is disabled"); } if (UrlTrackerSettings.NotFoundUrlsToIgnore.Contains(urlWithoutQueryString)) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, url is configured to be ignored: {0}", urlWithoutQueryString); } else if (UmbracoHelper.IsReservedPathOrUrl(urlWithoutQueryString)) { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, url is ignored because it's an umbraco reserved URL or path: {0}", urlWithoutQueryString); } else if (request.Headers["X-UrlTracker-Ignore404"] == "1") { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found, url is ignored because the 'X-UrlTracker-Ignore404' header was set to '1'. URL: {0}", urlWithoutQueryString); } } else { LoggingHelper.LogInformation("UrlTracker HttpModule | No match found in {0}", callingEventName); } } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Response statuscode is not 404, UrlTracker won't do anything"); } LoggingHelper.LogInformation("UrlTracker HttpModule | {0} end", callingEventName); }
static void LoadUrlTrackerMatchesFromDatabase(HttpRequest request, string urlWithoutQueryString, bool urlHasQueryString, string shortestUrl, int rootNodeId, ref string redirectUrl, ref int?redirectHttpCode, ref bool redirectPassThroughQueryString) { string query = "SELECT * FROM icUrlTracker WHERE Is404 = 0 AND ForceRedirect = 0 AND (RedirectRootNodeId = @redirectRootNodeId OR RedirectRootNodeId IS NULL OR RedirectRootNodeId = -1) AND (OldUrl = @url OR OldUrl = @shortestUrl) ORDER BY CASE WHEN RedirectHttpCode = 410 THEN 2 ELSE 1 END, OldUrlQueryString DESC"; using (IRecordsReader reader = _sqlHelper.ExecuteReader(query, _sqlHelper.CreateParameter("redirectRootNodeId", rootNodeId), _sqlHelper.CreateParameter("url", urlWithoutQueryString), _sqlHelper.CreateParameter("shortestUrl", shortestUrl))) { while (reader.Read()) { LoggingHelper.LogInformation("UrlTracker HttpModule | URL match found"); if (!reader.IsNull("RedirectNodeId") && reader.GetInt("RedirectHttpCode") != (int)HttpStatusCode.Gone) { int redirectNodeId = reader.GetInt("RedirectNodeId"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node id: {0}", redirectNodeId); Node n = new Node(redirectNodeId); if (n != null && n.Name != null && n.Id > 0) { string tempUrl = UmbracoHelper.GetUrl(redirectNodeId); redirectUrl = tempUrl.StartsWith(Uri.UriSchemeHttp) ? tempUrl : string.Format("{0}{1}{2}{3}{4}", HttpContext.Current.Request.Url.Scheme, Uri.SchemeDelimiter, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port != 80 && UrlTrackerSettings.AppendPortNumber ? string.Concat(":", HttpContext.Current.Request.Url.Port) : string.Empty, tempUrl); if (redirectUrl.StartsWith(Uri.UriSchemeHttp)) { Uri redirectUri = new Uri(redirectUrl); string pathAndQuery = Uri.UnescapeDataString(redirectUri.PathAndQuery) + redirectUri.Fragment; /*redirectUrl = pathAndQuery.StartsWith("/") && pathAndQuery != "/" ? pathAndQuery.Substring(1) : pathAndQuery; * * if (redirectUri.Host != HttpContext.Current.Request.Url.Host) * { * redirectUrl = new Uri(redirectUri, pathAndQuery).AbsoluteUri; * }*/ redirectUrl = GetCorrectedUrl(redirectUri, rootNodeId, pathAndQuery); } LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } else { LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect node is invalid; node is null, name is null or id <= 0"); continue; } } else if (!reader.IsNull("RedirectUrl")) { redirectUrl = reader.GetString("RedirectUrl"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect url set to: {0}", redirectUrl); } redirectPassThroughQueryString = reader.GetBoolean("RedirectPassThroughQueryString"); LoggingHelper.LogInformation("UrlTracker HttpModule | PassThroughQueryString is {0}", redirectPassThroughQueryString ? "enabled" : "disabled"); NameValueCollection oldUrlQueryString = null; if (!reader.IsNull("OldUrlQueryString")) { oldUrlQueryString = HttpUtility.ParseQueryString(reader.GetString("OldUrlQueryString")); LoggingHelper.LogInformation("UrlTracker HttpModule | Old URL query string set to: {0}", oldUrlQueryString.ToQueryString()); } if ((urlHasQueryString || oldUrlQueryString != null) && (oldUrlQueryString != null && !request.QueryString.CollectionEquals(oldUrlQueryString))) { LoggingHelper.LogInformation("UrlTracker HttpModule | Aborting; query strings don't match"); continue; } redirectHttpCode = reader.GetInt("RedirectHttpCode"); LoggingHelper.LogInformation("UrlTracker HttpModule | Redirect http code set to: {0}", redirectHttpCode); break; } } }
public static bool TryGetColumnBool(IRecordsReader reader, string columnName, out bool value) { if (reader.ContainsField(columnName) && !reader.IsNull(columnName)) { value = reader.GetBoolean(columnName); return true; } value = false; return false; }
protected void PopulateDocumentFromReader(IRecordsReader dr) { var hc = dr.GetInt("children") > 0; SetupDocumentForTree(dr.GetGuid("uniqueId") , dr.GetShort("level") , dr.GetInt("parentId") , dr.GetInt("nodeUser") , dr.GetInt("documentUser") , !dr.GetBoolean("trashed") && (dr.GetInt("isPublished") == 1) //set published... double check trashed property , dr.GetString("path") , dr.GetString("text") , dr.GetDateTime("createDate") , dr.GetDateTime("updateDate") , dr.GetDateTime("versionDate") , dr.GetString("icon") , hc , dr.GetString("alias") , dr.GetString("thumbnail") , dr.GetString("description") , null , dr.GetInt("contentTypeId") , dr.GetInt("templateId") , dr.GetBoolean("isContainer")); if (!dr.IsNull("releaseDate")) _release = dr.GetDateTime("releaseDate"); if (!dr.IsNull("expireDate")) _expire = dr.GetDateTime("expireDate"); }
public static UrlTrackerModel GetUrlTrackerEntryById(int id) { string query = "SELECT * FROM icUrlTracker WHERE Id = @id"; using (IRecordsReader reader = _sqlHelper.ExecuteReader(query, _sqlHelper.CreateParameter("id", id))) { if (reader.Read()) { return(new UrlTrackerModel(reader.GetInt("Id"), reader.GetString("OldUrl"), reader.GetString("OldUrlQueryString"), reader.GetString("OldRegex"), reader.GetInt("RedirectRootNodeId"), reader.Get <int?>("RedirectNodeId"), reader.GetString("RedirectUrl"), reader.GetInt("RedirectHttpCode"), reader.GetBoolean("RedirectPassThroughQueryString"), reader.GetBoolean("ForceRedirect"), reader.GetString("Notes"), reader.GetBoolean("Is404"), reader.GetString("Referrer"), reader.GetDateTime("Inserted"))); } } return(null); }
public static int MigrateData() { if (!GetUrlTrackerTableExists()) { throw new Exception("Url Tracker table not found."); } if (!GetUrlTrackeOldTableExists()) { throw new Exception("Old Url Tracker table not found."); } int newUrlTrackerEntriesCount = 0; List <OldUrlTrackerModel> oldUrlTrackerEntries = new List <OldUrlTrackerModel>(); string query = string.Format("SELECT * FROM {0}", UrlTrackerSettings.OldTableName); IRecordsReader recordsReader = _sqlHelper.ExecuteReader(query); while (recordsReader.Read()) { oldUrlTrackerEntries.Add(new OldUrlTrackerModel() { NodeId = recordsReader.GetInt("NodeID"), OldUrl = recordsReader.GetString("OldUrl"), IsCustom = recordsReader.GetBoolean("IsCustom"), Message = recordsReader.GetString("Message"), Inserted = recordsReader.GetDateTime("Inserted"), IsRegex = recordsReader.GetBoolean("IsRegex") }); } foreach (OldUrlTrackerModel oldUrlTrackerEntry in oldUrlTrackerEntries) { Node node = new Node(oldUrlTrackerEntry.NodeId); if ((node.Id > 0 || true) && !string.IsNullOrEmpty(oldUrlTrackerEntry.OldUrl) && oldUrlTrackerEntry.OldUrl != "#") { string oldUrl = oldUrlTrackerEntry.OldUrl; Uri oldUri = null; if (!oldUrlTrackerEntry.IsRegex) { if (!oldUrl.StartsWith(Uri.UriSchemeHttp)) { oldUri = new Uri(_baseUri, oldUrl); } else { oldUri = new Uri(oldUrl); } oldUrl = UrlTrackerHelper.ResolveShortestUrl(oldUri.AbsolutePath); } else { if (oldUrl.StartsWith("^/")) { oldUrl = string.Concat("^", oldUrl.Substring(2)); } if (oldUrl.StartsWith("/")) { oldUrl = oldUrl.Substring(1); } if (oldUrl.EndsWith("/$")) { oldUrl = string.Concat(oldUrl.Substring(0, oldUrl.Length - 2), "$"); } if (oldUrl.EndsWith("/")) { oldUrl = oldUrl.Substring(0, oldUrl.Length - 1); } } UrlTrackerModel newUrlTrackerEntry = new UrlTrackerModel( !oldUrlTrackerEntry.IsRegex ? oldUrl : string.Empty, oldUri != null ? !string.IsNullOrEmpty(oldUri.Query) && oldUri.Query.StartsWith("?") ? oldUri.Query.Substring(1) : oldUri.Query : string.Empty, oldUrlTrackerEntry.IsRegex ? oldUrl : string.Empty, node.GetDomainRootNode().Id, oldUrlTrackerEntry.NodeId, string.Empty, 301, true, false, oldUrlTrackerEntry.Message); newUrlTrackerEntry.Inserted = oldUrlTrackerEntry.Inserted; AddUrlTrackerEntry(newUrlTrackerEntry); newUrlTrackerEntriesCount++; } } return(newUrlTrackerEntriesCount); }
internal DocTypeProperty BuildProperty(IRecordsReader reader) { var p = new DocTypeProperty { Alias = reader.GetAlias(), Description = reader.GetDescription(), Id = reader.GetId(), Mandatory = reader.GetBoolean("Mandatory"), Name = reader.GetName(), RegularExpression = reader.GetString("RegularExpression"), ControlId = reader.GetGuid("ControlId") }; switch (reader.GetDbType()) { case "Date": p.DatabaseType = typeof(DateTime); break; case "Integer": p.DatabaseType = typeof(int); break; case "Ntext": case "Nvarchar": p.DatabaseType = typeof(string); break; default: p.DatabaseType = typeof(object); break; } return p; }