Upload images to Umbraco

It is easy to upload images to Media folder in Umbraco but there are some instances where you need to upload images to media folder programatically, via code.

Here is the code to do that. You can use this code to download and upload any image.


public class ImageService
{
  private readonly IUmbracoContextWrapper _umbCtxtHelper;
private readonly IMediaService _mediaService;

  public ImageService(IUmbracoContextWrapper umbCtxtHelper)
  {
     _umbCtxtHelper = umbCtxtHelper;
_mediaService = _umbCtxtHelper.MediaService;
  }  

  public int UploadMedia(string imageSrc)
  {
   IMedia newImage = null;
   try
   {
var mediaSvc = _mediaService; 
     var mediaExtension = Path.GetExtension(imageSrc);
     var imageName = Guid.NewGuid() + mediaExtension;

     var image = DownloadImageFromUrl(imageSrc);

     const string rootPath = "~\\media";
     var fileName = HttpContext.Current.Server.MapPath(Path.Combine(rootPath, imageName));
     image.Save(fileName);

     // -1 is the root folderID, i.e. Media.
     // All images will be saved under Media in Umbraco
     newImage = mediaSvc.CreateMedia(imageName, -1, "Image");
     var buffer = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));

     newImage.SetValue("umbracoFile", imageName, new MemoryStream(buffer));
     mediaSvc.Save(newImage);

     if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~\\media\\" + imageName)))
     {
       System.IO.File.Delete(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));
      }
   }
   catch (Exception ex)
   {
     // log the exception
   }

   return newImage.Id;
  }

  private System.Drawing.Image DownloadImageFromUrl(string imageUrl)
  {
   System.Drawing.Image image = null;
   try
   {
     var webRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
     webRequest.AllowWriteStreamBuffering = true;
     webRequest.Timeout = 30000;

     var webResponse = webRequest.GetResponse();
     var stream = webResponse.GetResponseStream();
     image = System.Drawing.Image.FromStream(stream);

     webResponse.Close();
   }
   catch (Exception ex)
   {
     // log the exception
   }
   return image;
  }
}

public interface IUmbracoContextWrapper
{
   IMediaService MediaService { get; }
}

If you want to create folders under Media and upload images to those in Umbraco. Read this post here

Advertisements

Extending uCommerce – Adding Custom Data

Custom data can be stored in uCommerce using Fluent NHibernate mappings.

Following things are required while adding custom data –

  • An entity class
  • A table to store the data in the database
  • A map to let uCommerce know how to store the data
  • A mapping tag to let uCommerce know that a particular DLLs contains maps

For complete tutorial, refer this doc – How to add custom data in uCommerce

After saving the data in the database, the next step is to create the UI, i.e. the grid.

Here is a sample code to create a grid in uCommerce – 


 $(function ()
 {
 $('#sampleTable').dataTable(
 {
 "bPaginate": false,
 "bFilter": false,
 "bSort": false
 });
 });</pre>
<div class="propertyPane">.. Add the headers .. Add the data bindings
<table id="sampleTable" class="dataList" style="width:100%;vertical-align:top;">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
<pre>

uCommerce is using Datatables plug-in for jQuery for its UI. Click here for more info

 

 

Get all URLs in Umbraco using SQL

Use the below SQL script to get all the Urls in your Umbraco project.

; WITH PathXml AS (

/* -- This gives nodes with their 'urlName' property
 -- not in recycle bin,
 -- level > 1 which excludes the top level documents which are not included in the url */
 SELECT
 nodeId,
 cast([xml] as xml).query('data(//@urlName[1])').value('.', 'varchar(max)') AS Path
 FROM cmsContentXml x
 JOIN umbracoNode n ON x.nodeId = n.id AND n.trashed = 0 AND n.level > 1
)

SELECT
 u.id,
 u.path,
 '/' +
 /* This is to get the top level document */
 IsNull((SELECT
 pl.Path + '/'
 FROM PathXml pl
 WHERE ',' + u.path + ',' LIKE '%,' + CAST(pl.nodeId AS VARCHAR(MAX)) + ',%'
 ORDER BY CHARINDEX(',' + CAST(pl.nodeId AS VARCHAR(MAX)) + ',',
 ',' + u.path + ',')

FOR XML PATH('')),
 '') AS Url,
 u.text PageName
FROM umbracoNode u
WHERE nodeObjectType = 'C66BA18E-EAF3-4CFF-8A22-41B16D66A972' /* Document node */
AND trashed = 0
ORDER BY 3 /* Url */