public void RefreshLiveEvent(LiveEvent liveEventItem)
        {
            int index = -1;

            foreach (LiveEventEntry CE in _MyObservLiveEvent) // let's search for index
            {
                if (CE.Name == liveEventItem.Name)
                {
                    index = _MyObservLiveEvent.IndexOf(CE);
                    break;
                }
            }

            if (index >= 0)                                                                                                                                         // we found it
            {                                                                                                                                                       // we update the observation collection
                _client.RefreshTokenIfNeeded();
                liveEventItem = _client.AMSclient.LiveEvents.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, liveEventItem.Name); //refresh
                if (liveEventItem != null)
                {
                    _MyObservLiveEvent[index].State        = liveEventItem.ResourceState;
                    _MyObservLiveEvent[index].Description  = liveEventItem.Description;
                    _MyObservLiveEvent[index].LastModified = liveEventItem.LastModified != null ? (DateTime?)((DateTime)liveEventItem.LastModified).ToLocalTime() : null;
                    this.Refresh();
                }
            }
        }
Exemplo n.º 2
0
        private void WorkerRefreshStreamingEndpoints_DoWork(object sender, DoWorkEventArgs e)
        {
            Debug.WriteLine("WorkerRefreshChannels_DoWork");
            BackgroundWorker  worker = sender as BackgroundWorker;
            StreamingEndpoint origin;

            _client.RefreshTokenIfNeeded();

            foreach (StreamingEndpointEntry OE in _MyObservStreamingEndpoints)
            {
                origin = null;
                try
                {
                    origin = _client.AMSclient.StreamingEndpoints.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, origin.Name); //refresh
                    if (origin != null)
                    {
                        OE.State = (StreamingEndpointResourceState)origin.ResourceState;

                        //if ((i % 5) == 0) this.BeginInvoke(new Action(() => this.Refresh()), null);
                        this.BeginInvoke(new Action(() => this.Refresh()), null);
                        //i++;
                    }
                }
                catch // in some case, we have a timeout on Assets.Where...
                {
                }
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    return;
                }
            }
            this.BeginInvoke(new Action(() => this.Refresh()), null);
        }
        private void BathUploadFrame2_Load(object sender, EventArgs e)
        {
            if (ErrorConnect)
            {
                Close();
            }
            _client.RefreshTokenIfNeeded();


            foreach (StorageAccount storage in _client.AMSclient.Mediaservices.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName).StorageAccounts)
            {
                string sname   = AMSClientV3.GetStorageName(storage.Id);
                bool   primary = (storage.Type == StorageAccountType.Primary);
                comboBoxStorage.Items.Add(new Item(string.Format("{0} {1}", sname, primary ? "(primary)" : ""), sname));
                if (primary)
                {
                    comboBoxStorage.SelectedIndex = comboBoxStorage.Items.Count - 1;
                }



                //                comboBoxStorage.Items.Add(new Item(string.Format("{0} {1}", storage.Name, storage.IsDefault ? AMSExplorer.Properties.Resources.BatchUploadFrame2_BathUploadFrame2_Load_Default : ""), storage.Name));
                //              if (storage.Name == _context.DefaultStorageAccount.Name) comboBoxStorage.SelectedIndex = comboBoxStorage.Items.Count - 1;
            }

            List <int> listInt = new List <int>()
            {
                1, 2, 4, 8, 16, 32, 64
            };

            comboBoxBlockSize.Items.Clear();
            listInt.ForEach(l => comboBoxBlockSize.Items.Add(l.ToString()));
            comboBoxBlockSize.SelectedIndex = 3;
        }
        private void ImportHttp_Load(object sender, EventArgs e)
        {
            labelURLFileNameWarning.Text = string.Empty;
            textBoxAssetName.Text        = "import-" + _uniqueness;

            _amsClientV3.RefreshTokenIfNeeded();


            if (_AzureStorageContainerSASListMode)
            {
                labelExamples.Visible       = false;
                labelSASListExample.Visible = true;
                labelTitle.Text             = this.Text = AMSExplorer.Properties.Resources.ImportHttp_ImportHttp_Load_ImportFromSASContainerPath;
            }

            var storAccounts = _amsClientV3.AMSclient.Mediaservices.Get(_amsClientV3.credentialsEntry.ResourceGroup, _amsClientV3.credentialsEntry.AccountName).StorageAccounts;

            comboBoxStorage.Items.Clear();
            foreach (var storage in storAccounts)
            {
                string sname   = AMSClientV3.GetStorageName(storage.Id);
                bool   primary = (storage.Type == StorageAccountType.Primary);
                comboBoxStorage.Items.Add(new Item(string.Format("{0} {1}", sname, primary ? "(primary)" : string.Empty), sname));
                if (primary)
                {
                    comboBoxStorage.SelectedIndex = comboBoxStorage.Items.Count - 1;
                }
            }
        }
