public void Process(IAsset asset)
        {
            var mediaProcessor = GetMediaProcessor(MediaProcessors.WINDOWS_AZURE_MEDIA_PACKAGER);
            var job = mediaContext.Jobs.Create(string.Format("{0} encode video job", asset.Name));

            //TODO: Create constants for task names
            var task = job.Tasks.AddNew("Convert Media Task", mediaProcessor, @"<taskDefinition xmlns=""http://schemas.microsoft.com/iis/media/v4/TM/TaskDefinition#"">
  <name>MP4 to Smooth Streams</name>
  <id>5e1e1a1c-bba6-11df-8991-0019d1916af0</id>
  <description xml:lang=""en"">Converts MP4 files encoded with H.264 (AVC) video and AAC-LC audio codecs to Smooth Streams.</description>
  <inputFolder />
  <properties namespace=""http://schemas.microsoft.com/iis/media/V4/TM/MP4ToSmooth#"" prefix=""mp4"">
    <property name=""keepSourceNames"" required=""false"" value=""false"" helpText=""This property tells the MP4 to Smooth task to keep the original file name rather than add the bitrate bitrate information."" />
  </properties>
  <taskCode>
    <type>Microsoft.Web.Media.TransformManager.MP4toSmooth.MP4toSmooth_Task, Microsoft.Web.Media.TransformManager.MP4toSmooth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</type>
  </taskCode>
</taskDefinition>", TaskOptions.None);
            task.InputAssets.Add(asset);
            var smoothAsset = task.OutputAssets.AddNew(string.Format("{0} smooth streaming", asset.Name), AssetCreationOptions.None);

            var thumbnailMediaProcessor = GetMediaProcessor(MediaProcessors.WINDOWS_AZURE_MEDIA_ENCODER);
            thumbnailService.GenerateThumbnail(job, smoothAsset, thumbnailMediaProcessor, 236, 177);

            job.Submit();             
        }
Esempio n. 2
0
        /// <summary>
        /// The handle.
        /// </summary>
        /// <param name="asset">
        /// The asset.
        /// </param>
        /// <param name="target">
        /// The target.
        /// </param>
        /// <returns>
        /// The <see cref="dynamic"/>.
        /// </returns>
        public IRawAsset Handle(IAsset asset, AssetTarget target)
        {
            var textAsset = asset as LanguageAsset;

            return
                new AnonymousObjectBasedRawAsset(new { Loader = typeof(LanguageAssetLoader).FullName, textAsset.Value });
        }
Esempio n. 3
0
 public PlainScript(IAsset asset, Bundle bundle, IModuleInitializer modules,string baseUrl = null)
     : base(asset, bundle, baseUrl)
 {
     this.modules = modules;
     jsonSerializer = new SimpleJsonSerializer();
     asset.AddAssetTransformer(this);
 }
Esempio n. 4
0
 static ModuleDefinitionParser ParseJavaScriptForModuleDefinition(IAsset asset)
 {
     var tree = ParseJavaScript(asset);
     var moduleDefinitionParser = new ModuleDefinitionParser();
     tree.Accept(moduleDefinitionParser);
     return moduleDefinitionParser;
 }
Esempio n. 5
0
        private static async Task<IJob> CreateMediaEncodeJob(CloudMediaContext context, IAsset assetToEncode)
        {
            //string encodingPreset = "H264 Broadband 720p";
            string encodingPreset = "H264 Smooth Streaming 720p";

            IJob job = context.Jobs.Create("Encoding " + assetToEncode.Name + " to " + encodingPreset);

            string[] y =
                context.MediaProcessors.Where(mp => mp.Name.Equals("Azure Media Encoder"))
                    .ToArray()
                    .Select(mp => mp.Version)
                    .ToArray();

            IMediaProcessor latestWameMediaProcessor =
                context.MediaProcessors.Where(mp => mp.Name.Equals("Azure Media Encoder"))
                    .ToArray()
                    .OrderByDescending(
                        mp =>
                            new Version(int.Parse(mp.Version.Split('.', ',')[0]),
                                int.Parse(mp.Version.Split('.', ',')[1])))
                    .First();

            ITask encodeTask = job.Tasks.AddNew("Encoding", latestWameMediaProcessor, encodingPreset, TaskOptions.None);
            encodeTask.InputAssets.Add(assetToEncode);
            encodeTask.OutputAssets.AddNew(assetToEncode.Name + " as " + encodingPreset, AssetCreationOptions.None);

            job.StateChanged += new EventHandler<JobStateChangedEventArgs>((sender, jsc) => Console.WriteLine(
                $"{((IJob) sender).Name}\n  State: {jsc.CurrentState}\n  Time: {DateTime.UtcNow.ToString(@"yyyy_M_d_hhmmss")}\n\n"));
            return await job.SubmitAsync();
        }
 /// <summary>
 /// Returns a new <see cref="ILocator"/> instance.
 /// </summary>
 /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param>
 /// <param name="locatorType">The <see cref="LocatorType"/>.</param>
 /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param>
 /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param>
 /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param>
 /// <param name="startTime">The start time of the new <see cref="ILocator"/>.</param>
 /// <returns>A a new <see cref="ILocator"/> instance.</returns>
 public static ILocator Create(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration, DateTime? startTime)
 {
     using (Task<ILocator> task = locators.CreateAsync(locatorType, asset, permissions, duration, startTime))
     {
         return task.Result;
     }
 }
        public void ShouldDownloadAssetFilesToFolder()
        {
            var originalFolderPath = "Media";
            this.asset = this.context.Assets.CreateFromFolder(originalFolderPath, AssetCreationOptions.None);
            var assetId = this.asset.Id;

            string downloadFolderPath = CreateEmptyDirectory();

            try
            {
                this.asset.DownloadToFolder(downloadFolderPath);

                Assert.AreEqual(3, Directory.GetFiles(downloadFolderPath).Length);

                AssertDownloadedFile(originalFolderPath, downloadFolderPath, "smallwmv1.wmv");
                AssertDownloadedFile(originalFolderPath, downloadFolderPath, "smallwmv2.wmv");
                AssertDownloadedFile(originalFolderPath, downloadFolderPath, "dummy.ism");

                this.context = TestHelper.CreateContext();
                Assert.AreEqual(0, this.context.Locators.Where(l => l.AssetId == assetId).Count());
            }
            finally
            {
                DeleteDirectoryIfExists(downloadFolderPath);
            }
        }
Esempio n. 8
0
        public static IAsset EncodeToAdaptiveBitrateMP4s(IAsset asset, AssetCreationOptions options)
        {
            // Prepare a job with a single task to transcode the specified asset
            // into a multi-bitrate asset.

            IJob job = _context.Jobs.CreateWithSingleTask(
                MediaProcessorNames.AzureMediaEncoder,
                MediaEncoderTaskPresetStrings.H264AdaptiveBitrateMP4Set720p,
                asset,
                "Adaptive Bitrate MP4",
                options);

            Console.WriteLine("Submitting transcoding job...");

            // Submit the job and wait until it is completed.
            job.Submit();

            job = job.StartExecutionProgressTask(
                j =>
                {
                    Console.WriteLine("Job state: {0}", j.State);
                    Console.WriteLine("Job progress: {0:0.##}%", j.GetOverallProgress());
                },
                CancellationToken.None).Result;

            Console.WriteLine("Transcoding job finished.");

            IAsset outputAsset = job.OutputMediaAssets[0];

            return outputAsset;
        }
Esempio n. 9
0
        /// <summary>
        /// The handle.
        /// </summary>
        /// <param name="asset">
        /// The asset.
        /// </param>
        /// <param name="target">
        /// The target.
        /// </param>
        /// <returns>
        /// The <see cref="dynamic"/>.
        /// </returns>
        public IRawAsset Handle(IAsset asset, AssetTarget target)
        {
            var textureAsset = asset as TextureAsset;

            if (textureAsset.SourcedFromRaw && target != AssetTarget.CompiledFile)
            {
                // We were sourced from a raw PNG; we don't want to save
                // an ".asset" file back to disk.
                return null;
            }

            if (target == AssetTarget.CompiledFile)
            {
                return new CompiledAsset
                {
                    Loader = typeof(TextureAssetLoader).FullName,
                    PlatformData = textureAsset.PlatformData
                };
            }

            return
                new AnonymousObjectBasedRawAsset(
                    new
                    {
                        Loader = typeof(TextureAssetLoader).FullName,
                        PlatformData = target == AssetTarget.SourceFile ? null : textureAsset.PlatformData,
                        RawData =
                            textureAsset.RawData == null ? null : textureAsset.RawData.Select(x => (int)x).ToList()
                    });
        }
 private static string GetAssetUrl(IAsset asset)
 {
     if (asset.CurrentPath.Contains("://")) {
         return asset.CurrentPath;
     }
     return VirtualPathUtility.ToAbsolute(asset.CurrentPath);
 }
        /// <summary>
        /// Translates a code of asset written on TypeScript to JS-code
        /// </summary>
        /// <param name="asset">Asset</param>
        /// <param name="transformer">Transformer</param>
        /// <param name="isDebugMode">Flag that web application is in debug mode</param>
        /// <returns>Translated asset</returns>
        protected override IAsset TranslateAsset(IAsset asset, ITransformer transformer, bool isDebugMode)
        {
            IAsset processedAsset = InnerTranslateAsset<TypeScriptTranslator>(
                Constants.TranslatorName.TypeScriptTranslator, asset, transformer, isDebugMode);

            return processedAsset;
        }
Esempio n. 12
0
        void SendAsset(HttpRequestBase request, HttpResponseBase response, Bundle bundle, IAsset asset)
        {
            response.ContentType = bundle.ContentType;

            var actualETag = "\"" + asset.Hash.ToHexString() + "\"";
            if(request.RawUrl.Contains(asset.Hash.ToHexString())) {
                CacheLongTime(response, actualETag);
            }
            else {
                NoCache(response);
            }

            var givenETag = request.Headers["If-None-Match"];
            if (!disableHashCheck && givenETag == actualETag)
            {
                SendNotModified(response);
            }
            else
            {
                using (var stream = asset.OpenStream())
                {
                    stream.CopyTo(response.OutputStream);
                }
            }
        }
Esempio n. 13
0
 public PlainScript(IAsset asset, Bundle bundle, IAmdConfiguration modules)
     : base(asset, bundle)
 {
     this.modules = modules;
     jsonSerializer = new SimpleJsonSerializer();
     asset.AddAssetTransformer(this);
 }
Esempio n. 14
0
 void AddRawFileReferenceForEachImportedFile(IAsset asset, CompileResult compileResult)
 {
     foreach (var importedFilePath in compileResult.ImportedFilePaths)
     {
         asset.AddRawFileReference(importedFilePath);
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetFileCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The cloud media context.</param>
 /// <param name="parentAsset">The parent <see cref="IAsset"/>.</param>
 internal AssetFileCollection(MediaContextBase cloudMediaContext, IAsset parentAsset)
     : this(cloudMediaContext)
 {
     _parentAsset = parentAsset;
     MediaServicesClassFactory factory = this.MediaContext.MediaServicesClassFactory;
     this._assetFileQuery = new Lazy<IQueryable<IAssetFile>>(() => factory.CreateDataServiceContext().CreateQuery<IAssetFile, AssetFileData>(FileSet));
 }
Esempio n. 16
0
        void SendAsset(Bundle bundle, IAsset asset)
        {
            response.ContentType = bundle.ContentType;

            var actualETag = "\"" + asset.Hash.ToHexString() + "\"";
            if(request.RawUrl.Contains(asset.Hash.ToHexString())) {
                HttpResponseUtil.CacheLongTime(response, actualETag);
            }
            else {
                HttpResponseUtil.NoCache(response);
            }

            var givenETag = request.Headers["If-None-Match"];
            if (givenETag == actualETag)
            {
                HttpResponseUtil.SendNotModified(response);
            }
            else
            {
                HttpResponseUtil.EncodeStreamAndAppendResponseHeaders(request, response);

                using (var stream = asset.OpenStream())
                {
                    stream.CopyTo(response.OutputStream);
                }
            }
        }
Esempio n. 17
0
        /**
         * Create a simulated asset from a real one.
         * It extract the name of real asset for "fake" one
         * and the first price (at first date) and simulate
         * at all dates from dates_simul.
         * 
         * getPrice(t) with t from dates_simul will then return
         * a simulated price
         * getPrice(t) with t before first date from dates_simul
         * will return real price of asset
         * getPrice(t) with all others date will throw exception
         **/
        public AssetSimulated(IAsset real, LinkedList<DateTime> dates_simul, RandomNormal rand)
        {
            this.real = real;
            prices = new Dictionary<DateTime, double>();
            first_date = dates_simul.First();
            r = 0.04;
                //real.getCurrency().getInterestRate(first_date, TimeSpan.Zero);
            // TODO
            //sigma = real.getVolatility(first_date);
            sigma = 0.2;

            // debug kevin
            double St = 75 + 50*rand.NextDouble();
            DateTime lastDate = first_date;
            //double S0 = real.getPrice(first_date);
            int i = 0;
            foreach (DateTime date in dates_simul)
            {
                double T = (date - lastDate).TotalDays / 365; // time in year
                double WT = Math.Sqrt(T) * rand.NextNormal();
                St = St * Math.Exp((r - sigma * sigma / 2) * T + sigma * WT);
                prices[date] = St;
                lastDate = date;
                i++;
            }
        }
        public ExportAssetToAzureStorage(CloudMediaContext contextUploadArg, string MediaServicesStorageAccountKeyArg, IAsset sourceAsset, string StorageSuffix)
        {
            InitializeComponent();
            this.Icon = Bitmaps.Azure_Explorer_ico;
            MediaServicesStorageAccountKey = MediaServicesStorageAccountKeyArg;
            contextUpload = contextUploadArg;

            // list asset files ///////////////////////
            bool bfileinasset = (sourceAsset.AssetFiles.Count() == 0) ? false : true;
            listViewAssetFiles.Items.Clear();
            if (bfileinasset)
            {
                listViewAssetFiles.BeginUpdate();
                foreach (IAssetFile file in sourceAsset.AssetFiles)
                {
                    ListViewItem item = new ListViewItem(file.Name, 0);
                    if (file.IsPrimary) item.ForeColor = Color.Blue;
                    item.SubItems.Add(file.LastModified.ToLocalTime().ToString("G"));
                    item.SubItems.Add(AssetInfo.FormatByteSize(file.ContentFileSize));
                    (listViewAssetFiles.Items.Add(item)).Selected = true;
                    listassetfiles.Add(file);
                }

                listViewAssetFiles.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
                listViewAssetFiles.EndUpdate();

            }
            myStorageSuffix = StorageSuffix;
        }
        public Func<Stream> Transform(Func<Stream> openSourceStream, IAsset asset)
        {
            return () =>
            {
                var addTemplateCalls = openSourceStream().ReadToEnd();

                var output = string.Format(
                    @"(function(d) {{
            var addTemplate = function(id, content) {{
            var script = d.createElement('script');
            script.type = '{0}';
            script.id = id;
            if (typeof script.textContent !== 'undefined') {{
            script.textContent = content;
            }} else {{
            script.innerText = content;
            }}
            var x = d.getElementsByTagName('script')[0];
            x.parentNode.insertBefore(script, x);
            }};
            {1}
            }}(document));",
                    contentType,
                    addTemplateCalls);

                return new MemoryStream(Encoding.UTF8.GetBytes(output));
            };
        }
