Posts

Showing posts from 2014

Umbraco 7 Partial View List Sub Pages from a Particular Node

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{   var startNode = Umbraco.Content(1105); try { foreach (var page in startNode.Children.Where("Visible")) { <li><a href="#">@page.Name</a></li> } } catch{} }

Umbraco Razor Simple Alternative Subnav

@inherits umbraco.MacroEngines.DynamicNodeContext @{  var startLevel = String.IsNullOrEmpty(Parameter.Level) ? 2 : int.Parse(Parameter.StartLevel);  var finishLevel = String.IsNullOrEmpty(Parameter.Level) ? 8 : int.Parse(Parameter.FinishLevel);    var parent = Model.AncestorOrSelf(startLevel);  if (parent != null) { @traverse(parent,startLevel,finishLevel) ; } } @helper traverse(dynamic parent,int startLevel,int finishLevel) {  foreach (var node in parent.Children.Where("Visible")) {  var selected = Array.IndexOf(Model.Path.Split(','), node.Id.ToString()) >= 0 ? " id=\"current\"" : ""; <li >  <a href="@node.Url">@node.Name</a>                                       ...

Umbraco Razor Alternative method for Breadcrumbs

@inherits umbraco.MacroEngines.DynamicNodeContext <a href="@Model.AncestorOrSelf(2).Url">@Model.AncestorOrSelf(2).Name</a> @try{ @Html.Raw(" | " + @Model.AncestorOrSelf(3).Name) } catch{} @try{ @Html.Raw(" | " + @Model.AncestorOrSelf(4).Name) } catch{} @try{ @Html.Raw(" | " + @Model.AncestorOrSelf(5).Name) } catch{}

Read in a CSV file using C# Razor in Umbraco and Display the details:

@{ try { var dataFile = Server.MapPath("~/App_Data/Contact-List.csv"); Array csvData = File.ReadAllLines(dataFile); int dataStartsRow = 5; int thisRow = 0; <h2>Reading File Starting at 5th Row, because that is where the data Starts</h2> foreach (string dataLine in csvData) { thisRow = thisRow  +1; int columnInSpreadsheet = 0; foreach (string dataItem in dataLine.Split(',')) { if (thisRow >= dataStartsRow) { @dataItem <br /> } } } } catch { <h2>Error:  Check to see if the file Contact-List.csv exists and is not open.</h2> } }

Umbraco Razor. Read Contents of A CSV File and Create nodes

The Script below reads the contents of a CSV Spreasheet in Razor, in Umbraco. It's pretty specific for something I was working on, but there are bits of code that can be reused: Loading a CSV file in Razor, Reading the Contents of a CSV file in Razor, Creating Nodes in Umbraco from a CSV file in Razor, Deleting Nodes using Razor. @inherits umbraco.MacroEngines.DynamicNodeContext @using umbraco.cms.businesslogic.web   <!-- This Script Reads from a CSV file in the Data App Folder -->   <!-- It then finds Dates in the File and Creates New Event Nodes with the Date as part of the name-->   <!-- There are 3 Types of Events, so it selects the type of event which is decided on by the column it is in-->   <!-- See the CSV for examples-->    <!-- The ETSR Mettings comes from a file "ETSRMeeting.csv" that should be stored in the App_Data folder.     The file is read in and used in the Events Calander. -->  ...

Umbraco Razor: Check to see Whether the Date Field is Filled in and Only Display time if the Time is filled in.

Umbraco Razor: Check to see Whether the Date Field is Filled in and Only Display time if the Time is filled in.    and Formating the Time in Umbraco using Razor <p>Event Date: @Model.eventDate.ToString("dd MMMM yyyy")</p> <!-- If the start time is filled in then write it out --> @if(@Model.eventDate.ToString("H:mm") != "0:00") { <p>Start Time: @Model.eventDate.ToString("H:mm")</p> } <!-- If the End date is filled in write it out --> @if (Model.endDate.ToString() != "") { <p>End Date: @Model.endDate.ToString("dd MMMM yyyy")</p> } <!-- If the end time is filled in then write it out --> @if(@Model.endDate.ToString("H:mm") != "0:00" && Model.endDate.ToString() != "") { <p>End Time: @Model.endDate.ToString("H:mm")</p> }

Umbraco Razor, How to Connect and Query to a SQL Database and Loop around the Results, and use a Helper to display the results

1. Connect to the Database (the connection string must be in the Web config file) 2. Loop around the results (this code loops around a database that stores vistits to FAQ pages, and stores the Page ID) 3. Use a helper to display the results KEY: Field names in Database  @inherits umbraco.MacroEngines.DynamicNodeContext @using WebMatrix.Data @{ // 1 Contect to the Database and Select the items         var DB = Database.Open("myAnalyticsConnection"); var FAQs = DB.Query("SELECT * FROM Analytics WHERE docType='FAQ'  ORDER BY numberOfClicks DESC").Take(5); } @{ // 2For Each of the Items(FAQs) loop arround foreach (var FAQ in FAQs) { @getPageLink(FAQ. pageId ) } } @helper getPageLink(int thisPage) { //3.  A Helper to get the node URL, as this is not stored in the database try { var thisPageId = @Model.NodeById(@thisPage); <li style="text-align:left;background-image: url(/images/arrow-white.png);...

Umbraco Razor C# Hide a site from Search engies and Visitors while it is in development

If you are working on a site that is on a live server and has the live url, you could create a page on another site with a link on it that directs to your development site. Give your client, or whoever you want to see the development site a link to that page.  When they click the link they will be able to see the actual live website.  Without the link they are redirected to a "under development" page.     var myReferrer = Request.UrlReferrer;         string thisString = "" + myReferrer;          if (thisString == null  || thisString == ("www.A-PAGE-ON-ANOTHER-SITE-WITH-A LINK.html") || Session["legit"] == "yes" )         {                     Session["legit"] = "yes";         }     else         {   ...

Umbraco Razor For Each Check for ODD and Even

This script is for something else (an rss feed from Vimeo), but the bits to check for ODD and EVEN are  Highlighted in Yellow @using umbraco.MacroEngines @inherits DynamicNodeContext @using System.Xml; <div id="portfolio-wrapper" style="position: relative; overflow: hidden; height: 921px;" class="isotope"> @{ var odd = true; } @{     //Get the XML from remote URL     XmlDocument xml = new XmlDocument();         //URL currently hardcoded - but you could use a macro param to pass in URL     xml.Load("******");     //Select the nodes we want to loop through     XmlNodeList nodes = xml.SelectNodes("//item");       //Traverse the entire XML nodes.     foreach (XmlNode node in nodes)     {         //Get the value from the <title> node         var title = node.SelectSingleNode("title").InnerText; ...

Umbraco Razor List Random Pages from a specific node from anywhere on the site and exclude by Node Type Alias

@inherits umbraco.MacroEngines.DynamicNodeContext @{ var siteInfoPage = @Model.NodeById(1064); <h3><a href="@siteInfoPage.Url" title="@siteInfoPage.pageNavigationName">Popular Pages</h3> <ul> @foreach (var thisPage in @Model.NodeById(1064).Descendants().Where("visible && NodeTypeAlias != \"Faq\"").Random(7)) {   <li><a href="@thisPage.Url">@thisPage.pageHeadingName</a></li> } </ul> }

Umbraco Razor Writing to a Text File by getting a Querystring and Reading From a Text File

Please see this great post: http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files Reading From: @using System.IO; @{     var result = "";     Array userData = null;     char[] delimiterChar = {','};     var dataFile = Server.MapPath("~/App_Data/MyTextFile.txt");     if (File.Exists(dataFile)) {         userData = File.ReadAllLines(dataFile);         if (userData == null) { result = "failed";             @Html.Raw("The file is empty");         }     }     else {         result = "failed";             @Html.Raw("The file does not exist. MyTextFile.txt");     } } @{         if (result == "") {                     foreach (string dataLine ...

Umbraco JQuery Search with drop down selection, Usinc C# Razor

Umbraco Razor List Pages of a Certain Type from Anywhere in the site

Image
The following script takes a look through all the nodes in the umbraco structure, and lists all the nodes of a certain type: (in this case "FAQ"s - good for Front Page News) @inherits umbraco.MacroEngines.DynamicNodeContext     @foreach (var thisPage in @Model.Descendants("Faq").Take(5))     {       <li style="text-align:left;"><a href="@thisPage.Url" style="color:#ffffff">@thisPage.Name</a></li>     }   To Sort by the updated date: @inherits umbraco.MacroEngines.DynamicNodeContext         @foreach (var thisPage in @Model.Descendants("Faq") .OrderBy("UpdateDate descending").Take(5))     {       <li style="text-align:left;"><a href="@thisPage.Url" style="color:#ffffff">@thisPage.Name</a></li>     }  Output:

Umbraco Razor Home Page Link

@{ var theHomePage = @Model.NodeById(home page id); @theHomePage.siteName }

Umbraco Drop Down from Datatypes and URL redirect

Image
 @using System.Xml.XPath  @{  XPathNodeIterator preValueRootElementIterator3 = umbraco.library.GetPreValues(????);  preValueRootElementIterator3.MoveNext();  XPathNodeIterator preValueIterator3 = preValueRootElementIterator3.Current.SelectChildren("preValue", "");  <select name="forma" onchange="location = this.options[this.selectedIndex].value;" style="width:220px;background-color:#514e4b;color:#ffffff;box-shadow: 5px 5px 5px #888888;padding:3px;padding-bottom:5px;">  <option value="" style="font-size:1.6em">Playwrights by Category:</option>  @{  while (preValueIterator3.MoveNext())  {    @Html.Raw("<option value=\"my-web-page.aspx" + "?q=" + preValueIterator3.Current.Value + "\">" + preValueIterator3.Current.Value + "</option>");  }  }  </select>  }   You can then do something like this with the Qu...

Umbraco Razor For Each Where Contains Order

  if  ( Model.NodeById ( 1066 ) . Children.Where ( "relatedTo == \"" +  @qFilter  +  "\"" ) . Any ( ) )          {              int  counter  =  Model.NodeById ( 1066 ) . Children.Skip ( 10  *  @thisPage ) . Take ( 10 ) . Where ( "relatedTo.Contains(\"" +  @qFilter  +  "\")" ) . Count ( ) ;          @Html.Raw ( "hello" ) ;                   foreach  ( var  thisItem  in  Model.NodeById ( 1066 ) . Children. Where ( "relatedTo.Contains(\"" +  @qFilter  +  "\")" ) . OrderBy ( "newsDate descending" ) . Skip ( 10  *  @thisPage ) . Take ( 10 ) )                   {                                       stri...

Umbraco Razor 301 vs 302 Redirect

Umbraco Razor 302 Redirect Response.Redirect(theUrl); Umbraco Razor 301 Redirect: Response.StatusCode = 301; Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", theLocation); Response.Flush(); Response.End();

Umbraco Razor List Nodes Where Statement

if  ( Model.NodeById ( 1066 ) . Children.Where ( "relatedTo == \"Stage\"" ) . Any ( ) ) In this snippet "relatedTo" is a property in Umbraco, "Stage" is what the property has been ticked with.

Umbraco Razor get Querystring

var  qFilter  =  Request [ "qFilter" ] ; / *  Filter * /      if  ( Request [ "qFilter" ]  !=  null  | |  Request [ "qFilter" ]  ==  "All" )      {        qFilter  =  Request [ "qFilter" ] ;      }      else      {        qFilter  =  "" ;      }