public AttachStorage(CredentialsEntry credentials) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; linkLabelAttach.Links.Add(new LinkLabel.Link(0, linkLabelAttach.Text.Length, "https://manage.windowsazure.com/publishsettings")); _credentials = credentials; }
public void Init(CredentialsEntry credentials) { IEnumerable <ProgramEntry> programquery; _credentials = credentials; _context = Program.ConnectAndGetNewContext(_credentials); programquery = from c in _context.Programs orderby c.LastModified descending select new ProgramEntry { Name = c.Name, Id = c.Id, State = c.State, Description = c.Description, ArchiveWindowLength = c.ArchiveWindowLength, LastModified = c.LastModified.ToLocalTime(), ChannelName = c.Channel.Name, ChannelId = c.Channel.Id }; BindingList <ProgramEntry> MyObservProgramInPage = new BindingList <ProgramEntry>(programquery.Take(0).ToList()); this.DataSource = MyObservProgramInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveProgramIDinGrid; this.Columns["ChannelId"].Visible = false; WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
private void buttonSaveToList_Click(object sender, EventArgs e) { LoginCredentials = GenerateLoginCredentials; // New code for JSON if (string.IsNullOrEmpty(LoginCredentials.ReturnAccountName())) { MessageBox.Show(AMSExplorer.Properties.Resources.AMSLogin_buttonSaveToList_Click_TheAccountNameCannotBeEmpty); return; } var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.ReturnAccountName().ToLower().Trim() == LoginCredentials.ReturnAccountName().ToLower().Trim()).FirstOrDefault(); // if found the same name if (entryWithSameName != null) { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; } else { CredentialList.MediaServicesAccounts.Add(LoginCredentials); //listViewAccounts.Items.Add(ReturnAccountName(LoginCredentials)); AddItemToListviewAccounts(LoginCredentials); } Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); }
private void listBoxAcounts_SelectedIndexChanged(object sender, EventArgs e) { if (listBoxAccounts.SelectedIndex > -1) // one selected { int index = listBoxAccounts.SelectedIndex * CredentialsEntry.StringsCount; string[] temp = CredentialsList[index + 9].Split("|".ToCharArray()); SelectedCredentials = new CredentialsEntry( CredentialsList[index], CredentialsList[index + 1], CredentialsList[index + 2], CredentialsList[index + 3], CredentialsList[index + 4], CredentialsList[index + 5], CredentialsList[index + 6], CredentialsList[index + 7], CredentialsList[index + 8], ReturnAzureEndpoint(CredentialsList[index + 9]), ReturnManagementPortal(CredentialsList[index + 9]) ); labelDescription.Text = CredentialsList[listBoxAccounts.SelectedIndex * CredentialsEntry.StringsCount + 3]; if (Mode == CopyAssetBoxMode.CopyAsset) { labelWarning.Text = (string.IsNullOrEmpty(SelectedCredentials.StorageKey)) ? "Storage key is empty !" : string.Empty; } radioButtonDefaultStorage.Checked = true; listBoxStorage.Items.Clear(); } }
private void listBoxAcounts_SelectedIndexChanged(object sender, EventArgs e) { if (listBoxAccounts.SelectedIndex > -1) // one selected { int index = listBoxAccounts.SelectedIndex; SelectedCredentials = _listMediaAccounts[index]; if (Mode == CopyAssetBoxMode.CopyAsset) { labelWarning.Text = (string.IsNullOrEmpty(SelectedCredentials.DefaultStorageKey)) ? AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_StorageKeyIsEmpty : string.Empty; } radioButtonDefaultStorage.Checked = true; listBoxStorage.Items.Clear(); if (SelectedCredentials.UseAADServicePrincipal) // not supported for now { /* * labelWarningStorage.Text = AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_ErrorWhenConnectingToAccount; * ErrorConnectingAMS = true; * return; */ var spcrendentialsform = new AMSLoginServicePrincipal(); if (spcrendentialsform.ShowDialog() == DialogResult.OK) { SelectedCredentials.ADSPClientId = spcrendentialsform.ClientId; SelectedCredentials.ADSPClientSecret = spcrendentialsform.ClientSecret; } else { labelWarningStorage.Text = AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_ErrorWhenConnectingToAccount; ErrorConnectingAMS = true; return; } } // let's check connection to account try { this.Cursor = Cursors.WaitCursor; CloudMediaContext newcontext = Program.ConnectAndGetNewContext(SelectedCredentials, true, false); foreach (var storage in newcontext.StorageAccounts) { listBoxStorage.Items.Add(new Item(storage.Name + ((storage.Name == newcontext.DefaultStorageAccount.Name) ? AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_Default : string.Empty), storage.Name)); } labelWarningStorage.Text = ""; ErrorConnectingAMS = false; } catch { labelWarningStorage.Text = AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_ErrorWhenConnectingToAccount; ErrorConnectingAMS = true; } finally { this.Cursor = Cursors.Arrow; } UpdateStatusButtonOk(); } }
public void Init(CredentialsEntry credentials) { IEnumerable <ChannelEntry> channelquery; _credentials = credentials; _context = Program.ConnectAndGetNewContext(_credentials); channelquery = from c in _context.Channels orderby c.LastModified descending select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = c.Input.StreamingProtocol, IngestUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; /* * try * { * int c = jobs.Count(); * } * catch (Exception e) * { * MessageBox.Show("There is a problem when connecting to Azure Media Services. Application will close. " + e.Message); * Environment.Exit(0); * } * */ //DataGridViewProgressBarColumn col = new DataGridViewProgressBarColumn(); //DataGridViewCellStyle cellstyle = new DataGridViewCellStyle(); //col.Name = "Progress"; //col.DataPropertyName = "Progress"; //this.Columns.Add(col); BindingList <ChannelEntry> MyObservJobInPage = new BindingList <ChannelEntry>(channelquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveChannelIDinGrid; /*this.Columns["Progress"].DisplayIndex = 6; * this.Columns["Tasks"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; * this.Columns["Tasks"].Width = 50; * this.Columns["Priority"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; * this.Columns["Priority"].Width = 50; * Task.Run(() => RestoreJobProgress());*/ WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
public DisplayTelemetry(Mainform mainform, object entity, CloudMediaContext context, CredentialsEntry credentials) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; MyMainForm = mainform; _context = context; _credentials = credentials; _entity = entity; }
private void listBoxAcounts_SelectedIndexChanged(object sender, EventArgs e) { if (listBoxAccounts.SelectedIndex > -1) // one selected { int index = listBoxAccounts.SelectedIndex; // * CredentialsEntry.StringsCount; // string[] temp = CredentialList[index + 9].Split("|".ToCharArray()); SelectedCredentials = CredentialList.MediaServicesAccounts[index]; /* * new CredentialsEntry( * CredentialList[index], * CredentialList[index + 1], * CredentialList[index + 2], * CredentialList[index + 3], * CredentialList[index + 4] == true.ToString() ? true : false, * CredentialList[index + 5] == true.ToString() ? true : false, * CredentialList[index + 6], * CredentialList[index + 7], * CredentialList[index + 8], * ReturnAzureEndpoint(CredentialList[index + 9]), * ReturnManagementPortal(CredentialList[index + 9]), * ); */ labelDescription.Text = SelectedCredentials.Description; if (Mode == CopyAssetBoxMode.CopyAsset) { labelWarning.Text = (string.IsNullOrEmpty(SelectedCredentials.DefaultStorageKey)) ? "Storage key is empty !" : string.Empty; } radioButtonDefaultStorage.Checked = true; listBoxStorage.Items.Clear(); // let's check connection to account try { this.Cursor = Cursors.WaitCursor; CloudMediaContext newcontext = Program.ConnectAndGetNewContext(SelectedCredentials, true, false); foreach (var storage in newcontext.StorageAccounts) { listBoxStorage.Items.Add(new Item(storage.Name + ((storage.Name == newcontext.DefaultStorageAccount.Name) ? " (default)" : string.Empty), storage.Name)); } labelWarningStorage.Text = ""; ErrorConnectingAMS = false; } catch { labelWarningStorage.Text = "Error when connecting to account."; ErrorConnectingAMS = true; } finally { this.Cursor = Cursors.Arrow; } UpdateStatusButtonOk(); } }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable <ProgramEntry> programquery; _credentials = credentials; _context = context; programquery = from c in _context.Programs orderby c.LastModified descending select new ProgramEntry { Name = c.Name, Id = c.Id, State = c.State, Description = c.Description, ArchiveWindowLength = c.ArchiveWindowLength, LastModified = c.LastModified.ToLocalTime(), Published = null, ChannelName = c.Channel.Name, ChannelId = c.Channel.Id }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle() { NullValue = null, Alignment = DataGridViewContentAlignment.MiddleCenter }; DataGridViewImageColumn imageCol = new DataGridViewImageColumn() { DefaultCellStyle = cellstyle, Name = _published, DataPropertyName = _published, }; this.Columns.Add(imageCol); BindingList <ProgramEntry> MyObservProgramInPage = new BindingList <ProgramEntry>(programquery.Take(0).ToList()); this.DataSource = MyObservProgramInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveProgramIDinGrid; this.Columns["ChannelId"].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["Description"].Width = 150; this.Columns["ArchiveWindowLength"].Width = 130; WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
private void UpdateAADSettingsTextBoxes() { if (radioButtonAADProd.Checked) { textBoxAADAMSResource.Enabled = textBoxAADClienid.Enabled = textBoxAADRedirect.Enabled = textBoxAADAzureEndpoint.Enabled = textBoxAADManagementPortal.Enabled = false; AADEndPointMapping entrymapping = CredentialsEntry.AADMappings.Where(m => m.Name == nameof(AzureEnvironments.AzureCloudEnvironment)).FirstOrDefault(); var env = AzureEnvironments.AzureCloudEnvironment; textBoxAADAMSResource.Text = env.MediaServicesResource; textBoxAADClienid.Text = env.MediaServicesSdkClientId; textBoxAADRedirect.Text = env.MediaServicesSdkRedirectUri.ToString(); textBoxAADAzureEndpoint.Text = env.ActiveDirectoryEndpoint.ToString(); textBoxAADManagementPortal.Text = entrymapping.ManagementPortal; } else { if (((Item)comboBoxAADMappingList.SelectedItem).Value == CustomString) { textBoxAADAMSResource.Enabled = textBoxAADClienid.Enabled = textBoxAADRedirect.Enabled = textBoxAADAzureEndpoint.Enabled = textBoxAADManagementPortal.Enabled = true; textBoxAADAMSResource.Text = textBoxAADClienid.Text = textBoxAADRedirect.Text = textBoxAADAzureEndpoint.Text = textBoxAADManagementPortal.Text = ""; } else { textBoxAADAMSResource.Enabled = textBoxAADClienid.Enabled = textBoxAADRedirect.Enabled = textBoxAADAzureEndpoint.Enabled = textBoxAADManagementPortal.Enabled = false; AADEndPointMapping entrymapping = CredentialsEntry.AADMappings.Where(m => m.Name == ((Item)comboBoxAADMappingList.SelectedItem).Value).FirstOrDefault(); var env = CredentialsEntry.ReturnADEnvironment(((Item)comboBoxAADMappingList.SelectedItem).Value); textBoxAADAMSResource.Text = env.MediaServicesResource; textBoxAADClienid.Text = env.MediaServicesSdkClientId; textBoxAADRedirect.Text = env.MediaServicesSdkRedirectUri.ToString(); textBoxAADAzureEndpoint.Text = env.ActiveDirectoryEndpoint.ToString(); textBoxAADManagementPortal.Text = entrymapping.ManagementPortal; } } }
public static CloudMediaContext ConnectAndGetNewContext(CredentialsEntry credentials) { CloudMediaContext myContext = null; if (credentials.UsePartnerAPI == true.ToString()) { // Get the service context for partner context. try { Uri partnerAPIServer = new Uri(CredentialsEntry.PartnerAPIServer); myContext = new CloudMediaContext(partnerAPIServer, credentials.AccountName, credentials.AccountKey, CredentialsEntry.PartnerScope, CredentialsEntry.PartnerACSBaseAddress); } catch (Exception e) { MessageBox.Show("There is a credentials problem when connecting to Azure Media Services (custom API)." + Constants.endline + "Application will close. " + Constants.endline + e.Message); Environment.Exit(0); } } else if (credentials.UseOtherAPI == true.ToString()) { try { Uri otherAPIServer = new Uri(credentials.OtherAPIServer); myContext = new CloudMediaContext(otherAPIServer, credentials.AccountName, credentials.AccountKey, credentials.OtherScope, credentials.OtherACSBaseAddress); } catch (Exception e) { MessageBox.Show("There is a credentials problem when connecting to Azure Media Services (Partner API)." + Constants.endline + "Application will close." + Constants.endline + e.Message); Environment.Exit(0); } } else { // Get the service context. try { myContext = new CloudMediaContext(credentials.AccountName, credentials.AccountKey); } catch (Exception e) { MessageBox.Show("There is a credentials problem when connecting to Azure Media Services." + Constants.endline + "Application will close." + Constants.endline + e.Message); Environment.Exit(0); } } try { myContext.Credentials.RefreshToken(); } // to force connection to WAMS catch (Exception e) { // Add useful information to the exception MessageBox.Show("There is a credentials problem when connecting to Azure Media Services." + Constants.endline + "Application will close." + Constants.endline + e.Message); Environment.Exit(0); } return(myContext); }
private void buttonLogin_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxAccountName.Text)) { MessageBox.Show("The account name cannot be empty."); return; } CredentialsEntry myCredentials = new CredentialsEntry(textBoxAccountName.Text, textBoxAccountKey.Text, textBoxBlobKey.Text, textBoxAccountID.Text, textBoxDescription.Text, radioButtonPartner.Checked, radioButtonOther.Checked, textBoxAPIServer.Text, textBoxScope.Text, textBoxACSBaseAddress.Text, textBoxAzureEndpoint.Text, textBoxManagementPortal.Text); var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.AccountName.ToLower().Trim() == textBoxAccountName.Text.ToLower().Trim()).FirstOrDefault(); // if found the same name if (entryWithSameName == null) // not found { //CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = myCredentials; var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToSaveTheCredentialsFor0, textBoxAccountName.Text), AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_SaveCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to save { CredentialList.MediaServicesAccounts.Add(myCredentials); Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); listBoxAcounts.Items.Add(myCredentials.AccountName); } else if (result == DialogResult.Cancel) { return; } } else // found { if (!myCredentials.Equals(entryWithSameName)) // changed ? { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToUpdateTheCredentialsFor0, myCredentials.AccountName), AMSExplorer.Properties.Resources.AMSLogin_listBoxAccounts_SelectedIndexChanged_UpdateCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } else if (result == DialogResult.Cancel) { return; } } } this.DialogResult = DialogResult.OK; // form will close with OK result // else --> form won't close... }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable <IngestManifestEntry> ingestmanifestquery; _credentials = credentials; _context = context;// Program.ConnectAndGetNewContext(_credentials); ingestmanifestquery = from im in _context.IngestManifests.Take(0) orderby im.LastModified descending select new IngestManifestEntry { Name = im.Name, Id = im.Id, State = im.State, LastModified = im.LastModified.ToLocalTime().ToString("G"), URLForUpload = im.BlobStorageUriForUpload }; DataGridViewProgressBarColumn col = new DataGridViewProgressBarColumn() { Name = "Progress", DataPropertyName = "Progress", HeaderText = "Progress" }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle(); this.Columns.Add(col); BindingList <IngestManifestEntry> MyObservJobInPage = new BindingList <IngestManifestEntry>(ingestmanifestquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayIngestManifestIDinGrid; this.Columns["Progress"].DisplayIndex = 6; this.Columns["Progress"].Width = 150; this.Columns["URLForUpload"].Width = 200; this.Columns["LastModified"].HeaderText = "Last modified"; this.Columns["LastModified"].Width = 140; this.Columns["Storage"].Width = 140; this.Columns["PendingFiles"].HeaderText = "Pending Files"; this.Columns["FinishedFiles"].HeaderText = "Finished Files"; this.Columns["URLForUpload"].HeaderText = "Ingest Url"; this.Columns["LastModified"].HeaderText = "Last modified"; WorkerUpdateIngestManifest = new BackgroundWorker() { WorkerSupportsCancellation = true }; WorkerUpdateIngestManifest.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerUpdateIngestManifest_DoWork); _initialized = true; }
private void listBoxAccounts_SelectedIndexChanged(object sender, EventArgs e) { buttonDeleteAccountEntry.Enabled = (listBoxAcounts.SelectedIndex > -1); // no selected item, so login button not active buttonExport.Enabled = (listBoxAcounts.Items.Count > 0); if (listBoxAcounts.SelectedIndex > -1) // one selected { if (CurrentCredential != null) { var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.AccountName.ToLower().Trim() == CurrentCredential.AccountName.ToLower().Trim()).FirstOrDefault(); if (entryWithSameName != null && !LoginCredentials.Equals(CurrentCredential)) { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToUpdateTheCredentialsFor0, CurrentCredential.AccountName), AMSExplorer.Properties.Resources.AMSLogin_listBoxAccounts_SelectedIndexChanged_UpdateCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } } } var entry = CredentialList.MediaServicesAccounts[listBoxAcounts.SelectedIndex]; textBoxAccountName.Text = entry.AccountName; textBoxAccountKey.Text = entry.AccountKey; textBoxBlobKey.Text = entry.DefaultStorageKey; textBoxAccountID.Text = entry.AccountId; textBoxDescription.Text = entry.Description; radioButtonPartner.Checked = entry.UsePartnerAPI; radioButtonOther.Checked = entry.UseOtherAPI; textBoxAPIServer.Text = entry.OtherAPIServer; textBoxScope.Text = entry.OtherScope; textBoxACSBaseAddress.Text = entry.OtherACSBaseAddress; textBoxAzureEndpoint.Text = entry.OtherAzureEndpoint; textBoxManagementPortal.Text = entry.OtherManagementPortal; // if not partner or other, then defaut if (!radioButtonPartner.Checked && !radioButtonOther.Checked) { radioButtonProd.Checked = true; } // to clear or set the error CheckTextBox((object)textBoxAccountName); CheckTextBox((object)textBoxAccountKey); CurrentCredential = LoginCredentials; } }
private void buttonSaveToList_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxAccountName.Text)) { MessageBox.Show("The account name cannot be empty."); return; } CredentialsEntry myCredentials = new CredentialsEntry(textBoxAccountName.Text, textBoxAccountKey.Text, textBoxBlobKey.Text, textBoxDescription.Text, radioButtonPartner.Checked.ToString(), radioButtonOther.Checked.ToString(), textBoxAPIServer.Text, textBoxScope.Text, textBoxACSBaseAddress.Text, textBoxAzureEndpoint.Text, textBoxManagementPortal.Text); if (CredentialsList == null) { CredentialsList = new StringCollection(); } //let's find if the account name is already in the list int foundindex = -1; for (int i = 0; i < CredentialsList.Count; i += CredentialsEntry.StringsCount) { if (CredentialsList[i] == textBoxAccountName.Text) { foundindex = i; break; } } if (foundindex == -1) // not found { CredentialsList.AddRange(myCredentials.ToArray()); Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); listBoxAcounts.Items.Add(myCredentials.AccountName); } else { //found, let's update the entry et insert the new data for (int i = 0; i < CredentialsEntry.StringsCount; i++) { CredentialsList.RemoveAt(foundindex); } for (int i = 0; i < CredentialsEntry.StringsCount; i++) { CredentialsList.Insert(foundindex + i, myCredentials.ToArray().Skip(i).Take(1).FirstOrDefault()); } Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); } }
public static bool ConnectToStorage(CloudMediaContext context, CredentialsEntry credentials) { try { CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(context.DefaultStorageAccount.Name, credentials.StorageKey), true); CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); return(true); } catch { MessageBox.Show(string.Format("There is a problem when connecting to the Azure storage account {0}.\r\nIs the storage key correct ?", context.DefaultStorageAccount.Name), "Storage Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } }
private void AddItemToListviewAccounts(CredentialsEntry c) { var item = listViewAccounts.Items.Add(c.ReturnAccountName()); if (!c.UseAADInteract && !c.UseAADServicePrincipal) { listViewAccounts.Items[item.Index].ForeColor = Color.Red; listViewAccounts.Items[item.Index].ToolTipText = "Configured for deprecated ACS authentication. Please use Azure Active Directory."; } else { listViewAccounts.Items[item.Index].ForeColor = Color.Black; listViewAccounts.Items[item.Index].ToolTipText = null; } }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable<IngestManifestEntry> ingestmanifestquery; _credentials = credentials; _context = context;// Program.ConnectAndGetNewContext(_credentials); ingestmanifestquery = from im in _context.IngestManifests.Take(0) orderby im.LastModified descending select new IngestManifestEntry { Name = im.Name, Id = im.Id, State = im.State, LastModified = im.LastModified.ToLocalTime().ToString("G"), URLForUpload = im.BlobStorageUriForUpload }; DataGridViewProgressBarColumn col = new DataGridViewProgressBarColumn() { Name = "Progress", DataPropertyName = "Progress", HeaderText = "Progress" }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle(); this.Columns.Add(col); BindingList<IngestManifestEntry> MyObservJobInPage = new BindingList<IngestManifestEntry>(ingestmanifestquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayIngestManifestIDinGrid; this.Columns["Progress"].DisplayIndex = 6; this.Columns["Progress"].Width = 150; this.Columns["URLForUpload"].Width = 200; this.Columns["LastModified"].HeaderText = "Last modified"; this.Columns["LastModified"].Width = 140; this.Columns["Storage"].Width = 140; this.Columns["PendingFiles"].HeaderText = "Pending Files"; this.Columns["FinishedFiles"].HeaderText = "Finished Files"; this.Columns["URLForUpload"].HeaderText = "Ingest Url"; this.Columns["LastModified"].HeaderText = "Last modified"; WorkerUpdateIngestManifest = new BackgroundWorker() { WorkerSupportsCancellation = true }; WorkerUpdateIngestManifest.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerUpdateIngestManifest_DoWork); _initialized = true; }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable <StreamingEndpointEntry> originquery; _credentials = credentials; _context = context; originquery = from o in _context.StreamingEndpoints orderby o.LastModified descending select new StreamingEndpointEntry { Name = o.Name, Id = o.Id, Description = o.Description, CDN = o.CdnEnabled ? StreamingEndpointInformation.ReturnDisplayedProvider(o.CdnProvider) ?? "CDN" : string.Empty, ScaleUnits = StreamingEndpointInformation.ReturnTypeSE(o) != StreamingEndpointInformation.StreamEndpointType.Premium ? "" : ((int)o.ScaleUnits).ToString(), Type = StreamingEndpointInformation.ReturnTypeSE(o), State = o.State, LastModified = o.LastModified.ToLocalTime() }; SortableBindingList <StreamingEndpointEntry> MyObservOriginInPage = new SortableBindingList <StreamingEndpointEntry>(originquery.Take(0).ToList()); this.DataSource = MyObservOriginInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayOriginIDinGrid; 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; }
private void listBoxAcounts_SelectedIndexChanged(object sender, EventArgs e) { if (listBoxAccounts.SelectedIndex > -1) // one selected { int index = listBoxAccounts.SelectedIndex; SelectedCredentials = CredentialList.MediaServicesAccounts[index]; labelDescription.Text = SelectedCredentials.Description; if (Mode == CopyAssetBoxMode.CopyAsset) { labelWarning.Text = (string.IsNullOrEmpty(SelectedCredentials.DefaultStorageKey)) ? AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_StorageKeyIsEmpty : string.Empty; } radioButtonDefaultStorage.Checked = true; listBoxStorage.Items.Clear(); // let's check connection to account try { this.Cursor = Cursors.WaitCursor; CloudMediaContext newcontext = Program.ConnectAndGetNewContext(SelectedCredentials, true, false); foreach (var storage in newcontext.StorageAccounts) { listBoxStorage.Items.Add(new Item(storage.Name + ((storage.Name == newcontext.DefaultStorageAccount.Name) ? AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_Default : string.Empty), storage.Name)); } labelWarningStorage.Text = ""; ErrorConnectingAMS = false; } catch { labelWarningStorage.Text = AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_ErrorWhenConnectingToAccount; ErrorConnectingAMS = true; } finally { this.Cursor = Cursors.Arrow; } UpdateStatusButtonOk(); } }
/// <summary> /// Creates a new instance of <see cref="MediaServiceContextForDynManifest"/> /// </summary> /// <param name="accountName"> /// Media service account name. /// </param> /// <param name="accountKey"> /// Media service account key. /// </param> public MediaServiceContextForDynManifest(CredentialsEntry credentials) { this._accountName = credentials.AccountName; this._accountKey = credentials.AccountKey; if (credentials.UsePartnerAPI == true.ToString()) { _wamsEndpoint = CredentialsEntry.PartnerAPIServer; scope = CredentialsEntry.PartnerScope; acsEndpoint = CredentialsEntry.PartnerACSBaseAddress; } else if (credentials.UseOtherAPI == true.ToString()) { _wamsEndpoint = credentials.OtherAPIServer; scope = credentials.OtherScope; acsEndpoint = credentials.OtherACSBaseAddress; } else { // Global Azure } }
public static string ReturnAccountName(CredentialsEntry entry) { string accName = ""; if (!entry.UseAADInteract && !entry.UseAADServicePrincipal) { return(entry.AccountName); } else if (!string.IsNullOrEmpty(entry.ADRestAPIEndpoint)) { try { accName = (new Uri(entry.ADRestAPIEndpoint)).Host.Split('.')[0]; } catch { } } return(accName); }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable <StreamingEndpointEntry> originquery; _credentials = credentials; _context = context; originquery = from o in _context.StreamingEndpoints orderby o.LastModified descending select new StreamingEndpointEntry { Name = o.Name, Id = o.Id, Description = o.Description, ScaleUnits = o.ScaleUnits, State = o.State, LastModified = o.LastModified.ToLocalTime() }; SortableBindingList <StreamingEndpointEntry> MyObservOriginInPage = new SortableBindingList <StreamingEndpointEntry>(originquery.Take(0).ToList()); this.DataSource = MyObservOriginInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayOriginIDinGrid; this.Columns["Name"].Width = 300; this.Columns["State"].Width = 100; this.Columns["CDN"].Width = 100; this.Columns["Description"].Width = 230; this.Columns["ScaleUnits"].Width = 100; this.Columns["LastModified"].Width = 150; WorkerRefreshStreamingEndpoints = new BackgroundWorker(); WorkerRefreshStreamingEndpoints.WorkerSupportsCancellation = true; WorkerRefreshStreamingEndpoints.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshStreamingEndpoints_DoWork); _initialized = true; }
private void buttonSaveToList_Click(object sender, EventArgs e) { // New code for JSON if (string.IsNullOrEmpty(textBoxAccountName.Text)) { MessageBox.Show(AMSExplorer.Properties.Resources.AMSLogin_buttonSaveToList_Click_TheAccountNameCannotBeEmpty); return; } CredentialsEntry myCredentials = new CredentialsEntry(textBoxAccountName.Text, textBoxAccountKey.Text, textBoxBlobKey.Text, textBoxAccountID.Text, textBoxDescription.Text, radioButtonPartner.Checked, radioButtonOther.Checked, textBoxAPIServer.Text, textBoxScope.Text, textBoxACSBaseAddress.Text, textBoxAzureEndpoint.Text, textBoxManagementPortal.Text); var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.AccountName.ToLower().Trim() == textBoxAccountName.Text.ToLower().Trim()).FirstOrDefault(); // if found the same name if (entryWithSameName != null) { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = myCredentials; } else { CredentialList.MediaServicesAccounts.Add(myCredentials); } Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); }
private void buttonLogin_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxAccountName.Text)) { MessageBox.Show("The account name cannot be empty."); return; } CredentialsEntry myCredentials = new CredentialsEntry(textBoxAccountName.Text, textBoxAccountKey.Text, textBoxBlobKey.Text, textBoxDescription.Text, radioButtonPartner.Checked.ToString(), radioButtonOther.Checked.ToString(), textBoxAPIServer.Text, textBoxScope.Text, textBoxACSBaseAddress.Text, textBoxAzureEndpoint.Text, textBoxManagementPortal.Text); if (CredentialsList == null) CredentialsList = new StringCollection(); //let's find if the account name is already in the list int foundindex = -1; for (int i = 0; i < CredentialsList.Count; i += CredentialsEntry.StringsCount) { if (CredentialsList[i] == textBoxAccountName.Text) { foundindex = i; break; } } if (foundindex == -1) // not found { var result = MessageBox.Show(string.Format("Do you want to save the credentials for {0} ?", textBoxAccountName.Text), "Save credentials", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to save { CredentialsList.AddRange(myCredentials.ToArray()); Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); listBoxAcounts.Items.Add(myCredentials.AccountName); } else if (result == DialogResult.Cancel) { return; } } else { //found, let's compare the entry and propose to save credentials bool changed = false; for (int i = 0; i < CredentialsEntry.StringsCount; i++) { if (CredentialsList[foundindex + i] != myCredentials.ToArray().Skip(i).Take(1).FirstOrDefault()) { changed = true; } } if (changed) { var result = MessageBox.Show(string.Format("Do you want to update the credentials for {0} ?", CredentialsList[foundindex]), "Update credentials", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { for (int i = 0; i < CredentialsEntry.StringsCount; i++) { CredentialsList[foundindex + i] = myCredentials.ToArray().Skip(i).Take(1).FirstOrDefault(); } Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); } else if (result == DialogResult.Cancel) { return; } } } this.DialogResult = DialogResult.OK; // form will close with OK result // else --> form won't close... }
public AttachStorage(CredentialsEntry credentials) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; _credentials = credentials; }
public static string GetACSBaseAddress(CredentialsEntry credentials) { if (credentials.UsePartnerAPI == true.ToString()) { return CredentialsEntry.PartnerACSBaseAddress; } else if (credentials.UseOtherAPI == true.ToString()) { return credentials.OtherACSBaseAddress; } else { return Constants.ProdACSBaseAddress; } }
public static CloudMediaContext ConnectAndGetNewContext(CredentialsEntry credentials) { CloudMediaContext myContext = null; if (credentials.UsePartnerAPI == true.ToString()) { // Get the service context for partner context. try { Uri partnerAPIServer = new Uri(CredentialsEntry.PartnerAPIServer); myContext = new CloudMediaContext(partnerAPIServer, credentials.AccountName, credentials.AccountKey, CredentialsEntry.PartnerScope, CredentialsEntry.PartnerACSBaseAddress); } catch (Exception e) { MessageBox.Show("There is a credentials problem when connecting to Azure Media Services (custom API)." + Constants.endline + "Application will close. " + Constants.endline + e.Message); Environment.Exit(0); } } else if (credentials.UseOtherAPI == true.ToString()) { try { Uri otherAPIServer = new Uri(credentials.OtherAPIServer); myContext = new CloudMediaContext(otherAPIServer, credentials.AccountName, credentials.AccountKey, credentials.OtherScope, credentials.OtherACSBaseAddress); } catch (Exception e) { MessageBox.Show("There is a credentials problem when connecting to Azure Media Services (Partner API)." + Constants.endline + "Application will close." + Constants.endline + e.Message); Environment.Exit(0); } } else { // Get the service context. try { myContext = new CloudMediaContext(credentials.AccountName, credentials.AccountKey); } catch (Exception e) { MessageBox.Show("There is a credentials problem when connecting to Azure Media Services." + Constants.endline + "Application will close." + Constants.endline + e.Message); Environment.Exit(0); } } try { myContext.Credentials.RefreshToken(); } // to force connection to WAMS catch (Exception e) { // Add useful information to the exception MessageBox.Show("There is a credentials problem when connecting to Azure Media Services." + Constants.endline + "Application will close." + Constants.endline + e.Message); Environment.Exit(0); } return myContext; }
private void buttonLogin_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxAccountName.Text)) { MessageBox.Show("The account name cannot be empty."); return; } CredentialsEntry myCredentials = new CredentialsEntry(textBoxAccountName.Text, textBoxAccountKey.Text, textBoxBlobKey.Text, textBoxDescription.Text, radioButtonPartner.Checked.ToString(), radioButtonOther.Checked.ToString(), textBoxAPIServer.Text, textBoxScope.Text, textBoxACSBaseAddress.Text, textBoxAzureEndpoint.Text, textBoxManagementPortal.Text); if (CredentialsList == null) { CredentialsList = new StringCollection(); } //let's find if the account name is already in the list int foundindex = -1; for (int i = 0; i < CredentialsList.Count; i += CredentialsEntry.StringsCount) { if (CredentialsList[i] == textBoxAccountName.Text) { foundindex = i; break; } } if (foundindex == -1) // not found { var result = MessageBox.Show(string.Format("Do you want to save the credentials for {0} ?", textBoxAccountName.Text), "Save credentials", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to save { CredentialsList.AddRange(myCredentials.ToArray()); Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); listBoxAcounts.Items.Add(myCredentials.AccountName); } else if (result == DialogResult.Cancel) { return; } } else { //found, let's compare the entry and propose to save credentials bool changed = false; for (int i = 0; i < CredentialsEntry.StringsCount; i++) { if (CredentialsList[foundindex + i] != myCredentials.ToArray().Skip(i).Take(1).FirstOrDefault()) { changed = true; } } if (changed) { var result = MessageBox.Show(string.Format("Do you want to update the credentials for {0} ?", CredentialsList[foundindex]), "Update credentials", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { for (int i = 0; i < CredentialsEntry.StringsCount; i++) { CredentialsList[foundindex + i] = myCredentials.ToArray().Skip(i).Take(1).FirstOrDefault(); } Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); } else if (result == DialogResult.Cancel) { return; } } } this.DialogResult = DialogResult.OK; // form will close with OK result // else --> form won't close... }
private async void ProcessExportAssetToAnotherAMSAccount(CredentialsEntry DestinationCredentialsEntry, string DestinationStorageAccount, Dictionary<string, string> storagekeys, List<IAsset> SourceAssets, string TargetAssetName, int index, bool DeleteSourceAssets = false, bool CopyDynEnc = false, bool ReWriteLAURL = false, bool CloneAssetFilters = false) { // If upload in the queue, let's wait our turn DoGridTransferWaitIfNeeded(index); CloudMediaContext DestinationContext = Program.ConnectAndGetNewContext(DestinationCredentialsEntry); IAsset TargetAsset = DestinationContext.Assets.Create(TargetAssetName, DestinationStorageAccount, AssetCreationOptions.None); // let's backup the primary file from the first asset to set it to the copied/merged asset var ismAssetFile = SourceAssets.FirstOrDefault().AssetFiles.ToList().Where(f => f.IsPrimary).ToArray(); bool ErrorCopyAsset = false; TextBoxLogWriteLine("Starting the asset copy process."); // let's get cloudblobcontainer for target CloudStorageAccount DestinationCloudStorageAccount = (DestinationStorageAccount == null) ? new CloudStorageAccount(new StorageCredentials(DestinationContext.DefaultStorageAccount.Name, storagekeys[DestinationContext.DefaultStorageAccount.Name]), DestinationCredentialsEntry.ReturnStorageSuffix(), true) : new CloudStorageAccount(new StorageCredentials(DestinationStorageAccount, storagekeys[DestinationStorageAccount]), DestinationCredentialsEntry.ReturnStorageSuffix(), true); var DestinationCloudBlobClient = DestinationCloudStorageAccount.CreateCloudBlobClient(); IAccessPolicy writePolicy = DestinationContext.AccessPolicies.Create("writepolicy", TimeSpan.FromDays(1), AccessPermissions.Write); ILocator DestinationLocator = DestinationContext.Locators.CreateLocator(LocatorType.Sas, TargetAsset, writePolicy); // Get the asset container URI and copy blobs from mediaContainer to assetContainer. Uri targetUri = new Uri(DestinationLocator.Path); CloudBlobContainer DestinationCloudBlobContainer = DestinationCloudBlobClient.GetContainerReference(targetUri.Segments[1]); foreach (IAsset SourceAsset in SourceAssets) // there are several assets only if user wants to do a copy with merge { if (storagekeys.ContainsKey(SourceAsset.StorageAccountName)) { // let's get cloudblobcontainer for source CloudStorageAccount SourceCloudStorageAccount = new CloudStorageAccount(new StorageCredentials(SourceAsset.StorageAccountName, storagekeys[SourceAsset.StorageAccountName]), _credentials.ReturnStorageSuffix(), true); var SourceCloudBlobClient = SourceCloudStorageAccount.CreateCloudBlobClient(); IAccessPolicy readpolicy = _context.AccessPolicies.Create("readpolicy", TimeSpan.FromDays(1), AccessPermissions.Read); ILocator SourceLocator = _context.Locators.CreateLocator(LocatorType.Sas, SourceAsset, readpolicy); // Get the asset container URI and copy blobs from mediaContainer to assetContainer. Uri sourceUri = new Uri(SourceLocator.Path); CloudBlobContainer SourceCloudBlobContainer = SourceCloudBlobClient.GetContainerReference(sourceUri.Segments[1]); ErrorCopyAsset = false; CloudBlockBlob sourceCloudBlockBlob, destinationCloudBlockBlob; long Length = 0; long BytesCopied = 0; double percentComplete = 0; //calculate size foreach (IAssetFile file in SourceAsset.AssetFiles) { Length += file.ContentFileSize; } if (Length == 0) Length = 1; // as this could happen with Live archive and create a divide error // do the copy int nbblob = 0; // foreach (IAssetFile file in SourceAsset.AssetFiles) // For LIve archive, the folder for chiks are returnbed as files. So we detect this case and don't try to copy the folders as asset files IEnumerable<IAssetFile> assetFilesToCopy = SourceAsset.AssetFiles.ToList(); if ( assetFilesToCopy.Where(af => af.Name.Contains(".")).Count() == 2 && assetFilesToCopy.Where(af => af.Name.ToUpper().EndsWith(".ISMC")).Count() == 1 && assetFilesToCopy.Where(af => af.Name.ToUpper().EndsWith(".ISM")).Count() == 1 ) // only 2 files with extensions, and these files are ISMC and ISM { assetFilesToCopy = SourceAsset.AssetFiles.ToList().Where(af => !af.Name.StartsWith("audio_") && !af.Name.StartsWith("video_") && !af.Name.StartsWith("scte35_")); var assetFilesLiveFolders = SourceAsset.AssetFiles.ToList().Where(af => af.Name.StartsWith("audio_") || af.Name.StartsWith("video_") || af.Name.StartsWith("scte35_")); foreach (IAssetFile sourcefolder in assetFilesLiveFolders) { var folder = TargetAsset.AssetFiles.Create(sourcefolder.Name); folder.ContentFileSize = sourcefolder.ContentFileSize; folder.MimeType = sourcefolder.MimeType; folder.Update(); } } foreach (IAssetFile file in assetFilesToCopy) { if (file.IsEncrypted) { TextBoxLogWriteLine(" Cannot copy file '{0}' because it is encrypted.", file.Name, true); } else { bool ErrorCopyAssetFile = false; nbblob++; try { sourceCloudBlockBlob = SourceCloudBlobContainer.GetBlockBlobReference(file.Name); // TO DO: chek if this is a folder or a file sourceCloudBlockBlob.FetchAttributes(); if (sourceCloudBlockBlob.Properties.Length > 0) { if (!TargetAsset.AssetFiles.ToList().Any(f => f.Name == file.Name)) // file does not exist in the target asset { IAssetFile destinationAssetFile = TargetAsset.AssetFiles.Create(file.Name); destinationCloudBlockBlob = DestinationCloudBlobContainer.GetBlockBlobReference(destinationAssetFile.Name); try { destinationCloudBlockBlob.DeleteIfExists(); } catch { // exception if Blob does not exist, which is fine } destinationCloudBlockBlob.StartCopy(file.GetSasUri()); CloudBlockBlob blob; blob = (CloudBlockBlob)DestinationCloudBlobContainer.GetBlobReferenceFromServer(file.Name); while (blob.CopyState.Status == CopyStatus.Pending) { Task.Delay(TimeSpan.FromSeconds(0.5d)).Wait(); blob.FetchAttributes(); percentComplete = (Convert.ToDouble(nbblob) / Convert.ToDouble(SourceAsset.AssetFiles.Count())) * 100d * (long)(BytesCopied + blob.CopyState.BytesCopied) / Length; DoGridTransferUpdateProgressText(string.Format("File '{0}'", file.Name), (int)percentComplete, index); } if (blob.CopyState.Status == CopyStatus.Failed) { DoGridTransferDeclareError(index, blob.CopyState.StatusDescription); ErrorCopyAssetFile = true; ErrorCopyAsset = true; break; } destinationCloudBlockBlob.FetchAttributes(); destinationAssetFile.ContentFileSize = sourceCloudBlockBlob.Properties.Length; destinationAssetFile.Update(); if (sourceCloudBlockBlob.Properties.Length != destinationCloudBlockBlob.Properties.Length) { DoGridTransferDeclareError(index, "Error during blob copy."); ErrorCopyAssetFile = true; ErrorCopyAsset = true; break; } BytesCopied += sourceCloudBlockBlob.Properties.Length; percentComplete = (long)100 * (long)BytesCopied / (long)Length; } else // file already exists.Can occur with merge function { TextBoxLogWriteLine("Failed to copy file '{0} as file already exists in the destination asset.", file.Name, true); ErrorCopyAssetFile = true; } } } catch (Exception ex) { TextBoxLogWriteLine("Failed to copy file '{0}'", file.Name, true); DoGridTransferDeclareError(index, ex); ErrorCopyAsset = true; ErrorCopyAssetFile = true; } if (!ErrorCopyAssetFile) TextBoxLogWriteLine("File '{0}' copied.", file.Name); } } if (!ErrorCopyAsset) // let's do the copy of additional fragblob if there are { List<CloudBlobDirectory> ListDirectories = new List<CloudBlobDirectory>(); // do the copy nbblob = 0; DoGridTransferUpdateProgressText(string.Format("fragblobs", SourceAsset.Name, DestinationCredentialsEntry.AccountName), 0, index); try { var mediablobs = SourceCloudBlobContainer.ListBlobs(); if (mediablobs.ToList().Any(b => b.GetType() == typeof(CloudBlobDirectory))) // there are fragblobs { List<Task> mylistresults = new List<Task>(); foreach (var blob in mediablobs) { if (blob.GetType() == typeof(CloudBlobDirectory)) { CloudBlobDirectory blobdir = (CloudBlobDirectory)blob; ListDirectories.Add(blobdir); TextBoxLogWriteLine("Fragblobs detected (live archive) '{0}'.", blobdir.Prefix); } else if (blob.GetType() == typeof(CloudBlockBlob)) { // we must copy the file.ismc too var blockblob = (CloudBlockBlob)blob; if (blockblob.Name.EndsWith(".ismc") && !SourceAsset.AssetFiles.ToList().Any(f => f.Name == blockblob.Name)) // if there is a .ismc in the blov and not in the asset files, then we need to copy it { CloudBlockBlob targetBlob = DestinationCloudBlobContainer.GetBlockBlobReference(blockblob.Name); // copy using src blob as SAS mylistresults.Add(targetBlob.StartCopyAsync(new Uri(blockblob.Uri.AbsoluteUri + SourceLocator.ContentAccessComponent))); } } } // let's launch the copy of fragblobs double ind = 0; foreach (var dir in ListDirectories) { TextBoxLogWriteLine("Copying fragblobs directory '{0}'....", dir.Prefix); mylistresults.AddRange(AssetInfo.CopyBlobDirectory(dir, DestinationCloudBlobContainer, SourceLocator.ContentAccessComponent));//blobToken)); if (mylistresults.Count > 0) { while (!mylistresults.All(r => r.IsCompleted)) { Task.Delay(TimeSpan.FromSeconds(3d)).Wait(); percentComplete = 100d * (ind + Convert.ToDouble(mylistresults.Where(c => c.IsCompleted).Count()) / Convert.ToDouble(mylistresults.Count)) / Convert.ToDouble(ListDirectories.Count); DoGridTransferUpdateProgressText(string.Format("fragblobs directory '{0}' ({1}/{2})", dir.Prefix, mylistresults.Where(r => r.IsCompleted).Count(), mylistresults.Count), (int)percentComplete, index); } } ind++; mylistresults.Clear(); } } } catch (Exception ex) { TextBoxLogWriteLine("Failed to copy live fragblobs", true); TextBoxLogWriteLine(ex); DoGridTransferDeclareError(index, ex); ErrorCopyAsset = true; } } SourceLocator.Delete(); readpolicy.Delete(); } else { TextBoxLogWriteLine("Error storage key not found for asset '{0}'.", SourceAsset.Name, true); ErrorCopyAsset = true; } } // let's set the primary file if (ismAssetFile.Count() > 0) { AssetInfo.SetFileAsPrimary(TargetAsset, ismAssetFile.FirstOrDefault().Name); } else { AssetInfo.SetISMFileAsPrimary(TargetAsset); } // Copy Dynamic Encryption if (CopyDynEnc && !ErrorCopyAsset) { TextBoxLogWriteLine("Dynamic encryption settings copy..."); try { await DynamicEncryption.CopyDynamicEncryption(SourceAssets.FirstOrDefault(), TargetAsset, ReWriteLAURL); TextBoxLogWriteLine("Dynamic encryption settings copied."); } catch (Exception ex) { TextBoxLogWriteLine("Error when copying Dynamic encryption", true); TextBoxLogWriteLine(ex); } } // Copy filters if (CloneAssetFilters && !ErrorCopyAsset && SourceAssets.FirstOrDefault().AssetFilters.Count() > 0) { try { TextBoxLogWriteLine("Copying filter(s) to cloned asset '{0}'", SourceAssets.FirstOrDefault().Name); foreach (var filter in SourceAssets.FirstOrDefault().AssetFilters) { TargetAsset.AssetFilters.Create(filter.Name, filter.PresentationTimeRange, filter.Tracks); TextBoxLogWriteLine(string.Format("Cloned filter {0} created.", filter.Name)); } } catch (Exception ex) { // Add useful information to the exception TextBoxLogWriteLine("There is a problem when copying filter(s) to the asset '{0}'.", TargetAsset.Name, true); TextBoxLogWriteLine(ex); } } DestinationLocator.Delete(); writePolicy.Delete(); if (!ErrorCopyAsset) { if (DeleteSourceAssets) SourceAssets.ForEach(a => a.Delete()); TextBoxLogWriteLine("Asset copy completed. The new asset in '{0}' has the Id :", DestinationCredentialsEntry.AccountName); TextBoxLogWriteLine(TargetAsset.Id); DoGridTransferDeclareCompleted(index, DestinationCloudBlobContainer.Uri.AbsoluteUri); } DoRefreshGridAssetV(false); }
private async void ProcessCloneProgramToAnotherAMSAccount(CredentialsEntry DestinationCredentialsEntry, string DestinationStorageAccount, IProgram sourceProgram, bool CopyDynEnc, bool RewriteLAURL, bool CloneLocators, bool CloneAssetFilters) { TextBoxLogWriteLine("Starting the program cloning process."); CloudMediaContext DestinationContext = Program.ConnectAndGetNewContext(DestinationCredentialsEntry); // let's check that target channel exists IChannel clonedchannel = DestinationContext.Channels.Where(c => c.Name == sourceProgram.Channel.Name).FirstOrDefault(); if (clonedchannel == null) { TextBoxLogWriteLine(string.Format("Cloned channel '{0}' not found in destination account!", sourceProgram.Channel.Name), true); return; } // let's check that a program with same name does not already exist for the channel if (DestinationContext.Programs.Where(p => p.Name == sourceProgram.Name && p.ChannelId == clonedchannel.Id).FirstOrDefault() != null) { TextBoxLogWriteLine(string.Format("A program '{0}' has been already found in destination account for channel '{1}'. A new one cannot be created.", sourceProgram.Name, clonedchannel.Name), true); return; } // Cloned asset creation IAsset clonedAsset = DestinationContext.Assets.Create(sourceProgram.Asset.Name, DestinationStorageAccount, AssetCreationOptions.None); TextBoxLogWriteLine(string.Format("Cloned asset {0} created.", sourceProgram.Asset.Name)); if (CopyDynEnc) { TextBoxLogWriteLine("Dynamic encryption settings copy..."); try { await DynamicEncryption.CopyDynamicEncryption(sourceProgram.Asset, clonedAsset, RewriteLAURL); TextBoxLogWriteLine("Dynamic encryption settings copied."); } catch (Exception ex) { TextBoxLogWriteLine("Error when copying Dynamic encryption", true); TextBoxLogWriteLine(ex); } } if (CloneLocators) { try { TextBoxLogWriteLine("Creating locator for cloned asset '{0}'", sourceProgram.Asset.Name); foreach (var streamlocator in sourceProgram.Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin)) { IAccessPolicy policy = DestinationContext.AccessPolicies.Create("AP:" + sourceProgram.Asset.Name, (streamlocator.ExpirationDateTime - DateTime.UtcNow), AccessPermissions.Read); DestinationContext.Locators.CreateLocator(streamlocator.Id, LocatorType.OnDemandOrigin, clonedAsset, policy, streamlocator.StartTime); TextBoxLogWriteLine(string.Format("Cloned locator {0} created.", streamlocator.Id)); } } catch (Exception ex) { // Add useful information to the exception TextBoxLogWriteLine("There is a problem when creating the locator for the asset '{0}'.", clonedAsset.Name, true); TextBoxLogWriteLine(ex); } } if (CloneAssetFilters && sourceProgram.Asset.AssetFilters.Count() > 0) { try { TextBoxLogWriteLine("Copying filter(s) to cloned asset '{0}'", sourceProgram.Asset.Name); foreach (var filter in sourceProgram.Asset.AssetFilters) { // let's remove start and end time var PTR = new PresentationTimeRange(filter.PresentationTimeRange.Timescale, null, null, filter.PresentationTimeRange.PresentationWindowDuration, filter.PresentationTimeRange.LiveBackoffDuration); clonedAsset.AssetFilters.Create(filter.Name, PTR, filter.Tracks); TextBoxLogWriteLine(string.Format("Cloned filter {0} created.", filter.Name)); } } catch (Exception ex) { // Add useful information to the exception TextBoxLogWriteLine("There is a problem when copying filter(s) to the asset '{0}'.", clonedAsset.Name, true); TextBoxLogWriteLine(ex); } } var options = new ProgramCreationOptions() { Name = sourceProgram.Name, Description = sourceProgram.Description, ArchiveWindowLength = sourceProgram.ArchiveWindowLength, AssetId = clonedAsset.Id, ManifestName = sourceProgram.ManifestName }; var STask = ProgramExecuteAsync( () => clonedchannel.Programs.CreateAsync(options), sourceProgram.Name, "created"); await STask; TextBoxLogWriteLine(string.Format("Cloned program {0} created.", sourceProgram.Name)); }
private void buttonLogin_Click(object sender, EventArgs e) { LoginCredentials = GenerateLoginCredentials; if (string.IsNullOrEmpty(ReturnAccountName(LoginCredentials))) { MessageBox.Show("The account name cannot be empty."); return; } /* * CredentialsEntry myCredentials = new CredentialsEntry( * textBoxAccountName.Text, * textBoxAccountKey.Text, * textBoxADTenantDomain.Text, * textBoxADRestAPIEndpoint.Text, * textBoxBlobKey.Text, * textBoxDescription.Text, * radioButtonAADInteract.Checked, * radioButtonPartner.Checked, * radioButtonOther.Checked, * textBoxAPIServer.Text, * textBoxScope.Text, * textBoxACSBaseAddress.Text, * textBoxAzureEndpoint.Text, * textBoxManagementPortal.Text * ); */ var accName = ReturnAccountName(LoginCredentials); var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => ReturnAccountName(c).ToLower().Trim() == accName.ToLower().Trim()).FirstOrDefault(); // if found the same name if (entryWithSameName == null) // not found { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToSaveTheCredentialsFor0, accName), AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_SaveCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to save { CredentialList.MediaServicesAccounts.Add(LoginCredentials); Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); listBoxAcounts.Items.Add(ReturnAccountName(LoginCredentials)); } else if (result == DialogResult.Cancel) { return; } } else // found { if (!LoginCredentials.Equals(entryWithSameName)) // changed ? { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToUpdateTheCredentialsFor0, accName), AMSExplorer.Properties.Resources.AMSLogin_listBoxAccounts_SelectedIndexChanged_UpdateCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } else if (result == DialogResult.Cancel) { return; } } } if (LoginCredentials.UseAADServicePrincipal) // service principal mode { var spcrendentialsform = new AMSLoginServicePrincipal(); if (spcrendentialsform.ShowDialog() == DialogResult.OK) { LoginCredentials.ADSPClientId = spcrendentialsform.ClientId; LoginCredentials.ADSPClientSecret = spcrendentialsform.ClientSecret; } else { return; } } // Context creation this.Cursor = Cursors.WaitCursor; context = Program.ConnectAndGetNewContext(LoginCredentials, false, true); accName = ReturnAccountName(LoginCredentials); try { var a = context.Assets.FirstOrDefault(); this.Cursor = Cursors.Default; } catch (Exception ex) { MessageBox.Show(Program.GetErrorMessage(ex), "Login error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Cursor = Cursors.Default; return; } accountName = accName; this.DialogResult = DialogResult.OK; // form will close with OK result // else --> form won't close... }
public void Init(CredentialsEntry credentials) { IEnumerable<ChannelEntry> channelquery; _credentials = credentials; _context = Program.ConnectAndGetNewContext(_credentials); channelquery = from c in _context.Channels orderby c.LastModified descending select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = c.EncodingType != ChannelEncodingType.None ? EncodingImage : null, InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle() { NullValue = null, Alignment = DataGridViewContentAlignment.MiddleCenter }; DataGridViewImageColumn imageCol = new DataGridViewImageColumn() { DefaultCellStyle = cellstyle, Name = _encoded, DataPropertyName = _encoded, }; this.Columns.Add(imageCol); BindingList<ChannelEntry> MyObservJobInPage = new BindingList<ChannelEntry>(channelquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveChannelIDinGrid; this.Columns["InputUrl"].HeaderText = "Primary Input Url"; this.Columns["InputProtocol"].HeaderText = "Input Protocol (input nb)"; this.Columns[_encoded].DisplayIndex = this.ColumnCount - 3; this.Columns[_encoded].DefaultCellStyle.NullValue = null; this.Columns[_encoded].HeaderText = "Cloud Encoding"; WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable <ChannelEntry> channelquery; _credentials = credentials; _context = context; channelquery = from c in _context.Channels orderby c.LastModified descending select new ChannelEntry { Name = c.Name, Id = c.Id, Description = c.Description, InputProtocol = string.Format("{0} ({1})", Program.ReturnNameForProtocol(c.Input.StreamingProtocol), c.Input.Endpoints.Count), Encoding = ReturnChannelBitmap(c), InputUrl = c.Input.Endpoints.FirstOrDefault().Url, PreviewUrl = c.Preview.Endpoints.FirstOrDefault().Url, State = c.State, LastModified = c.LastModified.ToLocalTime() }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle() { NullValue = null, Alignment = DataGridViewContentAlignment.MiddleCenter }; DataGridViewImageColumn imageCol = new DataGridViewImageColumn() { DefaultCellStyle = cellstyle, Name = _encoded, DataPropertyName = _encoded, }; this.Columns.Add(imageCol); BindingList <ChannelEntry> MyObservJobInPage = new BindingList <ChannelEntry>(channelquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveChannelIDinGrid; this.Columns["InputUrl"].HeaderText = "Primary Input Url"; this.Columns["InputUrl"].Width = 140; this.Columns["InputProtocol"].HeaderText = "Input Protocol (input nb)"; this.Columns["InputProtocol"].Width = 180; this.Columns["PreviewUrl"].Width = 120; this.Columns[_encoded].DisplayIndex = this.ColumnCount - 3; this.Columns[_encoded].DefaultCellStyle.NullValue = null; this.Columns[_encoded].HeaderText = "Cloud Encoding"; this.Columns[_encoded].Width = 100; this.Columns["LastModified"].Width = 140; this.Columns["State"].Width = 75; this.Columns["Description"].Width = 110; WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
public void Init(CredentialsEntry credentials) { IEnumerable<ProgramEntry> programquery; _credentials = credentials; _context = Program.ConnectAndGetNewContext(_credentials); programquery = from c in _context.Programs orderby c.LastModified descending select new ProgramEntry { Name = c.Name, Id = c.Id, State = c.State, Description = c.Description, ArchiveWindowLength = c.ArchiveWindowLength, LastModified = c.LastModified.ToLocalTime(), Published = null, ChannelName = c.Channel.Name, ChannelId = c.Channel.Id }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle() { NullValue = null, Alignment = DataGridViewContentAlignment.MiddleCenter }; DataGridViewImageColumn imageCol = new DataGridViewImageColumn() { DefaultCellStyle = cellstyle, Name = _published, DataPropertyName = _published, }; this.Columns.Add(imageCol); BindingList<ProgramEntry> MyObservProgramInPage = new BindingList<ProgramEntry>(programquery.Take(0).ToList()); this.DataSource = MyObservProgramInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayLiveProgramIDinGrid; this.Columns["ChannelId"].Visible = false; this.Columns[_published].DisplayIndex = this.ColumnCount - 3; this.Columns[_published].DefaultCellStyle.NullValue = null; this.Columns[_published].HeaderText = _published; WorkerRefreshChannels = new BackgroundWorker(); WorkerRefreshChannels.WorkerSupportsCancellation = true; WorkerRefreshChannels.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshChannels_DoWork); _initialized = true; }
private void listViewAccounts_SelectedIndexChanged(object sender, EventArgs e) { LoginCredentials = GenerateLoginCredentials; buttonDeleteAccountEntry.Enabled = (listViewAccounts.SelectedIndices.Count > 0); // no selected item, so login button not active buttonExport.Enabled = (listViewAccounts.Items.Count > 0); if (listViewAccounts.SelectedIndices.Count > 0) // one selected { if (LoginCredentials != null) { var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.ReturnAccountName().ToLower().Trim() == LoginCredentials.ReturnAccountName().ToLower().Trim()).FirstOrDefault(); if (entryWithSameName != null && !LoginCredentials.Equals(entryWithSameName)) { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToUpdateTheCredentialsFor0, LoginCredentials.ReturnAccountName()), AMSExplorer.Properties.Resources.AMSLogin_listBoxAccounts_SelectedIndexChanged_UpdateCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } } } var entry = CredentialList.MediaServicesAccounts[listViewAccounts.SelectedIndices[0]]; radioButtonAADAut.Checked = entry.UseAADInteract || entry.UseAADServicePrincipal; radioButtonAADServicePrincipal.Checked = entry.UseAADServicePrincipal; radioButtonAADInteractive.Checked = !radioButtonAADServicePrincipal.Checked; if (entry.ADCustomSettings != null) // custom settings { radioButtonAADOther.Checked = true; comboBoxAADMappingList.SelectedIndex = comboBoxAADMappingList.Items.Count - 1; // last one textBoxAADAMSResource.Text = entry.ADCustomSettings.MediaServicesResource; textBoxAADClienid.Text = entry.ADCustomSettings.MediaServicesSdkClientId; textBoxAADRedirect.Text = entry.ADCustomSettings.MediaServicesSdkRedirectUri.ToString(); textBoxAADAzureEndpoint.Text = entry.ADCustomSettings.ActiveDirectoryEndpoint.ToString(); textBoxAADManagementPortal.Text = entry.OtherManagementPortal; } else if (entry.ADDeploymentName != null) { radioButtonAADOther.Checked = true; int index = 0; foreach (var it in comboBoxAADMappingList.Items) { if (((Item)it).Value == entry.ADDeploymentName) { break; } index++; } comboBoxAADMappingList.SelectedIndex = index; } else { radioButtonAADProd.Checked = true; } textBoxAccountName.Text = entry.AccountName; textBoxAccountKey.Text = entry.AccountKey; textBoxAADtenant.Text = entry.ADTenantDomain; textBoxRestAPIEndpoint.Text = entry.ADRestAPIEndpoint; textBoxBlobKey.Text = entry.DefaultStorageKey; textBoxDescription.Text = entry.Description; radioButtonACSAut.Checked = !entry.UseAADInteract && !entry.UseAADServicePrincipal;; radioButtonAADAut.Checked = entry.UseAADInteract || entry.UseAADServicePrincipal; radioButtonPartner.Checked = entry.UsePartnerAPI; radioButtonOther.Checked = entry.UseOtherAPI; textBoxAPIServer.Text = entry.OtherAPIServer; textBoxScope.Text = entry.OtherScope; textBoxACSBaseAddress.Text = entry.OtherACSBaseAddress; textBoxAzureEndpoint.Text = entry.OtherAzureEndpoint; textBoxManagementPortal.Text = entry.OtherManagementPortal; // if not partner or other, then defaut if (!radioButtonPartner.Checked && !radioButtonOther.Checked) { radioButtonProd.Checked = true; } // to clear or set the error CheckTextBox((object)textBoxAccountName); CheckTextBox((object)textBoxAccountKey); CheckTextBox((object)textBoxAADtenant); CheckTextBox((object)textBoxRestAPIEndpoint); UpdateTexboxUI(); } }
private static Dictionary<string, string> BuildStorageKeyDictionary(List<IAsset> SelectedAssets, CredentialsEntry DestinationCredentials, ref bool usercanceled, string SourceDefaultStorageName = null, string SourceDefaultStorageKey = null, string DestinationOtherStorage = null) { Dictionary<string, string> storagekeys = new Dictionary<string, string>(); bool canceled = false; if (!string.IsNullOrEmpty(SourceDefaultStorageName) && !string.IsNullOrEmpty(SourceDefaultStorageKey)) { storagekeys.Add(SourceDefaultStorageName, SourceDefaultStorageKey); } foreach (IAsset asset in SelectedAssets) { if (!storagekeys.ContainsKey(asset.StorageAccountName)) { string valuekey = ""; if (Program.InputBox("Source Storage Account Key Needed", string.Format("Please enter the Storage Account Access Key for '{0}' : ", asset.StorageAccountName), ref valuekey) == DialogResult.OK) { storagekeys.Add(asset.StorageAccountName, valuekey); } else { canceled = true; } } } // useful for destination media services account with non default storage selected if (DestinationOtherStorage != null) { string valuekey = ""; if (Program.InputBox("Destination Storage Account Key Needed", string.Format("Please enter the Storage Account Access Key for '{0}' : ", DestinationOtherStorage), ref valuekey) == DialogResult.OK) { storagekeys.Add(DestinationOtherStorage, valuekey); } else { canceled = true; } } else // default destination storage is used { CloudMediaContext newcontext = null; bool ErrorConnect = false; try { newcontext = Program.ConnectAndGetNewContext(DestinationCredentials); } catch { ErrorConnect = true; } if (!ErrorConnect) { if (string.IsNullOrEmpty(DestinationCredentials.StorageKey)) // but key is not provided { string valuekey = ""; if (Program.InputBox("Destination Storage Account Key Needed", string.Format("Please enter the Storage Account Access Key of the destination storage account ('{0}') : ", newcontext.DefaultStorageAccount.Name), ref valuekey) == DialogResult.OK) { storagekeys.Add(newcontext.DefaultStorageAccount.Name, valuekey); } else { canceled = true; } } else // key is provided { if (!storagekeys.ContainsKey(newcontext.DefaultStorageAccount.Name)) { storagekeys.Add(newcontext.DefaultStorageAccount.Name, DestinationCredentials.StorageKey); } } } } usercanceled = canceled; return storagekeys; }
public Mainform() { InitializeComponent(); // for player control embedded in UI Program.SetWebBrowserFeatures(); this.Icon = Bitmaps.Azure_Explorer_ico; // USER SETTINSG CHECKS & UPDATES // upgrade settings from previous version if (Properties.Settings.Default.CallUpgrade) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.CallUpgrade = false; } // if installation file has been downloaded, let's delete it now if (!string.IsNullOrEmpty(Properties.Settings.Default.DeleteInstallationFile)) { try { File.Delete(Properties.Settings.Default.DeleteInstallationFile); Properties.Settings.Default.DeleteInstallationFile = string.Empty; Properties.Settings.Default.Save(); } catch { } } _configurationXMLFiles = Application.StartupPath + Constants.PathConfigFiles; // AME Standard preset folder if ((Properties.Settings.Default.WAMEPresetXMLFilesCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.WAMEPresetXMLFilesCurrentFolder))) { Properties.Settings.Default.WAMEPresetXMLFilesCurrentFolder = Application.StartupPath + Constants.PathAMEFiles; } // AME Premium Workflow preset folder if ((Properties.Settings.Default.PremiumWorkflowPresetXMLFilesCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.PremiumWorkflowPresetXMLFilesCurrentFolder))) { Properties.Settings.Default.PremiumWorkflowPresetXMLFilesCurrentFolder = Application.StartupPath + Constants.PathPremiumWorkflowFiles; } // AME Standard preset folder if ((Properties.Settings.Default.AMEStandardPresetXMLFilesCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.AMEStandardPresetXMLFilesCurrentFolder))) { Properties.Settings.Default.AMEStandardPresetXMLFilesCurrentFolder = Application.StartupPath + Constants.PathAMEStdFiles; } // Default Slate Image if ((Properties.Settings.Default.DefaultSlateCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.DefaultSlateCurrentFolder))) { Properties.Settings.Default.DefaultSlateCurrentFolder = Application.StartupPath + Constants.PathDefaultSlateJPG; } Program.SaveAndProtectUserConfig(); // to save settings _HelpFiles = Application.StartupPath + Constants.PathHelpFiles; AMSLogin form = new AMSLogin(); if (form.ShowDialog() == DialogResult.Cancel) { Environment.Exit(0); } _credentials = form.LoginCredentials; DisplaySplashDuringLoading = true; ThreadPool.QueueUserWorkItem((x) => { using (var splashForm = new Splash(_credentials.AccountName)) { splashForm.Show(); while (DisplaySplashDuringLoading) Application.DoEvents(); splashForm.Close(); } }); // Get the service context. _context = Program.ConnectAndGetNewContext(_credentials, true); // mainform title toolStripStatusLabelConnection.Text = String.Format("Version {0}", Assembly.GetExecutingAssembly().GetName().Version) + " - Connected to " + _context.Credentials.ClientId; // notification title notifyIcon1.Text = string.Format(notifyIcon1.Text, _context.Credentials.ClientId); // name of the ams acount in the title of the form - useful when several instances to navigate with icons this.Text = string.Format(this.Text, _context.Credentials.ClientId); // Let's check storage credentials if (string.IsNullOrEmpty(_credentials.StorageKey)) { havestoragecredentials = false; } else { bool ret = Program.ConnectToStorage(_context, _credentials); } if ((GetLatestMediaProcessorByName(Constants.ZeniumEncoder) == null) && (GetLatestMediaProcessorByName(Constants.AzureMediaEncoderPremiumWorkflow) == null)) { AMEPremiumWorkflowPresent = false; encodeAssetWithPremiumWorkflowToolStripMenuItem.Enabled = false; //menu ContextMenuItemPremiumWorkflow.Enabled = false; // mouse context menu } if (GetLatestMediaProcessorByName(Constants.AzureMediaEncoderStandard) == null) { AMEStandardPresent = false; encodeAssetsWithAMEStandardToolStripMenuItem.Visible = false; encodeAssetWithAMEStandardToolStripMenuItem.Visible = false; toolStripSeparator35.Visible = false; toolStripSeparator32.Visible = false; // subclipping subclipLiveStreamsarchivesToolStripMenuItem.Visible = false; subclipProgramsToolStripMenuItem.Visible = false; subclipToolStripMenuItem.Visible = false; } if (GetLatestMediaProcessorByName(Constants.AzureMediaFaceDetector) == null) { AMFaceDetectorPresent = false; ProcessFaceDetectortoolStripMenuItem.Visible = false; toolStripMenuItemFaceDetector.Visible = false; } if (GetLatestMediaProcessorByName(Constants.AzureMediaMotionDetector) == null) { AMMotionDetectorPresent = false; ProcessMotionDetectortoolStripMenuItem.Visible = false; toolStripMenuItemMotionDetector.Visible = false; } if (GetLatestMediaProcessorByName(Constants.AzureMediaRedactor) == null) { AMRedactorPresent = false; ProcessRedactortoolStripMenuItem.Visible = false; toolStripMenuItemRedactor.Visible = false; } if (GetLatestMediaProcessorByName(Constants.AzureMediaStabilizer) == null) { AMStabilizerPresent = false; ProcessStabilizertoolStripMenuItem.Visible = false; toolStripMenuItemStabilizer.Visible = false; } // Timer Auto Refresh TimerAutoRefresh = new System.Timers.Timer(Properties.Settings.Default.AutoRefreshTime * 1000); TimerAutoRefresh.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Let's check if there is one streaming unit running if (_context.StreamingEndpoints.AsEnumerable().Where(o => o.State == StreamingEndpointState.Running).ToList().Count == 0) TextBoxLogWriteLine("There is no streaming endpoint running in this account.", true); // Warning // Let's check if there is one streaming scale units if (_context.StreamingEndpoints.Where(o => o.ScaleUnits > 0).ToList().Count == 0) TextBoxLogWriteLine("There is no reserved unit streaming endpoint in this account. Dynamic packaging and live streaming output will not work.", true); // Warning // Let's check if there is enough streaming scale units for the channels double nbchannels = (double)_context.Channels.Count(); double nbse = (double)_context.StreamingEndpoints.Where(o => o.ScaleUnits > 0).ToList().Count; if (nbse > 0 && nbchannels > 0 && (nbchannels / nbse) > 5) TextBoxLogWriteLine("There are {0} channels and {1} streaming endpoint(s). Recommandation is to provision at least 1 streaming endpoint per group of 5 channels.", nbchannels, nbse, true); // Warning // let's check the encoding reserved unit and type try { if ((_context.EncodingReservedUnits.FirstOrDefault().CurrentReservedUnits == 0) && (_context.EncodingReservedUnits.FirstOrDefault().ReservedUnitType != ReservedUnitType.Basic)) TextBoxLogWriteLine("There is no Media Reserved Unit (encoding will use a shared pool) but unit type is not set to S1 (Basic).", true); // Warning } catch // can occur on test account { MediaRUFeatureOn = false; TextBoxLogWriteLine("There is an error when accessing to the Media Reserved Units API. Some controls are disabled in the processors tab.", true); // Warning } // nb assets limits int nbassets = _context.Assets.Count(); largeAccount = nbassets > triggerForLargeAccountNbAssets; if (largeAccount) { TextBoxLogWriteLine("This account contains a lot of assets. Some queries are disabled."); // Warning } if (nbassets > (0.75 * maxNbAssets)) { TextBoxLogWriteLine("This account contains {0} assets. Warning, the limit is {1}.", nbassets, maxNbAssets, true); // Warning } // nb jobs limits int nbjobs = _context.Jobs.Count(); /* if (nbjobs > triggerForLargeAccountNbJobs) { TextBoxLogWriteLine("This account contains a lot of jobs. Sorting is disabled."); // Warning } */ if (nbjobs > (0.75 * maxNbJobs)) { TextBoxLogWriteLine("This account contains {0} jobs. Warning, the limit is {1}.", nbjobs, maxNbJobs, true); // Warning } ApplySettingsOptions(true); }
public static bool ConnectToStorage(CloudMediaContext context, CredentialsEntry credentials) { try { CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(context.DefaultStorageAccount.Name, credentials.StorageKey), credentials.ReturnStorageSuffix(), true); CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); return true; } catch (Exception e) { MessageBox.Show(string.Format("There is a problem when connecting to the Azure storage account.\r\nIs the storage key correct ?\r\n{0}", e.Message), "Storage Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } }
private bool EncodingRUFeatureOn = true; // On some test account, there is no Encoding RU so let's switch to OFF the feature in that case public Mainform() { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; // USER SETTINSG CHECKS & UPDATES if (Properties.Settings.Default.CallUpgrade) // upgrade settings from previous version { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.CallUpgrade = false; } _configurationXMLFiles = Application.StartupPath + Constants.PathConfigFiles; // AME Standard preset folder if ((Properties.Settings.Default.WAMEPresetXMLFilesCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.WAMEPresetXMLFilesCurrentFolder))) { Properties.Settings.Default.WAMEPresetXMLFilesCurrentFolder = Application.StartupPath + Constants.PathAMEFiles; } // AME Premium Workflow preset folder if ((Properties.Settings.Default.PremiumWorkflowPresetXMLFilesCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.PremiumWorkflowPresetXMLFilesCurrentFolder))) { Properties.Settings.Default.PremiumWorkflowPresetXMLFilesCurrentFolder = Application.StartupPath + Constants.PathPremiumWorkflowFiles; } // AME Standard preset folder if ((Properties.Settings.Default.AMEStandardPresetXMLFilesCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.AMEStandardPresetXMLFilesCurrentFolder))) { Properties.Settings.Default.AMEStandardPresetXMLFilesCurrentFolder = Application.StartupPath + Constants.PathAMEStdFiles; } // Default Slate Image if ((Properties.Settings.Default.DefaultSlateCurrentFolder == string.Empty) || (!Directory.Exists(Properties.Settings.Default.DefaultSlateCurrentFolder))) { Properties.Settings.Default.DefaultSlateCurrentFolder = Application.StartupPath + Constants.PathDefaultSlateJPG; } Program.SaveAndProtectUserConfig(); // to save settings _HelpFiles = Application.StartupPath + Constants.PathHelpFiles; AMSLogin form = new AMSLogin(); if (form.ShowDialog() == DialogResult.Cancel) { Environment.Exit(0); } _credentials = form.LoginCredentials; DisplaySplashDuringLoading = true; ThreadPool.QueueUserWorkItem((x) => { using (var splashForm = new Splash(_credentials.AccountName)) { splashForm.Show(); while (DisplaySplashDuringLoading) Application.DoEvents(); splashForm.Close(); } }); // Get the service context. _context = Program.ConnectAndGetNewContext(_credentials); // Dynamic filter _contextdynmanifest = new MediaServiceContextForDynManifest(_credentials); _contextdynmanifest.AccessToken = _context.Credentials.AccessToken; _contextdynmanifest.CheckForRedirection(); // mainform title toolStripStatusLabelConnection.Text = String.Format("Version {0}", Assembly.GetExecutingAssembly().GetName().Version) + " - Connected to " + _context.Credentials.ClientId; // notification title notifyIcon1.Text = string.Format(notifyIcon1.Text, _context.Credentials.ClientId); // name of the ams acount in the title of the form - useful when several instances to navigate with icons this.Text = string.Format(this.Text, _context.Credentials.ClientId); // Let's check storage credentials if (string.IsNullOrEmpty(_credentials.StorageKey)) { havestoragecredentials = false; } else { bool ret = Program.ConnectToStorage(_context, _credentials); } if ((GetLatestMediaProcessorByName(Constants.ZeniumEncoder) == null) && (GetLatestMediaProcessorByName(Constants.AzureMediaEncoderPremiumWorkflow) == null)) { AMEPremiumWorkflowPresent = false; encodeAssetWithPremiumWorkflowToolStripMenuItem.Enabled = false; //menu ContextMenuItemPremiumWorkflow.Enabled = false; // mouse context menu } if (GetLatestMediaProcessorByName(Constants.AzureMediaEncoderStandard) == null) { AMEStandardPresent = false; encodeAssetsWithAMEStandardToolStripMenuItem.Visible = false; encodeAssetWithAMEStandardToolStripMenuItem.Visible = false; toolStripSeparator35.Visible = false; toolStripSeparator32.Visible = false; } if (GetLatestMediaProcessorByName(Constants.AzureMediaHyperlapse) == null) { HyperlapsePresent = false; processAssetsWithHyperlapseToolStripMenuItem.Enabled = false; processAssetsWithHyperlapseToolStripMenuItem1.Enabled = false; } // Timer Auto Refresh TimerAutoRefresh = new System.Timers.Timer(Properties.Settings.Default.AutoRefreshTime * 1000); TimerAutoRefresh.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Let's check if there is one streaming unit running if (_context.StreamingEndpoints.AsEnumerable().Where(o => o.State == StreamingEndpointState.Running).ToList().Count == 0) TextBoxLogWriteLine("There is no streaming endpoint running in this account.", true); // Warning // Let's check if there is one streaming scale units if (_context.StreamingEndpoints.Where(o => o.ScaleUnits > 0).ToList().Count == 0) TextBoxLogWriteLine("There is no reserved unit streaming endpoint in this account. Dynamic packaging and live streaming output will not work.", true); // Warning // Let's check if there is enough streaming scale units for the channels double nbchannels = (double)_context.Channels.Count(); double nbse = (double)_context.StreamingEndpoints.Where(o => o.ScaleUnits > 0).ToList().Count; if (nbse > 0 && nbchannels > 0 && (nbchannels / nbse) > 5) TextBoxLogWriteLine("There are {0} channels and {1} streaming endpoint(s). Recommandation is to provision at least 1 streaming endpoint per group of 5 channels.", nbchannels, nbse, true); // Warning // let's check the encoding reserved unit and type try { if ((_context.EncodingReservedUnits.FirstOrDefault().CurrentReservedUnits == 0) && (_context.EncodingReservedUnits.FirstOrDefault().ReservedUnitType != ReservedUnitType.Basic)) TextBoxLogWriteLine("There is no reserved encoding unit (encoding will use a shared pool) but unit type is not set to BASIC.", true); // Warning } catch // can occur on test account { EncodingRUFeatureOn = false; TextBoxLogWriteLine("There is an error when accessing to the Encoding Reserved Units API. Some controls are disabled in the processors tab.", true); // Warning } ApplySettingsOptions(true); }
public static string GetAPIServer(CredentialsEntry credentials) { if (credentials.UsePartnerAPI == true.ToString()) { return CredentialsEntry.PartnerAPIServer; } else if (credentials.UseOtherAPI == true.ToString()) { return credentials.OtherAPIServer; } else { return Constants.ProdAPIServer; } }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable<StreamingEndpointEntry> originquery; _credentials = credentials; _context = context; originquery = from o in _context.StreamingEndpoints orderby o.LastModified descending select new StreamingEndpointEntry { Name = o.Name, Id = o.Id, Description = o.Description, ScaleUnits = o.ScaleUnits, State = o.State, LastModified = o.LastModified.ToLocalTime() }; BindingList<StreamingEndpointEntry> MyObservOriginInPage = new BindingList<StreamingEndpointEntry>(originquery.Take(0).ToList()); this.DataSource = MyObservOriginInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayOriginIDinGrid; this.Columns["Name"].Width = 300; this.Columns["State"].Width = 100; this.Columns["CDN"].Width = 100; this.Columns["Description"].Width = 230; this.Columns["ScaleUnits"].Width = 100; this.Columns["LastModified"].Width = 150; WorkerRefreshStreamingEndpoints = new BackgroundWorker(); WorkerRefreshStreamingEndpoints.WorkerSupportsCancellation = true; WorkerRefreshStreamingEndpoints.DoWork += new System.ComponentModel.DoWorkEventHandler(this.WorkerRefreshStreamingEndpoints_DoWork); _initialized = true; }
private void buttonSaveToList_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxAccountName.Text)) { MessageBox.Show("The account name cannot be empty."); return; } CredentialsEntry myCredentials = new CredentialsEntry(textBoxAccountName.Text, textBoxAccountKey.Text, textBoxBlobKey.Text, textBoxDescription.Text, radioButtonPartner.Checked.ToString(), radioButtonOther.Checked.ToString(), textBoxAPIServer.Text, textBoxScope.Text, textBoxACSBaseAddress.Text, textBoxAzureEndpoint.Text, textBoxManagementPortal.Text); if (CredentialsList == null) CredentialsList = new StringCollection(); //let's find if the account name is already in the list int foundindex = -1; for (int i = 0; i < CredentialsList.Count; i += CredentialsEntry.StringsCount) { if (CredentialsList[i] == textBoxAccountName.Text) { foundindex = i; break; } } if (foundindex == -1) // not found { CredentialsList.AddRange(myCredentials.ToArray()); Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); listBoxAcounts.Items.Add(myCredentials.AccountName); } else { //found, let's update the entry et insert the new data for (int i = 0; i < CredentialsEntry.StringsCount; i++) CredentialsList.RemoveAt(foundindex); for (int i = 0; i < CredentialsEntry.StringsCount; i++) CredentialsList.Insert(foundindex + i, myCredentials.ToArray().Skip(i).Take(1).FirstOrDefault()); Properties.Settings.Default.LoginList = CredentialsList; Program.SaveAndProtectUserConfig(); } }
public void Init(CredentialsEntry credentials, CloudMediaContext context) { IEnumerable<JobEntry> jobquery; _credentials = credentials; _context = context;// Program.ConnectAndGetNewContext(_credentials); jobquery = from j in _context.Jobs.Take(0) orderby j.LastModified descending select new JobEntry { Name = j.Name, Id = j.Id, Tasks = j.Tasks.Count, Priority = j.Priority, State = j.State, StartTime = j.StartTime.HasValue ? ((DateTime)j.StartTime).ToLocalTime().ToString("G") : null, EndTime = j.EndTime.HasValue ? ((DateTime)j.EndTime).ToLocalTime().ToString("G") : null, Duration = (j.StartTime.HasValue && j.EndTime.HasValue) ? ((DateTime)j.EndTime).Subtract((DateTime)j.StartTime).ToString(@"d\.hh\:mm\:ss") : string.Empty, Progress = (j.State == JobState.Scheduled || j.State == JobState.Processing || j.State == JobState.Queued) ? j.GetOverallProgress() : 101d }; DataGridViewProgressBarColumn col = new DataGridViewProgressBarColumn() { Name = "Progress", DataPropertyName = "Progress", HeaderText = "Progress" }; DataGridViewCellStyle cellstyle = new DataGridViewCellStyle(); this.Columns.Add(col); BindingList<JobEntry> MyObservJobInPage = new BindingList<JobEntry>(jobquery.Take(0).ToList()); this.DataSource = MyObservJobInPage; this.Columns["Id"].Visible = Properties.Settings.Default.DisplayJobIDinGrid; this.Columns["Progress"].DisplayIndex = 5; this.Columns["Progress"].Width = 150; this.Columns["Tasks"].Width = 50; this.Columns["Priority"].Width = 50; this.Columns["State"].Width = 80; this.Columns["StartTime"].Width = 150; this.Columns["EndTime"].Width = 150; this.Columns["Duration"].Width = 90; _initialized = true; }
private void buttonImportAll_Click(object sender, EventArgs e) { bool mergesentries = false; if (CredentialList.MediaServicesAccounts.Count > 0) // There are entries. Let's ask if user want to delete them or merge { if (System.Windows.Forms.MessageBox.Show(AMSExplorer.Properties.Resources.AMSLogin_buttonImportAll_Click_ThereAreCurrentEntriesInTheListNDoYouWantReplaceThemWithTheNewOnesOrDoAMergeNNSelectYesToReplaceThemNoToMergeThem, AMSExplorer.Properties.Resources.AMSLogin_buttonImportAll_Click_ImportAndReplace, System.Windows.Forms.MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { mergesentries = true; } } DialogResult diares = openFileDialog1.ShowDialog(); if (diares == DialogResult.OK) { if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".xml") // XML file { XDocument xmlimport = new XDocument(); System.IO.Stream myStream = openFileDialog1.OpenFile(); xmlimport = XDocument.Load(myStream); var test = xmlimport.Descendants("Credentials").FirstOrDefault(); Version version = new Version(xmlimport.Descendants("Credentials").Attributes("Version").FirstOrDefault().Value.ToString()); if ((test != null) && (version >= new Version("1.0"))) { if (!mergesentries) { CredentialList.MediaServicesAccounts.Clear(); // let's purge entries if user does not want to keep them } try { foreach (var att in xmlimport.Descendants("Credentials").Elements("Entry")) { string OtherManagementPortal = ""; if ((version >= new Version("1.1")) && (att.Attribute("OtherManagementPortal")) != null) { OtherManagementPortal = att.Attribute("OtherManagementPortal").Value.ToString(); } string OtherAzureEndpoint = ""; if (att.Attribute("OtherAzureEndpoint") != null) { OtherAzureEndpoint = att.Attribute("OtherAzureEndpoint").Value.ToString(); } CredentialList.MediaServicesAccounts.Add(new CredentialsEntry( att.Attribute("AccountName").Value.ToString(), att.Attribute("AccountKey").Value.ToString(), string.Empty, // client id not stored in XML string.Empty, // client secret not stored in XML att.Attribute("StorageKey").Value.ToString(), att.Attribute("Description").Value.ToString(), false, false, att.Attribute("UsePartnerAPI").Value.ToString() == true.ToString() ? true : false, att.Attribute("UseOtherAPI").Value.ToString() == true.ToString() ? true : false, att.Attribute("OtherAPIServer").Value.ToString(), att.Attribute("OtherScope").Value.ToString(), att.Attribute("OtherACSBaseAddress").Value.ToString(), OtherAzureEndpoint, OtherManagementPortal )); } } catch { MessageBox.Show(AMSExplorer.Properties.Resources.AMSLogin_buttonImportAll_Click_FileNotRecognizedOrIncorrect); return; } listViewAccounts.Items.Clear(); DoClearFields(); CredentialList.MediaServicesAccounts.ForEach(c => AddItemToListviewAccounts(c) /* listViewAccounts.Items.Add(ReturnAccountName(c))*/); buttonExport.Enabled = (listViewAccounts.Items.Count > 0); // let's save the list of credentials in settings Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } else { MessageBox.Show("Wrong XML file."); return; } } else if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".json") { string json = System.IO.File.ReadAllText(openFileDialog1.FileName); if (!mergesentries) { CredentialList.MediaServicesAccounts.Clear(); // let's purge entries if user does not want to keep them } var ImportedCredentialList = (ListCredentials)JsonConvert.DeserializeObject(json, typeof(ListCredentials)); CredentialList.MediaServicesAccounts.AddRange(ImportedCredentialList.MediaServicesAccounts); listViewAccounts.Items.Clear(); DoClearFields(); CredentialList.MediaServicesAccounts.ForEach(c => AddItemToListviewAccounts(c) /* listViewAccounts.Items.Add(ReturnAccountName(c))*/); buttonExport.Enabled = (listViewAccounts.Items.Count > 0); // let's save the list of credentials in settings Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); LoginCredentials = null; } } }
private async void ProcessCloneChannelToAnotherAMSAccount(CredentialsEntry DestinationCredentialsEntry, string DestinationStorageAccount, IChannel sourceChannel) { TextBoxLogWriteLine("Starting the channel cloning process..."); CloudMediaContext DestinationContext = Program.ConnectAndGetNewContext(DestinationCredentialsEntry); var options = new ChannelCreationOptions() { Name = sourceChannel.Name, Description = sourceChannel.Description, EncodingType = sourceChannel.EncodingType, Input = sourceChannel.Input, Output = sourceChannel.Output, Preview = sourceChannel.Preview }; if (sourceChannel.EncodingType != ChannelEncodingType.None) { options.Encoding = sourceChannel.Encoding; options.Slate = sourceChannel.Slate; } await Task.Run(() => IObjectExecuteOperationAsync( () => DestinationContext.Channels.SendCreateOperationAsync( options), sourceChannel.Name, "Cloned channel", "created", DestinationContext)); }
private void buttonLogin_Click(object sender, EventArgs e) { LoginCredentials = GenerateLoginCredentials; if (string.IsNullOrEmpty(LoginCredentials.ReturnAccountName())) { MessageBox.Show(string.Format("The {0} cannot be empty.", labelE1.Text), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var accName = LoginCredentials.ReturnAccountName(); var entryWithSameName = CredentialList.MediaServicesAccounts.Where(c => c.ReturnAccountName().ToLower().Trim() == accName.ToLower().Trim()).FirstOrDefault(); // if found the same name if (entryWithSameName == null) // not found { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToSaveTheCredentialsFor0, accName), AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_SaveCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to save { CredentialList.MediaServicesAccounts.Add(LoginCredentials); Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); AddItemToListviewAccounts(LoginCredentials); //listViewAccounts.Items.Add(ReturnAccountName(LoginCredentials)); } else if (result == DialogResult.Cancel) { return; } } else // found { if (!LoginCredentials.Equals(entryWithSameName)) // changed ? { var result = MessageBox.Show(string.Format(AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_DoYouWantToUpdateTheCredentialsFor0, accName), AMSExplorer.Properties.Resources.AMSLogin_listBoxAccounts_SelectedIndexChanged_UpdateCredentials, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) // ok to update the credentials { CredentialList.MediaServicesAccounts[CredentialList.MediaServicesAccounts.IndexOf(entryWithSameName)] = LoginCredentials; Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } else if (result == DialogResult.Cancel) { return; } } } if (LoginCredentials.UseAADServicePrincipal) // service principal mode { var spcrendentialsform = new AMSLoginServicePrincipal(); if (spcrendentialsform.ShowDialog() == DialogResult.OK) { LoginCredentials.ADSPClientId = spcrendentialsform.ClientId; LoginCredentials.ADSPClientSecret = spcrendentialsform.ClientSecret; } else { return; } } // OLD ACS Mode - let's warm the user if (!LoginCredentials.UseAADServicePrincipal && !LoginCredentials.UseAADInteract) { var f = new DisplayBox("Warning", AMSExplorer.Properties.Resources.AMSLogin_buttonLogin_Click_ACSAuthenticationWarning, 10); f.ShowDialog(); } // Context creation this.Cursor = Cursors.WaitCursor; context = Program.ConnectAndGetNewContext(LoginCredentials, false, true); accName = LoginCredentials.ReturnAccountName(); try { var a = context.Assets.FirstOrDefault(); this.Cursor = Cursors.Default; } catch (Exception ex) { MessageBox.Show(Program.GetErrorMessage(ex), "Login error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Cursor = Cursors.Default; return; } accountName = accName; this.DialogResult = DialogResult.OK; // form will close with OK result // else --> form won't close... }