Tuesday, 5 November 2013

C# WebClient with Timeout to get the HTML of a remote page

Sometimes you just need a simple WebClient to get back the results from an HTTP Post, but you need to set the timeout, this is how to do that.

public class TimeoutWebClient : WebClient
    {
        public int Timeout { get; set; }

        public TimeoutWebClient()
        {
            Timeout = 60000;
        }

        public TimeoutWebClient(int timeout)
        {
            Timeout = timeout;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            request.Timeout = Timeout;
            return request;
        }
    }

and call like

 TimeoutWebClient client = new TimeoutWebClient { Timeout = 5000 };
 var htmlText = client.DownloadString(url);

Tuesday, 22 January 2013

Tridion 2009 using Custom URLs for components

If you need to populate a field in a Tridion component using advanced parameters or information from other services you can use Custom URLs to get the value of the field, and pass it to the custom page, you can also send that value back, once it has been modified by your custom page.


Below you can see how this would work, followed by some sample source code.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
 Untitled Page
</title>
    <style type="text/css">
        .style1
        {
            width: 97px;
        }
        em
        {
         color:Red;
         font-style:italic;
         font-weight:bold;
        }
    </style>

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript" language="javascript">
        function SaveAndClose() {
            var newValue = new Array();
            var Host = window.location.hostname;
            Host = Host.toLowerCase();
            if (Host.indexOf("dev") !== -1) {
                Host = "http://www.mydevsite.com";
            }
            else if (Host.indexOf("qa") !== -1) {
                Host = "http://www.myqasite.com";
            }
            else {
                Host = "http://www.mylivesite.com";
            }

            if ($("#User").val().length > 0) {
                newValue[0] = Host + "/feed.ashx?type=" + $("#Type").val() + "&user=" + $("#User").val();
                window.returnValue = newValue;
                self.close();
            }
            else {
                alert("You need to fill in the user field");
            }
        }

        function HideUserBox() {
            $("#User").hide();
            $("#ContextUser").html("Username is not required for this type of feed");
            $("#User").val("");
        }

        function ShowUserBox() {
            $("#User").show();
            $("#ContextUser").html("");
        }

        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.dialogArguments.customArguments.fieldValue);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        }


        function SetContextHelp() {
            var str = "<h1>Help</h1>Select the type of feed you would like to use.";
            var Type = $("#Type").val();
            switch (Type) {
                case "Facebook":
                    str = "<h1>FaceBook<\/h1>All you need to enter for the User field is the numeric part so for the test feed <b>http:\/\/www.dummyfacebookfeedsite.com\/feeds\/feed<em>24<\/em>.xml<\/b> it would be <em>24<\/em><\/p>";
                    ShowUserBox();
                    break;
                case "Investis":
                    str = "<h1>Investis<\/h1>No additional parameters are required<\/p>";
                    HideUserBox();
                    break;
                case "Taleo":
                    str = "<h1>Taleo<\/h1>No additional parameters are required<\/p>";
                    HideUserBox();
                    break;
                case "Twitter":
                    str = "<h1>Twitter<\/h1>All you need to enter for the User field is the part after twitter.com\/ so for the test feed <b>https:\/\/twitter.com\/<em>MyUsername<\/em><\/b> it would be <em>MyUsername<\/em><\/p>";
                    ShowUserBox();
                    break;
                case "Youtube":
                    str = "<h1>Youtube<\/h1>All you need to enter for the User field is the part after \/user\/ so for the test feed <b>http:\/\/www.youtube.com\/user\/<em>MyUsername<\/em><\/b> it would be <em>MyUsername<\/em><\/p>";
                    ShowUserBox();
                    break;
            }
            $("#ContextHelp").html(str);
        }

        $(document).ready(function () {
            $("#User").val(getParameterByName("user"));
            $("#Type").val(getParameterByName("type"));
            SetContextHelp();
        });


    </script>


</head>
<body style ="padding:8px;">
    <form name="form1" method="post" action="default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTMxODExNTY1MA9kFgICAw9kFgICAQ8QD2QWAh4Ib25jaGFuZ2UFEVNldENvbnRleHRIZWxwKCk7ZGRkZIJa/6lFwnHB6cSID/LnPwxZzMB7" />
</div>

<div>

 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBwL729DXAwLYobCbAwKbwILMBwL7reHFDQKNhbybDAKEnqumCgL8gpeMB6O7pPSCvvDDegx8LyqfWc6lzux3" />
</div>
    <div id="Main">
        <table border="0" width = "100%">
            <tr>
                <td>Type</td>
                <td>
                    <select name="Type" id="Type" onchange="SetContextHelp();">
 <option value="Facebook">Facebook</option>
 <option value="Investis">Investis</option>
 <option value="Taleo">Taleo</option>
 <option value="Twitter">Twitter</option>
 <option value="Youtube">Youtube</option>