Esempio n. 20
0
        public NamedModule(IAsset asset, Bundle bundle, string modulePath)
            : base(asset, bundle)
        {
            if (modulePath == null) throw new ArgumentNullException("modulePath");

            ModulePath = modulePath;
        }
 public Func<Stream> Transform(Func<Stream> openSourceStream, IAsset asset)
 {
     return delegate
     {
         var css = ReadCss(openSourceStream);
         var currentDirectory = GetCurrentDirectory(asset);
         var urlMatches = UrlMatchesInReverse(css);
         var builder = new StringBuilder(css);
         foreach (var match in urlMatches)
         {
             var matchedUrlGroup = match.Groups["url"];
             string queryString;
             string fragment;
             var relativeFilename = GetImageFilename(matchedUrlGroup, currentDirectory, out queryString, out fragment);
             if (ReplaceUrlWithCassetteRawFileUrl(builder, matchedUrlGroup, relativeFilename, queryString, fragment))
             {
                 asset.AddRawFileReference(relativeFilename);
             }
             else
             {
                 ReplaceUrlWithAbsoluteUrl(builder, matchedUrlGroup, currentDirectory);
             }
         }
         return builder.ToString().AsStream();
     };
 }
        /// <summary>
        /// Translates a code of asset written on EcmaScript2015 to JS-code
        /// </summary>
        /// <param name="asset">Asset</param>
        /// <param name="transformer">Transformer</param>
        /// <param name="isDebugMode">Flag that web application is in debug mode</param>
        /// <returns>Translated asset</returns>
        protected override IAsset TranslateAsset(IAsset asset, ITransformer transformer, bool isDebugMode)
        {
            IAsset processedAsset = InnerTranslateAsset<BabelJsTranslator>(
                AssetTypeCode.EcmaScript2015, asset, transformer, isDebugMode);

            return processedAsset;
        }
        private static async Task<ILocator> CreateSasLocatorAsync(CloudMediaContext context, IAsset asset)
        {
            var accessPolicy = await context.AccessPolicies.CreateAsync(
                asset.Name, TimeSpan.FromDays(2), AccessPermissions.Write | AccessPermissions.List);

            return await context.Locators.CreateSasLocatorAsync(asset, accessPolicy);
        }
