public async Task<JsonResult> GetEditableContent(long id)
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext(_communityService, _notificationService);
            }

            var contentInputViewModel = new ContentInputViewModel();
            var contentDetails = _contentService.GetContentDetailsForEdit(id, CurrentUserId);

            // Set value from ContentDetials to ContentInputViewModel.
            contentInputViewModel.SetValuesFrom(contentDetails);

            // Set Thumbnail URL.
            contentInputViewModel.ThumbnailLink = contentInputViewModel.ThumbnailID != Guid.Empty ? 
                Url.Action("Thumbnail", "File", new { id = contentInputViewModel.ThumbnailID }) : 
                Url.Content("~/content/images/default" + Enum.GetName(typeof(ContentTypes), contentDetails.ContentData.ContentType) + "thumbnail.png");
            
            return new JsonResult{Data=contentInputViewModel,JsonRequestBehavior = JsonRequestBehavior.AllowGet};
        }
 public async Task<JsonResult> New(ContentInputViewModel contentInputViewModel, string id)
 {
     if (CurrentUserId == 0)
     {
         await TryAuthenticateFromHttpContext(_communityService, _notificationService);
     }
     if (ModelState.IsValid)
     {
         var contentDetails = new ContentDetails();
         contentDetails.SetValuesFrom(contentInputViewModel);
         contentDetails.CreatedByID = CurrentUserId;
         contentInputViewModel.ID = contentDetails.ID = _contentService.CreateContent(contentDetails);
     }
     return new JsonResult { Data = contentInputViewModel };
 }
        public async Task<string> BuildPublicTourXml(bool webclient)
        {
            
            var adminCommunityId = 596915;
            var adminId = 184331;
            var tourDetailList = await _communityService.GetCommunityContents(adminCommunityId, adminId);
            var tourContentList = new List<ContentInputViewModel>();
            foreach (var item in tourDetailList)
            {
                
                var contentInputViewModel = new ContentInputViewModel();
                contentInputViewModel.SetValuesFrom(item);
                tourContentList.Add(contentInputViewModel);
                
            }
            var children = await _communityService.GetChildCommunities(adminCommunityId, adminId);
            var folders = new List<CommunityViewModel>();
            foreach (var child in children)
            {
                var communityViewModel = new CommunityViewModel();
                Mapper.Map(child, communityViewModel);
                folders.Add(communityViewModel);
            }
            using (var sw = new StringWriter())
            {
                using (var xmlWriter = new XmlTextWriter(sw))
                {
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                    xmlWriter.WriteStartElement("Folder");
                    foreach (var folder in folders)
                    {
                        
                        var tourIds = folder.Description != null ? folder.Description.Split(',') : new string[0];
                        var toursInFolder = false;
                        foreach (var tourId in tourIds)
                        {
                            try
                            {
                                var id = Convert.ToInt32(tourId);
                                var tourDetails = tourDetailList.Find(details => details.ID == id);
                                if (tourDetails == null || tourDetails.IsDeleted) continue;
                                var tourContents = tourContentList.Find(model => model.ID == id);
                                var json = tourDetails.Citation.Replace("json://", "");
                                var extData = JsonConvert.DeserializeObject<dynamic>(json);
                                if (webclient && (extData.webclient == null || extData.webclient != true)) continue;
                                Newtonsoft.Json.Linq.JArray related = extData.related;
                                var relatedTours = string.Empty;
                                if (webclient)
                                {
                                    foreach (Guid guid in related)
                                    {
                                        var relatedTour = tourContentList.Find(t => t.ContentDataID == guid);
                                        var relatedJson = relatedTour.Citation.Replace("json://", "");
                                        var relatedExtData = JsonConvert.DeserializeObject<dynamic>(relatedJson);
                                        // only include related tours that are also webclient friendly
                                        if (relatedExtData.webclient == null || relatedExtData.webclient != true)
                                            continue;
                                        if (relatedTours.Length > 0)
                                        {
                                            relatedTours += ";";
                                        }
                                        relatedTours += guid.ToString();
                                    }
                                }
                                else
                                {
                                    relatedTours = string.Join(";", related);
                                }
                                // write folder xml ONLY after first viable tour obj is found
                                if (!toursInFolder)
                                {
                                    xmlWriter.WriteStartElement("Folder");
                                    xmlWriter.WriteAttributeString("Name", folder.Name);
                                    xmlWriter.WriteAttributeString("Group", "Tour");
                                    xmlWriter.WriteAttributeString("Thumbnail", "");
                                    toursInFolder = true;
                                }
                                xmlWriter.WriteStartElement("Tour");
                                xmlWriter.WriteAttributeString("Title", tourDetails.Name.Replace("&", "&amp;"));
                                xmlWriter.WriteAttributeString("ID", tourContents.ContentDataID.ToString());
                                xmlWriter.WriteAttributeString("Description",
                                    tourDetails.Description.Replace("&", "&amp;"));
                                xmlWriter.WriteAttributeString("Classification",
                                    extData["classification"] != null ? extData["classification"].ToString() : "Other");
                                xmlWriter.WriteAttributeString("AuthorEmail",
                                    extData.authorEmail != null ? extData.authorEmail.ToString() : "");
                                xmlWriter.WriteAttributeString("Author",
                                    extData.author != null ? extData.author.ToString().Replace("&", "&amp;") : "");
                                xmlWriter.WriteAttributeString("AverageRating",
                                    tourDetails.AverageRating.ToString(CultureInfo.InvariantCulture));
                                xmlWriter.WriteAttributeString("LengthInSecs", tourContents.TourLength);
                                xmlWriter.WriteAttributeString("OrganizationUrl",
                                    extData.organizationUrl != null
                                        ? extData.organizationUrl.ToString().Replace("&", "&amp;")
                                        : "");
                                xmlWriter.WriteAttributeString("OrganizationName",
                                    extData.organization != null
                                        ? extData.organization.ToString().Replace("&", "&amp;")
                                        : "");
                                xmlWriter.WriteAttributeString("ITHList",
                                    extData.ithList != null
                                        ? extData.ithList.ToString()
                                        : extData.taxonomy != null ? extData.taxonomy.ToString() : "");
                                xmlWriter.WriteAttributeString("AstroObjectsList", string.Empty);
                                xmlWriter.WriteAttributeString("Keywords",
                                    tourDetails.Tags.Replace(',', ';').Replace(" ", ""));
                                xmlWriter.WriteAttributeString("RelatedTours", relatedTours);
                                xmlWriter.WriteEndElement();
                            }
                            catch (NullReferenceException)
                            {
                                //ignore - deleted tour
                            }
                        }
                        if (toursInFolder)
                            xmlWriter.WriteEndElement();
                    }
                    
                    xmlWriter.WriteEndElement();

                    xmlWriter.Close();
                }
                sw.Close();
                var xml = sw.ToString();
                var storageAccount =
                    Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                        ConfigReader<string>.GetSetting("WWTWebBlobs"));
                
                var blobClient = storageAccount.CreateCloudBlobClient();
                var cloudBlobContainer = blobClient.GetContainerReference("tours");
                var toursBlob = cloudBlobContainer.GetBlobReferenceFromServer(webclient? "webclienttours.wtml" : "alltours.wtml");
                var bytes = new byte[xml.Length * sizeof(char)];
                Buffer.BlockCopy(xml.ToCharArray(), 0, bytes, 0, bytes.Length);
                toursBlob.UploadFromByteArray(bytes,0,bytes.Length);
                return toursBlob.StorageUri.PrimaryUri.AbsoluteUri;
            }
        }
        /// <summary>
        /// Populates the ContentViewModel object's properties from the given ContentsView object's properties.
        /// </summary>
        /// <param name="thisObject">Current content view model on which the extension method is called</param>
        /// <param name="content">ContentInputViewModel model from which values to be read</param>
        public static void SetValuesFrom(this ContentDetails thisObject, ContentInputViewModel content)
        {
            if (thisObject != null && content != null)
            {
                // Populate the base values using the EntityViewModel's SetValuesFrom method.
                (thisObject as EntityDetails).SetValuesFrom(content);

                thisObject.DistributedBy = content.DistributedBy;
                thisObject.Citation = content.Citation;

                // Set the access type for the content
                thisObject.AccessTypeID = content.AccessTypeID;

                thisObject.TourLength = content.TourLength;

                // Set content data properties.
                if (content.IsLink)
                {
                    thisObject.ContentData = new LinkDetail(content.ContentUrl);
                }
                else
                {
                    string[] fileDetails = content.ContentFileDetail.Split('~');

                    if (fileDetails.Count() == 5)
                    {
                        string mimeType = fileDetails[3];

                        // If the content file details does not have the following details 
                        // then do not process the file.
                        DataDetail contentDetail = null;

                        if (mimeType.ToUpperInvariant().Equals(Constants.LinkMimeType.ToUpperInvariant()))
                        {
                            contentDetail = new LinkDetail(content.FileName);
                        }
                        else
                        {
                            var fileDetail = new FileDetail();

                            // Get file name and Content type.
                            fileDetail.Name = content.FileName;
                            fileDetail.ContentType = fileDetails[0].GetContentTypes();

                            // Get File size.
                            long fileSize;
                            if (long.TryParse(fileDetails[1], out fileSize))
                            {
                                fileDetail.Size = fileSize;
                            }

                            fileDetail.AzureID = content.ContentDataID;

                            // Get content mime Type.
                            fileDetail.MimeType = fileDetails[3];

                            contentDetail = fileDetail;
                        }

                        // Set Content ID if present.
                        long contentID;
                        if (long.TryParse(fileDetails[4], out contentID))
                        {
                            contentDetail.ContentID = contentID;
                        }

                        thisObject.ContentData = contentDetail;
                    }
                }

                // Set video properties.
                if (content.VideoID != Guid.Empty && content.VideoFileDetail != null)
                {
                    var video = new FileDetail();
                    string[] videoDetails = content.VideoFileDetail.Split('~');

                    if (videoDetails.Count() == 5)
                    {
                        var fileDetail = new FileDetail();

                        // Get file name and Content type.
                        fileDetail.Name = content.VideoName;
                        fileDetail.ContentType = videoDetails[0].GetContentTypes();

                        // Get File size.
                        long fileSize;
                        if (long.TryParse(videoDetails[1], out fileSize))
                        {
                            fileDetail.Size = fileSize;
                        }

                        fileDetail.AzureID = content.VideoID;

                        // Get content mime Type.
                        fileDetail.MimeType = videoDetails[3];

                        video = fileDetail;
                    }

                    thisObject.Video = video;
                }

                // Set associated file details.
                thisObject.AssociatedFiles = GetAssociatedFiles(content);
            }
        }
        /// <summary>
        /// Gets the associated files from content input view model.
        /// </summary>
        /// <param name="content">Input view model.</param>
        /// <returns>Associated files.</returns>
        private static IEnumerable<DataDetail> GetAssociatedFiles(ContentInputViewModel content)
        {
            var associatedFiles = new List<DataDetail>();
            if (content.PostedFileDetail != null)
            {
                for (int i = 0; i < content.PostedFileDetail.Count(); i++)
                {
                    var file = content.PostedFileDetail.ElementAt(i);
                    string[] fileDetails = file.Split('~');

                    if (fileDetails.Count() == 5)
                    {
                        string mimeType = fileDetails[3];

                        // If the posted file details does not have the following details 
                        // then do not process the file.
                        DataDetail contentDetail = null;

                        if (mimeType.ToUpperInvariant().Equals(Constants.LinkMimeType.ToUpperInvariant()))
                        {
                            contentDetail = new LinkDetail(content.PostedFileName.ElementAt(i));
                        }
                        else
                        {
                            var fileDetail = new FileDetail();

                            // Get and set Content type.
                            fileDetail.ContentType = fileDetails[0].GetContentTypes();

                            // Get file name and extension.
                            fileDetail.Name = string.Format(
                                System.Globalization.CultureInfo.InvariantCulture,
                                "{0}{1}",
                                content.PostedFileName.ElementAt(i),
                                fileDetails[0]);

                            // Get File size.
                            long fileSize;
                            if (long.TryParse(fileDetails[1], out fileSize))
                            {
                                fileDetail.Size = fileSize;
                            }

                            // Get Azure ID
                            Guid fileID;
                            if (Guid.TryParse(fileDetails[2], out fileID))
                            {
                                fileDetail.AzureID = fileID;
                            }

                            // Get content mime Type.
                            fileDetail.MimeType = fileDetails[3];

                            contentDetail = fileDetail;
                        }

                        // Set Content ID if present.
                        long contentID;
                        if (long.TryParse(fileDetails[4], out contentID))
                        {
                            contentDetail.ContentID = contentID;
                        }

                        associatedFiles.Add(contentDetail);
                    }
                }
            }

            return associatedFiles;
        }
        /// <summary>
        /// Updates the associated files from content details model.
        /// </summary>
        /// <param name="thisObject">ContentInput ViewModel.</param>
        /// <param name="content">COntent details model.</param>
        private static void UpdateAssociatedFiles(ContentInputViewModel thisObject, ContentDetails content)
        {
            List<string> postedFileNames = new List<string>();
            List<string> postedFileDetails = new List<string>();

            if (content.AssociatedFiles != null)
            {
                foreach (var item in content.AssociatedFiles)
                {
                    string postedFileDetail = string.Empty;
                    if (item is LinkDetail)
                    {
                        postedFileDetail = string.Format(CultureInfo.InvariantCulture, "link~0~{1}~link~{0}", item.ContentID, Guid.Empty);
                    }
                    else 
                    {
                        var fileDetail = item as FileDetail;
                        if (item != null)
                        {
                            postedFileDetail = string.Format(
                                CultureInfo.InvariantCulture,
                                "{0}~{1}~{2}~{3}~{4}",
                                Path.GetExtension(fileDetail.Name),
                                fileDetail.Size,
                                fileDetail.AzureID.ToString(),
                                fileDetail.MimeType,
                                item.ContentID);
                        }
                    }

                    postedFileNames.Add(item.Name);
                    postedFileDetails.Add(postedFileDetail);
                }
            }

            thisObject.PostedFileName = postedFileNames;
            thisObject.PostedFileDetail = postedFileDetails;
        }