Exemplo n.º 5
0
        public List <JobExtension> ReturnSelectedJobs()
        {
            var SelectedJobs = new List <JobExtension>();

            _client.RefreshTokenIfNeeded();

            foreach (DataGridViewRow Row in this.SelectedRows)
            {
                string tName = Row.Cells[this.Columns["TransformName"].Index].Value.ToString();
                // sometimes, the transform can be null (if just deleted)
                var job = _client.AMSclient.Jobs.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, tName, Row.Cells[this.Columns["Name"].Index].Value.ToString());
                if (job != null)
                {
                    SelectedJobs.Add(new JobExtension()
                    {
                        Job = job, TransformName = tName
                    });
                }
            }
            SelectedJobs.Reverse();
            return(SelectedJobs);
        }
        private void LoadTransforms()
        {
            _client.RefreshTokenIfNeeded();

            _transforms = _client.AMSclient.Transforms.List(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName);

            this.BeginUpdate();
            this.Items.Clear();

            foreach (var transform in _transforms)
            {
                ListViewItem item = new ListViewItem(transform.Name);
                item.SubItems.Add(transform.Description);
                item.SubItems.Add(transform.LastModified.ToLocalTime().ToString("G"));
                if (_selectedTransformName == transform.Name)
                {
                    item.Selected = true;
                }
                this.Items.Add(item);
            }
            this.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            this.EndUpdate();
        }
Exemplo n.º 7
0
        public void RefreshProgram(string liveeventName, LiveOutput program)
        {
            int index = -1;

            if (_MyObservLiveOutputs != null)
            {
                foreach (LiveOutputEntry CE in _MyObservLiveOutputs) // let's search for index
                {
                    if (CE.Name == program.Name)
                    {
                        index = _MyObservLiveOutputs.IndexOf(CE);
                        break;
                    }
                }
            }

            if (index >= 0) // we found it
            {               // we update the observation collection
                _client.RefreshTokenIfNeeded();

                program = _client.AMSclient.LiveOutputs.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, liveeventName, program.Name); //refresh
                if (program != null)
                {
                    try // sometimes, index could be wrong id program has been deleted
                    {
                        _MyObservLiveOutputs[index].State               = program.ResourceState;
                        _MyObservLiveOutputs[index].Description         = program.Description;
                        _MyObservLiveOutputs[index].ArchiveWindowLength = program.ArchiveWindowLength;
                        _MyObservLiveOutputs[index].LastModified        = program.LastModified != null ? (DateTime?)((DateTime)program.LastModified).ToLocalTime() : null;
                        this.Refresh();
                    }
                    catch
                    {
                    }
                }
            }
        }
        public static int?ReturnNumberAssetFilters(string assetName, AMSClientV3 client)
        {
            client.RefreshTokenIfNeeded();
            IPage <AssetFilter> filters;

            try
            {
                filters = client.AMSclient.AssetFilters.List(client.credentialsEntry.ResourceGroup, client.credentialsEntry.AccountName, assetName);
            }
            catch
            {
                return(null);
            }

            return(filters.Count());
        }
Exemplo n.º 9
0
        private void ControlsResetToDefault()
        {
            _amsClientV3.RefreshTokenIfNeeded();
            IList <StorageAccount> storAccounts = _amsClientV3.AMSclient.Mediaservices.Get(_amsClientV3.credentialsEntry.ResourceGroup, _amsClientV3.credentialsEntry.AccountName).StorageAccounts;

            comboBoxStorage.Items.Clear();
            foreach (StorageAccount storage in storAccounts)
            {
                string sname   = AMSClientV3.GetStorageName(storage.Id);
                bool   primary = (storage.Type == StorageAccountType.Primary);
                comboBoxStorage.Items.Add(new Item(string.Format("{0} {1}", sname, primary ? "(primary)" : string.Empty), sname));
                if (primary)
                {
                    comboBoxStorage.SelectedIndex = comboBoxStorage.Items.Count - 1;
                }
            }
        }
        private void ControlsResetToDefault()
        {
            _amsClientV3.RefreshTokenIfNeeded();
            var storAccounts = Task.Run(() => _amsClientV3.AMSclient.Mediaservices.GetAsync(_amsClientV3.credentialsEntry.ResourceGroup, _amsClientV3.credentialsEntry.AccountName)).GetAwaiter().GetResult().StorageAccounts;

            comboBoxStorage.Items.Clear();
            foreach (Microsoft.Azure.Management.Media.Models.StorageAccount storage in storAccounts)
            {
                string sname   = AMSClientV3.GetStorageName(storage.Id);
                bool   primary = (storage.Type == StorageAccountType.Primary);
                comboBoxStorage.Items.Add(new Item(string.Format("{0} {1}", sname, primary ? "(primary)" : string.Empty), sname));
                if (primary)
                {
                    comboBoxStorage.SelectedIndex = comboBoxStorage.Items.Count - 1;
                }
            }
        }