Esempio n. 24
0
 public void setParam(List<Param> param)
 {
     Param[] P = param.ToArray();
     underlying = ModelManage.instance.Assets.Find(x => String.Compare(x.getName(), P[0].getString()) == 0);
     strike = P[1].getDouble();
     maturity = P[2].getDate();
 }
 public CssBackgroundImageUrlMatchTransformer(Match match, IAsset asset)
     : base(match, asset)
 {
     fullProperty = match.Value;
     start = match.Groups["start"].Value;
     end = match.Groups["end"].Value;
 }
Esempio n. 26
0
        public async void RenameAsset(IAsset asset, string newName)
        {
            // Create the request
            var client = new HttpClient();
            var resource = string.Format("https://wamsbluclus001rest-hs.cloudapp.net/API/Assets('{0}')", asset.Id);
            var request = new HttpRequestMessage(new HttpMethod("MERGE"), resource);

            // Set the request content
            var content = string.Format("{{ 'Name' : '{0}' }}", newName);
            var stringContent = new StringContent(content, Encoding.UTF8, "application/json");
            var oDataParameter = new NameValueHeaderValue("odata", "verbose");
            stringContent.Headers.ContentType.Parameters.Add(oDataParameter);
            request.Content = stringContent;
            
            // Set the request headers
            var jsonAccessToken = await this.GetAccessToken();
            string accessToken = JsonConvert.DeserializeObject<dynamic>(jsonAccessToken).access_token.Value;
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            request.Headers.Add("DataServiceVersion", "3.0");
            request.Headers.Add("MaxDataServiceVersion", "3.0");
            request.Headers.Add("x-ms-version", "1.0");
            request.Headers.Host = "wamsbluclus001rest-hs.cloudapp.net";
            var mediaType = new MediaTypeWithQualityHeaderValue("application/json");
            mediaType.Parameters.Add(oDataParameter);
            client.DefaultRequestHeaders.Accept.Add(mediaType);

            // Make the request
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
        }
Esempio n. 27
0
		private IEnumerator LoadAsset(IAsset asset)
		{
			if (!asset.Loaded)
			{
				ResourceRequest request = Resources.LoadAsync(PathPrefix != null ? PathPrefix + "/" + asset.Path : asset.Path);

				Requests[asset] = request;

				yield return request;

				if (request.asset != null)
				{
					asset.Resource = Instantiate(request.asset);

					if (asset.Resource is GameObject)
					{
						((GameObject)(asset.Resource)).transform.SetParent(AssetPool.transform, false);
					}

					asset.Loaded = true;
				}
				else
				{
					Debug.LogError("Failed to load asset! Could not find: " + asset.Path);
				}
			}
		}
        public static string ConvertAssetToSmoothStreaming(this CloudMediaContext context, IAsset asset, bool createThumbnail)
        {
            var configuration = MediaServicesHelper.H264SmoothStreamingEncodingPreset;
            var processor = context.MediaProcessors.Where(m => m.Id == MediaServicesHelper.EncoderProcessorId).FirstOrDefault();            

            var job = context.Jobs.Create(asset.Name);

            var task = job.Tasks.AddNew(
                MediaServicesHelper.EncodingTask,
                processor,
                configuration,
                TaskOptions.None);

            task.InputAssets.Add(asset);
            var encodedAsset = task.OutputAssets.AddNew(asset.Name + " - [" + configuration + "]", true, AssetCreationOptions.None);
            encodedAsset.AlternateId = asset.AlternateId + "_0";

            if (createThumbnail)
            {
                var thumbnailTask = job.Tasks.AddNew(
                    MediaServicesHelper.ThumbnailTask,
                    processor,
                    MediaServicesHelper.ThumbnailPreset,
                    TaskOptions.None);

                thumbnailTask.InputAssets.Add(asset);
                var thumbnailAsset = thumbnailTask.OutputAssets.AddNew(asset.Name + " - [thumbnail]", true, AssetCreationOptions.None);
                thumbnailAsset.AlternateId = asset.AlternateId + "_1";
            }
            
            job.Submit();

            return job.Id;
        }
Esempio n. 29
0
        /// <summary>
        /// The handle.
        /// </summary>
        /// <param name="asset">
        /// The asset.
        /// </param>
        /// <param name="target">
        /// The target.
        /// </param>
        /// <returns>
        /// The <see cref="dynamic"/>.
        /// </returns>
        public IRawAsset Handle(IAsset asset, AssetTarget target)
        {
            var fontAsset = asset as FontAsset;

            if (target == AssetTarget.CompiledFile)
            {
                if (fontAsset.PlatformData == null)
                {
                    throw new InvalidOperationException(
                        "Attempted save of font asset as a compiled file, but the font wasn't compiled.  This usually " +
                        "indicates that the font '" + fontAsset.FontName + "' is not installed on the current system.");
                }

                return new CompiledAsset
                {
                    Loader = typeof(FontAssetLoader).FullName,
                    PlatformData = fontAsset.PlatformData
                };
            }

            return
                new AnonymousObjectBasedRawAsset(
                    new
                    {
                        Loader = typeof(FontAssetLoader).FullName,
                        fontAsset.FontSize,
                        fontAsset.FontName,
                        fontAsset.UseKerning,
                        fontAsset.Spacing,
                        PlatformData = target == AssetTarget.SourceFile ? null : fontAsset.PlatformData
                    });
        }
        public Func<Stream> Transform(Func<Stream> openSourceStream, IAsset asset)
        {
            return delegate
            {
                using (var input = new StreamReader(openSourceStream()))
                {
                    var stream = new MemoryStream();
                    var writer = new StreamWriter(stream);

                    var regex = new Regex("__R\\([\"']{1}.*?[\"']{1}\\)", RegexOptions.Compiled);
                    var script = regex.Replace(input.ReadToEnd(), delegate(Match match)
                    {
                        var resource = match.Value
                            .Remove(match.Value.LastIndexOf(")"), 1)
                            .Replace("__R", "$.localize");

                        resource = string.Format("{0}, \"{1}\")", resource, _path);

                        return Path.GetExtension(_path) == ".htm" ? "${" + resource + "}" : resource;
                    });

                    writer.Write(script);
                    writer.Flush();
                    stream.Position = 0;

                    return stream;
                }
            };
        }
        public static IJob CreateAndSubmitOneTaskJob(CloudMediaContext context, string name, IMediaProcessor mediaProcessor, string preset, IAsset asset, TaskOptions options)
        {
            IJob job = context.Jobs.Create(name);

            job.Priority = InitialJobPriority;
            ITask task = job.Tasks.AddNew("Task1", mediaProcessor, preset, options);

            task.InputAssets.Add(asset);
            task.OutputAssets.AddNew("Output asset", AssetCreationOptions.None);
            DateTime timebeforeSubmit = DateTime.UtcNow;

            job.Submit();
            Assert.AreEqual(1, job.Tasks.Count, "Job contains unexpected amount of tasks");
            Assert.AreEqual(1, job.InputMediaAssets.Count, "Job contains unexpected total amount of input assets");
            Assert.AreEqual(1, job.OutputMediaAssets.Count, "Job contains unexpected total amount of output assets");
            Assert.AreEqual(1, job.Tasks[0].InputAssets.Count, "job.Task[0] contains unexpected amount of input assets");
            Assert.AreEqual(1, job.Tasks[0].OutputAssets.Count, "job.Task[0] contains unexpected amount of output assets");
            Assert.IsFalse(String.IsNullOrEmpty(job.Tasks[0].InputAssets[0].Id), "Asset Id is Null or empty");
            Assert.IsFalse(String.IsNullOrEmpty(job.Tasks[0].OutputAssets[0].Id), "Asset Id is Null or empty");
            return(job);
        }