</select>
                </td>
            </tr>
            <tr>
                <td>User</td>
                <td>
                    <input name="User" type="text" id="User" /><p id = "ContextUser"></p>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td>
                    <input type="button" value="Save" onclick="SaveAndClose()" />
                </td>
            </tr>
        </table>
        <p style ="padding:8px;background-color:#dbdbdb;" id="ContextHelp"></p>
    </div>
    </form>
</body>
</html>

Monday, 22 October 2012

How to get the contents of a field out of a component on the page in Tridion

This will allow you to pass in a Page TCM, and get back the summary from the first component based on the General schema, if not it will return a default string

This also limits to 
  • Pages ending with .aspx
  • not in a Structure group of "so"
  • not in a structure group of "so2010"
  • Published to the Publish target specified





int Days = Convert.ToInt32(ConfigurationManager.AppSettings["Days"]);
string CMSUrl = Convert.ToString(ConfigurationManager.AppSettings["CMSUrl"]);
string GlobalSiteURL = Convert.ToString(ConfigurationManager.AppSettings["GlobalSiteURL"]);
int GlobalPublicationID = Convert.ToInt32(ConfigurationManager.AppSettings["GlobalPublicationID"]);
string PublishTarget = Convert.ToString(ConfigurationManager.AppSettings["PublishTarget"]); 

private string GetPageSummary(string Pagetcm)
    {
        TDSE tdse = new TDSE();
        tdse.Initialize();

        Tridion.ContentManager.Interop.TDS.Page page = (Tridion.ContentManager.Interop.TDS.Page)tdse.GetObject(Pagetcm, EnumOpenMode.OpenModeView, "tcm:0-0-0", XMLReadFilter.XMLReadAll);
        if (!page.Info.PublishLocationUrl.Contains("/so/") && !page.Info.PublishLocationUrl.Contains("/so2010/") && page.Info.PublishLocationUrl.EndsWith(".aspx") && (page.IsPublishedTo(PublishTarget)))
        {
            string summary = "";
            if (page.ComponentPresentations.Count > 0)
            {
                foreach (ComponentPresentation cp in page.ComponentPresentations)
                {
                    if (cp.Component.Schema.Title == "General")
                    {
                        summary += "<div style=\"background-color:#EAEAAE;padding:5px;\">" + cp.Component.Fields["summary"].value[1].ToString() + "</div>";
                        break;
                    }
                }
            }
            if (string.IsNullOrEmpty(summary))
            {
                summary += "No Summary available<br>";
            }
            summary += "<a href = \"" + CMSUrl + "Default.asp?URI=" + Pagetcm + "&CONTEXTURI=&FILTER=Data&ITEMTYPE=64&MODE=OpenModeEditWithFallback\" target = \"blank\">Edit page in Tridion</a>";
            summary += "<br><a href = \"" + GlobalSiteURL + page.Info.PublishLocationUrl + "\" target = \"blank\">View Page on website</a><br>";

            return summary;
        }
        return string.Empty;
    }

Get list of publications from Tridion sorted using Linq


Sometimes you need to get a list of child publications in to a dropdown etc, this is an extension to the code from http://stringwriter.com/tag/tridion/



//Call like this  GetChildPublications("tcm:0-5-1");     
private string GetChildPublications(string parentTCM)
    {
        TDSE tdse = new TDSE();
        tdse.Initialize();

        //gets current publication object
        Publication pub = tdse.GetPublication(parentTCM);
        //gets row filter object
        ListRowFilter filter = tdse.CreateListRowFilter();
        //filter only publication type
        filter.SetCondition("ItemType", 1);
        //returns using publications as xml

        string temp = "";

        XDocument xmlPublications = XDocument.Parse(pub.Info.GetListUsingItems(ListColumnFilter.XMLListIDAndTitle, filter));
        XmlNamespaceManager NS = new XmlNamespaceManager(new NameTable());
        NS.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");

        ListItem li;
        foreach (XElement PubNode in xmlPublications.XPathSelectElements("/tcm:ListUsingItems/tcm:Item", NS).OrderBy(s => (string)s.Attribute("Title")))
        {
            li = new ListItem();
            li.Text = PubNode.Attribute("Title").Value;
            li.Value = PubNode.Attribute("ID").Value;
            GlobalPublicationID.Items.Add(li);
        }

        return temp;
    }

Thursday, 22 March 2012

Tridion Loop through multiple embedded fields


Schema


Embeddable Schema

Field1 and Field2 both optional and multi value.



Component




Component Template
[%
For Each value in Component.Fields.Item("EmbeddedFields").Value
                For Each value2 in value.Item("Field1").Value
                                WriteOut "Field1: " & value2 & "<br>"
                Next
                For Each value2 in value.Item("Field2").Value
                                WriteOut "Field2: " & value2 & "<br>"
                Next
Next
%]


The outcome