<?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>Media service account &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/media-service-account/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>Media service account &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Upload Images To Azure Media Service From Client Side</title>
		<link>https://mail.sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/</link>
					<comments>https://mail.sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 30 Jun 2016 00:00:31 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Client Side Uploading Using SAS In Azure]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Media service account]]></category>
		<category><![CDATA[SAS in Azure]]></category>
		<category><![CDATA[Upload images to Azure]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11734</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. If you are new to Azure media service account, I strongly recommend you to read my previous post related to media service account. Once we create a media service account, we will create an asset and get the SAS token related to the asset we created, we will discuss more about asset and SAS token. I hope you will like this. Download the source code You can always download the source code here: Azure Media Service From Client [&#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>. 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>. Once we create a media service account, we will create an asset and get the SAS token related to the asset we created, we will discuss more about asset and SAS token. 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-To-Azure-Media-fd2c0449" target="_blank">Azure Media Service From Client Side</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. The tricky part was I needed to upload the files from client side itself. Here we are going to see how we can create an Azure media service account and how to use the same. </p>
<p><strong>What is media service account?</strong></p>
<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>
<p><strong>Prerequisites</strong></p>
<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">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 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>Create an Asset in Media service account</li>
<li>Get the SAS token for an Asset</li>
<li>Client side upload process</li>
<li>Retrieves the uploaded items</li>
<p>Now we will go and create our media service account.</p>
<p><strong>Create an Azure media service account</strong></p>
<p>To create an azure media service account, please see the link given below. I have explained the steps there.</p>
<li><a href="http://sibeeshpassion.com/working-with-azure-media-service-account/" target="_blank">Working With Azure Media Service Account</a></li>
<p>Hope you have got the storage account and media service account with you.</p>
<p><strong>Create an Asset in Media service account</strong></p>
<p>You can always create an Asset either via code or manually in <em>https://portal.azure.com</em>.</p>
<div id="attachment_11736" style="width: 596px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Blob-Service-In-Portal.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11736" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Blob-Service-In-Portal.png" alt="Blob Service In Portal" width="586" height="134" class="size-full wp-image-11736" srcset="/wp-content/uploads/2016/06/Blob-Service-In-Portal.png 586w, /wp-content/uploads/2016/06/Blob-Service-In-Portal-300x69.png 300w, /wp-content/uploads/2016/06/Blob-Service-In-Portal-400x91.png 400w" sizes="(max-width: 586px) 100vw, 586px" /></a><p id="caption-attachment-11736" class="wp-caption-text">Blob Service In Portal</p></div>
<div id="attachment_11737" style="width: 328px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/New-Container.png"><img decoding="async" aria-describedby="caption-attachment-11737" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/New-Container.png" alt="New Container" width="318" height="308" class="size-full wp-image-11737" srcset="/wp-content/uploads/2016/06/New-Container.png 318w, /wp-content/uploads/2016/06/New-Container-300x291.png 300w" sizes="(max-width: 318px) 100vw, 318px" /></a><p id="caption-attachment-11737" class="wp-caption-text">New Container</p></div>
<p>If you want to create the Asset via code, you can create as below. </p>
<p>[csharp]<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 />
[/csharp]</p>
<p>You can always get the sample codes for creating the assets from here: <a href="https://code.msdn.microsoft.com/Working-With-Azure-Media-ad283589#content" target="_blank">Azure Media Service Account</a></p>
<p><strong>Get the SAS token for an Asset</strong></p>
<p>Before going to generate SAS, we want to know what is a SAS right?</p>
<p><strong>What is SAS?</strong></p>
<p>SAS stands for shared access signature, it is the mechanism used for giving limited access to the objects in your storage account to your clients, in the way that you do not need to share your account key. In SAS, you can set how long the given access must be active and you can always set the read/write access too. If you want to know more about the SAS, I recommend you to read <a href="https://azure.microsoft.com/en-in/documentation/articles/storage-dotnet-shared-access-signature-part-1/" target="_blank">here</a>. </p>
<p>Once you downloaded the application from <a href="https://code.msdn.microsoft.com/Working-With-Azure-Media-ad283589" target="_blank">here</a>, you can add a function to generate the SAS token dynamically</p>
<p>[csharp]<br />
 private static string GenerateSASToken(string assetId)<br />
        {<br />
            CloudStorageAccount backupStorageAccount = CloudStorageAccount.Parse(myAzureCon);<br />
            CloudBlobClient client = backupStorageAccount.CreateCloudBlobClient();<br />
            CloudBlobContainer container = client.GetContainerReference(assetId);<br />
            BlobContainerPermissions permissions = container.GetPermissions();</p>
<p>            permissions.SharedAccessPolicies.Add(string.Concat(assetId, &quot;AccessPolicy&quot;), new SharedAccessBlobPolicy<br />
            {<br />
                Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,<br />
                SharedAccessExpiryTime = DateTime.UtcNow.AddDays(365)<br />
            });<br />
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;<br />
            container.SetPermissions(permissions);</p>
<p>            ServiceProperties sp = client.GetServiceProperties();<br />
            sp.DefaultServiceVersion = &quot;2013-08-15&quot;;<br />
            CorsRule cr = new CorsRule(); cr.AllowedHeaders.Add(&quot;*&quot;);<br />
            cr.AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Put | CorsHttpMethods.Post;<br />
            cr.AllowedOrigins.Add(&quot;*&quot;);<br />
            cr.ExposedHeaders.Add(&quot;x-ms-*&quot;);<br />
            sp.Cors.CorsRules.Clear();<br />
            sp.Cors.CorsRules.Add(cr);<br />
            client.SetServiceProperties(sp);<br />
            var sas = container.GetSharedAccessSignature(new SharedAccessBlobPolicy(), string.Concat(assetId, &quot;AccessPolicy&quot;));<br />
            return container.Uri + sas;<br />
        }<br />
[/csharp]</p>
<p>Here we are giving the asset id of the asset we just created. And the function will give you the SAS token we need. Hope you understood. Now we can start our client side coding for uploading.</p>
<p><strong>Client side upload process</strong></p>
<p>Create an index page with an input file and other needed UI as follows.</p>
<p>[html]<br />
&lt;!doctype html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;meta charset=&quot;utf-8&quot;&gt;<br />
    &lt;meta name=&quot;viewport&quot; content=&quot;user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width&quot;&gt;<br />
    &lt;link href=&quot;CSS/Index.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;div class=&quot;container&quot;&gt;<br />
        &lt;div class=&quot;thumbnail-fit&quot; id=&quot;azureImage&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;/div&gt;<br />
    &lt;/div&gt;<br />
    &lt;div id=&quot;uploaderDiv&quot;&gt;<br />
        &lt;form&gt;<br />
            &lt;span class=&quot;input-control text&quot;&gt;<br />
                &lt;input type=&quot;file&quot; id=&quot;file&quot; multiple accept=&quot;image/*&quot; name=&quot;file&quot; /&gt;<br />
            &lt;/span&gt;<br />
            &lt;br /&gt;<br />
            &lt;br /&gt;<br />
            &lt;input type=&quot;button&quot; value=&quot;Upload File&quot; id=&quot;buttonUploadFile&quot; /&gt;<br />
        &lt;/form&gt;<br />
    &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/jquery-ui-1.9.2.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;scripts/Index.js&quot;&gt;&lt;/script&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Now create a JS file <em>Index.js</em>. And create a file change function as follows. Sounds good?</p>
<p>[js]<br />
$(document).ready(function () {<br />
    $(&#8216;#fiesInfo&#8217;).html(&#8221;);<br />
    $(&#8216;#divOutput&#8217;).html(&#8221;);<br />
    upldCount = 0;<br />
    totSize = 0;</p>
<p>    $(&#8216;#file&#8217;).change(function () {<br />
        selectedFile = [];<br />
        if (this.files.length &gt; 0) {<br />
            $.each(this.files, function (i, v) {<br />
                totalFileSize = totalFileSize + v.size;<br />
                selectedFile.push({ size: v.size, name: v.name, file: v });<br />
            });<br />
        }<br />
    });<br />
});<br />
[/js]</p>
<p>Here we are pushing the selected files to an array in a needed format. Now we will add the upload click event.</p>
<p>[js]</p>
<p>$(&quot;#buttonUploadFile&quot;).click(function (e) {<br />
    upload();<br />
});<br />
[/js]</p>
<p>And following is the code for the function <em>upload</em>.</p>
<p>[js]<br />
function upload() {<br />
    $(&#8216;#fiesInfo&#8217;).html(&#8221;);<br />
    $(&#8216;#divOutput&#8217;).html(&#8221;);<br />
    upldCount = 0;<br />
    totSize = 0;<br />
    startDateTime = new Date();<br />
    $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;span&gt;&lt;b&gt; Uploading starts at &lt;/b&gt;&lt;/span&gt;&#8217; + startDateTime);<br />
    if (selectedFile == null) {<br />
        alert(&quot;Please select a file first.&quot;);<br />
    }<br />
    else {<br />
        for (var i = 0; i &lt; selectedFile.length; i++) {<br />
            fileUploader(selectedFile[i]);<br />
            upldCount = upldCount + 1;;<br />
            totSize = totSize + selectedFile[i].size;<br />
        }<br />
    }<br />
};<br />
[/js]</p>
<p>Did you notice that we are calling a function inside a loop which accepts file content as parameter?</p>
<p>[js]<br />
function fileUploader(selectedFileContent) {<br />
    reader = new FileReader();<br />
    var fileContent = selectedFileContent.file.slice(0, selectedFileContent.size &#8211; 1);<br />
    reader.readAsArrayBuffer(fileContent);<br />
    reader.onloadend = function (evt) {<br />
        if (evt.target.readyState == FileReader.DONE) {<br />
            var currentAzureStorageUrl = baseUrl;<br />
            var indexOfQueryStart = currentAzureStorageUrl.indexOf(&quot;?&quot;);<br />
            var uuid = generateUUID();<br />
            var fileExtension = selectedFileContent.name.split(&#8216;.&#8217;).pop();<br />
            var azureFileName = uuid + &#8216;.&#8217; + fileExtension;<br />
            submitUri = currentAzureStorageUrl.substring(0, indexOfQueryStart) + &#8216;/&#8217; + azureFileName + currentAzureStorageUrl.substring(indexOfQueryStart);<br />
            var requestData = new Uint8Array(evt.target.result);<br />
            ajaxUploadCall(submitUri, requestData);<br />
        }<br />
    };<br />
}<br />
[/js]</p>
<blockquote><p>
Here <em>baseUrl</em> is the SAS you just created for an asset. The example of SAS is <em>https://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sv=2015-04-05&#038;st=2015-04-29T22%3A18%3A26Z&#038;se=2015-04-30T02%3A23%3A26Z&#038;sr=b&#038;sp=rw&#038;sip=168.1.5.60-168.1.5.70&#038;spr=https&#038;sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D</em></p></blockquote>
<p>Once the reader onloadend event is finished we are passing the uri and data in the format of array. Can we see the AJAX call now?</p>
<p>[js]<br />
function ajaxUploadCall(submitUri, selectedFileContent) {<br />
    $.ajax({<br />
        url: submitUri,<br />
        type: &quot;PUT&quot;,<br />
        data: selectedFileContent,<br />
        processData: false,<br />
        async: false,<br />
        beforeSend: function (xhr) {<br />
            xhr.setRequestHeader(&#8216;x-ms-blob-type&#8217;, &#8216;BlockBlob&#8217;);<br />
        },<br />
        success: function (data, status) {</p>
<p>        },<br />
        complete: function (event, xhr, settings) {<br />
            compCount = compCount + 1;<br />
            if (selectedFile.length == compCount) {<br />
                RptDisplay();<br />
            }<br />
        },<br />
        error: function (xhr, desc, err) {<br />
        }<br />
    });<br />
}<br />
[/js]</p>
<p>In your ajax call please do not forget to add the header as below. </p>
<p>[js]<br />
 beforeSend: function (xhr) {<br />
            xhr.setRequestHeader(&#8216;x-ms-blob-type&#8217;, &#8216;BlockBlob&#8217;);<br />
        }<br />
[/js]</p>
<p>If every selected files are uploaded we are calling a function <em>RptDisplay()</em> right?</p>
<p>[js]<br />
function RptDisplay() {<br />
    $(&#8216;#divOutput&#8217;).hide();<br />
    $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;table&gt;&lt;/table&gt;&#8217;);<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; + upldCount + &#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 />
[/js]</p>
<p>You can get all the other needed functions like findDateDiff(), formatSizeUnits(), generateUUID() and the CSS from the source code attached. Please download the same. Now please run your page and you can find an input file there, select few files and try upload, if you have configured everything fine, I am sure you will get a report. Let us see that now. </p>
<div id="attachment_11738" style="width: 266px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File.png"><img decoding="async" aria-describedby="caption-attachment-11738" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File.png" alt="Upload File" width="256" height="130" class="size-full wp-image-11738" /></a><p id="caption-attachment-11738" class="wp-caption-text">Upload File</p></div>
<div id="attachment_11739" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png"><img decoding="async" aria-describedby="caption-attachment-11739" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png" alt="Upload File Output" width="650" height="215" class="size-full wp-image-11739" srcset="/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png 650w, /wp-content/uploads/2016/06/Upload-File-Output-e1467268304577-300x99.png 300w, /wp-content/uploads/2016/06/Upload-File-Output-e1467268304577-400x132.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11739" class="wp-caption-text">Upload File Output</p></div>
<p><strong>Retrieves the uploaded items</strong></p>
<p>To retrieve the items you can always create a function as follows, which accepts asset id as parameter. </p>
<p>[csharp]<br />
public string getEventImage(string assetID)<br />
        {<br />
            CloudStorageAccount backupStorageAccount = CloudStorageAccount.Parse(myAzureCon);<br />
            CloudBlobClient client = backupStorageAccount.CreateCloudBlobClient();<br />
            CloudBlobContainer container = client.GetContainerReference(assetID.Replace(&quot;nb:cid:UUID:&quot;, &quot;asset-&quot;));<br />
            List&lt;string&gt; results = new List&lt;string&gt;();<br />
            foreach (IListBlobItem item in container.ListBlobs(null, false))<br />
            {<br />
                results.Add(item.Uri.ToString());<br />
            }<br />
            return JsonConvert.SerializeObject(results);<br />
        }<br />
[/csharp]</p>
<p>Now if you login to your azure portal and click on the asset you created, you can see the contents are uploaded there.</p>
<div id="attachment_11742" style="width: 599px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Uploaded-Contents.png"><img decoding="async" aria-describedby="caption-attachment-11742" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Uploaded-Contents.png" alt="Uploaded Contents" width="589" height="315" class="size-full wp-image-11742" srcset="/wp-content/uploads/2016/06/Uploaded-Contents.png 589w, /wp-content/uploads/2016/06/Uploaded-Contents-300x160.png 300w, /wp-content/uploads/2016/06/Uploaded-Contents-400x214.png 400w" sizes="(max-width: 589px) 100vw, 589px" /></a><p id="caption-attachment-11742" class="wp-caption-text">Uploaded Contents</p></div>
<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-images-to-azure-media-service-from-client-side/feed/</wfw:commentRss>
			<slash:comments>0</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>