Esempio n. 32
0
        public bool execute(ICustomRequest request)
        {
            bool response = true;
            MediaServicesCredentials xIdentity = new MediaServicesCredentials(request.MediaAccountName, request.MediaAccountKey);

            _MediaServicesContext = new CloudMediaContext(xIdentity);

            IJob job = _MediaServicesContext.Jobs.Create("Video Thumbnail Job");

            string MediaProcessorName = "Azure Media Video Thumbnails";

            var processor = GetLatestMediaProcessorByName(MediaProcessorName);

            IAsset curretAsset = _MediaServicesContext.Assets.Where(a => a.Id == request.AssetId).FirstOrDefault();

            IAsset video360 = _MediaServicesContext.Assets.Create(curretAsset.Name.ToString() + " 360", AssetCreationOptions.None);

            List <IAssetFile> filesToCopy;

            filesToCopy = GetFiles(curretAsset, "360_500.mp4");

            CopyAssetFiles(video360, filesToCopy);

            String configuration = "{\"version\":\"1.0\",\"options\":{\"outputAudio\" : \"false\", \"maxMotionThumbnailDurationInSecs\": \"10\", \"fadeInFadeOut\" : \"false\" }}";

            // Create a task with the encoding details, using a string preset.
            ITask task = job.Tasks.AddNew("My Video Thumbnail Task " + curretAsset.Id.ToString(),
                                          processor,
                                          configuration,
                                          TaskOptions.None);

            // Specify the input asset.
            task.InputAssets.Add(video360);

            // Specify the output asset.

            task.OutputAssets.AddNew(curretAsset.Id.ToString() + " Summarized", AssetCreationOptions.None);

            // Use the following event handler to check job progress.
            job.StateChanged += new EventHandler <JobStateChangedEventArgs>(StateChanged);

            // Launch the job.
            job.Submit();

            // Check job execution and wait for job to finish.
            Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);

            progressJobTask.Wait();

            // If job state is Error, the event handling
            // method for job progress should log errors.  Here we check
            // for error state and exit if needed.
            if (job.State == JobState.Error)
            {
                ErrorDetail error = job.Tasks.First().ErrorDetails.First();
                Console.WriteLine(string.Format("Error: {0}. {1}",
                                                error.Code,
                                                error.Message));
                response = false;
            }

            IAsset summarizedAsset = _MediaServicesContext.Assets.Where(a => a.Name == curretAsset.Id.ToString() + " Summarized").FirstOrDefault();

            List <IAssetFile> filesToCopy2;

            filesToCopy2 = GetFiles(summarizedAsset, ".mp4");

            CopyAssetFiles(curretAsset, filesToCopy2);

            video360.Delete();
            summarizedAsset.Delete();

            return(response);
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            try
            {
                MediaServicesCredentials credentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey);
                CloudMediaContext        context     = new CloudMediaContext(credentials);

                Console.WriteLine("Creating new asset from local file...");

                // 1. Create a new asset by uploading a mezzanine file from a local path.
                IAsset inputAsset = context.Assets.CreateFromFile(_singleInputMp4Path, AssetCreationOptions.None,
                                                                  (af, p) =>
                {
                    Console.WriteLine("Uploading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);
                });

                Console.WriteLine("Asset created.");

                // 2. Prepare a job with a single task to transcode the previous mezzanine asset
                // into a multi-bitrate asset.
                IJob job = context.Jobs.CreateWithSingleTask(MediaProcessorNames.WindowsAzureMediaEncoder,
                                                             MediaEncoderTaskPresetStrings.H264AdaptiveBitrateMP4Set720p,
                                                             inputAsset,
                                                             "Sample Adaptive Bitrate MP4",
                                                             AssetCreationOptions.None);

                Console.WriteLine("Submitting transcoding job...");

                // 3. Submit the job and wait until it is completed.
                job.Submit();
                job = job.StartExecutionProgressTask(j => {
                    Console.WriteLine("Job state: {0}", j.State);
                    Console.WriteLine("Job progress: {0:0.##}%", j.GetOverallProgress());
                }, CancellationToken.None).Result;

                Console.WriteLine("Transcoding job finished.");

                IAsset outputAsset = job.OutputMediaAssets[0];

                Console.WriteLine("Publishing output asset...");

                // 4. Publish the output asset by creating an Origin locator for adaptive streaming,
                // and a SAS locator for progressive download.
                context.Locators.Create(LocatorType.OnDemandOrigin, outputAsset, AccessPermissions.Read, TimeSpan.FromDays(30));
                context.Locators.Create(LocatorType.Sas, outputAsset, AccessPermissions.Read, TimeSpan.FromDays(30));

                IEnumerable <IAssetFile> mp4AssetFiles = outputAsset.AssetFiles.ToList()
                                                         .Where(af => af.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase));

                // 5. Generate the Smooth Streaming, HLS and MPEG-DASH URLs for adaptive streaming,
                // and the Progressive Download URL.
                Uri        smoothStreamingUri         = outputAsset.GetSmoothStreamingUri();
                Uri        hlsUri                     = outputAsset.GetHlsUri();
                Uri        mpegDashUri                = outputAsset.GetMpegDashUri();
                List <Uri> mp4ProgressiveDownloadUris = mp4AssetFiles.Select(af => af.GetSasUri()).ToList();

                // 6. Get the asset URLs.
                Console.WriteLine(smoothStreamingUri);
                Console.WriteLine(hlsUri);
                Console.WriteLine(mpegDashUri);
                mp4ProgressiveDownloadUris.ForEach(uri => Console.WriteLine(uri));

                Console.WriteLine("Output asset available for adaptive streaming and progressive download.");

                Console.WriteLine("VOD workflow finished.");
            }
            catch (Exception exception)
            {
                // Parse the XML error message in the Media Services response and create a new
                // exception with its content.
                exception = MediaServicesExceptionParser.Parse(exception);

                Console.Error.WriteLine(exception.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Esempio n. 34
0
 private void Setup()
 {
     _MediaServicesContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey);
     theAsset = _MediaServicesContext.Assets.Where(xx => xx.Id == myRequest.AssetId).FirstOrDefault();
 }
Esempio n. 35
0
    static IAsset RunIndexingJob(string inputMediaFilePath, string configurationFile)
    {
        Console.WriteLine("Preparing to Upload '{0}'", inputMediaFilePath);
        // Create an asset and upload the input media file to storage.
        IAsset asset = UploadFile(inputMediaFilePath, AssetCreationOptions.None);

        // Declare a new job.
        IJob job = _context.Jobs.Create("Voice2Text Job");

        // Get a reference to Azure Media Indexer 2 Preview.
        string MediaProcessorName = "Azure Media Indexer 2 Preview";

        var processor = GetLatestMediaProcessorByName(MediaProcessorName);

        Console.WriteLine("Reading Configuration File {0}", configurationFile);
        // Read configuration from the specified file.
        string configuration = File.ReadAllText(configurationFile);

        // Create a task with the encoding details, using a string preset.
        ITask task = job.Tasks.AddNew("Voice2Text Task",
                                      processor,
                                      configuration,
                                      TaskOptions.None);

        // Specify the input asset to be indexed.
        task.InputAssets.Add(asset);

        // Add an output asset to contain the results of the job.
        task.OutputAssets.AddNew("Voice2Text Output", AssetCreationOptions.None);

        // Use the following event handler to check job progress.
        job.StateChanged += new EventHandler <JobStateChangedEventArgs>(StateChanged);

        Console.WriteLine("Submitting Speach Recognition Job.");
        // Launch the job.
        job.Submit();


        // Check job execution and wait for job to finish.
        Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);

        // Show Job Progress until Job completed, Escape key cancels
        while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
        {
            Console.Write("\rProcessing - {0:0}% {1}", job.GetOverallProgress(), progressJobTask.Status);
            if (progressJobTask.IsCompleted || progressJobTask.IsCompletedSuccessfully || progressJobTask.IsCanceled || progressJobTask.IsFaulted)
            {
                break;
            }
        }

        // If job state is Error, the event handling
        // method for job progress should log errors.  Here we check
        // for error state and exit if needed.
        if (job.State == JobState.Error)
        {
            ErrorDetail error = job.Tasks.First().ErrorDetails.First();
            Console.WriteLine(string.Format("Error: {0}. {1}",
                                            error.Code,
                                            error.Message));
            return(null);
        }
        Console.WriteLine("\nCleaning Input Asset: " + asset.Name);
        asset.Delete();

        return(job.OutputMediaAssets[0]);
    }