Exemplo n.º 11
0
        private void FillLocatorComboInPolicyTab()
        {
            comboBoxPolicyLocators.Items.Clear();
            comboBoxPolicyLocators.BeginUpdate();

            _client.RefreshTokenIfNeeded();
            _locators = _client.AMSclient.Assets.ListStreamingLocators(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, _asset.Name).StreamingLocators;
            foreach (AssetStreamingLocator locator in _locators.ToList())
            {
                int index = comboBoxPolicyLocators.Items.Add(new Item(locator.Name, locator.Name));
                if (_path.Contains(locator.StreamingLocatorId.ToString()))
                {
                    comboBoxPolicyLocators.SelectedIndex = index;
                }
            }
            comboBoxPolicyLocators.EndUpdate();
        }
        public List <Transform> ReturnSelectedTransforms()
        {
            _client.RefreshTokenIfNeeded();

            List <Transform> SelectedTransforms = new List <Transform>();

            foreach (DataGridViewRow Row in SelectedRows)
            {
                // sometimes, the transform can be null (if just deleted)
                Transform transform = _client.AMSclient.Transforms.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, Row.Cells[Columns["Name"].Index].Value.ToString());
                if (transform != null)
                {
                    SelectedTransforms.Add(transform);
                }
            }
            SelectedTransforms.Reverse();
            return(SelectedTransforms);
        }
