public void FailIfProcessTakesTooLongToRespondTest() { Assert.False(GeneralUtilities.Probe(_pwsh, "-c \"sleep 4\"")); }
public static string ConstructDeploymentVariableTable(Dictionary <string, DeploymentVariable> dictionary) { if (dictionary == null) { return(null); } var maxNameLength = 15; dictionary.Keys.ForEach(k => maxNameLength = Math.Max(maxNameLength, k.Length + 2)); var maxTypeLength = 25; dictionary.Values.ForEach(v => maxTypeLength = Math.Max(maxTypeLength, v.Type.Length + 2)); StringBuilder result = new StringBuilder(); if (dictionary.Count > 0) { string rowFormat = "{0, -" + maxNameLength + "} {1, -" + maxTypeLength + "} {2, -10}\r\n"; result.AppendLine(); result.AppendFormat(rowFormat, "Name", "Type", "Value"); result.AppendFormat(rowFormat, GeneralUtilities.GenerateSeparator(maxNameLength, "="), GeneralUtilities.GenerateSeparator(maxTypeLength, "="), GeneralUtilities.GenerateSeparator(10, "=")); foreach (KeyValuePair <string, DeploymentVariable> pair in dictionary) { result.AppendFormat(rowFormat, pair.Key, pair.Value.Type, pair.Value.Value); } } return(result.ToString()); }
protected async virtual Task CreateMetadataTemplatesFromFile(string filePath, string filePathFields = "", bool save = false, string overrideSavePath = "", string overrideSaveFileFormat = "", bool json = false) { var boxClient = base.ConfigureBoxClient(oneCallAsUserId: this._asUser.Value(), oneCallWithToken: base._oneUseToken.Value()); if (!string.IsNullOrEmpty(filePath)) { filePath = GeneralUtilities.TranslatePath(filePath); } if (!string.IsNullOrEmpty(filePathFields)) { filePathFields = GeneralUtilities.TranslatePath(filePathFields); } try { var fileFormat = base.ProcessFileFormatFromPath(filePath); List <BoxMetadataTemplate> templateRequests; if (fileFormat.ToLower() == base._settings.FILE_FORMAT_CSV) { if (string.IsNullOrEmpty(filePathFields)) { throw new Exception("You must use the --bulk-file-path-csv option with metadata templates and provide file paths to CSV files for the tempate and the template fields."); } templateRequests = this.ReadMetadataTemplateCsvFile(filePath, filePathFields); } else if (fileFormat.ToLower() == base._settings.FILE_FORMAT_JSON) { templateRequests = this.ReadMetadataTemplateJsonFile(filePath); } else { throw new Exception($"File format {fileFormat} is not currently supported."); } var saveCreated = new List <BoxMetadataTemplate>(); foreach (var templateRequest in templateRequests) { BoxMetadataTemplate createdTemplate = null; try { createdTemplate = await boxClient.MetadataManager.CreateMetadataTemplate(templateRequest); } catch (Exception e) { Reporter.WriteError("Couldn't create metadata template..."); Reporter.WriteError(e.Message); } if (createdTemplate != null) { this.PrintMetadataTemplate(createdTemplate, json); if (save || !string.IsNullOrEmpty(overrideSavePath) || base._settings.GetAutoSaveSetting()) { saveCreated.Add(createdTemplate); } } } if (save || !string.IsNullOrEmpty(overrideSavePath) || base._settings.GetAutoSaveSetting()) { var saveFileFormat = base._settings.GetBoxReportsFileFormatSetting(); if (!string.IsNullOrEmpty(overrideSaveFileFormat)) { saveFileFormat = overrideSaveFileFormat; } var savePath = base._settings.GetBoxReportsFolderPath(); if (!string.IsNullOrEmpty(overrideSavePath)) { savePath = overrideSavePath; } var dateString = DateTime.Now.ToString(GeneralUtilities.GetDateFormatString()); var fileName = $"{base._names.CommandNames.MetadataTemplates}-{base._names.SubCommandNames.Create}-{dateString}"; var fileNameFields = $"{base._names.CommandNames.MetadataTemplateFields}-{base._names.SubCommandNames.Create}-{dateString}"; base.WriteMetadataTemplateCollectionResultsToReport(saveCreated, fileName, fileNameFields: fileNameFields, filePathTemplate: savePath, fileFormat: fileFormat); } } catch (Exception e) { Reporter.WriteError(e.Message); } }
/// <summary> /// Converts The Given XmlNode into a Rule /// </summary> /// <param name="node">The XmlNode To Be Converted To Rule</param> /// <param name="ary">The Arraylist to be used to add the created rule</param> /// <returns></returns> public static Rule XmlToRule(XmlNode node, ArrayList ary) { IEnumerator enumator = node.Attributes.GetEnumerator(); if (!GeneralUtilities.CheckString(node.InnerText)) { return(null); } int count = 0; string values = "", tip = "", rulename = "", action = ""; while (enumator.MoveNext()) { XmlAttribute atrb = (XmlAttribute)enumator.Current; string atrbb = atrb.Name.ToLower(); StringBuilder attributebuild = new StringBuilder(); attributebuild.Append("attribute name:"); attributebuild.Append(atrbb); attributebuild.Append(" value:"); attributebuild.Append(atrb.Value); log.Info(attributebuild.ToString()); if (atrbb == "name" || atrbb == "action" || atrbb == "type") { if (!GeneralUtilities.CheckString(atrb.Value)) { break; } } else { continue; } if (atrbb == "name") { rulename = atrb.Value; count++; } else if (atrbb == "action") { action = atrb.Value; count++; } else if (atrbb == "type") { tip = atrb.Value; count++; } if (count == 3) { values = node.InnerText; count = 0; try { if ((Enum.Parse(typeof(RuleTypes), tip, true) != null) && (Enum.Parse(typeof(ActionTypes), action, true) != null)) { object[] args = new object[3]; args[0] = rulename; args[1] = values; args[2] = Enum.Parse(typeof(ActionTypes), action, true); Type tips = System.Type.GetType(typeof(Rule).Namespace + "." + tip); object obj = Activator.CreateInstance(tips, args); ary.Add(obj); return((Rule)obj); } } catch (Exception ex) { log.Error(ex.Message); } } } return(null); }
/* Implement methods from NetworkUtilities.IMessageReceiver */ public void OnReceiveComplete(Socket handler, string msg) { string[] cmd = msg.Split(UCCommand.Separator); switch (cmd[0]) { case UCCommand.Register: if (cmd.Length == UCCommand.RegisterLength) { RegisterClient(handler, cmd[1]); } else { InvalidCommand(handler, msg); } break; case UCCommand.Deregister: { if (cmd.Length == UCCommand.DeregisterLength) { int playerId; if (int.TryParse(cmd[1], out playerId)) { DeregisterClient(handler, playerId); } else { // Cannot parse to int InvalidCommand(handler, msg); } } else { // Command length not match InvalidCommand(handler, msg); } break; } default: { int playerId; if (int.TryParse(cmd[0], out playerId)) { // If the command is from a registered // player. if (playerId < clients.Length && clients[playerId] != null) { HandleInputCommands( handler, playerId, // Create a new command array GeneralUtilities.ArrayCopy <string>( cmd, 1, cmd.Length - 1 ), msg ); } else { PlayerNotFound(handler, playerId); } } else { // Cannot parse to int InvalidCommand(handler, msg); } break; } } }
public void ExecuteCommand() { string configString = string.Empty; if (!string.IsNullOrEmpty(Configuration)) { configString = GeneralUtilities.GetConfiguration(Configuration); } ExtensionConfiguration extConfig = null; if (ExtensionConfiguration != null) { string errorConfigInput = null; if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } foreach (ExtensionConfigurationInput context in ExtensionConfiguration) { if (context != null && context.X509Certificate != null) { ExecuteClientActionNewSM( null, string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint), () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate))); } } var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true); DeploymentGetResponse d = null; InvokeInOperationContext(() => { try { d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType); } catch (CloudException ex) { if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false) { this.WriteExceptionDetails(ex); } } }); ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName); extConfig = extensionMgr.Add(d, ExtensionConfiguration, this.Slot); } // Upgrade Parameter Set if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0) { bool removePackage = false; var storageName = CurrentContext.Subscription.GetProperty(AzureSubscription.Property.StorageAccount); Uri packageUrl = null; if (Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { packageUrl = new Uri(Package); } else { if (string.IsNullOrEmpty(storageName)) { throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet); } var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage); WriteProgress(progress); removePackage = true; InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.StorageClient, storageName, Package, null))); } DeploymentUpgradeMode upgradeMode; if (!Enum.TryParse <DeploymentUpgradeMode>(Mode, out upgradeMode)) { upgradeMode = DeploymentUpgradeMode.Auto; } var upgradeDeploymentInput = new DeploymentUpgradeParameters { Mode = upgradeMode, Configuration = configString, ExtensionConfiguration = extConfig, PackageUri = packageUrl, Label = Label ?? ServiceName, Force = Force.IsPresent }; if (!string.IsNullOrEmpty(RoleName)) { upgradeDeploymentInput.RoleToUpgrade = RoleName; } InvokeInOperationContext(() => { try { ExecuteClientActionNewSM( upgradeDeploymentInput, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.UpgradeBySlot( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), upgradeDeploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.StorageClient, storageName, packageUrl)); } } catch (CloudException ex) { this.WriteExceptionDetails(ex); } }); } else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0) { // Config parameter set var changeDeploymentStatusParams = new DeploymentChangeConfigurationParameters { Configuration = configString, ExtensionConfiguration = extConfig }; ExecuteClientActionNewSM( changeDeploymentStatusParams, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.ChangeConfigurationBySlot( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), changeDeploymentStatusParams)); } else { // Status parameter set var updateDeploymentStatusParams = new DeploymentUpdateStatusParameters { Status = (UpdatedDeploymentStatus)Enum.Parse(typeof(UpdatedDeploymentStatus), this.NewStatus, true) }; ExecuteClientActionNewSM( null, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.UpdateStatusByDeploymentSlot( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), updateDeploymentStatusParams)); } }
//protected void Page_Load(object sender, EventArgs e) { protected void Page_Init(object sender, EventArgs e) { guidContentID = GetGuidIDFromQuery(); EditorPrefs = UserEditState.cmsUserEditState; if (EditorPrefs == null) { EditorPrefs = new UserEditState(); EditorPrefs.Init(); } string sCurrentPage = SiteData.CurrentScriptName; string sScrubbedURL = SiteData.AlternateCurrentScriptName; if (sScrubbedURL.ToLowerInvariant() != sCurrentPage.ToLowerInvariant()) { sCurrentPage = sScrubbedURL; } ContentPage pageContents = new ContentPage(); if (guidContentID == Guid.Empty) { pageContents = pageHelper.FindByFilename(SiteData.CurrentSiteID, sCurrentPage); } else { pageContents = pageHelper.FindContentByID(SiteData.CurrentSiteID, guidContentID); } PageType = pageContents.ContentType; EditedPageFileName = pageContents.FileName; btnEditCoreInfo.Attributes["onclick"] = "cmsShowEditPageInfo();"; if (pageContents.ContentType == ContentPageType.PageType.BlogEntry) { btnEditCoreInfo.Attributes["onclick"] = "cmsShowEditPostInfo();"; btnSortChildPages.Visible = false; } if (cmsHelper.cmsAdminContent != null) { EditedPageFileName = cmsHelper.cmsAdminContent.FileName; } if (cmsHelper.ToolboxPlugins.Any()) { GeneralUtilities.BindRepeater(rpTools, cmsHelper.ToolboxPlugins); } else { rpTools.Visible = false; } bLocked = pageHelper.IsPageLocked(pageContents.Root_ContentID, SiteData.CurrentSiteID, SecurityData.CurrentUserGuid); GeneralUtilities.BindList(ddlTemplate, cmsHelper.Templates); try { GeneralUtilities.SelectListValue(ddlTemplate, cmsHelper.cmsAdminContent.TemplateFile.ToLowerInvariant()); } catch { } if (!bLocked) { foreach (Control c in plcIncludes.Controls) { this.Page.Header.Controls.Add(c); } //jquerybasic jquerybasic2 = new jquerybasic(); //jquerybasic2.SelectedSkin = jquerybasic.jQueryTheme.NotUsed; //Page.Header.Controls.AddAt(0, jquerybasic2); //BasicControlUtils.InsertjQuery(this.Page); BasicControlUtils.InsertjQueryMain(this.Page); BasicControlUtils.InsertjQueryUI(this.Page); guidContentID = pageContents.Root_ContentID; if (cmsHelper.cmsAdminContent == null) { pageContents.LoadAttributes(); cmsHelper.cmsAdminContent = pageContents; } else { pageContents = cmsHelper.cmsAdminContent; } bool bRet = pageHelper.RecordPageLock(pageContents.Root_ContentID, SiteData.CurrentSite.SiteID, SecurityData.CurrentUserGuid); cmsDivEditing.Visible = false; BasicControlUtils.MakeXUACompatibleFirst(this.Page); } else { pnlCMSEditZone.Visible = false; rpTools.Visible = false; btnToolboxSave1.Visible = false; btnToolboxSave2.Visible = false; btnToolboxSave3.Visible = false; btnTemplate.Visible = false; btnEditCoreInfo.Visible = false; cmsDivEditing.Visible = true; if (bLocked && pageContents.Heartbeat_UserId != null) { MembershipUser usr = SecurityData.GetUserByGuid(pageContents.Heartbeat_UserId.Value); EditUserName = usr.UserName; litUser.Text = "Read only mode. User '" + usr.UserName + "' is currently editing the page.<br />" + " Click <b><a href=\"" + pageContents.FileName + "\">here</a></b> to return to the browse view.<br />"; } } }
public void ReceiveResponse(string invocationId, HttpResponseMessage response) { Write(GeneralUtilities.GetLog(response)); }
protected void SavePage(bool bRedirect) { ContentPage pageContents = null; if (guidVersionContentID != Guid.Empty) { pageContents = pageHelper.GetVersion(SiteID, guidVersionContentID); } if (guidContentID != Guid.Empty && pageContents == null) { pageContents = pageHelper.FindContentByID(SiteID, guidContentID); } if (guidImportContentID != Guid.Empty) { pageContents = ContentImportExportUtils.GetSerializedContentPageExport(guidImportContentID).ThePage; if (pageContents != null) { pageContents.SiteID = SiteID; pageContents.EditDate = SiteData.CurrentSite.Now; pageContents.CreateUserId = SecurityData.CurrentUserGuid; pageContents.CreateDate = SiteData.CurrentSite.Now; var rp = pageHelper.GetLatestContentByURL(SiteID, false, pageContents.FileName); if (rp != null) { pageContents.Root_ContentID = rp.Root_ContentID; pageContents.ContentID = rp.ContentID; } else { pageContents.Root_ContentID = Guid.Empty; pageContents.ContentID = Guid.Empty; } pageContents.Parent_ContentID = null; pageContents.NavOrder = SiteData.BlogSortOrderNumber; } } if (pageContents == null) { pageContents = new ContentPage(SiteData.CurrentSiteID, ContentPageType.PageType.BlogEntry); } DateTime dtSite = CMSConfigHelper.CalcNearestFiveMinTime(SiteData.CurrentSite.Now); pageContents.GoLiveDate = dtSite.AddMinutes(-5); pageContents.RetireDate = dtSite.AddYears(200); pageContents.IsLatestVersion = true; pageContents.Thumbnail = txtThumb.Text; pageContents.TemplateFile = ddlTemplate.SelectedValue; pageContents.TitleBar = txtTitle.Text; pageContents.NavMenuText = txtNav.Text; pageContents.PageHead = txtHead.Text; pageContents.PageSlug = txtPageSlug.Text; pageContents.MetaDescription = txtDescription.Text; pageContents.MetaKeyword = txtKey.Text; pageContents.EditDate = SiteData.CurrentSite.Now; pageContents.NavOrder = SiteData.BlogSortOrderNumber; pageContents.PageText = reBody.Text; pageContents.LeftPageText = reLeftBody.Text; pageContents.RightPageText = reRightBody.Text; pageContents.PageActive = chkActive.Checked; pageContents.ShowInSiteNav = false; pageContents.ShowInSiteMap = false; pageContents.BlockIndex = chkHide.Checked; pageContents.ContentType = ContentPageType.PageType.BlogEntry; pageContents.Parent_ContentID = null; if (String.IsNullOrEmpty(hdnCreditUserID.Value)) { pageContents.CreditUserId = null; } else { var usr = new ExtendedUserData(hdnCreditUserID.Value); pageContents.CreditUserId = usr.UserId; } pageContents.GoLiveDate = ucReleaseDate.GetDate(); pageContents.RetireDate = ucRetireDate.GetDate(); pageContents.EditUserId = SecurityData.CurrentUserGuid; pageContents.NewTrackBackURLs = txtTrackback.Text; List <ContentCategory> lstCat = new List <ContentCategory>(); List <ContentTag> lstTag = new List <ContentTag>(); lstCat = (from cr in GeneralUtilities.GetSelectedValues(listCats).Select(x => new Guid(x)) join l in SiteData.CurrentSite.GetCategoryList() on cr equals l.ContentCategoryID select l).ToList(); lstTag = (from cr in GeneralUtilities.GetSelectedValues(listTags).Select(x => new Guid(x)) join l in SiteData.CurrentSite.GetTagList() on cr equals l.ContentTagID select l).ToList(); pageContents.ContentCategories = lstCat; pageContents.ContentTags = lstTag; if (!chkDraft.Checked) { pageContents.SavePageEdit(); } else { pageContents.SavePageAsDraft(); } //if importing, copy in all meta data possible if (guidImportContentID != Guid.Empty) { List <Widget> widgets = ContentImportExportUtils.GetSerializedContentPageExport(guidImportContentID).ThePageWidgets; foreach (var wd in widgets) { wd.Root_ContentID = pageContents.Root_ContentID; wd.Root_WidgetID = Guid.NewGuid(); wd.WidgetDataID = Guid.NewGuid(); wd.IsPendingChange = true; wd.EditDate = SiteData.CurrentSite.Now; wd.Save(); } ContentImportExportUtils.RemoveSerializedExportData(guidImportContentID); } cmsHelper.OverrideKey(pageContents.Root_ContentID); if (cmsHelper.cmsAdminWidget != null) { var ww = (from w in cmsHelper.cmsAdminWidget where w.IsLatestVersion == true && w.IsPendingChange == true && (w.ControlPath.StartsWith("CLASS:Carrotware.CMS.UI.Controls.ContentRichText,") || w.ControlPath.StartsWith("CLASS:Carrotware.CMS.UI.Controls.ContentPlainText,")) select w); foreach (Widget w in ww) { w.Save(); } } cmsHelper.cmsAdminContent = null; cmsHelper.cmsAdminWidget = null; if (pageContents.FileName.ToLowerInvariant().EndsWith(SiteData.DefaultDirectoryFilename)) { VirtualDirectory.RegisterRoutes(true); } if (!bRedirect) { if (sPageMode.Length < 1) { Response.Redirect(SiteData.CurrentScriptName + "?id=" + pageContents.Root_ContentID.ToString()); } else { Response.Redirect(SiteData.CurrentScriptName + "?mode=raw&id=" + pageContents.Root_ContentID.ToString()); } } else { Response.Redirect(pageContents.FileName); } }
internal string GetServiceSettingsPath(bool global) { return(new CloudServiceProject(GeneralUtilities.GetServiceRootPath(CurrentPath()), null).Paths.Settings); }
public void SendRequest(string invocationId, HttpRequestMessage request) { Write(GeneralUtilities.GetLog(request)); }
public LevelFilterAuthor(string match) { this.match = match.ToLower().Trim(); matchRegex = GeneralUtilities.getSearchRegex(match); }
private async Task RunList() { base.CheckForValue(this._id.Value, this._app, "A group ID or user ID is required for this command"); var boxClient = base.ConfigureBoxClient(oneCallAsUserId: base._asUser.Value(), oneCallWithToken: base._oneUseToken.Value()); var BoxCollectionsIterators = base.GetIterators(!String.IsNullOrEmpty(base._oneUseToken.Value())); if (this._listGroups.HasValue()) { if (_save.HasValue()) { var userMemberships = await boxClient.GroupsManager.GetAllGroupMembershipsForUserAsync(this._id.Value, autoPaginate : true); var fileName = $"{base._names.CommandNames.GroupMembership}-{base._names.SubCommandNames.List}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}"; Reporter.WriteInformation("Saving file..."); var saved = base.WriteOffsetCollectionResultsToReport <BoxGroupMembership, BoxGroupMembershipMap>(userMemberships, fileName, fileFormat: this._fileFormat.Value()); Reporter.WriteInformation($"File saved: {saved}"); return; } if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { var memberships = await boxClient.GroupsManager.GetAllGroupMembershipsForUserAsync(this._id.Value, autoPaginate : true); base.OutputJson(memberships); return; } await BoxCollectionsIterators.ListOffsetCollectionToConsole <BoxGroupMembership>((offset) => { return(boxClient.GroupsManager.GetAllGroupMembershipsForUserAsync(this._id.Value, offset: (int)offset)); }, base.PrintGroupMember); } else if (this._listCollab.HasValue()) { if (_save.HasValue()) { var membershipCollaborations = await boxClient.GroupsManager.GetCollaborationsForGroupAsync(this._id.Value, autoPaginate : true); var fileName = $"{base._names.CommandNames.GroupMembership}-{base._names.SubCommandNames.List}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}"; Reporter.WriteInformation("Saving file..."); var saved = base.WriteOffsetCollectionResultsToReport <BoxCollaboration, BoxCollaborationMap>(membershipCollaborations, fileName, fileFormat: this._fileFormat.Value()); Reporter.WriteInformation($"File saved: {saved}"); return; } if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { var memberships = await boxClient.GroupsManager.GetCollaborationsForGroupAsync(this._id.Value, autoPaginate : true); base.OutputJson(memberships); return; } await BoxCollectionsIterators.ListOffsetCollectionToConsole <BoxCollaboration>((offset) => { return(boxClient.GroupsManager.GetCollaborationsForGroupAsync(this._id.Value, offset: (int)offset)); }, base.PrintCollaboration); } else { if (_save.HasValue()) { var memberships = await boxClient.GroupsManager.GetAllGroupMembershipsForGroupAsync(this._id.Value, autoPaginate : true); var fileName = $"{base._names.CommandNames.GroupMembership}-{base._names.SubCommandNames.List}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}"; Reporter.WriteInformation("Saving file..."); var saved = base.WriteOffsetCollectionResultsToReport <BoxGroupMembership, BoxGroupMembershipMap>(memberships, fileName, fileFormat: this._fileFormat.Value()); Reporter.WriteInformation($"File saved: {saved}"); return; } if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { var memberships = await boxClient.GroupsManager.GetAllGroupMembershipsForGroupAsync(this._id.Value, autoPaginate : true); base.OutputJson(memberships); return; } await BoxCollectionsIterators.ListOffsetCollectionToConsole <BoxGroupMembership>((offset) => { return(boxClient.GroupsManager.GetAllGroupMembershipsForGroupAsync(this._id.Value, offset: (int)offset)); }, base.PrintGroupMember); } }
private async Task RunUpdate() { base.CheckForId(this._id.Value, this._app); if (base._t == BoxType.enterprise) { if (this._type.Value == String.Empty && this._type.Value != SharedLinkSubCommandBase.BOX_FILE && this._type.Value != SharedLinkSubCommandBase.BOX_FOLDER) { _app.ShowHelp(); throw new Exception("You must provide an item type for this command: choose file or folder"); } } var boxClient = base.ConfigureBoxClient(oneCallAsUserId: base._asUser.Value(), oneCallWithToken: base._oneUseToken.Value()); if (base._t == BoxType.file || (this._type != null && this._type.Value == SharedLinkSubCommandBase.BOX_FILE)) { var fileRequest = new BoxFileRequest(); fileRequest.Id = this._id.Value; fileRequest.SharedLink = new BoxSharedLinkRequest(); if (this._access.HasValue()) { fileRequest.SharedLink.Access = base.ResolveSharedLinkAccessType(this._access.Value()); } if (this._password.HasValue()) { fileRequest.SharedLink.Password = this._password.Value(); } if (this._unsharedAt.HasValue()) { fileRequest.SharedLink.UnsharedAt = GeneralUtilities.GetDateTimeFromString(this._unsharedAt.Value()); } if (this._canDownload.HasValue()) { fileRequest.SharedLink.Permissions = new BoxPermissionsRequest(); fileRequest.SharedLink.Permissions.Download = true; } var result = await boxClient.FilesManager.UpdateInformationAsync(fileRequest); if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { base.OutputJson(result); return; } Reporter.WriteSuccess("Updated shared link:"); base.PrintSharedLink(result.SharedLink); } else if (base._t == BoxType.folder || (this._type != null && this._type.Value == SharedLinkSubCommandBase.BOX_FOLDER)) { var folderUpdateRequest = new BoxFolderRequest(); folderUpdateRequest.Id = this._id.Value; folderUpdateRequest.SharedLink = new BoxSharedLinkRequest(); if (this._access.HasValue()) { folderUpdateRequest.SharedLink.Access = base.ResolveSharedLinkAccessType(this._access.Value()); } if (this._password.HasValue()) { folderUpdateRequest.SharedLink.Password = this._password.Value(); } if (this._unsharedAt.HasValue()) { folderUpdateRequest.SharedLink.UnsharedAt = GeneralUtilities.GetDateTimeFromString(this._unsharedAt.Value()); } if (this._canDownload.HasValue()) { folderUpdateRequest.SharedLink.Permissions = new BoxPermissionsRequest(); folderUpdateRequest.SharedLink.Permissions.Download = true; } var updated = await boxClient.FoldersManager.UpdateInformationAsync(folderUpdateRequest); if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { base.OutputJson(updated); return; } Reporter.WriteSuccess("Updated shared link:"); base.PrintSharedLink(updated.SharedLink); } else { throw new Exception("Box type not supported for this command."); } }
protected void Page_Load(object sender, EventArgs e) { Master.UsesSaved = true; Master.HideSave(); guidWidget = GetGuidIDFromQuery(); guidContentID = GetGuidPageIDFromQuery(); cmsHelper.OverrideKey(guidContentID); Widget w = (from aw in cmsHelper.cmsAdminWidget where aw.Root_WidgetID == guidWidget orderby aw.WidgetOrder, aw.EditDate select aw).FirstOrDefault(); if (!IsPostBack) { lstProps = w.ParseDefaultControlProperties(); Control widget = new Control(); if (w.ControlPath.EndsWith(".ascx")) { try { widget = Page.LoadControl(w.ControlPath); } catch (Exception ex) { } } if (w.ControlPath.ToLower().StartsWith("class:")) { try { Assembly a = Assembly.GetExecutingAssembly(); var className = w.ControlPath.Replace("CLASS:", ""); Type t = Type.GetType(className); Object o = Activator.CreateInstance(t); if (o != null) { widget = o as Control; } } catch (Exception ex) { } } List <ObjectProperty> props = new List <ObjectProperty>(); List <ObjectProperty> props_tmp = new List <ObjectProperty>(); if (widget is BaseUserControl) { props_tmp = ObjectProperty.GetTypeProperties(typeof(BaseUserControl)); props = props.Union(props_tmp).ToList(); } if (widget is BaseShellUserControl) { props_tmp = ObjectProperty.GetTypeProperties(typeof(BaseShellUserControl)); props = props.Union(props_tmp).ToList(); } if (widget is UserControl) { props_tmp = ObjectProperty.GetTypeProperties(typeof(UserControl)); props = props.Union(props_tmp).ToList(); } if (widget is IAdminModule) { var w1 = (IAdminModule)widget; w1.SiteID = SiteData.CurrentSiteID; props_tmp = ObjectProperty.GetTypeProperties(typeof(IAdminModule)); props = props.Union(props_tmp).ToList(); } if (widget is IWidget) { var w1 = (IWidget)widget; w1.SiteID = SiteData.CurrentSiteID; w1.PageWidgetID = w.Root_WidgetID; w1.RootContentID = w.Root_ContentID; props_tmp = ObjectProperty.GetTypeProperties(typeof(IWidget)); props = props.Union(props_tmp).ToList(); } if (widget is IWidgetEditStatus) { props_tmp = ObjectProperty.GetTypeProperties(typeof(IWidgetEditStatus)); props = props.Union(props_tmp).ToList(); } if (widget is IWidgetParmData) { props_tmp = ObjectProperty.GetTypeProperties(typeof(IWidgetParmData)); props = props.Union(props_tmp).ToList(); } if (widget is IWidgetRawData) { var w1 = (IWidgetRawData)widget; w1.RawWidgetData = w.ControlProperties; props_tmp = ObjectProperty.GetTypeProperties(typeof(IWidgetRawData)); props = props.Union(props_tmp).ToList(); } lstDefProps = ObjectProperty.GetObjectProperties(widget); List <string> limitedPropertyList = new List <string>(); if (widget is IWidgetLimitedProperties) { limitedPropertyList = ((IWidgetLimitedProperties)(widget)).LimitedPropertyList; } else { limitedPropertyList = (from p in lstDefProps select p.Name.ToLower()).ToList(); } if (limitedPropertyList != null && limitedPropertyList.Any()) { limitedPropertyList = (from p in limitedPropertyList select p.ToLower()).ToList(); } var defprops = (from p in lstDefProps join l in limitedPropertyList on p.Name.ToLower() equals l.ToLower() where p.CanRead == true && p.CanWrite == true && !props.Contains(p) select p).ToList(); GeneralUtilities.BindRepeater(rpProps, defprops); } }
protected void Page_Load(object sender, EventArgs e) { Master.ActivateTab(AdminBaseMasterPage.SectionID.BlogContentAdd); RedirectIfNoSite(); lblUpdated.Text = SiteData.CurrentSite.Now.ToString(); lblCreateDate.Text = SiteData.CurrentSite.Now.ToString(); guidContentID = GetGuidIDFromQuery(); guidVersionContentID = GetGuidParameterFromQuery("versionid"); guidImportContentID = GetGuidParameterFromQuery("importid"); sPageMode = GetStringParameterFromQuery("mode"); if (sPageMode.ToLowerInvariant() == "raw") { reBody.CssClass = "rawEditor"; reLeftBody.CssClass = "rawEditor"; reRightBody.CssClass = "rawEditor"; divCenter.Visible = false; divRight.Visible = false; divLeft.Visible = false; } if (!IsPostBack) { DateTime dtSite = CMSConfigHelper.CalcNearestFiveMinTime(SiteData.CurrentSite.Now); ucReleaseDate.SetDate(dtSite); ucRetireDate.SetDate(dtSite.AddYears(200)); hdnRootID.Value = Guid.Empty.ToString(); GeneralUtilities.BindList(listCats, SiteData.CurrentSite.GetCategoryList().OrderBy(x => x.CategoryText)); GeneralUtilities.BindList(listTags, SiteData.CurrentSite.GetTagList().OrderBy(x => x.TagText)); ContentPage pageContents = null; if (guidVersionContentID != Guid.Empty) { pageContents = pageHelper.GetVersion(SiteID, guidVersionContentID); } if (guidContentID != Guid.Empty && pageContents == null) { pageContents = pageHelper.FindContentByID(SiteID, guidContentID); } if (guidImportContentID != Guid.Empty) { ContentPageExport cpe = ContentImportExportUtils.GetSerializedContentPageExport(guidImportContentID); if (cpe != null) { pageContents = cpe.ThePage; pageContents.EditDate = SiteData.CurrentSite.Now; pageContents.Parent_ContentID = null; } var rp = pageHelper.GetLatestContentByURL(SiteID, false, pageContents.FileName); if (rp != null) { pageContents.Root_ContentID = rp.Root_ContentID; pageContents.ContentID = rp.ContentID; } else { pageContents.Root_ContentID = Guid.Empty; pageContents.ContentID = Guid.Empty; } pageContents.Parent_ContentID = null; pageContents.NavOrder = SiteData.BlogSortOrderNumber; } //if (pageContents == null) { // pageContents = new ContentPage(SiteData.CurrentSiteID, ContentPageType.PageType.BlogEntry); //} List <ContentPage> lstContent = pageHelper.GetAllLatestContentList(SiteID); GeneralUtilities.BindList(ddlTemplate, cmsHelper.Templates); chkDraft.Visible = false; divEditing.Visible = false; Dictionary <string, float> dictTemplates = pageHelper.GetPopularTemplateList(SiteID, ContentPageType.PageType.BlogEntry); if (dictTemplates.Any()) { try { GeneralUtilities.SelectListValue(ddlTemplate, dictTemplates.First().Key); } catch { } } if (pageContents == null) { btnDeleteButton.Visible = false; } if (pageContents != null) { bool bRet = pageHelper.RecordPageLock(pageContents.Root_ContentID, SiteData.CurrentSite.SiteID, SecurityData.CurrentUserGuid); if (pageContents.ContentType != ContentPageType.PageType.BlogEntry) { Response.Redirect(SiteFilename.PageAddEditURL + "?id=" + Request.QueryString.ToString()); } cmsHelper.OverrideKey(pageContents.Root_ContentID); cmsHelper.cmsAdminContent = pageContents; cmsHelper.cmsAdminWidget = pageContents.GetWidgetList(); BindTextDataGrid(); guidRootContentID = pageContents.Root_ContentID; hdnRootID.Value = guidRootContentID.ToString(); txtOldFile.Text = pageContents.FileName; if (guidImportContentID != Guid.Empty) { txtOldFile.Text = ""; } Dictionary <string, string> dataVersions = (from v in pageHelper.GetVersionHistory(SiteID, pageContents.Root_ContentID) join u in ExtendedUserData.GetUserList() on v.EditUserId equals u.UserId orderby v.EditDate descending select new KeyValuePair <string, string>(v.ContentID.ToString(), string.Format("{0} ({1}) {2}", v.EditDate, u.UserName, (v.IsLatestVersion ? " [**] " : " "))) ).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); GeneralUtilities.BindListDefaultText(ddlVersions, dataVersions, null, "Page Versions", "00000"); bLocked = pageHelper.IsPageLocked(pageContents); pnlHB.Visible = !bLocked; pnlButtons.Visible = !bLocked; divEditing.Visible = bLocked; chkDraft.Visible = !bLocked; pnlHBEmpty.Visible = bLocked; if (bLocked && pageContents.Heartbeat_UserId != null) { MembershipUser usr = SecurityData.GetUserByGuid(pageContents.Heartbeat_UserId.Value); litUser.Text = "Read only mode. User '" + usr.UserName + "' is currently editing the page."; } txtTitle.Text = pageContents.TitleBar; txtNav.Text = pageContents.NavMenuText; txtHead.Text = pageContents.PageHead; txtPageSlug.Text = pageContents.PageSlug; txtThumb.Text = pageContents.Thumbnail; txtDescription.Text = pageContents.MetaDescription; txtKey.Text = pageContents.MetaKeyword; lblUpdated.Text = pageContents.EditDate.ToString(); lblCreateDate.Text = pageContents.CreateDate.ToString(); reBody.Text = pageContents.PageText; reLeftBody.Text = pageContents.LeftPageText; reRightBody.Text = pageContents.RightPageText; chkActive.Checked = pageContents.PageActive; chkHide.Checked = pageContents.BlockIndex; GeneralUtilities.BindDataBoundControl(gvTracks, pageContents.GetTrackbacks()); ucReleaseDate.SetDate(pageContents.GoLiveDate); ucRetireDate.SetDate(pageContents.RetireDate); if (pageContents.CreditUserId.HasValue) { var usr = new ExtendedUserData(pageContents.CreditUserId.Value); hdnCreditUserID.Value = usr.UserName; txtSearchUser.Text = string.Format("{0} ({1})", usr.UserName, usr.EmailAddress); } pageContents.Parent_ContentID = null; GeneralUtilities.SelectListValue(ddlTemplate, pageContents.TemplateFile.ToLowerInvariant()); GeneralUtilities.SelectListValues(listTags, pageContents.ContentTags.Cast <IContentMetaInfo>().Select(x => x.ContentMetaInfoID.ToString()).ToList()); GeneralUtilities.SelectListValues(listCats, pageContents.ContentCategories.Cast <IContentMetaInfo>().Select(x => x.ContentMetaInfoID.ToString()).ToList()); } } SetBlankText(reBody); SetBlankText(reLeftBody); SetBlankText(reRightBody); if (ddlVersions.Items.Count < 1) { pnlReview.Visible = false; } }
public override void ExecuteCmdlet() { ConfirmAction("updating environment", Name, () => { if (AzureEnvironment.PublicEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot change built-in environment {0}.", Name)); } if (this.ParameterSetName.Equals(MetadataParameterSet, StringComparison.Ordinal)) { // Simply use built-in environments if the ARM endpoint matches the ARM endpoint for a built-in environment var publicEnvironment = AzureEnvironment.PublicEnvironments.FirstOrDefault( env => !string.IsNullOrWhiteSpace(ARMEndpoint) && string.Equals( env.Value?.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager)?.ToLowerInvariant(), GeneralUtilities.EnsureTrailingSlash(ARMEndpoint)?.ToLowerInvariant(), StringComparison.CurrentCultureIgnoreCase)); var defProfile = GetDefaultProfile(); IAzureEnvironment newEnvironment; if (!defProfile.TryGetEnvironment(this.Name, out newEnvironment)) { newEnvironment = new AzureEnvironment { Name = this.Name }; } if (publicEnvironment.Key == null) { SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, ARMEndpoint); try { EnvHelper = (EnvHelper == null ? new EnvironmentHelper() : EnvHelper); MetadataResponse metadataEndpoints = EnvHelper.RetrieveMetaDataEndpoints(newEnvironment.ResourceManagerUrl).Result; string domain = EnvHelper.RetrieveDomain(ARMEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory, metadataEndpoints.authentication.LoginEndpoint.TrimEnd('/') + '/'); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, metadataEndpoints.authentication.Audiences[0]); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Gallery, metadataEndpoints.GalleryEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Graph, metadataEndpoints.GraphEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.GraphEndpointResourceId, metadataEndpoints.GraphEndpoint); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, AzureKeyVaultDnsSuffix ?? string.Format("vault.{0}", domain).ToLowerInvariant()); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, AzureKeyVaultServiceEndpointResourceId ?? string.Format("https://vault.{0}", domain).ToLowerInvariant()); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, StorageEndpoint ?? domain); newEnvironment.OnPremise = metadataEndpoints.authentication.LoginEndpoint.TrimEnd('/').EndsWith("/adfs", System.StringComparison.OrdinalIgnoreCase); } catch (AggregateException ae) { if (ae.Flatten().InnerExceptions.Count > 1) { throw; } if (ae.InnerException != null) { throw ae.InnerException; } } } else { newEnvironment = new AzureEnvironment(publicEnvironment.Value); newEnvironment.Name = Name; SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, AzureKeyVaultDnsSuffix); SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, AzureKeyVaultServiceEndpointResourceId); } ModifyContext((profile, client) => { WriteObject(new PSAzureEnvironment(client.AddOrSetEnvironment(newEnvironment))); }); } else { ModifyContext((profile, profileClient) => { IAzureEnvironment newEnvironment = new AzureEnvironment { Name = Name }; if (profile.EnvironmentTable.ContainsKey(Name)) { newEnvironment = profile.EnvironmentTable[Name]; } if (MyInvocation != null && MyInvocation.BoundParameters != null) { if (MyInvocation.BoundParameters.ContainsKey(nameof(EnableAdfsAuthentication))) { newEnvironment.OnPremise = EnableAdfsAuthentication; } SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.PublishSettingsFileUrl, nameof(PublishSettingsFileUrl)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ServiceManagement, nameof(ServiceEndpoint)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, nameof(ResourceManagerEndpoint)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ManagementPortalUrl, nameof(ManagementPortalUrl)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, nameof(StorageEndpoint)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory, nameof(ActiveDirectoryEndpoint)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, nameof(ActiveDirectoryServiceEndpointResourceId)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.Gallery, nameof(GalleryEndpoint)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.Graph, nameof(GraphEndpoint)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, nameof(AzureKeyVaultDnsSuffix)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, nameof(AzureKeyVaultServiceEndpointResourceId)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.TrafficManagerDnsSuffix, nameof(TrafficManagerDnsSuffix)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix, nameof(SqlDatabaseDnsSuffix)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix, nameof(AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix, nameof(AzureDataLakeStoreFileSystemEndpointSuffix)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AdTenant, nameof(AdTenant)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.GraphEndpointResourceId, nameof(GraphAudience)); SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.DataLakeEndpointResourceId, nameof(DataLakeAudience)); WriteObject(new PSAzureEnvironment(profileClient.AddOrSetEnvironment(newEnvironment))); } }); } }); }
private async Task RunCreate() { if (this._bulkPath.HasValue()) { var json = false; if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { json = true; } await base.CreateGroupsFromFile(this._bulkPath.Value(), this._save.HasValue(), json : json, overrideSaveFileFormat : this._fileFormat.Value()); return; } base.CheckForValue(this._name.Value, this._app, "A group name is required for this command"); var boxClient = base.ConfigureBoxClient(oneCallAsUserId: base._asUser.Value(), oneCallWithToken: base._oneUseToken.Value()); var groupRequest = new BoxGroupRequest(); groupRequest.Name = this._name.Value; if (this._inviteLevel.HasValue()) { groupRequest.InvitabilityLevel = base.CheckInvitabilityLevel(this._inviteLevel.Value()); } if (this._viewMembershipLevel.HasValue()) { groupRequest.MemberViewabilityLevel = base.CheckViewMembersLevel(this._viewMembershipLevel.Value()); } var createdGroup = await boxClient.GroupsManager.CreateAsync(groupRequest); if (_save.HasValue()) { var fileName = $"{base._names.CommandNames.Groups}-{base._names.SubCommandNames.Create}-{DateTime.Now.ToString(GeneralUtilities.GetDateFormatString())}"; Reporter.WriteInformation("Saving file..."); var listWrapper = new List <BoxGroup>(); listWrapper.Add(createdGroup); var saved = base.WriteListResultsToReport <BoxGroup, BoxGroupMap>(listWrapper, fileName, fileFormat: this._fileFormat.Value()); Reporter.WriteInformation($"File saved: {saved}"); return; } if (this._idOnly.HasValue()) { Reporter.WriteInformation(createdGroup.Id); return; } if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { base.OutputJson(createdGroup); return; } base.PrintGroup(createdGroup); }
private CloudServiceProject GetCurrentServiceProject() { return new CloudServiceProject(GeneralUtilities.GetServiceRootPath(GetCurrentDirectory()), null); }
/// <summary> /// Applies required configuration for enabling cache in SDK 1.8.0 version by: /// * Add MemcacheShim runtime installation. /// * Add startup task to install memcache shim on the client side. /// * Add default memcache internal endpoint. /// * Add cache diagnostic to local resources. /// * Add ClientDiagnosticLevel setting to service configuration. /// * Adjust web.config to enable auto discovery for the caching role. /// </summary> /// <param name="cloudServiceProject">The azure service instance</param> /// <param name="webRole">The web role to enable caching on</param> /// <param name="isWebRole">Flag indicating if the provided role is web or not</param> /// <param name="cacheWorkerRole">The memcache worker role name</param> /// <param name="startup">The role startup</param> /// <param name="endpoints">The role endpoints</param> /// <param name="localResources">The role local resources</param> /// <param name="configurationSettings">The role configuration settings</param> private void Version180Configuration( CloudServiceProject cloudServiceProject, string roleName, bool isWebRole, string cacheWorkerRole, Startup startup, Endpoints endpoints, LocalResources localResources, ref DefinitionConfigurationSetting[] configurationSettings) { if (isWebRole) { // Generate cache scaffolding for web role cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WebRole.ToString()), roleName, new Dictionary <string, object>()); // Adjust web.config to enable auto discovery for the caching role. string webCloudConfigPath = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebCloudConfig); string webConfigPath = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebConfigTemplateFileName); UpdateWebConfig(roleName, cacheWorkerRole, webCloudConfigPath); UpdateWebConfig(roleName, cacheWorkerRole, webConfigPath); } else { // Generate cache scaffolding for worker role Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters[ScaffoldParams.RoleName] = cacheWorkerRole; cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WorkerRole.ToString()), roleName, parameters); } // Add default memcache internal endpoint. InternalEndpoint memcacheEndpoint = new InternalEndpoint { name = Resources.MemcacheEndpointName, protocol = InternalProtocol.tcp, port = Resources.MemcacheEndpointPort }; endpoints.InternalEndpoint = GeneralUtilities.ExtendArray <InternalEndpoint>(endpoints.InternalEndpoint, memcacheEndpoint); // Enable cache diagnostic LocalStore localStore = new LocalStore { name = Resources.CacheDiagnosticStoreName, cleanOnRoleRecycle = false }; localResources.LocalStorage = GeneralUtilities.ExtendArray <LocalStore>(localResources.LocalStorage, localStore); DefinitionConfigurationSetting diagnosticLevel = new DefinitionConfigurationSetting { name = Resources.CacheClientDiagnosticLevelAssemblyName }; configurationSettings = GeneralUtilities.ExtendArray <DefinitionConfigurationSetting>(configurationSettings, diagnosticLevel); // Add ClientDiagnosticLevel setting to service configuration. AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetCloudConfigRole(roleName)); AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetLocalConfigRole(roleName)); }
/// <summary> /// Makes The String Representation Of The Object /// </summary> /// <returns>The String Representation Of The Object</returns> public override string ToString() { return(GeneralUtilities.ToString(this)); }
protected void Page_Load(object sender, EventArgs e) { Master.ActivateTab(AdminBaseMasterPage.SectionID.UserAdmin); userID = GetGuidIDFromQuery(); btnApply.Visible = SecurityData.IsAdmin; if (!IsPostBack) { if (userID != Guid.Empty) { var dsRoles = SecurityData.GetRoleListRestricted(); ExtendedUserData exUsr = new ExtendedUserData(userID); CheckBox chkSelected = null; gvSites.Visible = false; if (SecurityData.IsAdmin) { gvSites.Visible = true; GeneralUtilities.BindDataBoundControl(gvSites, SiteData.GetSiteList()); List <SiteData> lstSites = exUsr.GetSiteList(); chkSelected = null; if (lstSites.Any()) { HiddenField hdnSiteID = null; foreach (GridViewRow dgItem in gvSites.Rows) { hdnSiteID = (HiddenField)dgItem.FindControl("hdnSiteID"); if (hdnSiteID != null) { Guid locID = new Guid(hdnSiteID.Value); chkSelected = (CheckBox)dgItem.FindControl("chkSelected"); int ct = (from l in lstSites where l.SiteID == locID select l).Count(); if (ct > 0) { chkSelected.Checked = true; } } } } } MembershipUser usr = Membership.GetUser(userID); Email.Text = usr.Email; lblUserName.Text = usr.UserName; UserName.Text = usr.UserName; lblUserName.Visible = true; UserName.Visible = false; chkLocked.Checked = usr.IsLockedOut; txtNickName.Text = exUsr.UserNickName; txtFirstName.Text = exUsr.FirstName; txtLastName.Text = exUsr.LastName; reBody.Text = exUsr.UserBio; GeneralUtilities.BindDataBoundControl(gvRoles, dsRoles); chkSelected = null; HiddenField hdnRoleId = null; foreach (GridViewRow dgItem in gvRoles.Rows) { hdnRoleId = (HiddenField)dgItem.FindControl("hdnRoleId"); if (hdnRoleId != null) { chkSelected = (CheckBox)dgItem.FindControl("chkSelected"); if (Roles.IsUserInRole(usr.UserName, hdnRoleId.Value)) { chkSelected.Checked = true; } } } } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); switch (ParameterSetName) { case IdParameterSet: { var resource = new ResourceIdentifier(Id); ResourceGroupName = resource.ResourceGroupName; Name = resource.ResourceName; break; } case InputObjectParameterSet: { var resource = new ResourceIdentifier(InputObject.Id); ResourceGroupName = resource.ResourceGroupName; Name = resource.ResourceName; break; } } RunCmdLet(() => { if (!GeneralUtilities.Probe("kubectl")) { throw new CmdletInvocationException(Resources.KubectlIsRequriedToBeInstalledAndOnYourPathToExecute); } var tmpFileName = Path.GetTempFileName(); var encoded = Client.ManagedClusters.GetAccessProfiles(ResourceGroupName, Name, "clusterUser") .KubeConfig; AzureSession.Instance.DataStore.WriteFile( tmpFileName, Encoding.UTF8.GetString(Convert.FromBase64String(encoded))); WriteVerbose(string.Format( Resources.RunningKubectlGetPodsKubeconfigNamespaceSelector, tmpFileName)); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "kubectl", Arguments = $"get pods --kubeconfig {tmpFileName} --namespace kube-system --output name --selector k8s-app=kubernetes-dashboard", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); var dashPodName = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); // remove "pods/" dashPodName = dashPodName.Substring(5).TrimEnd('\r', '\n'); WriteVerbose(string.Format( Resources.RunningInBackgroundJobKubectlTunnel, tmpFileName, dashPodName)); var exitingJob = JobRepository.Jobs.FirstOrDefault(j => j.Name == "Kubectl-Tunnel"); if (exitingJob != null) { WriteVerbose(Resources.StoppingExistingKubectlTunnelJob); exitingJob.StopJob(); JobRepository.Remove(exitingJob); } var job = new KubeTunnelJob(tmpFileName, dashPodName); if (!DisableBrowser) { WriteVerbose(Resources.SettingUpBrowserPop); job.StartJobCompleted += (sender, evt) => { WriteVerbose(string.Format(Resources.StartingBrowser, ProxyUrl)); PopBrowser(ProxyUrl); }; } JobRepository.Add(job); job.StartJob(); WriteObject(job); }); }
protected void Page_Load(object sender, EventArgs e) { DatabaseUpdate du = new DatabaseUpdate(true); if (!String.IsNullOrEmpty(Request.QueryString["signout"])) { FormsAuthentication.SignOut(); } List <DatabaseUpdateMessage> lst = new List <DatabaseUpdateMessage>(); btnLogin.Visible = false; btnCreate.Visible = false; if (DatabaseUpdate.LastSQLError != null) { du.HandleResponse(lst, DatabaseUpdate.LastSQLError); DatabaseUpdate.LastSQLError = null; } else { bool bUpdate = true; if (!du.DoCMSTablesExist()) { bUpdate = false; } bUpdate = du.DatabaseNeedsUpdate(); if (bUpdate) { DatabaseUpdateStatus status = du.PerformUpdates(); lst = du.MergeMessages(lst, status.Messages); } else { DataInfo ver = DatabaseUpdate.GetDbSchemaVersion(); du.HandleResponse(lst, "Database up-to-date [" + ver.DataValue + "] "); } bUpdate = du.DatabaseNeedsUpdate(); if (!bUpdate && DatabaseUpdate.LastSQLError == null) { if (DatabaseUpdate.UsersExist) { btnLogin.Visible = true; } else { btnCreate.Visible = true; } } } if (DatabaseUpdate.LastSQLError != null) { du.HandleResponse(lst, DatabaseUpdate.LastSQLError); } if (lst.Where(x => !String.IsNullOrEmpty(x.ExceptionText)).Count() > 0) { bOK = false; } else { bOK = true; } GeneralUtilities.BindRepeater(rpMessages, lst.OrderBy(x => x.Order)); using (CMSConfigHelper cmsHelper = new CMSConfigHelper()) { cmsHelper.ResetConfigs(); } }
public static string ConstructDeploymentVariableTable(Dictionary <string, DeploymentVariable> dictionary) { if (dictionary == null) { return(null); } StringBuilder result = new StringBuilder(); if (dictionary.Count > 0) { string rowFormat = "{0, -15} {1, -25} {2, -10}\r\n"; result.AppendLine(); result.AppendFormat(rowFormat, "Name", "Type", "Value"); result.AppendFormat(rowFormat, GeneralUtilities.GenerateSeparator(15, "="), GeneralUtilities.GenerateSeparator(25, "="), GeneralUtilities.GenerateSeparator(10, "=")); foreach (KeyValuePair <string, DeploymentVariable> pair in dictionary) { result.AppendFormat(rowFormat, pair.Key, pair.Value.Type, pair.Value.Value); } } return(result.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="Pictures"/> class. /// </summary> /// <param name="numberOfPictures">The number of pictures these pictures hold.</param> public Pictures(int numberOfPictures) : this(GeneralUtilities.ExecuteNTimes(numberOfPictures, () => new Picture()).ToList()) { }
protected void SetGrid(bool bAll, DateTime dateRange, int dateRangeDays) { List <ContentPage> lstContent = null; if (bAll) { dateRangeDays = -1; } ContentPageType.PageType pageType = ContentPageType.PageType.Unknown; if (rdoPost.Checked) { pageType = ContentPageType.PageType.BlogEntry; } if (rdoPage.Checked) { pageType = ContentPageType.PageType.ContentEntry; } lstContent = pageHelper.GetContentByDateRange(SiteID, dateRange, dateRangeDays, pageType, GeneralUtilities.GetNullableBoolValue(ddlActive), GeneralUtilities.GetNullableBoolValue(ddlSiteMap), GeneralUtilities.GetNullableBoolValue(ddlNavigation), GeneralUtilities.GetNullableBoolValue(ddlHide)); lblPages.Text = string.Format(" {0} ", lstContent.Count); GeneralUtilities.BindDataBoundControl(gvPages, lstContent); }
protected void rpProps_Bind(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { HiddenField hdnName = (HiddenField)e.Item.FindControl("hdnName"); TextBox txtValue = (TextBox)e.Item.FindControl("txtValue"); DropDownList ddlValue = (DropDownList)e.Item.FindControl("ddlValue"); CheckBox chkValue = (CheckBox)e.Item.FindControl("chkValue"); CheckBoxList chkValues = (CheckBoxList)e.Item.FindControl("chkValues"); txtValue.Visible = true; string sName = hdnName.Value; ObjectProperty ListSourceProperty = new ObjectProperty(); string sListSourcePropertyName = (from p in lstDefProps where p.Name.ToLower() == sName.ToLower() && !String.IsNullOrEmpty(p.CompanionSourceFieldName) select p.CompanionSourceFieldName).FirstOrDefault(); if (String.IsNullOrEmpty(sListSourcePropertyName)) { sListSourcePropertyName = String.Empty; } ListSourceProperty = (from p in lstDefProps where p.CanRead == true && p.CanWrite == false && p.Name.ToLower() == sListSourcePropertyName.ToLower() select p).FirstOrDefault(); var dp = (from p in lstDefProps where p.Name.ToLower() == sName.ToLower() select p).FirstOrDefault(); if (ListSourceProperty != null) { if (ListSourceProperty.DefValue is Dictionary <string, string> ) { txtValue.Visible = false; //work with a drop down list, only allow one item in the drop down. if (dp.FieldMode == WidgetAttribute.FieldMode.DropDownList) { ddlValue.Visible = true; ddlValue.DataTextField = "Value"; ddlValue.DataValueField = "Key"; GeneralUtilities.BindListDefaultText(ddlValue, ListSourceProperty.DefValue, null, "Select Value", ""); if (!String.IsNullOrEmpty(txtValue.Text)) { try { GeneralUtilities.SelectListValue(ddlValue, txtValue.Text); } catch { } } } // work with a checkbox list, allow more than one value if (dp.FieldMode == WidgetAttribute.FieldMode.CheckBoxList) { chkValues.Visible = true; chkValues.DataTextField = "Value"; chkValues.DataValueField = "Key"; GeneralUtilities.BindList(chkValues, ListSourceProperty.DefValue); // since this is a multi selected capable field, look for anything that starts with the // field name and has the delimeter trailing var pp = (from p in lstProps where p.KeyName.ToLower().StartsWith(sName.ToLower() + "|") select p).ToList(); if (pp.Any()) { foreach (ListItem v in chkValues.Items) { v.Selected = (from p in pp where p.KeyValue == v.Value select p.KeyValue).Count() < 1 ? false : true; } } } } } if (dp.FieldMode == WidgetAttribute.FieldMode.RichHTMLTextBox || dp.FieldMode == WidgetAttribute.FieldMode.MultiLineTextBox) { txtValue.Visible = true; txtValue.TextMode = TextBoxMode.MultiLine; txtValue.Columns = 60; txtValue.Rows = 5; if (dp.FieldMode == WidgetAttribute.FieldMode.RichHTMLTextBox) { txtValue.CssClass = "mceEditor"; } } if (dp.PropertyType == typeof(bool) || dp.FieldMode == WidgetAttribute.FieldMode.CheckBox) { txtValue.Visible = false; chkValue.Visible = true; chkValue.Checked = Convert.ToBoolean(txtValue.Text); } } }
public virtual void NewPaaSDeploymentProcess() { bool removePackage = false; AssertNoPersistenVmRoleExistsInDeployment(PVM.DeploymentSlotType.Production); AssertNoPersistenVmRoleExistsInDeployment(PVM.DeploymentSlotType.Staging); var storageName = Profile.Context.Subscription.GetProperty(AzureSubscription.Property.StorageAccount); Uri packageUrl; if (this.Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || this.Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { packageUrl = new Uri(this.Package); } else { if (string.IsNullOrEmpty(storageName)) { throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet); } var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage); WriteProgress(progress); removePackage = true; packageUrl = this.RetryCall(s => AzureBlob.UploadPackageToBlob( this.StorageClient, storageName, this.Package, null)); } ExtensionConfiguration extConfig = null; if (ExtensionConfiguration != null) { string errorConfigInput = null; if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } foreach (ExtensionConfigurationInput context in ExtensionConfiguration) { if (context != null && context.X509Certificate != null) { ExecuteClientActionNewSM( null, string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint), () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate))); } } Func <DeploymentSlot, DeploymentGetResponse> func = t => { DeploymentGetResponse d = null; try { d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, t); } catch (CloudException ex) { if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false) { WriteExceptionError(ex); } } return(d); }; var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true); DeploymentGetResponse currentDeployment = null; InvokeInOperationContext(() => currentDeployment = func(slotType)); var peerSlottype = slotType == DeploymentSlot.Production ? DeploymentSlot.Staging : DeploymentSlot.Production; DeploymentGetResponse peerDeployment = null; InvokeInOperationContext(() => peerDeployment = func(peerSlottype)); ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName); extConfig = extensionMgr.Set(currentDeployment, peerDeployment, ExtensionConfiguration, this.Slot); } var deploymentInput = new DeploymentCreateParameters { PackageUri = packageUrl, Configuration = GeneralUtilities.GetConfiguration(this.Configuration), ExtensionConfiguration = extConfig, Label = this.Label, Name = this.Name, StartDeployment = !this.DoNotStart.IsPresent, TreatWarningsAsError = this.TreatWarningsAsError.IsPresent, }; InvokeInOperationContext(() => { try { var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.CreatingNewDeployment); WriteProgress(progress); ExecuteClientActionNewSM( deploymentInput, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.Create( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), deploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.StorageClient, storageName, packageUrl)); } } catch (CloudException ex) { WriteExceptionError(ex); } }); }
public void TrueWhenProgramDoesExistTest() { Assert.True(GeneralUtilities.Probe(_pwsh, " -c 'echo hello world!'")); }