(macrosAddedKey));
TraceInfo(loadUserControlKey, string.Format("Usercontrol added with id '{0}'", oControl.ID));
Type type = oControl.GetType();
if (type == null)
{
TraceWarn(loadUserControlKey, "Unable to retrieve control type: " + fileName);
return oControl;
}
AddCurrentNodeToControl(oControl, type);
updateControlProperties(type, oControl, model);
return oControl;
}
catch (Exception e)
{
UmbracoContext.Current.Trace.Warn("macro", string.Format("Error creating usercontrol ({0})", fileName),
e);
return new LiteralControl(
string.Format(
"Error creating control ({0}).
Maybe file doesn't exists or the usercontrol has a cache directive, which is not allowed! See the tracestack for more information!
",
fileName));
}
}
private static void AddCurrentNodeToControl(Control control, Type type)
{
PropertyInfo currentNodeProperty = type.GetProperty("CurrentNode");
if (currentNodeProperty != null && currentNodeProperty.CanWrite &&
currentNodeProperty.PropertyType.IsAssignableFrom(typeof(Node)))
{
currentNodeProperty.SetValue(control, Node.GetCurrent(), null);
}
currentNodeProperty = type.GetProperty("currentNode");
if (currentNodeProperty != null && currentNodeProperty.CanWrite &&
currentNodeProperty.PropertyType.IsAssignableFrom(typeof(Node)))
{
currentNodeProperty.SetValue(control, Node.GetCurrent(), null);
}
}
private void TraceInfo(string category, string message)
{
if (HttpContext.Current != null)
UmbracoContext.Current.Trace.Write(category, message);
}
private void TraceWarn(string category, string message)
{
if (HttpContext.Current != null)
UmbracoContext.Current.Trace.Warn(category, message);
}
public static string renderMacroStartTag(Hashtable attributes, int pageId, Guid versionId)
{
string div = "";
return div;
}
private static string encodeMacroAttribute(string attributeContents)
{
// Replace linebreaks
attributeContents = attributeContents.Replace("\n", "\\n").Replace("\r", "\\r");
// Replace quotes
attributeContents =
attributeContents.Replace("\"", """);
// Replace tag start/ends
attributeContents =
attributeContents.Replace("<", "<").Replace(">", ">");
return attributeContents;
}
public static string renderMacroEndTag()
{
return "
";
}
public static string GetRenderedMacro(int MacroId, page umbPage, Hashtable attributes, int pageId)
{
macro m = GetMacro(MacroId);
Control c = m.renderMacro(attributes, umbPage.Elements, pageId);
TextWriter writer = new StringWriter();
var ht = new HtmlTextWriter(writer);
c.RenderControl(ht);
string result = writer.ToString();
// remove hrefs
string pattern = "href=\"([^\"]*)\"";
MatchCollection hrefs =
Regex.Matches(result, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match href in hrefs)
result = result.Replace(href.Value, "href=\"javascript:void(0)\"");
return result;
}
public static string MacroContentByHttp(int PageID, Guid PageVersion, Hashtable attributes)
{
string tempAlias = (attributes["macroalias"] != null)
? attributes["macroalias"].ToString()
: attributes["macroAlias"].ToString();
macro currentMacro = GetMacro(tempAlias);
if (!currentMacro.DontRenderInEditor)
{
string querystring = "umbPageId=" + PageID + "&umbVersionId=" + PageVersion;
IDictionaryEnumerator ide = attributes.GetEnumerator();
while (ide.MoveNext())
querystring += "&umb_" + ide.Key + "=" + HttpContext.Current.Server.UrlEncode(ide.Value.ToString());
// Create a new 'HttpWebRequest' Object to the mentioned URL.
string retVal = string.Empty;
string protocol = GlobalSettings.UseSSL ? "https" : "http";
string url = string.Format("{0}://{1}:{2}{3}/macroResultWrapper.aspx?{4}", protocol,
HttpContext.Current.Request.ServerVariables["SERVER_NAME"],
HttpContext.Current.Request.ServerVariables["SERVER_PORT"],
IOHelper.ResolveUrl(SystemDirectories.Umbraco), querystring);
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// allows for validation of SSL conversations (to bypass SSL errors in debug mode!)
ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
// propagate the user's context
// zb-00004 #29956 : refactor cookies names & handling
HttpCookie inCookie = StateHelper.Cookies.UserContext.RequestCookie;
var cookie = new Cookie(inCookie.Name, inCookie.Value, inCookie.Path,
HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);
myHttpWebRequest.CookieContainer = new CookieContainer();
myHttpWebRequest.CookieContainer.Add(cookie);
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse = null;
try
{
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
{
Stream streamResponse = myHttpWebResponse.GetResponseStream();
var streamRead = new StreamReader(streamResponse);
var readBuff = new Char[256];
int count = streamRead.Read(readBuff, 0, 256);
while (count > 0)
{
var outputData = new String(readBuff, 0, count);
retVal += outputData;
count = streamRead.Read(readBuff, 0, 256);
}
// Close the Stream object.
streamResponse.Close();
streamRead.Close();
// Find the content of a form
string grabStart = "";
string grabEnd = "";
int grabStartPos = retVal.IndexOf(grabStart) + grabStart.Length;
int grabEndPos = retVal.IndexOf(grabEnd) - grabStartPos;
retVal = retVal.Substring(grabStartPos, grabEndPos);
}
else
retVal = showNoMacroContent(currentMacro);
// Release the HttpWebResponse Resource.
myHttpWebResponse.Close();
}
catch (Exception)
{
retVal = showNoMacroContent(currentMacro);
}
finally
{
// Release the HttpWebResponse Resource.
if (myHttpWebResponse != null)
myHttpWebResponse.Close();
}
return retVal.Replace("\n", string.Empty).Replace("\r", string.Empty);
}
return showNoMacroContent(currentMacro);
}
private static string showNoMacroContent(macro currentMacro)
{
return "" + currentMacro.Name +
"
No macro content available for WYSIWYG editing";
}
private static bool ValidateRemoteCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors policyErrors
)
{
if (GlobalSettings.DebugMode)
{
// allow any old dodgy certificate...
return true;
}
else
{
return policyErrors == SslPolicyErrors.None;
}
}
///
/// Adds the XSLT extension namespaces to the XSLT header using
/// {0} as the container for the namespace references and
/// {1} as the container for the exclude-result-prefixes
///
/// The XSLT
///
public static string AddXsltExtensionsToHeader(string xslt)
{
var namespaceList = new StringBuilder();
var namespaceDeclaractions = new StringBuilder();
foreach (var extension in GetXsltExtensions())
{
namespaceList.Append(extension.Key).Append(' ');
namespaceDeclaractions.AppendFormat("xmlns:{0}=\"urn:{0}\" ", extension.Key);
}
// parse xslt
xslt = xslt.Replace("{0}", namespaceDeclaractions.ToString());
xslt = xslt.Replace("{1}", namespaceList.ToString());
return xslt;
}
[Obsolete("Please stop using these as they'll be removed in v4.8")]
public static bool TryGetColumnString(IRecordsReader reader, string columnName, out string value)
{
if (reader.ContainsField(columnName) && !reader.IsNull(columnName))
{
value = reader.GetString(columnName);
return true;
}
value = string.Empty;
return false;
}
[Obsolete("Please stop using these as they'll be removed in v4.8")]
public static bool TryGetColumnInt32(IRecordsReader reader, string columnName, out int value)
{
if (reader.ContainsField(columnName) && !reader.IsNull(columnName))
{
value = reader.GetInt(columnName);
return true;
}
value = -1;
return false;
}
[Obsolete("Please stop using these as they'll be removed in v4.8")]
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;
}
}
public class MacroCacheContent
{
private readonly Control _control;
private readonly string _id;
public MacroCacheContent(Control control, string ID)
{
_control = control;
_id = ID;
}
public string ID
{
get { return _id; }
}
public Control Content
{
get { return _control; }
}
}
public class macroCacheRefresh : ICacheRefresher
{
#region ICacheRefresher Members
public string Name
{
get
{
// TODO: Add templateCacheRefresh.Name getter implementation
return "Macro cache refresher";
}
}
public Guid UniqueIdentifier
{
get
{
// TODO: Add templateCacheRefresh.UniqueIdentifier getter implementation
return new Guid("7B1E683C-5F34-43dd-803D-9699EA1E98CA");
}
}
public void RefreshAll()
{
}
public void Refresh(Guid Id)
{
// Doesn't do anything
}
void ICacheRefresher.Refresh(int Id)
{
macro.GetMacro(Id).removeFromCache();
}
void ICacheRefresher.Remove(int Id)
{
macro.GetMacro(Id).removeFromCache();
}
#endregion
}
///
/// Allows App_Code XSLT extensions to be declared using the [XsltExtension] class attribute.
///
///
/// An optional XML namespace can be specified using [XsltExtension("MyNamespace")].
///
[AttributeUsage(AttributeTargets.Class)]
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium, Unrestricted = false)]
public class XsltExtensionAttribute : Attribute
{
public XsltExtensionAttribute()
{
Namespace = String.Empty;
}
public XsltExtensionAttribute(string ns)
{
Namespace = ns;
}
public string Namespace { get; set; }
public override string ToString()
{
return Namespace;
}
}
public class ScriptingMacroResult
{
public ScriptingMacroResult()
{
}
public ScriptingMacroResult(string result, Exception resultException)
{
Result = result;
ResultException = resultException;
}
public string Result { get; set; }
public Exception ResultException { get; set; }
}
[Obsolete("This has been replaced with ScriptingMacroResult instead")]
public class DLRMacroResult
{
public DLRMacroResult()
{
}
public DLRMacroResult(Control control, Exception resultException)
{
Control = control;
ResultException = resultException;
}
public Control Control { get; set; }
public Exception ResultException { get; set; }
}
}