Skip to main content

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. -->
   <!-- Further Documentation at http://our.umbraco.org/documentation/Reference/management/Documents/ -->
   <!-- http://our.umbraco.org/documentation/Reference/management/Documents/document -->

   <!-- If an ETST Event Node exists with the same (or very similar name) the script deletes it before creating the new node -->
   <!-- The reason for this is the script may be run a few times and we do not want to keep creating new nodes for the same event -->


   <!-- This Script is split in to 2 Sections-->
   <!-- The *Helper createEventNode is called from the Main Section-->
   <!-- The **Main Section Reads the File and Decide what bits Are Dates-->

@{
var theEventNode = 1404; //Manualy chcnge this below if the node moves
}
 

   <!-- **************** START HELPER ******************************************->
   <!-- *Try and Create the Node with thie Info that has been passed in -->
   <!-- This info that is getting passed to it, is the date of the event and the type of event -->
   <!--  Depending on the type of event, tick the related tick box -->

   @helper createEventNode (string dateIn, string formatedDateIn, string dateType, int dateTypeRef)
    {
        var successfulPost = false;
        <p>Attemting to Create an Event Node with the Following Details:
            <br />
            '@dateIn' |-  <strong>@dateType</strong>
        </p>

         var dt = DocumentType.GetByAlias("AnEvent");
         if (dt != null)
         {
             try {
                 var author = umbraco.BusinessLogic.User.GetUser(0);
                 var nodeName = @dateType + " " + @dateIn;

                 <!-- Lets see if the Node has been created before-->
                 <!-- If So, Lets Delete it -->
                 <!-- As -->
                 var listOfExistingNodes = Document.GetChildrenBySearch(1404, @nodeName);
                 @listOfExistingNodes.Count;
             
                 foreach (var existingNode in listOfExistingNodes)
                 {
                     try{
                     <p>Node Already Exists; so deleting the existing one (@existingNode.Id) first.</p>
                       Document docToDelete = new Document(@existingNode.Id);
                       umbraco.library.UnPublishSingleNode(docToDelete.Id);
                       docToDelete.delete(true);
                       umbraco.library.UpdateDocumentCache(docToDelete.Id);
                     
                       }
                       catch{<p>Cannot Delete</p>}  
                   
                   
                 }
             

             


                 <!-- Lets Create The Node -->                      
    var doc = Document.MakeNew(@nodeName, dt, author, 1404);
                 doc.getProperty("eventName").Value =  @dateType + "";
                 doc.getProperty("eventDate").Value =   @formatedDateIn;

<!-- Fill in Tick Boxes -->
doc.getProperty("ETSRCategory").Value =  @dateTypeRef;
             
               


<!-- DO CHECKING HERE!!!-->

    doc.Publish(author);
    umbraco.library.UpdateDocumentCache(doc.Id);
                 successfulPost = true;
                }
                catch{
                     successfulPost = false;
                }
         
         }
         else
         {
            <p>!The Data Type Does Not Exist</p>  
         }
     
         if (successfulPost){
             <p>Node Created</p>
         }
        else{<p>Cannot Create Node</p>}
     
         <hr />
    }

<!--******************************END HELPER *****************************-->






    <!-- ** Read the CSV File, Find Dates, Pass them to the Helper along with the Type of Date/Event-->
@{
try {
var dataFile = Server.MapPath("~/App_Data/ETSRMeeting.csv");
Array eventData = File.ReadAllLines(dataFile);


foreach (string dataLine in eventData)
{
   
                    int columnInSpreadsheet = 0;
  foreach (string dataItem in dataLine.Split(','))
  {
                        // Lets Check to see if we are on the Dates ex: 10/12/2013
                        if (dataItem.Length == 10 && dataItem.Contains("/"))
                        {                      
                                columnInSpreadsheet  += 1;

// The umbraco date picker is in US Format,
// Our Spreadsheet is in UK Format,
// So we need reformat the date
// You cannot change the date in the date picker to UK in the config files,
// Not consistently through an umbraco install.

var thisDay = dataItem.Substring(0,2);
var thisMonth = dataItem.Substring(3,2);
var thisYear =  dataItem.Substring(6,4);

var thisDate = thisYear + "/" + thisMonth + "/" + thisDay;

   
// 59, 60, 61 relate to the values in the Datatype
                                if (columnInSpreadsheet  == 1)
                                {
                                   @createEventNode(@dataItem, @thisDate, "ETSR Deadline Submission to Mailbox", 59);                    
                                }
                                if (columnInSpreadsheet  == 2)
                                {
                                   @createEventNode(@dataItem, @thisDate, "ETSR Meeting Date", 60);
                                }
                                if (columnInSpreadsheet  == 3)
                                {
                                    @createEventNode(@dataItem, @thisDate, "Executive Team Meeting Date", 61);                                        
                                }
                          }
else {
<p>Cannot Format the Date!!!! -> Error! @dataItem </p>
}

}
  <br />
}
}
catch {
<h2>Error:  Chck to see if the file ETSRMeeting.csv exists.  </h2>
}

}

Comments

Popular posts from this blog

Create a .NET Contact Form that Gets the Last Url Visited in C# Can also be Used in Umbraco

This is a Simple Contact From done in C# .Net and also can be used in Umbraco.  Paste the code in to Visual Web Developer for a better view. The important bits are coment in the second file.  One of the Commented out lines highlights how to get the mailto address from an Umbraco field. The code Below includes the myContactForm.ascx.cs codebehind file and the myContactForm.ascx file. 1) The myContactForm.ascx file:  <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ContactFormforPublications.ascx.cs" Inherits="usercontrols_ContactFormPublications" %> <div class="contact-form" id="contactForm" runat="server">     <h3>Request a Publication</h3>     <div class='int'>         <form runat="server">         <asp:Panel DefaultButton="contactFormSubmit" runat="server">         <fieldset>             <div class='

Umbraco 7 - C# Razor - Passing a parameter variable from a Template to a Partial View.

Passing a parameter variable from a Template to a Partial View Example - Passing a Page Id to a Partial View. In the example below we are passing 3 page Ids (1090. 1091, 1092) to a partial view.  The Partial View will display the details for each of these nodes on a home page.  See final output below. 1) In your Template: @Html.Partial("HomePageLinksToLandingPages", new ViewDataDictionary{{ "pageId", 1090}}) @Html.Partial("HomePageLinksToLandingPages", new ViewDataDictionary{{ "pageId", 1091}}) @Html.Partial("HomePageLinksToLandingPages", new ViewDataDictionary{{ "pageId", 1092}}) 2) The Partial View: @inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ var thisPageId = 1090; var stringPage = @ViewData["pageId"]; thisPageId = Convert.ToInt32(stringPage); } <div class="col-md-4"> <arti