Esempio n. 36
0
 public override void RequestAsset(WithAssetObject source, IAsset asset, PayMoneyReason reason)
 {
 }
Esempio n. 37
0
 public void Visit(IAsset asset)
 {
     count++;
 }
        private async Task <double> GetBalance(string address, IEnumerable <IAsset> assets, IAsset asset)
        {
            var btc = assets.First(x => x.Id == LykkeConstants.BitcoinAssetId);

            var result = await DoRequest($"{_url}balances/{address}/summary?colored=true");

            var model = Newtonsoft.Json.JsonConvert.DeserializeObject <BalanceSummaryModel>(result);

            if (asset.BlockChainAssetId == null)
            {
                return(model.Spendable.Amount * btc.Multiplier);
            }
            var balanceSummaryForAsset = model.Spendable.Assets.FirstOrDefault(x => x.AssetId == asset.BlockChainAssetId);

            if (balanceSummaryForAsset != null)
            {
                return(balanceSummaryForAsset.Quantity * asset.Multiplier);
            }

            return(0);
        }
        public async Task <double> GetBalancesSum(IEnumerable <string> addresses, IEnumerable <IAsset> assets, IAsset asset)
        {
            var getBalanceTasks = addresses.Select(address => GetBalance(address, assets, asset)).ToList();

            var balances = await Task.WhenAll(getBalanceTasks);

            return(balances.Sum());
        }
Esempio n. 40
0
        public AssetEntity(IAsset request)
        {
            Programme            = request.Programme;
            EquityOwner          = request.EquityOwner;
            SchemeId             = request.SchemeId;
            LocationLaRegionName = request.LocationLaRegionName;
            ImsOldRegion         = request.ImsOldRegion;
            NoOfBeds             = request.NoOfBeds;
            Address              = request.Address;
            PropertyHouseName    = request.PropertyHouseName;
            PropertyStreetNumber = request.PropertyStreetNumber;
            PropertyStreet       = request.PropertyStreet;
            PropertyTown         = request.PropertyTown;
            PropertyPostcode     = request.PropertyPostcode;
            DevelopingRslName    = request.DevelopingRslName;
            LBHA = request.LBHA;
            CompletionDateForHpiStart = request.CompletionDateForHpiStart;
            ImsActualCompletionDate   = request.ImsActualCompletionDate;
            ImsExpectedCompletionDate = request.ImsExpectedCompletionDate;
            ImsLegalCompletionDate    = request.ImsLegalCompletionDate;
            HopCompletionDate         = request.HopCompletionDate;
            Deposit                 = request.Deposit;
            AgencyEquityLoan        = request.AgencyEquityLoan;
            DeveloperEquityLoan     = request.DeveloperEquityLoan;
            ShareOfRestrictedEquity = request.ShareOfRestrictedEquity;
            DeveloperDiscount       = request.DeveloperDiscount;
            Mortgage                = request.Mortgage;
            PurchasePrice           = request.PurchasePrice;
            Fees = request.Fees;
            HistoricUnallocatedFees = request.HistoricUnallocatedFees;
            ActualAgencyEquityCostIncludingHomeBuyAgentFee = request.ActualAgencyEquityCostIncludingHomeBuyAgentFee;
            FullDisposalDate         = request.FullDisposalDate;
            OriginalAgencyPercentage = request.OriginalAgencyPercentage;
            StaircasingPercentage    = request.StaircasingPercentage;
            NewAgencyPercentage      = request.NewAgencyPercentage;
            Invested                                     = request.Invested;
            Month                                        = request.Month;
            CalendarYear                                 = request.CalendarYear;
            MMYYYY                                       = request.MMYYYY;
            Row                                          = request.Row;
            Col                                          = request.Col;
            HPIStart                                     = request.HPIStart;
            HPIEnd                                       = request.HPIEnd;
            HPIPlusMinus                                 = request.HPIPlusMinus;
            AgencyPercentage                             = request.AgencyPercentage;
            MortgageEffect                               = request.MortgageEffect;
            RemainingAgencyCost                          = request.RemainingAgencyCost;
            WAEstimatedPropertyValue                     = request.WAEstimatedPropertyValue;
            AgencyFairValueDifference                    = request.AgencyFairValueDifference;
            ImpairmentProvision                          = request.ImpairmentProvision;
            FairValueReserve                             = request.FairValueReserve;
            AgencyFairValue                              = request.AgencyFairValue;
            DisposalsCost                                = request.DisposalsCost;
            DurationInMonths                             = request.DurationInMonths;
            MonthOfCompletionSinceSchemeStart            = request.MonthOfCompletionSinceSchemeStart;
            DisposalMonthSinceCompletion                 = request.DisposalMonthSinceCompletion;
            IMSPaymentDate                               = request.IMSPaymentDate;
            IsPaid                                       = request.IsPaid;
            IsAsset                                      = request.IsAsset;
            PropertyType                                 = request.PropertyType;
            Tenure                                       = request.Tenure;
            ExpectedStaircasingRate                      = request.ExpectedStaircasingRate;
            EstimatedSalePrice                           = request.EstimatedSalePrice;
            RegionalSaleAdjust                           = request.RegionalSaleAdjust;
            RegionalStairAdjust                          = request.RegionalStairAdjust;
            NotLimitedByFirstCharge                      = request.NotLimitedByFirstCharge;
            EarlyMortgageIfNeverRepay                    = request.EarlyMortgageIfNeverRepay;
            ArrearsEffectAppliedOrLimited                = request.ArrearsEffectAppliedOrLimited;
            RelativeSalePropertyTypeAndTenureAdjustment  = request.RelativeSalePropertyTypeAndTenureAdjustment;
            RelativeStairPropertyTypeAndTenureAdjustment = request.RelativeStairPropertyTypeAndTenureAdjustment;
            IsLondon                                     = request.IsLondon;
            QuarterSpend                                 = request.QuarterSpend;
            MortgageProvider                             = request.MortgageProvider;
            HouseType                                    = request.HouseType;
            PurchasePriceBand                            = request.PurchasePriceBand;
            HouseholdFiveKIncomeBand                     = request.HouseholdFiveKIncomeBand;
            HouseholdFiftyKIncomeBand                    = request.HouseholdFiftyKIncomeBand;
            FirstTimeBuyer                               = request.FirstTimeBuyer;

            HouseholdIncome    = request.HouseholdIncome;
            EstimatedValuation = request.EstimatedValuation;

            AssetRegisterVersionId = request.AssetRegisterVersionId;
        }