Exemplo n.º 13
0
        private void buttonOpenAsset_Click(object sender, EventArgs e)
        {
            _client.RefreshTokenIfNeeded();
            Asset AssetToDisplayP = _client.AMSclient.Assets.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, MyLiveOutput.AssetName);

            if (AssetToDisplayP != null)
            {
                AssetInformation form = new AssetInformation(MyMainForm, _client)
                {
                    myAssetV3            = AssetToDisplayP,
                    myStreamingEndpoints = MyStreamingEndpoints // we want to keep the same sorting
                };
                DialogResult dialogResult = form.ShowDialog(this);
            }
            else
            {
                MessageBox.Show(string.Format("Asset '{0}' not found !", MyLiveOutput.AssetName), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 14
0
        private void AttachStorage_Load(object sender, EventArgs e)
        {
            DpiUtils.InitPerMonitorDpi(this);

            try
            {
                _amsClient.RefreshTokenIfNeeded();

                mediaClient = _amsClient.AMSclient;
                // Set the polling interval for long running operations to 2 seconds.
                // The default value is 30 seconds for the .NET client SDK
                mediaClient.LongRunningOperationRetryTimeout = 2;

                mediaService = mediaClient.Mediaservices.Get(_amsClient.credentialsEntry.ResourceGroup, _amsClient.credentialsEntry.AccountName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error when connecting", MessageBoxButtons.OK, MessageBoxIcon.Error);
                buttonAttach.Enabled = false;
                return;
            }

            List <StorageAccount> storages = mediaService.StorageAccounts.ToList();

            listViewStorage.Items.Clear();

            storages.ForEach(s =>
            {
                if (s.Type == StorageAccountType.Secondary)
                {
                    string[] names      = s.Id.Split('/');
                    ListViewItem lvitem = new ListViewItem(new string[] { names.Last(), s.Id })
                    {
                        ToolTipText = s.Id
                    };
                    listViewStorage.Items.Add(lvitem);
                }
            }
                             );
            buttonAttach.Enabled = true;
        }
        private void LiveOutputCreation_Load(object sender, EventArgs e)
        {
            this.Text = string.Format(this.Text, LiveEventName);
            checkBoxCreateLocator.Text = string.Format(checkBoxCreateLocator.Text, Properties.Settings.Default.DefaultLocatorDurationDaysNew);

            _client.RefreshTokenIfNeeded();
            var storages = _client.AMSclient.Mediaservices.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName).StorageAccounts;

            foreach (var storage in storages)
            {
                bool primary = (storage.Type == StorageAccountType.Primary);

                comboBoxStorage.Items.Add(new Item(AMSClientV3.GetStorageName(storage.Id) + (primary ? " (primary)" : string.Empty), AMSClientV3.GetStorageName(storage.Id)));
                if (primary)
                {
                    comboBoxStorage.SelectedIndex = comboBoxStorage.Items.Count - 1;
                }
            }

            checkProgramName();
        }
Exemplo n.º 16
0
        private void DisplayAssetInfo(bool input)
        {
            string assetName = null;

            if (input)
            {
                if (MyJob.Input.GetType() == typeof(JobInputAsset))
                {
                    JobInputAsset inputAsset = MyJob.Input as JobInputAsset;
                    assetName = inputAsset.AssetName;
                }
            }
            else  // output
            {
                int index = listBoxOutputs.SelectedIndices[0];

                if (MyJob.Outputs[index].GetType() == typeof(JobOutputAsset))
                {
                    JobOutputAsset outputAsset = MyJob.Outputs[index] as JobOutputAsset;
                    assetName = outputAsset.AssetName;
                }
            }

            if (assetName != null)
            {
                _amsClient.RefreshTokenIfNeeded();
                Asset asset = Task.Run(() =>
                                       _amsClient.AMSclient.Assets.GetAsync(_amsClient.credentialsEntry.ResourceGroup, _amsClient.credentialsEntry.AccountName, assetName))
                              .GetAwaiter().GetResult();

                using (AssetInformation form = new AssetInformation(_mainform, _amsClient)
                {
                    myAssetV3 = asset,
                    myStreamingEndpoints = MyStreamingEndpoints // we want to keep the same sorting
                })
                {
                    DialogResult dialogResult = form.ShowDialog(this);
                }
            }
        }
Exemplo n.º 17
0
        public void Init(AMSClientV3 client)
        {
            IEnumerable <StreamingEndpointEntry> originquery;

            _client = client;
            _client.RefreshTokenIfNeeded();
            originquery = _client.AMSclient.StreamingEndpoints.List(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName).Select(o => new
                                                                                                                                                         StreamingEndpointEntry
            {
                Name         = o.Name,
                Id           = o.Id,
                Description  = o.Description,
                CDN          = ((bool)o.CdnEnabled) ? StreamingEndpointInformation.ReturnDisplayedProvider(o.CdnProvider) ?? "CDN" : string.Empty,
                ScaleUnits   = StreamingEndpointInformation.ReturnTypeSE(o) != StreamingEndpointInformation.StreamEndpointType.Premium ? string.Empty : ((int)o.ScaleUnits).ToString(),
                Type         = StreamingEndpointInformation.ReturnTypeSE(o),
                State        = (StreamingEndpointResourceState)o.ResourceState,
                LastModified = ((DateTime)o.LastModified).ToLocalTime()
            });


            SortableBindingList <StreamingEndpointEntry> MyObservOriginInPage = new SortableBindingList <StreamingEndpointEntry>(originquery.Take(0).ToList());

            this.DataSource                         = MyObservOriginInPage;
            this.Columns["Name"].Width              = 300;
            this.Columns["State"].Width             = 100;
            this.Columns["CDN"].Width               = 120;
            this.Columns["Description"].Width       = 230;
            this.Columns["ScaleUnits"].Width        = 100;
            this.Columns["ScaleUnits"].HeaderText   = "Streaming Units";
            this.Columns["LastModified"].Width      = 150;
            this.Columns["LastModified"].HeaderText = "Last modified";

            WorkerRefreshStreamingEndpoints = new BackgroundWorker();
            WorkerRefreshStreamingEndpoints.WorkerSupportsCancellation = true;
            WorkerRefreshStreamingEndpoints.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshStreamingEndpoints_DoWork);

            _initialized = true;
        }
        public void Init(AMSClientV3 client)
        {
            Debug.WriteLine("AssetsInit");

            client.RefreshTokenIfNeeded();

            _client = client;

            var assets = _client.AMSclient.Assets.List(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName).Select(a => new AssetEntryV3
            {
                Name               = a.Name,
                AssetId            = a.AssetId,
                Type               = a.Type,
                AlternateId        = a.AlternateId,
                Created            = ((DateTime)a.Created).ToLocalTime().ToString("G"),
                StorageAccountName = a.StorageAccountName,
                Filters            = null
            }
                                                                                                                                            );

            /*
             * assetquery = from a in client.Assets.Take(0)
             *           orderby a.LastModified descending
             *           select new AssetEntry
             *           {
             *               Name = a.Name,
             *               Id = a.Id,
             *               AlternateId = a.AlternateId,
             *               LastModified = ((DateTime)a.LastModified).ToLocalTime().ToString("G"),
             *               Storage = a.StorageAccountName
             *           };
             */

            DataGridViewCellStyle cellstyle = new DataGridViewCellStyle()
            {
                NullValue = null,
                Alignment = DataGridViewContentAlignment.MiddleCenter
            };

            DataGridViewImageColumn imageCol = new DataGridViewImageColumn()
            {
                DefaultCellStyle = cellstyle,
                Name             = _publication,
                DataPropertyName = _publication,
            };

            this.Columns.Add(imageCol);

            DataGridViewImageColumn imageCol3 = new DataGridViewImageColumn()
            {
                DefaultCellStyle = cellstyle,
                Name             = _dynEnc,
                DataPropertyName = _dynEnc,
            };

            this.Columns.Add(imageCol3);

            /*
             * DataGridViewImageColumn imageCol4 = new DataGridViewImageColumn()
             * {
             *  DefaultCellStyle = cellstyle,
             *  Name = _filter,
             *  DataPropertyName = _filter,
             * };
             * this.Columns.Add(imageCol4);
             */

            //BindingList<AssetEntry> MyObservAssethisPage = new BindingList<AssetEntry>(assetquery.Take(0).ToList()); // just to create columns
            BindingList <AssetEntryV3> MyObservAssethisPageV3 = new BindingList <AssetEntryV3>(assets.ToList());


            this.DataSource = MyObservAssethisPageV3;

            int lastColumn_sIndex = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None).DisplayIndex;

            this.Columns[_dynEncMouseOver].Visible      = false;
            this.Columns[_publicationMouseOver].Visible = false;
            this.Columns[_filterMouseOver].Visible      = false;

            this.Columns[_locatorexpirationdatewarning].Visible = false;   // used to store warning and put color in red
            this.Columns[_assetwarning].Visible                   = false; // used to store warning and put color in red
            this.Columns["Type"].HeaderText                       = "Type (streams nb)";
            this.Columns["Created"].HeaderText                    = "Created";
            this.Columns["AlternateId"].Visible                   = Properties.Settings.Default.DisplayAssetIDinGrid;
            this.Columns["StorageAccountName"].Visible            = Properties.Settings.Default.DisplayAssetStorageinGrid;
            this.Columns["SizeLong"].Visible                      = false;
            this.Columns[_filter].DisplayIndex                    = lastColumn_sIndex;
            this.Columns[_filter].DefaultCellStyle.NullValue      = null;
            this.Columns[_publication].DisplayIndex               = lastColumn_sIndex - 1;
            this.Columns[_publication].DefaultCellStyle.NullValue = null;
            this.Columns[_dynEnc].DisplayIndex                    = lastColumn_sIndex - 2;
            this.Columns[_dynEnc].DefaultCellStyle.NullValue      = null;

            this.Columns[_dynEnc].HeaderText = "Dynamic Encryption";

            this.Columns["Type"].Width       = 140;
            this.Columns["Size"].Width       = 80;
            this.Columns[_dynEnc].Width      = 80;
            this.Columns[_publication].Width = 90;
            this.Columns[_filter].Width      = 50;
            this.Columns[_locatorexpirationdate].HeaderText   = "Publication Expiration";
            this.Columns[_locatorexpirationdate].DisplayIndex = this.Columns.Count - 1;
            this.Columns[_locatorexpirationdate].Width        = 130;
            this.Columns["Created"].Width            = 140;
            this.Columns["AlternateId"].Width        = 300;
            this.Columns["StorageAccountName"].Width = 140;

            WorkerAnalyzeAssets = new BackgroundWorker()
            {
                WorkerSupportsCancellation = true
            };
            WorkerAnalyzeAssets.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerAnalyzeAssets_DoWork);

            _initialized = true;
        }
        private void WorkerAnalyzeAssets_DoWork(object sender, DoWorkEventArgs e)
        {
            Debug.WriteLine("WorkerAnalyzeAssets_DoWork");
            BackgroundWorker worker = sender as BackgroundWorker;
            Asset            asset  = null;

            var listae = _MyObservAssetV3.OrderBy(a => cacheAssetentriesV3.ContainsKey(a.Name)).ToList(); // as priority, assets not yet analyzed


            // test - let analyze only visible assets

            var visibleRowsCount       = this.DisplayedRowCount(true);
            var firstDisplayedRowIndex = (this.FirstDisplayedCell != null) ? this.FirstDisplayedCell.RowIndex : 0;
            var lastvisibleRowIndex    = (firstDisplayedRowIndex + visibleRowsCount) - 1;
            var VisibleAssets          = new List <String>();

            for (int rowIndex = firstDisplayedRowIndex; rowIndex <= lastvisibleRowIndex; rowIndex++)
            {
                var row = this.Rows[rowIndex];

                var assetname = row.Cells[this.Columns["Name"].Index].Value.ToString();
                VisibleAssets.Add(assetname);
            }

            var query   = from ae in listae join visAsset in VisibleAssets on ae.Name equals visAsset select ae;
            var listae2 = query.ToList();

            _client.RefreshTokenIfNeeded();

            foreach (AssetEntryV3 AE in listae2)
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    asset = _client.AMSclient.Assets.Get(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, AE.Name);

                    /*
                     * var firstPage = await MediaServicesArmClient.Assets.ListAsync(TestSettings.CustomerResourceGroup, TestSettings.CustomerAccountName);
                     *
                     * var currentPage = firstPage;
                     * while (currentPage.NextPageLink != null)
                     * {
                     *  currentPage = await MediaServicesArmClient.Assets.ListNextAsync(currentPage.NextPageLink);
                     * }
                     */

                    if (asset != null)
                    {
                        //AssetInfo myAssetInfo = new AssetInfo(asset);
                        AE.AlternateId  = asset.AlternateId;
                        AE.Description  = asset.Description;
                        AE.Created      = asset.Created.ToLocalTime().ToString("G");
                        AE.LastModified = asset.LastModified.ToLocalTime().ToString("G");
                        AE.Name         = asset.Name;
                        // AE.StorageAccountName = asset.StorageAccountName;

                        var assetBitmapAndText = DataGridViewAssets.BuildBitmapPublication(asset.Name, _client);
                        AE.Publication          = assetBitmapAndText.bitmap;
                        AE.PublicationMouseOver = assetBitmapAndText.MouseOverDesc;

                        // var assetfiles =  asset.AssetFiles.ToList();
                        var data = AssetInfo.GetAssetType(asset.Name, _client);
                        AE.Type         = data.Type;
                        AE.SizeLong     = data.Size;
                        AE.Size         = AssetInfo.FormatByteSize(AE.SizeLong);
                        AE.AssetWarning = (AE.SizeLong == 0);// || assetfiles.Any(f => f.ContentFileSize == 0));

                        assetBitmapAndText   = BuildBitmapDynEncryption(asset.Name, _client);
                        AE.DynamicEncryption = assetBitmapAndText.bitmap;
                        //AE.DynamicEncryptionMouseOver = assetBitmapAndText.MouseOverDesc;

                        if (assetBitmapAndText.Locators != null)
                        {
                            DateTime?LocDate = assetBitmapAndText.Locators.Any() ? (DateTime?)assetBitmapAndText.Locators.Min(l => l.EndTime).ToLocalTime() : null;
                            AE.LocatorExpirationDate        = LocDate.HasValue ? ((DateTime)LocDate).ToLocalTime().ToString() : null;
                            AE.LocatorExpirationDateWarning = LocDate.HasValue ? (LocDate < DateTime.Now.ToLocalTime()) : false;
                        }

                        //assetBitmapAndText = BuildBitmapAssetFilters(asset.Name, _client);
                        int?afcount = ReturnNumberAssetFilters(asset.Name, _client);
                        AE.Filters = afcount > 0 ? afcount : null;
                        //AE.FiltersMouseOver = assetBitmapAndText.MouseOverDesc;

                        cacheAssetentriesV3[asset.Name] = AE; // let's put it in cache (or update the cache)
                    }
                }
                catch // in some case, we have a timeout on Assets.Where...
                {
                }
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    return;
                }
            }
            this.BeginInvoke(new Action(() => this.Refresh()), null);
        }
        private void backgroundWorkerExcel_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                _amsClient.RefreshTokenIfNeeded();

                // Streaming endpoints
                Microsoft.Rest.Azure.IPage <StreamingEndpoint> streamingEndpoints = _amsClient.AMSclient.StreamingEndpoints.List(_amsClient.credentialsEntry.ResourceGroup, _amsClient.credentialsEntry.AccountName);
                var selist = streamingEndpoints.ToList();

                int  numberMaxLocators = 0;
                var  csvheader         = new StringBuilder();
                var  csv                = new StringBuilder();
                bool detailed           = radioButtonDetailledMode.Checked;
                Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

                if (xlApp == null)
                {
                    MessageBox.Show("Excel is not properly installed!!");
                    return;
                }

                Excel.Workbook  xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object          misValue = System.Reflection.Missing.Value;

                xlWorkBook  = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                xlWorkSheet.get_Range("a1", "f1").Merge(false);
                Excel.Range chartRange = xlWorkSheet.get_Range("a1", "f1");
                if (radioButtonAllAssets.Checked)
                {
                    chartRange.FormulaR1C1 = string.Format(AMSExplorer.Properties.Resources.ExportToExcel_backgroundWorker1_DoWork_AllAssetsInformationMediaAccount0, _amsClient.credentialsEntry.AccountName);
                }
                else
                {
                    chartRange.FormulaR1C1 = string.Format(AMSExplorer.Properties.Resources.ExportToExcel_backgroundWorker1_DoWork_SelectedAssetsInformationMediaAccount0, _amsClient.credentialsEntry.AccountName);
                }
                chartRange.VerticalAlignment = 3;
                chartRange.Font.Color        = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);
                chartRange.Font.Size         = 20;

                xlWorkSheet.get_Range("a2", "f2").Merge(false);
                Excel.Range chartRange2 = xlWorkSheet.get_Range("a2", "f2");
                chartRange2.FormulaR1C1 = string.Format("Exported with Azure Media Services Explorer v{0} on {1}. Dates are {2}.",
                                                        Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                                        checkBoxLocalTime.Checked ? DateTime.Now.ToString() : DateTime.UtcNow.ToString(),
                                                        checkBoxLocalTime.Checked ? "local" : "UTC based"
                                                        );
                chartRange2.VerticalAlignment = 3;
                chartRange2.Font.Color        = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);
                chartRange2.Font.Size         = 12;


                Excel.Range formatRange;
                formatRange = xlWorkSheet.get_Range("a4");
                formatRange.EntireRow.Font.Bold      = true;
                formatRange.EntireRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);

                int row   = 5;
                int index = 1;

                if (radioButtonAllAssets.Checked)
                {
                    IPage <Asset> currentPage = null;
                    currentPage = _amsClient.AMSclient.Assets.List(_amsClient.credentialsEntry.ResourceGroup, _amsClient.credentialsEntry.AccountName);

                    while (true)
                    {
                        foreach (Asset asset in currentPage)
                        {
                            var locatorCount = Task.Run(async() => await ExportAssetExcelAsync(asset, xlWorkSheet, row, detailed, checkBoxLocalTime.Checked, selist)).Result;
                            if (locatorCount != null)
                            {
                                numberMaxLocators = Math.Max(numberMaxLocators, (int)locatorCount);
                            }

                            backgroundWorkerCSV.ReportProgress(index, DateTime.Now); //notify progress to main thread. We also pass time information in UserState to cover this property in the example.
                                                                                     //if cancellation is pending, cancel work.
                            if (backgroundWorkerExcel.CancellationPending)
                            {
                                xlApp.DisplayAlerts = false;
                                xlWorkBook.Close();
                                xlApp.Quit();
                                releaseObject(xlWorkSheet);
                                releaseObject(xlWorkBook);
                                releaseObject(xlApp);
                                e.Cancel = true;
                                return;
                            }
                            index++;
                            row++;
                        }

                        if (currentPage.NextPageLink != null)
                        {
                            currentPage = _amsClient.AMSclient.Assets.ListNext(currentPage.NextPageLink);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else // Selected assets
                {
                    int total = _selassets.Count();

                    foreach (Asset asset in _selassets)
                    {
                        var locatorCount = Task.Run(async() => await ExportAssetExcelAsync(asset, xlWorkSheet, row, detailed, checkBoxLocalTime.Checked, selist)).Result;
                        if (locatorCount != null)
                        {
                            numberMaxLocators = Math.Max(numberMaxLocators, (int)locatorCount);
                        }

                        backgroundWorkerCSV.ReportProgress(100 * index / total, DateTime.Now); //notify progress to main thread. We also pass time information in UserState to cover this property in the example.
                                                                                               //if cancellation is pending, cancel work.
                        if (backgroundWorkerExcel.CancellationPending)
                        {
                            xlApp.DisplayAlerts = false;
                            xlWorkBook.Close();
                            xlApp.Quit();
                            releaseObject(xlWorkSheet);
                            releaseObject(xlWorkBook);
                            releaseObject(xlApp);
                            e.Cancel = true;
                            return;
                        }
                        index++;
                        row++;
                    }
                }

                // Header
                row   = 4;
                index = 1;
                xlWorkSheet.Cells[row, index++] = "Asset name";
                xlWorkSheet.Cells[row, index++] = "Description";
                xlWorkSheet.Cells[row, index++] = "Alternate Id";
                xlWorkSheet.Cells[row, index++] = "Asset Id";
                xlWorkSheet.Cells[row, index++] = "Created time";
                xlWorkSheet.Cells[row, index++] = "Last modified time";
                xlWorkSheet.Cells[row, index++] = "Storage account";
                xlWorkSheet.Cells[row, index++] = "Storage container";

                if (detailed)
                {
                    xlWorkSheet.Cells[row, index++] = "Asset type";
                    xlWorkSheet.Cells[row, index++] = "Size";
                }

                xlWorkSheet.Cells[row, index++] = "Streaming locators count";

                if (detailed)
                {
                    for (int iloc = 0; iloc < numberMaxLocators; iloc++)
                    {
                        xlWorkSheet.Cells[row, index++] = string.Format("Locator name #{0}", iloc + 1);
                        xlWorkSheet.Cells[row, index++] = "Created time";
                        xlWorkSheet.Cells[row, index++] = "Start time";
                        xlWorkSheet.Cells[row, index++] = "End time";
                        foreach (var se in selist)
                        {
                            xlWorkSheet.Cells[row, index++] = string.Format("Streaming Urls with streaming endpoint #{0}", selist.IndexOf(se));
                        }
                    }
                }

                // Set the range to fill.
                var aRange = xlWorkSheet.get_Range("A4", "Z100");
                aRange.EntireColumn.AutoFit();

                try
                {
                    xlWorkBook.SaveAs(filename, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();
                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);
                }
                catch
                {
                    MessageBox.Show(AMSExplorer.Properties.Resources.ExportToExcel_backgroundWorker1_DoWork_ErrorWhenSavingTheExcelFile, AMSExplorer.Properties.Resources.AMSLogin_buttonExport_Click_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (checkBoxOpenFileAfterExport.Checked)
                {
                    System.Diagnostics.Process.Start(filename);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(AMSExplorer.Properties.Resources.ExportToExcel_backgroundWorker1_DoWork_Error + ex.Message);
            }
        }
Exemplo n.º 21
0
        public void Init(AMSClientV3 client)
        {
            IEnumerable <LiveOutputEntry> programquery;

            client.RefreshTokenIfNeeded();

            _client = client;
            _client.RefreshTokenIfNeeded();

            var ListEvents = _client.AMSclient.LiveEvents.List(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName).ToList();
            List <Program.LiveOutputExt> LOList = new List <Program.LiveOutputExt>();

            foreach (var le in ListEvents)
            {
                var plist = _client.AMSclient.LiveOutputs.List(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, le.Name).ToList();
                plist.ForEach(p => LOList.Add(new Program.LiveOutputExt()
                {
                    LiveOutputItem = p, LiveEventName = le.Name
                }));
            }

            programquery = from c in (LOList.Take(0))
                           //orderby c.LastModified descending
                           select new LiveOutputEntry
            {
                Name                = c.LiveOutputItem.Name,
                State               = c.LiveOutputItem.ResourceState,
                Description         = c.LiveOutputItem.Description,
                ArchiveWindowLength = c.LiveOutputItem.ArchiveWindowLength,
                LastModified        = c.LiveOutputItem.LastModified != null ? (DateTime?)((DateTime)c.LiveOutputItem.LastModified).ToLocalTime() : null,
                Published           = null,
                LiveEventName       = c.LiveEventName
            };

            DataGridViewCellStyle cellstyle = new DataGridViewCellStyle()
            {
                NullValue = null,
                Alignment = DataGridViewContentAlignment.MiddleCenter
            };
            DataGridViewImageColumn imageCol = new DataGridViewImageColumn()
            {
                DefaultCellStyle = cellstyle,
                Name             = _published,
                DataPropertyName = _published,
            };

            this.Columns.Add(imageCol);


            SortableBindingList <LiveOutputEntry> MyObservProgramInPage = new SortableBindingList <LiveOutputEntry>(programquery.Take(0).ToList());

            this.DataSource = MyObservProgramInPage;
            //this.Columns["LiveEventName"].Visible = false;
            this.Columns[_published].DisplayIndex = this.ColumnCount - 3;
            this.Columns[_published].DefaultCellStyle.NullValue = null;
            this.Columns[_published].HeaderText            = _published;
            this.Columns["LastModified"].Width             = 130;
            this.Columns["LastModified"].HeaderText        = "Last modified";
            this.Columns["Description"].Width              = 150;
            this.Columns["ArchiveWindowLength"].Width      = 130;
            this.Columns["ArchiveWindowLength"].HeaderText = "Archive window";
            this.Columns["LiveEventName"].HeaderText       = "Live event name";

            WorkerRefreshChannels = new BackgroundWorker();
            WorkerRefreshChannels.WorkerSupportsCancellation = true;
            WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork);

            _initialized = true;
        }
        public static AssetBitmapAndText BuildBitmapPublication(string assetName, AMSClientV3 client)
        {
            Bitmap returnedImage = null;
            string returnedText  = null;

            client.RefreshTokenIfNeeded();
            IList <AssetStreamingLocator> locators;

            try
            {
                locators = client.AMSclient.Assets.ListStreamingLocators(client.credentialsEntry.ResourceGroup, client.credentialsEntry.AccountName, assetName).StreamingLocators;
            }
            catch
            {
                return(new AssetBitmapAndText()
                {
                    bitmap = BitmapCancel,
                    MouseOverDesc = "Error"
                });
            }

            foreach (var locator in locators)
            {
                Bitmap        newbitmap = null;
                string        newtext   = null;
                PublishStatus Status    = AssetInfo.GetPublishedStatusForLocator(locator);

                {
                    switch (Status)
                    {
                    case PublishStatus.PublishedActive:
                        newbitmap = Streaminglocatorimage;
                        newtext   = "Active Streaming locator";
                        break;

                    case PublishStatus.PublishedExpired:
                        newbitmap = Redstreamimage;
                        newtext   = "Expired Streaming locator";
                        break;

                    case PublishStatus.PublishedFuture:
                        newbitmap = Bluestreamimage;
                        newtext   = "Future Streaming locator";
                        break;

                    case PublishStatus.NotPublished:
                    default:
                        break;
                    }
                }

                returnedImage = AddBitmap(returnedImage, newbitmap);
                returnedText += !string.IsNullOrEmpty(newtext) ? newtext + Constants.endline : string.Empty;
            }

            return(new AssetBitmapAndText()
            {
                bitmap = returnedImage,
                MouseOverDesc = returnedText ?? "Not published"
            });
        }
        public static AssetBitmapAndText BuildBitmapDynEncryption(string assetName, AMSClientV3 client)
        {
            client.RefreshTokenIfNeeded();
            IList <AssetStreamingLocator> locators;

            try
            {
                locators = client.AMSclient.Assets.ListStreamingLocators(client.credentialsEntry.ResourceGroup, client.credentialsEntry.AccountName, assetName).StreamingLocators;
            }
            catch
            {
                return(new AssetBitmapAndText()
                {
                    bitmap = BitmapCancel,
                    MouseOverDesc = "Error"
                });
            }

            if (locators.Count == 0)
            {
                return(new AssetBitmapAndText());
            }

            AssetBitmapAndText ABT = new AssetBitmapAndText()
            {
                Locators = locators
            };

            var ClearEnable    = locators.Any(l => l.StreamingPolicyName == PredefinedStreamingPolicy.ClearStreamingOnly || l.StreamingPolicyName == PredefinedStreamingPolicy.DownloadAndClearStreaming);
            var CENCEnable     = locators.Any(l => l.StreamingPolicyName == PredefinedStreamingPolicy.MultiDrmCencStreaming || l.StreamingPolicyName == PredefinedStreamingPolicy.MultiDrmStreaming);
            var CENCCbcsEnable = locators.Any(l => l.StreamingPolicyName == PredefinedStreamingPolicy.MultiDrmStreaming);
            var EnvelopeEnable = locators.Any(l => l.StreamingPolicyName == PredefinedStreamingPolicy.ClearKey);


            int count = (ClearEnable ? 1 : 0) + (CENCEnable ? 1 : 0) + (CENCCbcsEnable ? 1 : 0) + (EnvelopeEnable ? 1 : 0);

            if (count == 0)
            {
                return(new AssetBitmapAndText());
            }

            ABT.bitmap = new Bitmap((envelopeencryptedimage.Width * count), envelopeencryptedimage.Height);
            int x = 0;

            using (Graphics graphicsObject = Graphics.FromImage(ABT.bitmap))
            {
                if (ClearEnable)
                {
                    graphicsObject.DrawImage(clearimage, new Point(x, 0));
                    x += envelopeencryptedimage.Width;
                }

                if (EnvelopeEnable)
                {
                    graphicsObject.DrawImage(envelopeencryptedimage, new Point(x, 0));
                    x += envelopeencryptedimage.Width;
                }

                if (CENCEnable)
                {
                    graphicsObject.DrawImage(CENCencryptedimage, new Point(x, 0));
                    x += CENCencryptedimage.Width;
                }

                if (CENCCbcsEnable)
                {
                    graphicsObject.DrawImage(CENCcbcsEncryptedImage, new Point(x, 0));
                    x += CENCcbcsEncryptedImage.Width;
                }
            }

            return(ABT);
        }