<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Uploading image to the assets &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/uploading-image-to-the-assets/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:21:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Uploading image to the assets &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Upload Files To Azure Media Service From Server Side In MVC</title>
		<link>https://mail.sibeeshpassion.com/upload-files-to-azure-media-service-from-server-side-in-mvc/</link>
					<comments>https://mail.sibeeshpassion.com/upload-files-to-azure-media-service-from-server-side-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 30 Jun 2016 12:06:57 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[File Uploading Using MVC]]></category>
		<category><![CDATA[Upload Files To Azure Media Service]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<category><![CDATA[Uploading image to the assets]]></category>
		<category><![CDATA[Using ImageResizer]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11744</guid>

					<description><![CDATA[In this article we are going to see how we can upload images or any files to Media Service Account in Azure from the server side. We will be doing the uploading in a MVC application. If you are new to Azure media service account, I strongly recommend you to read my previous post related to media service account. In my previous article we saw how we can Upload Images To Azure Media Service From Client Side. Here we will see how we can do the same process from the server side. We will also see how we can create [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we are going to see how we can upload images or any files to Media Service Account in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure</a> from the server side. We will be doing the uploading in a <a href="http://sibeeshpassion.com/category/mvc/" target="_blank">MVC </a>application. If you are new to Azure media service account, I strongly recommend you to read my previous post related to <a href="http://sibeeshpassion.com/working-with-azure-media-service-account/" target="_blank">media service account</a>. In my previous article we saw how we can <a href="http://sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/" target="_blank">Upload Images To Azure Media Service From Client Side</a>. Here we will see how we can do the same process from the server side. We will also see how we can create thumbnails for the image you upload, once we generated it, we will upload that to media service account. I hope you will like this.</p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Upload-Files-To-Azure-7ad7d20f" target="_blank">Upload Files To Azure Media Service</a></p>
<p><strong>Background</strong></p>
<p>For the past few weeks I am working in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure </a>. Recently I got a requirement of storing images to Azure. Thus I decided to create a media service account for this requirement. I hope you have already saw my previous articles related to Media Services, if not please find those from here: <a href="http://sibeeshpassion.com/category/azure/media-service/" target="_blank">Media Service</a>. </p>
<p>Now I assume that you have a little background of below items.</p>
<li>Azure media service account</li>
<li>Assets in media service account</li>
<li>Blobs in media service account</li>
<p>Shall we start now?</p>
<p><strong>Prerequisites</strong></p>
<li>Visual Studio</li>
<li>Azure account with active subscription</li>
<li>Active media service, associated storage account account and its keys</li>
<li>ImageResizer DLL for generating the resized stream</li>
<p>If you are a start up company or you are in thinking to start a one, you can always go for BizSpark(Software and services made for the start ups), to join please check here: <a href="http://sibeeshpassion.com/how-to-join-bizspark/" target="_blank">How to join bizspark</a>. Or you can always create a free account <a href="https://azure.microsoft.com/en-in/pricing/free-trial/" target="_blank">here</a>.</p>
<p><strong>Things we are going to do</strong></p>
<p>The following are the tasks we are going to do.</p>
<li>Creating a MVC application.</li>
<li>Create an Asset in Media service account</li>
<li>Upload the file to asset created dynamically</li>
<li>Resize the stream with help of ImageResizer and upload</li>
<li>Retrieves the uploaded items</li>
<p>Now we will go and create a MVC application.</p>
<p><strong>Create a MVC application</strong></p>
<p>Click on the File->New->Project and name your project, in the upcoming window please select MVC and create your project. Once your project is loaded, you can create a MVC controller as follows.</p>
<p>[csharp]<br />
 public class HomeController : Controller<br />
    {<br />
        public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
    }<br />
[/csharp]</p>
<p>And create a view as follows.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Home Page&quot;;<br />
}</p>
<p>&lt;div class=&quot;jumbotron&quot;&gt;<br />
    &lt;h1&gt;Sibeesh Venu&lt;/h1&gt;<br />
    &lt;p class=&quot;lead&quot;&gt;Welcome to Sibeesh Passion&#8217;s Azure Media Service Library&lt;/p&gt;<br />
    &lt;p&gt;&lt;a href=&quot;http://sibeeshpassion.com&quot; class=&quot;btn btn-primary btn-lg&quot;&gt;Learn more &amp;raquo;&lt;/a&gt;&lt;/p&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>Now we need to create an another action in the controller and view for upload. Shall we?</p>
<p>[csharp]<br />
 public ActionResult Upload()<br />
        {<br />
            return View();<br />
        }<br />
[/csharp]</p>
<p>And create a view as follows.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Upload&quot;;<br />
}</p>
<p>&lt;h2&gt;Upload&lt;/h2&gt;<br />
&lt;style&gt;<br />
    table, td, tr {<br />
        border: 1px solid #ccc;<br />
        border-radius: 5px;<br />
        padding: 10px;<br />
        margin: 10px;<br />
    }</p>
<p>    span {<br />
        padding: 10px;<br />
        margin: 10px;<br />
    }<br />
&lt;/style&gt;<br />
&lt;input name=&quot;myFile&quot; id=&quot;myFile&quot; type=&quot;file&quot; multiple /&gt;&lt;br/&gt;<br />
&lt;input type=&quot;button&quot; value=&quot;Submit&quot; id=&quot;btnSubmit&quot; class=&quot;btn btn-info&quot; /&gt;<br />
&lt;div id=&quot;fiesInfo&quot;&gt;&lt;/div&gt;<br />
&lt;div id=&quot;divOutput&quot;&gt;&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/Upload.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here <em>Upload.js</em> is the file where our client side codes relies. So shall we create the client side functions related to the upload process?</p>
<p>[js]<br />
  $(&#8216;#btnSubmit&#8217;).click(function () {<br />
        $(&#8216;#fiesInfo&#8217;).html(&#8221;);<br />
        $(&#8216;#divOutput&#8217;).html(&#8221;);<br />
        startDateTime = new Date();<br />
        $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;br/&gt;&lt;br/&gt;&lt;span&gt;&lt;b&gt;Uploading starts at&lt;/b&gt;&lt;/span&gt;&#8217; + startDateTime);<br />
        var data = new FormData();<br />
        var files = $(&quot;#myFile&quot;).get(0).files;<br />
        if (files.length &gt; 0) {<br />
            for (var i = 0; i &lt; files.length; i++) {<br />
                data.append(&quot;UploadedImage_&quot; + i, files[i]);<br />
            }<br />
            var ajaxRequest = $.ajax({<br />
                type: &quot;POST&quot;,<br />
                url: &quot;http://localhost:5022/Home/UploadFile&quot;,<br />
                contentType: false,<br />
                processData: false,<br />
                data: data,<br />
                cache: false,<br />
                success: function (data, status) {<br />
                    debugger;<br />
                    var totSize = 0;<br />
                    $(&#8216;#divOutput&#8217;).hide();<br />
                    $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;table&gt;&lt;/table&gt;&#8217;);<br />
                    for (var i = 0; i &lt; data.length; i++) {<br />
                        totSize = totSize + parseFloat(data[i].ImageSize);<br />
                        $(&#8216;#divOutput&#8217;).append(&#8216;&lt;img style=&quot;float: left;padding:10px;margin:5px;&quot;  src=https://&#8217; + mediaServiceAccount + &#8216;.blob.core.windows.net/&#8217; + data[i].AssetID + &#8216;/&#8217; + data[i].Title + &#8216; /&gt;&#8217;);<br />
                    }<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;No of files uploaded: &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + data.length + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Total size uploaded: &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + formatSizeUnits(totSize) + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    var endDateTime = new Date();<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Uploading ends at &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + endDateTime + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;The time taken is &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + findDateDiff(startDateTime, endDateTime) + &#8216; &lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
                    $(&#8216;#divOutput&#8217;).show();<br />
                },<br />
                error: function (xhr, desc, err) {<br />
                    $(&#8216;#divOutput&#8217;).html(&#8216;Error: &#8216; + err);<br />
                }<br />
            });<br />
        }</p>
<p>    });<br />
[/js]</p>
<p><em>findDateDiff(date1, date2)</em></p>
<p>[js]<br />
  function findDateDiff(date1, date2) {<br />
        //Get 1 day in milliseconds<br />
        var one_day = 1000 * 60 * 60 * 24;</p>
<p>        // Convert both dates to milliseconds<br />
        var date1_ms = date1.getTime();<br />
        var date2_ms = date2.getTime();</p>
<p>        // Calculate the difference in milliseconds<br />
        var difference_ms = date2_ms &#8211; date1_ms;<br />
        //take out milliseconds<br />
        difference_ms = difference_ms / 1000;<br />
        var seconds = Math.floor(difference_ms % 60);<br />
        difference_ms = difference_ms / 60;<br />
        var minutes = Math.floor(difference_ms % 60);<br />
        difference_ms = difference_ms / 60;</p>
<p>        //var hours = Math.floor(difference_ms % 24);<br />
        //var days = Math.floor(difference_ms / 24);</p>
<p>        return minutes + &#8216; minute (s), and &#8216; + seconds + &#8216; second (s)&#8217;;<br />
    };<br />
[/js]</p>
<p><em>formatSizeUnits(bytes)</em></p>
<p>[js]<br />
     function formatSizeUnits(bytes) {<br />
        if (bytes &gt;= 1000000000) { bytes = (bytes / 1000000000).toFixed(2) + &#8216; GB&#8217;; }<br />
        else if (bytes &gt;= 1000000) { bytes = (bytes / 1000000).toFixed(2) + &#8216; MB&#8217;; }<br />
        else if (bytes &gt;= 1000) { bytes = (bytes / 1000).toFixed(2) + &#8216; KB&#8217;; }<br />
        else if (bytes &gt; 1) { bytes = bytes + &#8216; bytes&#8217;; }<br />
        else if (bytes == 1) { bytes = bytes + &#8216; byte&#8217;; }<br />
        else { bytes = &#8216;0 byte&#8217;; }<br />
        return bytes;<br />
    }<br />
[/js]</p>
<p>As you can see in the <a href="http://sibeeshpassion.com/tag/ajax/" target="_blank">AJAX </a>call we have set URL as <em>http://localhost:5022/Home/UploadFile</em> so we need to create a JsonResult/ActionResult in our Home controller right? I will create an asynchronous JsonResult action there.</p>
<p>[csharp]<br />
#region UploadImages<br />
        /// &lt;summary&gt;<br />
        /// Upload images to the cloud and database. User can upload a single image or a collection of images.<br />
        /// &lt;/summary&gt;<br />
        [HttpPost]<br />
        public async Task&lt;JsonResult&gt; UploadFile()<br />
        {<br />
            try<br />
            {<br />
                List&lt;ImageLists&gt; prcssdImgLists = null;<br />
                if (HttpContext.Request.Files.AllKeys.Any())<br />
                {<br />
                    var httpPostedFile = HttpContext.Request.Files;<br />
                    if (httpPostedFile != null)<br />
                    {<br />
                        string result = string.Empty;<br />
                        string returnJson = string.Empty;<br />
                        using (var ah = new AzureHelper())<br />
                        {<br />
                            List&lt;Stream&gt; strmLists = new List&lt;Stream&gt;();<br />
                            List&lt;string&gt; lstContntTypes = new List&lt;string&gt;();<br />
                            for (int i = 0; i &lt; httpPostedFile.Count; i++)<br />
                            {<br />
                                strmLists.Add(httpPostedFile[i].InputStream);<br />
                                lstContntTypes.Add(httpPostedFile[i].ContentType);<br />
                            }<br />
                            prcssdImgLists = await ah.UploadImages(strmLists, lstContntTypes);<br />
                        }</p>
<p>                    }<br />
                }<br />
                return Json(prcssdImgLists, JsonRequestBehavior.AllowGet);<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
        #endregion<br />
[/csharp]</p>
<p>There we are getting the uploaded files from <em>HttpContext.Request.Files</em>. Did you notice that we are returning the data as collection of the class <em>ImageLists</em>? Where is our <em>ImageLists </em>class then?</p>
<p>[csharp]<br />
using System;<br />
using System.IO;</p>
<p>namespace WorkingWithImagesAndAzure.Models<br />
{<br />
    /// &lt;summary&gt;<br />
    /// Image Collection, describes the properties of the image uploaded<br />
    /// &lt;/summary&gt;<br />
    public class ImageLists<br />
    {<br />
        #region Private Collections<br />
        private Guid _imageID = Guid.Empty;<br />
        private string _imageTitle = string.Empty;<br />
        private string _imageData = string.Empty;<br />
        private string _assetID = string.Empty;<br />
        private long _imageSize = 0;<br />
        #endregion</p>
<p>        #region Public Properties<br />
        /// &lt;summary&gt;<br />
        /// The GUID of image<br />
        /// &lt;/summary&gt;<br />
        public Guid ImageID<br />
        {<br />
            get<br />
            {<br />
                return _imageID;<br />
            }<br />
            set<br />
            {<br />
                if (value != Guid.Empty &amp;&amp; value != _imageID)<br />
                {<br />
                    _imageID = value;<br />
                }<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// The name of the image, a string value<br />
        /// &lt;/summary&gt;<br />
        public string Title<br />
        {<br />
            get<br />
            {<br />
                return _imageTitle;<br />
            }<br />
            set<br />
            {<br />
                if (value != string.Empty &amp;&amp; value != _imageTitle)<br />
                    _imageTitle = value;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// AssetID<br />
        /// &lt;/summary&gt;<br />
        public string AssetID<br />
        {<br />
            get<br />
            {<br />
                return _assetID;<br />
            }<br />
            set<br />
            {<br />
                if (value != string.Empty &amp;&amp; value != _assetID)<br />
                    _assetID = value;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// The filesteam of the single image uploaded<br />
        /// &lt;/summary&gt;<br />
        public string ImageData<br />
        {<br />
            get<br />
            {<br />
                return _imageData;<br />
            }<br />
            set<br />
            {<br />
                if (value != null &amp;&amp; value != _imageData)<br />
                    _imageData = value;<br />
            }<br />
        }<br />
        /// &lt;summary&gt;<br />
        /// ImageSize<br />
        /// &lt;/summary&gt;<br />
        public long ImageSize<br />
        {<br />
            get<br />
            {<br />
                return _imageSize;<br />
            }<br />
            set<br />
            {<br />
                if (value != 0 &amp;&amp; value != _imageSize)<br />
                    _imageSize = value;<br />
            }<br />
        }<br />
        #endregion</p>
<p>    }<br />
}<br />
[/csharp]</p>
<p>Yes you are right, we need to create an another class too, <em>AzureHelper</em>. </p>
<p>[csharp]<br />
 public class AzureHelper : IDisposable<br />
    {<br />
        void IDisposable.Dispose()<br />
        {</p>
<p>        }<br />
    }<br />
[/csharp]</p>
<p>Here we will start all of our codes related to media service account. Before going further, please install <em>Microsoft.WindowsAzure.Storage</em> from NuGet package manager. And add the following references.</p>
<p>[csharp]<br />
using ImageResizer;<br />
using Microsoft.WindowsAzure.MediaServices.Client;<br />
using Microsoft.WindowsAzure.Storage;<br />
using Microsoft.WindowsAzure.Storage.Blob;<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Configuration;<br />
using System.IO;<br />
using System.Threading.Tasks;<br />
[/csharp]</p>
<p>You must add ImageResizer.dll to your references before you start using ImageResizer, you can get the DLL file from the source code attached. </p>
<p>Next, we will configure our <em>Web.config</em> with the keys and connection strings we needed. When I said, keys, it includes your media service account keys too, if you don&#8217;t know your media service account keys, please login to your azure portal and get it by selecting your media service account. We will be adding the following keys, please replace the information with yours.</p>
<p>[xml]<br />
&lt;appSettings&gt;<br />
    &lt;add key=&quot;webpages:Version&quot; value=&quot;3.0.0.0&quot; /&gt;<br />
    &lt;add key=&quot;webpages:Enabled&quot; value=&quot;false&quot; /&gt;<br />
    &lt;add key=&quot;ClientValidationEnabled&quot; value=&quot;true&quot; /&gt;<br />
    &lt;add key=&quot;UnobtrusiveJavaScriptEnabled&quot; value=&quot;true&quot; /&gt;<br />
    &lt;add key=&quot;imgRszeWdth&quot; value=&quot;120&quot; /&gt;<br />
    &lt;add key=&quot;imgRszeHgth&quot; value=&quot;120&quot; /&gt;<br />
    &lt;add key=&quot;myAzureStorageCon&quot; value=&quot;UseDevelopmentStorage=true;&quot; /&gt;<br />
    &lt;add key=&quot;MediaServicesAccountName&quot; value=&quot;&quot; /&gt;<br />
    &lt;add key=&quot;MediaServicesAccountKey&quot; value=&quot;&quot; /&gt;<br />
    &lt;add key=&quot;myAzureStorageConSetting&quot; value=&quot;&quot; /&gt;<br />
  &lt;/appSettings&gt;<br />
[/xml]</p>
<p>Now we can set our connection strings of both storage account and media service account. </p>
<p>[xml]<br />
 &lt;add name=&quot;myAzureStorageCon&quot; connectionString=&quot;DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey&quot; /&gt;<br />
    &lt;add name=&quot;MediaStorage&quot; connectionString=&quot;DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey&quot; /&gt;<br />
[/xml]</p>
<p>I hope you have set everything. Now we can create the functions and constants we need in our AzureHelper class. Are you ready?</p>
<p>[csharp]<br />
 #region Constants<br />
        private static readonly string imgRszeWdth = ConfigurationManager.AppSettings[&quot;imgRszeWdth&quot;];<br />
        private static readonly string imgRszeHgth = ConfigurationManager.AppSettings[&quot;imgRszeHgth&quot;];<br />
        private static readonly string mediaServicesAccountName = ConfigurationManager.AppSettings[&quot;MediaServicesAccountName&quot;];<br />
        private static readonly string mediaServicesAccountKey = ConfigurationManager.AppSettings[&quot;MediaServicesAccountKey&quot;];<br />
        private static readonly string myAzureStorageConSetting = ConfigurationManager.AppSettings[&quot;myAzureStorageConSetting&quot;];<br />
        private static readonly string myAzureCon = ConfigurationManager.ConnectionStrings[&quot;MediaStorage&quot;].ConnectionString;<br />
        #endregion<br />
[/csharp]</p>
<p>And we need to create a function named <em>UploadImages</em>, this is the one we are calling from our controller. </p>
<p>[csharp]<br />
 #region Public Methods<br />
        public async Task&lt;List&lt;ImageLists&gt;&gt; UploadImages(List&lt;Stream&gt; strmLists, List&lt;string&gt; lstContntTypes)<br />
        {<br />
            string myContainerName = &quot;Test007&quot;;<br />
            string assetID = CreateBLOBContainer(myContainerName);<br />
            assetID = assetID.Replace(&quot;nb:cid:UUID:&quot;, &quot;asset-&quot;);<br />
            List&lt;ImageLists&gt; retCollection = new List&lt;ImageLists&gt;();<br />
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(myAzureStorageConSetting);<br />
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();<br />
            CloudBlobContainer container = blobClient.GetContainerReference(assetID);<br />
            container.SetPermissions(<br />
              new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });</p>
<p>            if (strmLists != null)<br />
            {<br />
                for (int i = 0; i &lt; strmLists.Count; i++)<br />
                {<br />
                    string strExtension = string.Empty;<br />
                    if (lstContntTypes[i] == &quot;image/gif&quot;)<br />
                    {<br />
                        strExtension = &quot;.gif&quot;;<br />
                    }<br />
                    else if (lstContntTypes[i] == &quot;image/jpeg&quot;)<br />
                    {<br />
                        strExtension = &quot;.jpeg&quot;;<br />
                    }<br />
                    else if (lstContntTypes[i] == &quot;image/jpg&quot;)<br />
                    {<br />
                        strExtension = &quot;.jpg&quot;;<br />
                    }<br />
                    else if (lstContntTypes[i] == &quot;image/png&quot;)<br />
                    {<br />
                        strExtension = &quot;.png&quot;;<br />
                    }<br />
                    ImageLists img = new ImageLists();<br />
                    string imgGUID = Guid.NewGuid().ToString();<br />
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(string.Concat(imgGUID, strExtension));<br />
                    await blockBlob.UploadFromStreamAsync(strmLists[i]);</p>
<p>                    img.ImageID = new Guid(imgGUID);<br />
                    img.Title = string.Concat(imgGUID, strExtension);<br />
                    img.ImageSize = strmLists[i].Length;<br />
                    img.AssetID = assetID;<br />
                    retCollection.Add(img);</p>
<p>                    CloudBlockBlob blockblobthumb = container.GetBlockBlobReference(string.Concat(imgGUID, &quot;_thumb&quot;, strExtension));<br />
                    Stream strmThumb = ResizeImage(strmLists[i]);<br />
                    using (strmThumb)<br />
                    {<br />
                        await blockblobthumb.UploadFromStreamAsync(strmThumb);</p>
<p>                        img = new ImageLists();<br />
                        img.ImageID = new Guid(imgGUID);<br />
                        img.Title = string.Concat(imgGUID, &quot;_thumb&quot;, strExtension);<br />
                        img.ImageSize = strmThumb.Length;<br />
                        img.AssetID = assetID;<br />
                        retCollection.Add(img);<br />
                    }<br />
                }</p>
<p>            }<br />
            return retCollection;<br />
        }<br />
        #endregion<br />
[/csharp]</p>
<p>As you can see we are creating the asset as <em>CreateBLOBContainer(myContainerName)</em>. So shall we see the function now?</p>
<p>[csharp]<br />
 private string CreateBLOBContainer(string containerName)<br />
        {<br />
            try<br />
            {<br />
                string result = string.Empty;<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);<br />
                IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);<br />
                return asset.Id;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>That&#8217;s fantastic, we just created an asset in our media service account. And this is the code  <em>await blockBlob.UploadFromStreamAsync(strmLists[i]);</em> which does the uploading. Once the actual image is uploaded we are passing the stream to a function <em>ResizeImage(strmLists[i])</em> which will return the converted stream. </p>
<p>[csharp]<br />
 private static MemoryStream ResizeImage(Stream downloaded)<br />
        {<br />
            var memoryStream = new MemoryStream();<br />
            var settings = string.Format(&quot;mode=crop&amp;width={0}&amp;height={1}&quot;, Convert.ToInt32(imgRszeWdth), Convert.ToInt32(imgRszeHgth));<br />
            downloaded.Seek(0, SeekOrigin.Begin);<br />
            var i = new ImageJob(downloaded, memoryStream, new Instructions(settings));<br />
            i.Build();<br />
            memoryStream.Position = 0;<br />
            return memoryStream;<br />
        }<br />
[/csharp]</p>
<p>Once we finished uploading we are creating an output as follows.</p>
<p>[csharp]<br />
  ImageLists img = new ImageLists();<br />
   img.ImageID = new Guid(imgGUID);<br />
                    img.Title = string.Concat(imgGUID, strExtension);<br />
                    img.ImageSize = strmLists[i].Length;<br />
                    img.AssetID = assetID;<br />
                    retCollection.Add(img);<br />
[/csharp]</p>
<p>All good? Build your application and run!. Can you see outputs as below?</p>
<div id="attachment_11746" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11746" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-1024x380.png" alt="Upload Images To Azure Media Service Home Page" width="634" height="235" class="size-large wp-image-11746" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-1024x380.png 1024w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-300x111.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-768x285.png 768w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page-400x149.png 400w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Home-Page.png 1195w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11746" class="wp-caption-text">Upload Images To Azure Media Service Home Page</p></div>
<p>Click on the link <em>Upload Images</em>, you can see the Upload view now.</p>
<div id="attachment_11747" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720.png"><img decoding="async" aria-describedby="caption-attachment-11747" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720.png" alt="Upload Images To Azure Media Service Upload View" width="650" height="237" class="size-full wp-image-11747" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720.png 650w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720-300x109.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Upload-View-e1467288069720-400x146.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11747" class="wp-caption-text">Upload Images To Azure Media Service Upload View</p></div>
<p>Now select the files and click on Submit.</p>
<div id="attachment_11748" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output.png"><img decoding="async" aria-describedby="caption-attachment-11748" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-1024x629.png" alt="Upload Images To Azure Media Service Output" width="634" height="389" class="size-large wp-image-11748" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-1024x629.png 1024w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-300x184.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-768x472.png 768w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-400x246.png 400w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-977x600.png 977w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output.png 1107w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11748" class="wp-caption-text">Upload Images To Azure Media Service Output</p></div>
<p>You can select as many files as you wish.</p>
<div id="attachment_11751" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple.png"><img decoding="async" aria-describedby="caption-attachment-11751" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-1024x886.png" alt="Upload Images To Azure Media Service Output Multiple" width="634" height="549" class="size-large wp-image-11751" srcset="/wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-1024x886.png 1024w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-300x260.png 300w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-768x664.png 768w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-400x346.png 400w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple-693x600.png 693w, /wp-content/uploads/2016/06/Upload-Images-To-Azure-Media-Service-Output-Multiple.png 413w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11751" class="wp-caption-text">Upload Images To Azure Media Service Output Multiple</p></div>
<p>So we have uploaded both thumbnail and actual image. That&#8217;s cool. I guess we have done for now. Have a happy coding!.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever tried Azure media service account? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/upload-files-to-azure-media-service-from-server-side-in-mvc/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Working With Azure Media Service Account</title>
		<link>https://mail.sibeeshpassion.com/working-with-azure-media-service-account/</link>
					<comments>https://mail.sibeeshpassion.com/working-with-azure-media-service-account/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 25 May 2016 00:00:36 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Create an Asset dynamically via console application]]></category>
		<category><![CDATA[Media Service]]></category>
		<category><![CDATA[Media service account]]></category>
		<category><![CDATA[Retrieving the items from the Asset]]></category>
		<category><![CDATA[Uploading image to the assets]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11635</guid>

					<description><![CDATA[[toc] Introduction In this article we are going to work with Media Service Account in Azure. Once we create a media service account, we will create a console application in which we will add the operations like creating the media assets dynamically. You can also upload some files to the assets created. We will discuss here that too. I hope you will like this. Download the source code You can always download the source code here: Azure Media Service Background Few days back I have got a requirement of storing some files in the cloud. As you all know, Azure [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this article we are going to work with Media Service Account in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank" rel="noopener">Azure</a>. Once we create a media service account, we will create a console application in which we will add the operations like creating the media assets dynamically. You can also upload some files to the assets created. We will discuss here that too. I hope you will like this.</p>
<h3>Download the source code</h3>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Working-With-Azure-Media-ad283589" target="_blank" rel="noopener">Azure Media Service</a></p>
<h3>Background</h3>
<p>Few days back I have got a requirement of storing some files in the cloud. As you all know, <a href="http://sibeeshpassion.com/category/Azure/" target="_blank" rel="noopener">Azure </a>will be the right choice if you talk about the cloud services. And I had account with Azure already, so the things were pretty much easy for me. Thus I decided to create a media service account for this requirement. Here we are going to see how we can create an Azure media service account and how to use the same. Following are the prerequisites.</p>
<h3>What is media service account?</h3>
<li>A media service account is a Azure based account which gives you access to cloud based media services in Azure.</li>
<li>Stores metadata of the media files you create, instead saving the actual media content.</li>
<li>To work with media service account, you must have an associated storage account.</li>
<li>While creating a media service account, you can either select the storage account you already have or you can create a new one.</li>
<li>Since the media service account and storage account is treated separately, the content will be available in your storage account even if you delete your media service account</li>
<blockquote><p>
Please be noted that your storage account region must be same as your media service account region.
</p></blockquote>
<h3>Prerequisites</h3>
<li>Visual Studio</li>
<li>Azure account with active subscription</li>
<p>If you are a start up company or you are in thinking to start a one, you can always go for BizSpark(Software and services made for the start ups), to join please check here: <a href="http://sibeeshpassion.com/how-to-join-bizspark/" target="_blank" rel="noopener">How to join bizspark</a>. Or you can always create a free account <a href="https://azure.microsoft.com/en-in/pricing/free-trial/" target="_blank" rel="noopener">here</a>.</p>
<h3>Things we are going to do</h3>
<p>The following are the tasks we are going to do.</p>
<li>Creating an Azure media service account.</li>
<p>If you don&#8217;t have an Azure account with active subscription, you must creates it first before going to do this task.</p>
<li>Creating a Console application to use Media service account</li>
<li>Create an Asset dynamically via console application</li>
<li>Uploading image to the assets</li>
<li>Retrieving the items from the Asset</li>
<p>Now we will go and create our media service account.</p>
<h3>Steps to create an Azure media service account</h3>
<p>To create an azure media service account, please follows the preceding steps. </p>
<p>Step 1: Login to your Azure Portal (<a href="https://portal.azure.com" target="_blank" rel="noopener">https://portal.azure.com</a>)</p>
<div id="attachment_11636" style="width: 467px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Azure-Home.png"><img decoding="async" aria-describedby="caption-attachment-11636" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Azure-Home.png" alt="Azure Home" width="457" height="587" class="size-full wp-image-11636" srcset="/wp-content/uploads/2016/05/Azure-Home.png 457w, /wp-content/uploads/2016/05/Azure-Home-234x300.png 234w, /wp-content/uploads/2016/05/Azure-Home-400x514.png 400w" sizes="(max-width: 457px) 100vw, 457px" /></a><p id="caption-attachment-11636" class="wp-caption-text">Azure Home</p></div>
<p>Step 2: Click New and select Media + CDN</p>
<div id="attachment_11637" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-And-CDN-e1464160195844.png"><img decoding="async" aria-describedby="caption-attachment-11637" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-And-CDN-e1464160195844.png" alt="Media And CDN" width="650" height="463" class="size-full wp-image-11637" srcset="/wp-content/uploads/2016/05/Media-And-CDN-e1464160195844.png 501w, /wp-content/uploads/2016/05/Media-And-CDN-e1464160195844-300x214.png 300w, /wp-content/uploads/2016/05/Media-And-CDN-e1464160195844-400x285.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11637" class="wp-caption-text">Media And CDN</p></div>
<p>Step 3: Click on the media service</p>
<p>This will redirect you to <a href="https://manage.windowsazure.com" target="_blank" rel="noopener">old azure portal</a>, If you are not redirected, no worries. It is fine. </p>
<div id="attachment_11638" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-e1464160366877.png"><img decoding="async" aria-describedby="caption-attachment-11638" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-e1464160366877.png" alt="Media Service" width="650" height="355" class="size-full wp-image-11638" srcset="/wp-content/uploads/2016/05/Media-Service-e1464160366877.png 650w, /wp-content/uploads/2016/05/Media-Service-e1464160366877-300x164.png 300w, /wp-content/uploads/2016/05/Media-Service-e1464160366877-400x218.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11638" class="wp-caption-text">Media Service</p></div>
<p>Step 4: Give the details.</p>
<div id="attachment_11639" style="width: 381px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/New-Storage-Account.png"><img decoding="async" aria-describedby="caption-attachment-11639" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/New-Storage-Account.png" alt="New Storage Account" width="371" height="477" class="size-full wp-image-11639" srcset="/wp-content/uploads/2016/05/New-Storage-Account.png 371w, /wp-content/uploads/2016/05/New-Storage-Account-233x300.png 233w" sizes="(max-width: 371px) 100vw, 371px" /></a><p id="caption-attachment-11639" class="wp-caption-text">New Storage Account</p></div>
<p>Here you can select if you have a storage account or a new one will be created for you automatically. </p>
<p>Step 5: Finish </p>
<p>Once you give the needed details, you can click on the tick symbol. </p>
<div id="attachment_11640" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-Created-e1464160595700.png"><img decoding="async" aria-describedby="caption-attachment-11640" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-Created-e1464160595700.png" alt="Media Service Created" width="650" height="160" class="size-full wp-image-11640" srcset="/wp-content/uploads/2016/05/Media-Service-Created-e1464160595700.png 650w, /wp-content/uploads/2016/05/Media-Service-Created-e1464160595700-300x74.png 300w, /wp-content/uploads/2016/05/Media-Service-Created-e1464160595700-400x98.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11640" class="wp-caption-text">Media Service Created</p></div>
<p>Now we have our storage account and media service account with us. You can always download the sample applications given there. What you need to do all is just select the language you wish and click on the download link. We will create a console application to use this media service account. Sounds cool?</p>
<h3>Creating a Console application to use Media service account</h3>
<p>To create a console application in <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> click File->New project-> Select language->Select Console Application.</p>
<p>Now go back to your Azure portal and click on Manage Keys at the bottom, copy the MEDIA SERVICE ACCOUNT NAME and  MEDIA SERVICE ACCESS KEY (Either primary or secondary). Then you need to add the settings as appSettings in your App.config file as follows. </p>
<p>[xml]<br />
&lt;appSettings&gt;<br />
    &lt;add key=&quot;MediaServicesAccountName&quot; value=&quot;****&quot; /&gt;<br />
    &lt;add key=&quot;MediaServicesAccountKey&quot; value=&quot;***************************&quot; /&gt;<br />
  &lt;/appSettings&gt;<br />
[/xml]</p>
<p>The next thing you need to do is installing <em>windowsazure.mediaservices </em>from package manager console. For that please go to your package manger console from NuGet Package Manager. And run the below query.</p>
<p>[csharp]<br />
 install-package windowsazure.mediaservices<br />
[/csharp]</p>
<p>Now you need to include the preceding namespace to get started with.</p>
<p>[csharp]<br />
using Microsoft.WindowsAzure.MediaServices.Client;<br />
[/csharp]</p>
<p>Now change your Program.cs codes as follows</p>
<p>[csharp]<br />
using Microsoft.WindowsAzure.MediaServices.Client;<br />
using System;<br />
using System.Configuration;</p>
<p>namespace AzureMediaServiceApp<br />
{<br />
    class Program<br />
    {<br />
        #region Constants<br />
        private static string mediaServicesAccountName = ConfigurationManager.AppSettings[&quot;MediaServicesAccountName&quot;];<br />
        private static string mediaServicesAccountKey = ConfigurationManager.AppSettings[&quot;MediaServicesAccountKey&quot;];<br />
        #endregion<br />
        static void Main(string[] args)<br />
        {<br />
            string input = string.Empty;<br />
            Console.WriteLine(&quot;Enter the asset name to be created&#8230;&quot;);<br />
            input = Console.ReadLine();<br />
            CreateBLOBContainer(input);<br />
        }<br />
        public static string CreateBLOBContainer(string containerName)<br />
        {<br />
            try<br />
            {<br />
                string result = string.Empty;<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);<br />
                IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);<br />
                return asset.Uri.ToString();<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                return ex.Message;<br />
            }<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>What we are doing in the above code is, we are fetching the account details from the App.config and calling a function <em>CreateBLOBContainer</em> with the name of the asset as a parameter. We will ask for this name in the console window. Sounds good?</p>
<div id="attachment_11642" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-Created-Output-e1464167236811.png"><img decoding="async" aria-describedby="caption-attachment-11642" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-Created-Output-e1464167236811.png" alt="Media Service Created Output" width="650" height="327" class="size-full wp-image-11642" srcset="/wp-content/uploads/2016/05/Media-Service-Created-Output-e1464167236811.png 650w, /wp-content/uploads/2016/05/Media-Service-Created-Output-e1464167236811-300x151.png 300w, /wp-content/uploads/2016/05/Media-Service-Created-Output-e1464167236811-400x201.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11642" class="wp-caption-text">Media Service Created Output</p></div>
<p>Now go back to your azure portal and click on content tab, you can see the asset you are just created. </p>
<div id="attachment_11643" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-Created-Azure-Portal-Output-e1464167401891.png"><img decoding="async" aria-describedby="caption-attachment-11643" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Media-Service-Created-Azure-Portal-Output-e1464167401891.png" alt="Media Service Created Azure Portal Output" width="650" height="136" class="size-full wp-image-11643" srcset="/wp-content/uploads/2016/05/Media-Service-Created-Azure-Portal-Output-e1464167401891.png 650w, /wp-content/uploads/2016/05/Media-Service-Created-Azure-Portal-Output-e1464167401891-300x63.png 300w, /wp-content/uploads/2016/05/Media-Service-Created-Azure-Portal-Output-e1464167401891-400x84.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11643" class="wp-caption-text">Media Service Created Azure Portal Output</p></div>
<p>Now we will create a function which will upload some files to asset. So that we will change our Program.cs file as follows.</p>
<p>[csharp]<br />
using Microsoft.WindowsAzure.MediaServices.Client;<br />
using System;<br />
using System.Configuration;<br />
using System.IO;</p>
<p>namespace AzureMediaServiceApp<br />
{<br />
    class Program<br />
    {<br />
        #region Constants<br />
        private static readonly string mediaServicesAccountName = ConfigurationManager.AppSettings[&quot;MediaServicesAccountName&quot;];<br />
        private static readonly string mediaServicesAccountKey = ConfigurationManager.AppSettings[&quot;MediaServicesAccountKey&quot;];<br />
        private static readonly string myAzureCon = ConfigurationManager.ConnectionStrings[&quot;myAzureStorageCon&quot;].ConnectionString;<br />
        private static MediaServicesCredentials _mediaServiceCredentials = null;<br />
        #endregion<br />
        static void Main(string[] args)<br />
        {<br />
            string input = string.Empty;<br />
            Console.WriteLine(&quot;Enter the asset name to be created&#8230;&quot;);<br />
            input = Console.ReadLine();<br />
            _mediaServiceCredentials = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey);<br />
            IAsset asset = CreateBLOBContainer(input, _mediaServiceCredentials);<br />
            UploadImages(asset, _mediaServiceCredentials);<br />
        }<br />
        public static IAsset CreateBLOBContainer(string containerName, MediaServicesCredentials _medServCredentials)<br />
        {<br />
            try<br />
            {<br />
                string result = string.Empty;<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(_medServCredentials);<br />
                IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);<br />
                return asset;</p>
<p>            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
        public static string UploadImages(IAsset asset, MediaServicesCredentials _medServCredentials)<br />
        {<br />
            try<br />
            {<br />
                string _singleInputFilePath = Path.GetFullPath(@&quot;E:\X7Md4VB.JPG&quot;);<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(_medServCredentials);<br />
                var fileName = Path.GetFileName(_singleInputFilePath);<br />
                var assetFile = asset.AssetFiles.Create(fileName);<br />
                var policy = mediaContext.AccessPolicies.Create(&quot;policy for upload&quot;, TimeSpan.FromMinutes(30), AccessPermissions.Read | AccessPermissions.Write | AccessPermissions.List);<br />
                var locator = mediaContext.Locators.CreateSasLocator(asset, policy, DateTime.UtcNow.AddDays(1));<br />
                assetFile.Upload(_singleInputFilePath);<br />
                return &quot;Success!&quot;;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we calls a function <em>UploadImages</em> which accepts IAsset and MediaServicesCredentials as a parameter to upload the images to the asset we created. Once you run this, you can see that image has been uploaded in your asset. To check that, please go to your Azure portal and see your asset size in content tab. I am sure that the size must be changed. </p>
<div id="attachment_11644" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Image-uploaded-to-Media-Service-e1464177194192.png"><img decoding="async" aria-describedby="caption-attachment-11644" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Image-uploaded-to-Media-Service-e1464177194192.png" alt="Image uploaded to Media Service" width="650" height="105" class="size-full wp-image-11644" srcset="/wp-content/uploads/2016/05/Image-uploaded-to-Media-Service-e1464177194192.png 650w, /wp-content/uploads/2016/05/Image-uploaded-to-Media-Service-e1464177194192-300x48.png 300w, /wp-content/uploads/2016/05/Image-uploaded-to-Media-Service-e1464177194192-400x65.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11644" class="wp-caption-text">Image uploaded to Media Service</p></div>
<p>Now we will list down all the items we saved to the asset. Shall we?</p>
<p><strong>Retrieving the items from the Asset</strong></p>
<p>To retrieve the items we will add an another function as follows. </p>
<p>[csharp]<br />
 private static void GetAllTheAssetsAndFiles(MediaServicesCredentials _medServCredentials)<br />
        {<br />
            try<br />
            {<br />
                string result = string.Empty;<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(_medServCredentials);<br />
                StringBuilder myBuilder = new StringBuilder();<br />
                foreach (var item in mediaContext.Assets)<br />
                {<br />
                    myBuilder.AppendLine(Environment.NewLine);<br />
                    myBuilder.AppendLine(&quot;&#8211;My Assets&#8211;&quot;);<br />
                    myBuilder.AppendLine(&quot;Name: &quot; + item.Name);<br />
                    myBuilder.AppendLine(&quot;++++++++++++++++++++&quot;);</p>
<p>                    foreach (var subItem in item.AssetFiles)<br />
                    {<br />
                        myBuilder.AppendLine(&quot;File Name: &quot;+subItem.Name);<br />
                        myBuilder.AppendLine(&quot;Size: &quot; + subItem.ContentFileSize);<br />
                        myBuilder.AppendLine(&quot;++++++++++++++++++++++&quot;);<br />
                    }<br />
                }<br />
                Console.WriteLine(myBuilder);<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>And it will give you an output as follows. </p>
<div id="attachment_11645" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/My-Assets-and-contents.png"><img decoding="async" aria-describedby="caption-attachment-11645" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/My-Assets-and-contents-e1464178390636.png" alt="My Assets and contents" width="650" height="327" class="size-full wp-image-11645" srcset="/wp-content/uploads/2016/05/My-Assets-and-contents-e1464178390636.png 650w, /wp-content/uploads/2016/05/My-Assets-and-contents-e1464178390636-300x151.png 300w, /wp-content/uploads/2016/05/My-Assets-and-contents-e1464178390636-400x201.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11645" class="wp-caption-text">My Assets and contents</p></div>
<h3>Conclusion</h3>
<p>Did I miss anything that you may think which is needed? Have you ever tried Azure media service account? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3>Your turn. What do you think?</h3>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/working-with-azure-media-service-account/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