Esempio n. 41
0
        private static string GenerateHash(IAsset asset, HttpContext httpContext)
        {
            string hash = asset.GenerateCacheKey(httpContext);

            return($"{asset.Route}?v={hash}");
        }
Esempio n. 42
0
 public string GetMP4FileName(IAsset asset) =>
 Uri.EscapeDataString(asset.AssetFiles.Where(x => x.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)).FirstOrDefault()?.Name)?.ToString();
Esempio n. 43
0
        private void ExportAssetExcel(IAsset asset, Excel.Worksheet xlWorkSheet, int row, bool detailed, bool localtime)
        {
            int index = 1;

            xlWorkSheet.Cells[row, index++] = asset.Name;
            xlWorkSheet.Cells[row, index++] = asset.Id;
            xlWorkSheet.Cells[row, index++] = localtime ? asset.LastModified.ToLocalTime() : asset.LastModified;
            xlWorkSheet.Cells[row, index++] = AssetInfo.GetAssetType(asset);
            xlWorkSheet.Cells[row, index++] = AssetInfo.GetSize(asset);
            int backindex = index;
            var urls      = AssetInfo.GetURIs(asset);

            if (urls != null)
            {
                foreach (var url in urls)
                {
                    xlWorkSheet.Cells[row, index++] = url != null?url.ToString() : string.Empty;
                }
            }
            index = backindex + _context.StreamingEndpoints.Count();
            if (localtime)
            {
                xlWorkSheet.Cells[row, index++] = asset.Locators.Any() ? (DateTime?)asset.Locators.Max(l => l.ExpirationDateTime).ToLocalTime() : null;
            }
            else
            {
                xlWorkSheet.Cells[row, index++] = asset.Locators.Any() ? (DateTime?)asset.Locators.Max(l => l.ExpirationDateTime) : null;
            }

            if (detailed)
            {
                xlWorkSheet.Cells[row, index++] = asset.AlternateId;
                xlWorkSheet.Cells[row, index++] = asset.StorageAccount.Name;
                xlWorkSheet.Cells[row, index++] = asset.Uri == null ? string.Empty : asset.Uri.ToString();
                var streamingloc = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
                xlWorkSheet.Cells[row, index++] = streamingloc.Count();
                if (localtime)
                {
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Min(l => l.ExpirationDateTime).ToLocalTime() : null;
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Max(l => l.ExpirationDateTime).ToLocalTime() : null;
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Min(l => l.ExpirationDateTime) : null;
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Max(l => l.ExpirationDateTime) : null;
                }

                var sasloc = asset.Locators.Where(l => l.Type == LocatorType.Sas);
                xlWorkSheet.Cells[row, index++] = sasloc.Count();
                if (localtime)
                {
                    xlWorkSheet.Cells[row, index++] = sasloc.Any() ? (DateTime?)sasloc.Min(l => l.ExpirationDateTime).ToLocalTime() : null;
                    xlWorkSheet.Cells[row, index++] = sasloc.Any() ? (DateTime?)sasloc.Max(l => l.ExpirationDateTime).ToLocalTime() : null;
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = sasloc.Any() ? (DateTime?)sasloc.Min(l => l.ExpirationDateTime) : null;
                    xlWorkSheet.Cells[row, index++] = sasloc.Any() ? (DateTime?)sasloc.Max(l => l.ExpirationDateTime) : null;
                }

                xlWorkSheet.Cells[row, index++] = asset.GetEncryptionState(AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash).ToString();
                xlWorkSheet.Cells[row, index++] = asset.AssetFilters.Count().ToString();
            }
        }
Esempio n. 44
0
        CompileResult Compile(IAsset asset, StreamReader input)
        {
            var context = CreateCompileContext(asset);

            return(compiler.Compile(input.ReadToEnd(), context));
        }
Esempio n. 45
0
        public static bool HasThumbnail(this IAsset src)
        {
            var file = (from f in src.AssetFiles where f.Name.EndsWith(".jpg") && !f.IsEncrypted select f).FirstOrDefault();

            return(file != null);
        }
Esempio n. 46
0
 internal AssetFilterBaseCollection(MediaContextBase cloudMediaContext, IAsset parentAsset, List <AssetFilterData> filterDatas)
     : base(cloudMediaContext)
 {
     _parentAsset = parentAsset;
     _filterData  = filterDatas.Select(af => af as IStreamingAssetFilter).ToList();
 }
        /// <summary>
        /// Returns a <see cref="IJob"/> instance with a single <see cref="ITask"/> ready to be submitted.
        /// </summary>
        /// <param name="context">The <see cref="MediaContextBase"/> instance.</param>
        /// <param name="mediaProcessorName">The name of the media processor.</param>
        /// <param name="taskConfiguration">The task configuration.</param>
        /// <param name="inputAsset">The input <see cref="IAsset"/> instance.</param>
        /// <param name="outputAssetName">The name of the output asset.</param>
        /// <param name="outputAssetStorageAccountName">The name of the Storage Account where to store the output asset.</param>
        /// <param name="outputAssetOptions">The <see cref="AssetCreationOptions"/> of the output asset.</param>
        /// <returns>A <see cref="IJob"/> instance with a single <see cref="ITask"/> ready to be submitted.</returns>
        public static IJob PrepareJobWithSingleTask(this MediaContextBase context, string mediaProcessorName, string taskConfiguration, IAsset inputAsset, string outputAssetName, string outputAssetStorageAccountName, AssetCreationOptions outputAssetOptions)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "The context cannot be null.");
            }

            if (inputAsset == null)
            {
                throw new ArgumentNullException("inputAsset", "The input asset cannot be null.");
            }

            IMediaProcessor processor = context.MediaProcessors.GetLatestMediaProcessorByName(mediaProcessorName);

            if (processor == null)
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture, "Unknown media processor: '{0}'", mediaProcessorName), "mediaProcessorName");
            }

            IJob job = context.Jobs.Create(
                string.Format(CultureInfo.InvariantCulture, "Job for {0}", inputAsset.Name));

            ITask task = job.Tasks.AddNew(
                string.Format(CultureInfo.InvariantCulture, "Task for {0}", inputAsset.Name),
                processor,
                taskConfiguration,
                TaskOptions.ProtectedConfiguration);

            task.InputAssets.Add(inputAsset);

            if (string.IsNullOrWhiteSpace(outputAssetStorageAccountName))
            {
                outputAssetStorageAccountName = context.DefaultStorageAccount.Name;
            }

            task.OutputAssets.AddNew(outputAssetName, outputAssetStorageAccountName, outputAssetOptions);

            return(job);
        }
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)


        {
            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            log.Info("Request : " + jsonContent);

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();

            log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");

            // Validate input objects
            if (data.assetId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId in the input object" }));
            }

            string startsWith = data.startsWith;
            string endsWith   = data.endsWith;


            string assetId = data.assetId;

            IAsset asset = null;

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                // Find the Asset
                asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault();
                if (asset == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" }));
                }

                var files = asset.AssetFiles.ToList().Where(f => ((string.IsNullOrEmpty(endsWith) || f.Name.EndsWith(endsWith)) && (string.IsNullOrEmpty(startsWith) || f.Name.StartsWith(startsWith))));

                foreach (var file in files)
                {
                    file.Delete();
                    log.Info($"Deleted file: {file.Name}");
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message }));
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }
        public CreateTestToken(IAsset _asset, CloudMediaContext _context, ContentKeyType?keytype = null, string optionid = null)
        {
            InitializeComponent();
            this.Icon = Bitmaps.Azure_Explorer_ico;

            MyAsset   = _asset;
            mycontext = _context;

            var query = from key in MyAsset.ContentKeys
                        join autpol in _context.ContentKeyAuthorizationPolicies on key.AuthorizationPolicyId equals autpol.Id
                        select new { keyname = key.Name, keytype = key.ContentKeyType, keyid = key.Id, aupolid = autpol.Id };

            listViewAutOptions.BeginUpdate();
            listViewAutOptions.Items.Clear();
            foreach (var key in query)
            {
                var queryoptions = _context.ContentKeyAuthorizationPolicies.Where(a => a.Id == key.aupolid).FirstOrDefault().Options;

                foreach (var option in queryoptions)
                {
                    if (option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted)
                    {
                        ListViewItem item = new ListViewItem(key.keytype.ToString());

                        IContentKey keyj = MyAsset.ContentKeys.Where(k => k.Id == key.keyid).FirstOrDefault();
                        ContentKeyDisplayed.Add(keyj);

                        item.SubItems.Add(option.Name);
                        item.SubItems.Add(option.Id);
                        string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements;
                        if (!string.IsNullOrEmpty(tokenTemplateString))
                        {
                            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                            item.SubItems.Add(tokenTemplate.TokenType == TokenType.JWT ? "JWT" : "SWT");
                            if (tokenTemplate.PrimaryVerificationKey != null)
                            {
                                item.SubItems.Add(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey) ? "Symmetric" : "Asymmetric X509");
                            }
                            else if (tokenTemplate.OpenIdConnectDiscoveryDocument != null)
                            {
                                item.SubItems.Add("OpenID");
                            }
                        }
                        listViewAutOptions.Items.Add(item);
                        if (optionid == option.Id)
                        {
                            listViewAutOptions.Items[listViewAutOptions.Items.IndexOf(item)].Selected = true;
                        }
                    }
                }
            }

            if (listViewAutOptions.Items.Count > 0 && listViewAutOptions.SelectedItems.Count == 0) // no selection, in that case, first line selected
            {
                listViewAutOptions.Items[0].Selected = true;
            }

            listViewAutOptions.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewAutOptions.EndUpdate();
        }
Esempio n. 50
0
 /// <summary>
 /// Performs a dynamic dispatch by calling the most specific version of Visit method
 /// as determined at runtime (there is no need for switches based on type).
 /// Depending on the use-case this we can restrict access modifiers as appropriate.
 /// </summary>
 /// <param name="asset">Asset.</param>
 public void DynamicVisit(IAsset asset)
 {
     Visit((dynamic)asset);
 }
Esempio n. 51
0
 public static string GetMP4FileName(IAsset asset) =>
 Uri.EscapeDataString(asset.AssetFiles.Where(x => x.Name.ToLower().EndsWith(".mp4")).FirstOrDefault()?.Name)?.ToString();
 /// <summary>
 /// Returns a <see cref="IJob"/> instance with a single <see cref="ITask"/> ready to be submitted.
 /// </summary>
 /// <param name="context">The <see cref="MediaContextBase"/> instance.</param>
 /// <param name="mediaProcessorName">The name of the media processor.</param>
 /// <param name="taskConfiguration">The task configuration.</param>
 /// <param name="inputAsset">The input <see cref="IAsset"/> instance.</param>
 /// <param name="outputAssetName">The name of the output asset.</param>
 /// <param name="outputAssetOptions">The <see cref="AssetCreationOptions"/> of the output asset.</param>
 /// <returns>A <see cref="IJob"/> instance with a single <see cref="ITask"/> ready to be submitted.</returns>
 public static IJob PrepareJobWithSingleTask(this MediaContextBase context, string mediaProcessorName, string taskConfiguration, IAsset inputAsset, string outputAssetName, AssetCreationOptions outputAssetOptions)
 {
     return(context.PrepareJobWithSingleTask(mediaProcessorName, taskConfiguration, inputAsset, outputAssetName, null, outputAssetOptions));
 }
Esempio n. 53
0
 protected virtual bool ShouldParseAsset(IAsset asset)
 {
     return(true);
 }
Esempio n. 54
0
        public static (string manifestUri, string hlsUri, string mpegDashUri) BuildStreamingURLs(IAsset asset, ILocator locator)
        {
            var manifestFile = asset.AssetFiles.Where(x => x.Name.ToLower().EndsWith(".ism")).FirstOrDefault();

            var manifestUrl = GetStreamingManifestUrl(locator, manifestFile, cdnStreamingEndpointName);

            var hlsUrl  = $"{manifestUrl}(format=m3u8-aapl)";
            var dashUrl = $"{manifestUrl}(format=mpd-time-csf)";

            return(manifestUrl, hlsUrl, dashUrl);
        }
Esempio n. 55
0
 public TerrainChunk(IScene scene, IAsset parent, int x, int y, int z, object parameters)
 {
     m_world  = scene;
     m_parent = parent;
 }
Esempio n. 56
0
 // called via reflection
 // ReSharper disable once UnusedMember.Local
 private async Task <IProxyAsset> CreateProxyInternal <T>(IAsset <T> asset)
 {
     return(await CreateProxy(asset));
 }
        private string ExportAssetCSVLine(IAsset asset, bool detailed, bool localtime)
        {
            List <string> linec = new List <string>();

            linec.Add(asset.Name);
            linec.Add(asset.Id);
            linec.Add(localtime ? asset.LastModified.ToLocalTime().ToString() : asset.LastModified.ToString());
            linec.Add(AssetInfo.GetAssetType(asset));
            linec.Add(AssetInfo.GetSize(asset).ToString());
            var urls = AssetInfo.GetURIs(asset);

            if (urls != null && urls.Count() > 0)
            {
                foreach (var url in urls)
                {
                    linec.Add(url != null ? url.ToString() : string.Empty);
                }
            }
            else
            {
                for (int i = 0; i < _context.StreamingEndpoints.Count(); i++)
                {
                    linec.Add(string.Empty);
                }
            }

            var streamlocators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);

            if (streamlocators.Any())
            {
                if (localtime)
                {
                    linec.Add(streamlocators.Max(l => l.ExpirationDateTime).ToLocalTime().ToString());
                }
                else
                {
                    linec.Add(streamlocators.Max(l => l.ExpirationDateTime).ToString());
                }
            }
            else
            {
                linec.Add(string.Empty);
            }


            // SAS locator
            var saslocators = asset.Locators.Where(l => l.Type == LocatorType.Sas);
            var saslocator  = saslocators.ToList().OrderByDescending(l => l.ExpirationDateTime).FirstOrDefault();

            if (saslocator != null && asset.AssetFiles.Count() > 0)
            {
                if (asset.AssetFiles.Count() == 1)
                {
                    var ProgressiveDownloadUri = asset.AssetFiles.FirstOrDefault().GetSasUri(saslocator);
                    linec.Add(ProgressiveDownloadUri.AbsoluteUri);
                }
                else
                {
                    linec.Add(saslocator.Path);
                }

                if (localtime)
                {
                    linec.Add(saslocator.ExpirationDateTime.ToLocalTime().ToString());
                }
                else
                {
                    linec.Add(saslocator.ExpirationDateTime.ToString());
                }
            }
            else
            {
                linec.Add(string.Empty);
                linec.Add(string.Empty);
            }


            if (detailed)
            {
                linec.Add(asset.AlternateId);
                linec.Add(asset.StorageAccount.Name);
                linec.Add(asset.Uri == null ? string.Empty : asset.Uri.ToString());
                var streamingloc = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
                linec.Add(streamingloc.Count().ToString());
                if (localtime)
                {
                    linec.Add(streamingloc.Any() ? streamingloc.Min(l => l.ExpirationDateTime).ToLocalTime().ToString() : null);
                    linec.Add(streamingloc.Any() ? streamingloc.Max(l => l.ExpirationDateTime).ToLocalTime().ToString() : null);
                }
                else
                {
                    linec.Add(streamingloc.Any() ? streamingloc.Min(l => l.ExpirationDateTime).ToString() : null);
                    linec.Add(streamingloc.Any() ? streamingloc.Max(l => l.ExpirationDateTime).ToString() : null);
                }

                // SAS
                linec.Add(saslocators.Count().ToString());
                if (localtime)
                {
                    linec.Add(saslocators.Any() ? saslocators.Min(l => l.ExpirationDateTime).ToLocalTime().ToString() : null);
                    linec.Add(saslocators.Any() ? saslocators.Max(l => l.ExpirationDateTime).ToLocalTime().ToString() : null);
                }
                else
                {
                    linec.Add(saslocators.Any() ? saslocators.Min(l => l.ExpirationDateTime).ToString() : null);
                    linec.Add(saslocators.Any() ? saslocators.Max(l => l.ExpirationDateTime).ToString() : null);
                }

                linec.Add(asset.GetEncryptionState(AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash).ToString());
                linec.Add(asset.AssetFilters.Count().ToString());
            }

            return(convertCSVLine(linec));
        }
        private void ExportAssetExcel(IAsset asset, Excel.Worksheet xlWorkSheet, int row, bool detailed, bool localtime)
        {
            int index = 1;

            xlWorkSheet.Cells[row, index++] = asset.Name;
            xlWorkSheet.Cells[row, index++] = asset.Id;
            xlWorkSheet.Cells[row, index++] = localtime ? asset.LastModified.ToLocalTime() : asset.LastModified;
            xlWorkSheet.Cells[row, index++] = AssetInfo.GetAssetType(asset);
            xlWorkSheet.Cells[row, index++] = AssetInfo.GetSize(asset);
            int backindex = index;
            var urls      = AssetInfo.GetURIs(asset);

            if (urls != null)
            {
                foreach (var url in urls)
                {
                    xlWorkSheet.Cells[row, index++] = url != null?url.ToString() : string.Empty;
                }
            }
            index = backindex + _context.StreamingEndpoints.Count();
            var streamlocators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);

            if (streamlocators.Any())
            {
                if (localtime)
                {
                    xlWorkSheet.Cells[row, index++] = (DateTime?)streamlocators.Max(l => l.ExpirationDateTime).ToLocalTime();
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = (DateTime?)streamlocators.Max(l => l.ExpirationDateTime);
                }
            }
            else
            {
                xlWorkSheet.Cells[row, index++] = string.Empty;
            }


            // SAS locator
            var saslocators = asset.Locators.Where(l => l.Type == LocatorType.Sas);
            var saslocator  = saslocators.ToList().OrderByDescending(l => l.ExpirationDateTime).FirstOrDefault();

            if (saslocator != null && asset.AssetFiles.Count() > 0)
            {
                if (asset.AssetFiles.Count() == 1)
                {
                    var ProgressiveDownloadUri = asset.AssetFiles.FirstOrDefault().GetSasUri(saslocator);
                    xlWorkSheet.Cells[row, index++] = ProgressiveDownloadUri.AbsoluteUri;
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = saslocator.Path;
                }

                if (localtime)
                {
                    xlWorkSheet.Cells[row, index++] = saslocator.ExpirationDateTime.ToLocalTime();
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = saslocator.ExpirationDateTime;
                }
            }
            else
            {
                xlWorkSheet.Cells[row, index++] = string.Empty;
                xlWorkSheet.Cells[row, index++] = string.Empty;
            }


            if (detailed)
            {
                xlWorkSheet.Cells[row, index++] = asset.AlternateId;
                xlWorkSheet.Cells[row, index++] = asset.StorageAccount.Name;
                xlWorkSheet.Cells[row, index++] = asset.Uri == null ? string.Empty : asset.Uri.ToString();
                var streamingloc = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
                xlWorkSheet.Cells[row, index++] = streamingloc.Count();
                if (localtime)
                {
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Min(l => l.ExpirationDateTime).ToLocalTime() : null;
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Max(l => l.ExpirationDateTime).ToLocalTime() : null;
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Min(l => l.ExpirationDateTime) : null;
                    xlWorkSheet.Cells[row, index++] = streamingloc.Any() ? (DateTime?)streamingloc.Max(l => l.ExpirationDateTime) : null;
                }

                // SAS
                xlWorkSheet.Cells[row, index++] = saslocators.Count();
                if (localtime)
                {
                    xlWorkSheet.Cells[row, index++] = saslocators.Any() ? (DateTime?)saslocators.Min(l => l.ExpirationDateTime).ToLocalTime() : null;
                    xlWorkSheet.Cells[row, index++] = saslocators.Any() ? (DateTime?)saslocators.Max(l => l.ExpirationDateTime).ToLocalTime() : null;
                }
                else
                {
                    xlWorkSheet.Cells[row, index++] = saslocators.Any() ? (DateTime?)saslocators.Min(l => l.ExpirationDateTime) : null;
                    xlWorkSheet.Cells[row, index++] = saslocators.Any() ? (DateTime?)saslocators.Max(l => l.ExpirationDateTime) : null;
                }

                xlWorkSheet.Cells[row, index++] = asset.GetEncryptionState(AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash).ToString();
                xlWorkSheet.Cells[row, index++] = asset.AssetFilters.Count().ToString();
            }
        }
Esempio n. 59
0
 /// <summary>
 /// Translates a code of asset written on intermediate language to CSS or JS code
 /// </summary>
 /// <param name="asset">Asset with code written on intermediate language</param>
 /// <returns>Asset with translated code</returns>
 public abstract IAsset Translate(IAsset asset);
Esempio n. 60
0
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)


        {
            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            log.Info("Request : " + jsonContent);

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();

            log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");

            // Validate input objects
            if (data.assetId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId in the input object" }));
            }

            string assetId = data.assetId;

            var    attachedstoragecred = KeyHelper.ReturnStorageCredentials();
            string mp4FileName         = "";

            IAsset asset = null;

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                // Find the Asset
                asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault();
                if (asset == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" }));
                }

                var files = asset.AssetFiles.ToList().Where(f => !f.Name.EndsWith(".mp4"));

                string storname = amsCredentials.StorageAccountName;
                string storkey  = amsCredentials.StorageAccountKey;
                if (asset.StorageAccountName != amsCredentials.StorageAccountName)
                {
                    if (attachedstoragecred.ContainsKey(asset.StorageAccountName)) // asset is using another storage than default but we have the key
                    {
                        storname = asset.StorageAccountName;
                        storkey  = attachedstoragecred[storname];
                    }
                    else // we don't have the key for that storage
                    {
                        log.Info($"Face redaction Asset is in {asset.StorageAccountName} and key is not provided in MediaServicesAttachedStorageCredentials application settings");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            error = "Storage key is missing"
                        }));
                    }
                }

                // Setup blob container
                CloudBlobContainer sourceBlobContainer = CopyBlobHelpers.GetCloudBlobContainer(storname, storkey, asset.Uri.Segments[1]);

                foreach (var file in asset.AssetFiles.ToList())
                {
                    if (file.Name.EndsWith(".mp4"))
                    {
                        file.IsPrimary = true;
                        file.Update();
                        mp4FileName = file.Name;
                    }
                    else
                    {
                        file.Delete();
                        CloudBlob sourceBlob = sourceBlobContainer.GetBlockBlobReference(file.Name);
                        sourceBlob.DeleteIfExists();
                        log.Info($"Start copy of file : {file.Name}");
                    }
                }
                asset.Update();
                MediaServicesHelper.SetAFileAsPrimary(asset);
            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message }));
            }

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                mp4FileName
            }));
        }