/// <summary> /// 会员注册 /// </summary> public HttpResponseMessage MemberRegist(RequestModel request) { var result = WebHelper.GetResult <string>(request); if (result.Code == EnumHelper.GetValue(EnumResultCode.操作成功)) { string receiver = "", mobile = JsonHelper.GetValue(request.Obj, "Mobile"), email = JsonHelper.GetValue(request.Obj, "Email"), code = JsonHelper.GetValue(request.Obj, "Code"), pwd = JsonHelper.GetValue(request.Obj, "Pwd"), nameTag = JsonHelper.GetValue(request.Obj, "NameTag"), sendType = JsonHelper.GetValue(request.Obj, "SendType"); Guid taskId = GuidHelper.Get(JsonHelper.GetValue(request.Obj, "TaskId")); #region 入信息判断 if (VerifyHelper.IsEmpty(sendType) || (sendType != KeyModel.Config.Template.KeyRegistMobile && sendType != KeyModel.Config.Template.KeyRegistEmail)) { throw new MessageException(EnumMessageCode.信息错误); } if ((VerifyHelper.IsEmpty(mobile) && VerifyHelper.IsEmpty(email)) || VerifyHelper.IsEmpty(taskId)) { throw new MessageException(EnumMessageCode.信息错误); } if (sendType == KeyModel.Config.Template.KeyRegistMobile && VerifyHelper.IsEmpty(mobile)) { throw new MessageException(EnumMessageCode.请输入手机号码); } if (sendType == KeyModel.Config.Template.KeyRegistEmail && VerifyHelper.IsEmpty(email)) { throw new MessageException(EnumMessageCode.请输入邮箱地址); } if (VerifyHelper.IsEmpty(pwd)) { throw new MessageException(EnumMessageCode.请输入密码); } if (VerifyHelper.IsEmpty(code)) { throw new MessageException(EnumMessageCode.请输入验证码); } #endregion receiver = sendType == KeyModel.Config.Template.KeyRegistMobile ? mobile : email; //验证码效验 bool isSuccess = notificationService.ConfirmVerifyCode(taskId, receiver, code, request.CurrentContext.VisitId); if (!isSuccess) { throw new MessageException(EnumMessageCode.验证码错误); } //注册 var entity = memberService.Regist(receiver, email, mobile, pwd, nameTag, BrowserHelper.GetClientIP()); if (VerifyHelper.IsEmpty(entity)) { throw new MessageException(EnumMessageCode.注册失败); } //首次注册,送100元, 添加充值记录信息 rechargeRecordService.Insert(new RechargeRecordEntity { AccountId = entity.Id, MoneyValue = 100, Descript = "注册赠送", CreateId = entity.Id, CreateDt = DateTime.Now, LastId = entity.Id, LastDt = DateTime.Now }); //返回 if (!VerifyHelper.IsEmpty(entity) && !VerifyHelper.IsEmpty(entity.Id)) { notificationService.ExpireVerifyCode(taskId); WebHelper.SetMember(entity); result.Code = EnumHelper.GetValue(EnumResultCode.跳转地址); result.Redirect = UrlsHelper.GetRefUrl(defaultUrl: WebHelper.GetMemberUrl()); } } return(WebApiHelper.ToHttpResponseMessage(result)); }
/// <summary> /// 找回密码 /// </summary> public HttpResponseMessage MemberForgetPwd(RequestModel request) { var result = WebHelper.GetResult <string>(request); if (result.Code == EnumHelper.GetValue(EnumResultCode.操作成功)) { string receiver = "", mobile = JsonHelper.GetValue(request.Obj, "Mobile"), email = JsonHelper.GetValue(request.Obj, "Email"), code = JsonHelper.GetValue(request.Obj, "Code"), pwd = JsonHelper.GetValue(request.Obj, "Pwd"), sendType = JsonHelper.GetValue(request.Obj, "SendType"); Guid taskId = GuidHelper.Get(JsonHelper.GetValue(request.Obj, "TaskId")); #region 入信息判断 if (VerifyHelper.IsEmpty(sendType) || (sendType != KeyModel.Config.Template.KeyForgetPwdMobile && sendType != KeyModel.Config.Template.KeyForgetPwdEmail)) { throw new MessageException(EnumMessageCode.信息错误); } if ((VerifyHelper.IsEmpty(mobile) && VerifyHelper.IsEmpty(email)) || VerifyHelper.IsEmpty(taskId)) { throw new MessageException(EnumMessageCode.信息错误); } if (sendType == KeyModel.Config.Template.KeyForgetPwdMobile && VerifyHelper.IsEmpty(mobile)) { throw new MessageException(EnumMessageCode.请输入手机号码); } if (sendType == KeyModel.Config.Template.KeyForgetPwdEmail && VerifyHelper.IsEmpty(email)) { throw new MessageException(EnumMessageCode.请输入邮箱地址); } if (VerifyHelper.IsEmpty(pwd)) { throw new MessageException(EnumMessageCode.请输入密码); } if (VerifyHelper.IsEmpty(code)) { throw new MessageException(EnumMessageCode.请输入验证码); } #endregion receiver = sendType == KeyModel.Config.Template.KeyForgetPwdMobile ? mobile : email; //验证码效验 bool isSuccess = notificationService.ConfirmVerifyCode(taskId, receiver, code, request.CurrentContext.VisitId); if (!isSuccess) { throw new MessageException(EnumMessageCode.验证码错误); } //找回密码修改 var entity = memberService.MemberForgetPwd(email, mobile, pwd, BrowserHelper.GetClientIP()); if (VerifyHelper.IsEmpty(entity)) { throw new MessageException(EnumMessageCode.找回密码失败); } //返回 if (!VerifyHelper.IsEmpty(entity) && !VerifyHelper.IsEmpty(entity.Id)) { notificationService.ExpireVerifyCode(taskId); WebHelper.SetMember(entity); result.Code = EnumHelper.GetValue(EnumResultCode.跳转地址); result.Redirect = UrlsHelper.GetRefUrl(defaultUrl: WebHelper.GetMemberUrl()); } } return(WebApiHelper.ToHttpResponseMessage(result)); }
internal static PnPConnection CreateWithDeviceLogin(string clientId, string url, string tenantId, bool launchBrowser, CmdletMessageWriter messageWriter, AzureEnvironment azureEnvironment, CancellationTokenSource cancellationTokenSource) { var connectionUri = new Uri(url); var scopes = new[] { $"{connectionUri.Scheme}://{connectionUri.Authority}//.default" }; // the second double slash is not a typo. PnP.Framework.AuthenticationManager authManager = null; if (PnPConnection.CachedAuthenticationManager != null) { authManager = PnPConnection.CachedAuthenticationManager; PnPConnection.CachedAuthenticationManager = null; } else { authManager = PnP.Framework.AuthenticationManager.CreateWithDeviceLogin(clientId, tenantId, (deviceCodeResult) => { if (launchBrowser) { if (Utilities.OperatingSystem.IsWindows()) { ClipboardService.SetText(deviceCodeResult.UserCode); messageWriter.WriteWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard\n\n"); BrowserHelper.GetWebBrowserPopup(deviceCodeResult.VerificationUrl, "Please log in", cancellationTokenSource: cancellationTokenSource, cancelOnClose: false); } else { messageWriter.WriteWarning($"\n\n{deviceCodeResult.Message}\n\n"); } } else { messageWriter.WriteWarning($"\n\n{deviceCodeResult.Message}\n\n"); } return(Task.FromResult(0)); }, azureEnvironment); } using (authManager) { try { var clientContext = authManager.GetContext(url.ToString(), cancellationTokenSource.Token); var context = PnPClientContext.ConvertFrom(clientContext); context.ExecutingWebRequest += (sender, e) => { e.WebRequestExecutor.WebRequest.UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version} ({System.Environment.OSVersion.VersionString})"; }; var connectionType = ConnectionType.O365; var spoConnection = new PnPConnection(context, connectionType, null, clientId, null, url.ToString(), null, PnPPSVersionTag, InitializationType.DeviceLogin) { ConnectionMethod = ConnectionMethod.DeviceLogin, AzureEnvironment = azureEnvironment }; return(spoConnection); } catch (Microsoft.Identity.Client.MsalServiceException msalServiceException) { if (msalServiceException.Message.StartsWith("AADSTS50059:")) { cancellationTokenSource.Cancel(); throw new Exception("Please specify -Tenant with either the tenant id or hostname."); } else { throw; } } } }
/// <summary> /// 会员登录 /// </summary> public HttpResponseMessage MemberLogin(RequestModel request) { var result = WebHelper.GetResult <string>(request); if (result.Code == EnumHelper.GetValue(EnumResultCode.操作成功)) { var model = memberService.Login(StringHelper.Get(request.Obj["account"]), StringHelper.Get(request.Obj["password"]), BrowserHelper.GetClientIP()); if (!VerifyHelper.IsEmpty(model) && !VerifyHelper.IsEmpty(model.Id)) { WebHelper.SetMember(model); result.Code = EnumHelper.GetValue(EnumResultCode.跳转地址); result.Redirect = UrlsHelper.GetRefUrl(defaultUrl: WebHelper.GetMemberUrl()); } } return(WebApiHelper.ToHttpResponseMessage(result)); }
private void SecurityScoreOkClick(object obj) { MainpageHitTestTrueOpacity(); SecurityUpdatePopupVisibility = false; BrowserHelper.OpenInDefaultBrowser(new Uri(RedirectUrl, UriKind.RelativeOrAbsolute)); }
public bool TryCreateColumnContent(int index, string columnName, bool singleColumnView, out FrameworkElement content) { content = default(FrameworkElement); if (columnName != ShimTableColumnDefinitions.ErrorCode) { return(false); } var item = GetItem(index); if (item == null) { return(false); } Uri unused; if (BrowserHelper.TryGetUri(item.HelpLink, out unused)) { content = GetOrCreateTextBlock(ref _errorCodes, this.Count, index, item, i => GetHyperLinkTextBlock(i, new Uri(i.HelpLink, UriKind.Absolute), bingLink: false)); return(true); } if (!string.IsNullOrWhiteSpace(item.Id)) { // TODO: once we link descriptor with diagnostic, get en-us message for Uri creation content = GetOrCreateTextBlock(ref _errorCodes, this.Count, index, item, i => GetHyperLinkTextBlock(i, BrowserHelper.CreateBingQueryUri(item.Id, item.MessageFormat), bingLink: true)); return(true); } return(false); }
// use local token and lock on instance private void OnConnectionChanged(object sender, bool connected) { if (connected) { return; } if (_shutdownCancellationTokenSource.IsCancellationRequested) { lock (_gate) { // RemoteHost has been disabled _instanceTask = null; } } else { lock (_gate) { // save last remoteHostClient s_lastInstanceTask = _instanceTask; // save NoOpRemoteHostClient to instance so that all RemoteHost call becomes // No Op. this basically have same effect as disabling all RemoteHost features _instanceTask = Task.FromResult <RemoteHostClient>(new RemoteHostClient.NoOpClient(_workspace)); } // s_lastInstanceTask info should be saved in the dump // report NFW when connection is closed unless it is proper shutdown FatalError.ReportWithoutCrash(new Exception("Connection to remote host closed")); // use info bar to show warning to users _workspace.Services.GetService <IErrorReportingService>().ShowGlobalErrorInfo(ServicesVSResources.Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio, new ErrorReportingUI(ServicesVSResources.Learn_more, ErrorReportingUI.UIKind.HyperLink, () => BrowserHelper.StartBrowser(new Uri(OOPKilledMoreInfoLink)), closeAfterAction: false)); } }
public void OpenReadme() { BrowserHelper.TryOpenUrlIntegrated(GetUrl("readme")); }
private void LoadSettings() { config = new SharedFilesConfiguration(Settings); EditContentImage = WebConfigSettings.EditContentImage; lblError.Text = String.Empty; FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { return; } newWindowMarkup = displaySettings.NewWindowLinkMarkup; if (BrowserHelper.IsIE()) { //this is a needed hack because IE 8 doesn't work correctly with window.open // a "security feature" of IE 8 // unfortunately this is not valid xhtml to use target but it works in IE newWindowMarkup = displaySettings.IeNewWindowLinkMarkup; } if (!SharedFilesConfiguration.DownloadLinksOpenNewWindow) { newWindowMarkup = string.Empty; } TimeOffset = SiteUtils.GetUserTimeOffset(); timeZone = SiteUtils.GetUserTimeZone(); fileVirtualBasePath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/SharedFiles/"; try { // this keeps the action from changing during ajax postback in folder based sites SiteUtils.SetFormAction(Page, Request.RawUrl); } catch (MissingMethodException) { //this method was introduced in .NET 3.5 SP1 } btnUpload2.Visible = IsEditable; uploader.Visible = IsEditable; uploader.MaxFilesAllowed = SharedFilesConfiguration.MaxFilesToUploadAtOnce; uploader.ServiceUrl = SiteRoot + "/SharedFiles/upload.ashx?pageid=" + PageId.ToInvariantString() + "&mid=" + ModuleId.ToInvariantString(); uploader.FormFieldClientId = hdnCurrentFolderId.ClientID; uploader.UploadButtonClientId = btnUpload2.ClientID; if (IsEditable) { string refreshFunction = "function refresh" + ModuleId.ToInvariantString() + " () { $('#" + btnRefresh.ClientID + "').click(); } "; uploader.UploadCompleteCallback = "refresh" + ModuleId.ToInvariantString(); ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "refresh" + ModuleId.ToInvariantString(), refreshFunction, true); } if ((dgFile.TableCssClass.Contains("jqtable")) && (!WebConfigSettings.DisablejQuery)) { StringBuilder script = new StringBuilder(); script.Append("function setupJTable" + ModuleId.ToInvariantString() + "() {"); script.Append("$('#" + dgFile.ClientID + " th').each(function(){ "); script.Append("$(this).addClass('ui-state-default'); "); script.Append("}); "); script.Append("$('table.jqtable td').each(function(){ "); script.Append("$(this).addClass('ui-widget-content'); "); script.Append("}); "); script.Append("$('table.jqtable tr').hover( "); script.Append("function() {"); script.Append("$(this).children('td').addClass('ui-state-hover'); "); script.Append("},function() {"); script.Append("$(this).children('td').removeClass('ui-state-hover'); "); script.Append("} "); script.Append("); "); script.Append("$('table.jqtable tr').click(function() { "); script.Append("$(this).children('td').toggleClass('ui-state-highlight'); "); script.Append("}); "); script.Append("} "); // end function script.Append("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(setupJTable" + ModuleId.ToInvariantString() + "); "); ScriptManager.RegisterStartupScript( this, this.GetType(), "jTable" + ModuleId.ToInvariantString(), script.ToString(), true); } trObjectCount.Visible = config.ShowObjectCount; if (config.InstanceCssClass.Length > 0) { pnlOuterWrap.SetOrAppendCss(config.InstanceCssClass); } if (WebConfigSettings.ForceLegacyFileUpload) { ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnUpload2); } }
protected void Page_Load(object sender, EventArgs e) { // Display panel with additional controls place holder if required if (DisplayControlsPanel) { pnlAdditionalControls.Visible = true; } // Display panel with site selector if (DisplaySiteSelectorPanel) { pnlSiteSelector.Visible = true; } bodyElem.Attributes["class"] = mBodyClass; CurrentDeviceInfo device = DeviceContext.CurrentDevice; if (!device.IsMobile) { // Footer - apply fixed position pnlFooterContent.Style.Add("position", "fixed"); pnlFooterContent.Style.Add("width", "100%"); pnlFooterContent.Style.Add("bottom", "0px"); } StringBuilder resizeScript = new StringBuilder(); resizeScript.Append(@" var headerElem = null; var footerElem = null; var contentElem = null; var jIframe = null; var jIframeContents = null; var oldClientWidth = 0; var oldClientHeight = 0; var dialogCMSHeaderPad = null; var dialogCKFooter = null; function ResizeWorkingAreaIE() { ResizeWorkingArea(); window.onresize = function() { ResizeWorkingArea(); }; } function ResizeWorkingArea() { if (headerElem == null) { headerElem = document.getElementById('divHeader'); } if (footerElem == null) { footerElem = document.getElementById('divFooter'); } if (contentElem == null) { contentElem = document.getElementById('divContent'); } if (dialogCMSHeaderPad == null) { dialogCMSHeaderPad = document.getElementById('CMSHeaderPad'); } if (dialogCKFooter == null) { dialogCKFooter = document.getElementById('CKFooter'); } if ((headerElem != null) && (footerElem != null) && (contentElem != null)) { var headerHeight = headerElem.offsetHeight + ((dialogCMSHeaderPad != null) ? dialogCMSHeaderPad.offsetHeight : 0); var footerHeight = footerElem.offsetHeight + ((dialogCKFooter != null) ? dialogCKFooter.offsetHeight : 0); var height = (document.body.offsetHeight - headerHeight - footerHeight); if (height > 0) { var h = (height > 0 ? height : '0') + 'px'; if (contentElem.style.height != h) { contentElem.style.height = h; } }"); if (device.IsMobile) { resizeScript.Append(@" if ((jIframe == null) || (!jIframe.length)) { jIframe = jQuery('.EditableTextEdit iframe:first'); } if ((jIframeContents == null) || (!jIframeContents.length)) { jIframeContents = jIframe.contents(); } // Set height of the iframe manually for mobile devices jIframe.css('height', jIframeContents.height()); // WebKit browsers fix - width of the parent element of the iframe needs to be defined jIframe.parent().width(jIframeContents.width());"); } if (BrowserHelper.IsIE()) { resizeScript.Append(@" var pnlBody = null; var formElem = null; var bodyElement = null; if (pnlBody == null) { pnlBody = document.getElementById('", pnlBody.ClientID, @"'); } if (formElem == null) { formElem = document.getElementById('", form1.ClientID, @"'); } if (bodyElement == null) { bodyElement = document.getElementById('", bodyElem.ClientID, @"'); } if ((bodyElement != null) && (formElem != null) && (pnlBody != null)) { var newClientWidth = document.documentElement.clientWidth; var newClientHeight = document.documentElement.clientHeight; if (newClientWidth != oldClientWidth) { bodyElement.style.width = newClientWidth; formElem.style.width = newClientWidth; pnlBody.style.width = newClientWidth; headerElem.style.width = newClientWidth; contentElem.style.width = newClientWidth; oldClientWidth = newClientWidth; } if (newClientHeight != oldClientHeight) { bodyElement.style.height = newClientHeight; formElem.style.height = newClientHeight; pnlBody.style.height = newClientHeight; oldClientHeight = newClientHeight; } }"); } resizeScript.Append(@" } if (window.afterResize) { window.afterResize(); } }"); if (BrowserHelper.IsIE()) { resizeScript.Append(@" var timer = setInterval('ResizeWorkingAreaIE();', 50);"); } else { resizeScript.Append(@" window.onresize = function() { ResizeWorkingArea(); }; window.onload = function() { ResizeWorkingArea(); };"); } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "resizeScript", ScriptHelper.GetScript(resizeScript.ToString())); if (BrowserHelper.IsIE7()) { ScriptHelper.RegisterStartupScript(this, typeof(string), "ie7ResizeFix", ScriptHelper.GetScript("document.getElementById('divContent').style.height = '0px';")); } // Register a script that will re-calculate content height when the CKToolbar is displayed const string ckEditorScript = @" if (window.CKEDITOR) { CKEDITOR.on('instanceCreated', function(e) { e.editor.on('instanceReady', function(e) { setTimeout(function() { ResizeWorkingArea(); }, 200); }); }); }"; ScriptHelper.RegisterStartupScript(this, typeof(string), "ckEditorScript", ckEditorScript, true); }
protected override void Render(HtmlTextWriter writer) { if (HttpContext.Current == null) { return; } if (!BrowserHelper.IsIE()) { return; } bool allowPageOverride = true; if (Page is mojoBasePage) { mojoBasePage basePage = (mojoBasePage)Page; allowPageOverride = basePage.AllowSkinOverride; cacheBuster = "?sv=" + basePage.SiteInfo.SkinVersion.ToString(); } string skinBaseUrl = overrideCssBaseUrl; if (skinBaseUrl.Length == 0) { skinBaseUrl = SiteUtils.DetermineSkinBaseUrl(true, false, Page); } string scriptBaseUrl = ResolveUrl("~/ClientScript/"); if (!WebConfigSettings.CacheCssInBrowser) { cacheBuster += "&cb=" + Guid.NewGuid().ToString(); } if (includeHtml5Script) { writer.Write("\n<!--[if IE]>\n"); writer.Write("<script src=\"" + scriptBaseUrl + "html5shiv.js?v=2\" type=\"text/javascript\"></script>\n"); writer.Write("\n<![endif]-->"); } // IE 6 if ((includeIE6) && (BrowserHelper.IsIE6())) { writer.Write("\n<!--[if lt IE 7]>\n"); if (includeIE7Script) { writer.Write("<script defer=\"defer\" src=\"" + scriptBaseUrl + "IE7.js\" type=\"text/javascript\"></script>\n"); } writer.Write("<link rel=\"stylesheet\" href=\"" + skinBaseUrl + ie6CssFile + cacheBuster + "\" type=\"text/css\" id=\"IE6CSS\" />\n"); writer.Write("<![endif]-->\n"); } if ((includeIE7) && (BrowserHelper.IsIE7())) { writer.Write("<!--[if IE 7]>\n"); if (includeIE8Script) { writer.Write("<script defer=\"defer\" src=\"" + scriptBaseUrl + "IE8.js\" type=\"text/javascript\"></script>\n"); } writer.Write("<link rel=\"stylesheet\" href=\"" + skinBaseUrl + ie7CssFile + cacheBuster + "\" type=\"text/css\" id=\"IE7CSS\" />\n"); writer.Write("<![endif]-->\n"); } if ((includeIE8) && (BrowserHelper.IsIE8())) { writer.Write("<!--[if IE 8]>\n"); writer.Write("<link rel=\"stylesheet\" href=\"" + skinBaseUrl + ie8CssFile + cacheBuster + "\" type=\"text/css\" id=\"IE8CSS\" />\n"); writer.Write("<![endif]-->\n"); } if ((includeIE9) && (BrowserHelper.IsIE9())) { writer.Write("<!--[if IE 9]>\n"); writer.Write("<link rel=\"stylesheet\" href=\"" + skinBaseUrl + ie9CssFile + cacheBuster + "\" type=\"text/css\" id=\"IE9CSS\" />\n"); writer.Write("<![endif]-->\n"); } if (includeIETransitionMeta) { writer.Write("\n<meta http-equiv=\"Page-Enter\" content=\"blendTrans(Duration=0)\" /><meta http-equiv=\"Page-Exit\" content=\"blendTrans(Duration=0)\" />"); } }
protected void Page_Load(object sender, EventArgs e) { // Check license LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.DocumentLibrary); // Propagate Check permissions to underlying components arrowContextMenu.CheckPermissions = rowContextMenu.CheckPermissions = CheckPermissions; if (StopProcessing || (LibraryNode == null)) { gridDocuments.StopProcessing = true; arrowContextMenu.StopProcessing = true; rowContextMenu.StopProcessing = true; copyElem.StopProcessing = true; deleteElem.StopProcessing = true; localizeElem.StopProcessing = true; propertiesElem.StopProcessing = true; permissionsElem.StopProcessing = true; versionsElem.StopProcessing = true; DocumentManager.StopProcessing = true; pnlHeader.Visible = false; if (LibraryNode == null) { lblError.Text = ResHelper.GetStringFormat("documentlibrary.libraryrootnotexist", LibraryPath); } } else { gridDocuments.OnDataReload += gridDocuments_OnDataReload; gridDocuments.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocuments.OrderBy = OrderBy; gridDocuments.IsLiveSite = IsLiveSite; copyTitle.IsLiveSite = IsLiveSite; propertiesTitle.IsLiveSite = IsLiveSite; permissionsElem.IsLiveSite = IsLiveSite; arrowContextMenu.IsLiveSite = IsLiveSite; arrowContextMenu.JavaScriptPrefix = JS_PREFIX; arrowContextMenu.DocumentForm = DocumentForm; rowContextMenu.IsLiveSite = IsLiveSite; rowContextMenu.JavaScriptPrefix = JS_PREFIX; rowContextMenu.DocumentForm = DocumentForm; DocumentManager.IsLiveSite = IsLiveSite; // Optimize context menu position for all supported browsers bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL()); if (BrowserHelper.IsGecko() || BrowserHelper.IsIE8()) { arrowContextMenu.OffsetX = isRTL ? 0 : -1; if (BrowserHelper.IsIE8()) { arrowContextMenu.OffsetY = 21; } } else if (BrowserHelper.IsIE7()) { arrowContextMenu.OffsetX = isRTL ? 0 : -2; } else if (BrowserHelper.IsWebKit()) { arrowContextMenu.OffsetX = isRTL ? -1 : 1; arrowContextMenu.OffsetY = 21; } // Register full postback ControlsHelper.RegisterPostbackControl(btnLocalizeSaveClose); // Ensure adequate z-index for UI dialogs ScriptHelper.RegisterStartupScript(this, typeof(string), "dialogZIndex", ScriptHelper.GetScript("window.dialogZIndex = 30000;")); // Action handling scripts StringBuilder actionScript = new StringBuilder(); actionScript.AppendLine("function SetParameter_" + ClientID + "(parameter)"); actionScript.AppendLine("{"); actionScript.AppendLine(" document.getElementById('" + hdnParameter.ClientID + "').value = parameter;"); actionScript.AppendLine("}"); actionScript.AppendLine("function " + Action.RefreshGridSimple + "_" + ClientID + "()"); actionScript.AppendLine("{"); actionScript.AppendLine(" " + ControlsHelper.GetPostBackEventReference(this, Action.RefreshGridSimple.ToString()) + ";"); actionScript.AppendLine("}"); actionScript.AppendLine("function " + Action.HidePopup + "_" + ClientID + "()"); actionScript.AppendLine("{"); actionScript.AppendLine(" " + ControlsHelper.GetPostBackEventReference(this, Action.HidePopup.ToString()) + ";"); actionScript.AppendLine("}"); actionScript.AppendLine("function " + Action.InitRefresh + "_" + ClientID + "(message, fullRefresh, mode)"); actionScript.AppendLine("{"); actionScript.AppendLine(" if(message != '')"); actionScript.AppendLine(" {"); actionScript.AppendLine(" alert(message);"); actionScript.AppendLine(" }"); actionScript.AppendLine(" else"); actionScript.AppendLine(" {"); actionScript.AppendLine(" " + Action.RefreshGridSimple + "_" + ClientID + "();"); actionScript.AppendLine(" }"); actionScript.AppendLine("}"); actionScript.AppendLine("function InitRefresh_" + arrowContextMenu.ClientID + "(message, fullRefresh, mode)"); actionScript.AppendLine("{"); actionScript.AppendLine(Action.InitRefresh + "_" + ClientID + "(message, fullRefresh, mode);"); actionScript.AppendLine("}"); actionScript.AppendLine("function InitRefresh_" + rowContextMenu.ClientID + "(message, fullRefresh, mode)"); actionScript.AppendLine("{"); actionScript.AppendLine(Action.InitRefresh + "_" + ClientID + "(message, fullRefresh, mode);"); actionScript.AppendLine("}"); actionScript.AppendLine("function " + JS_PREFIX + "PerformAction(parameter, action)"); actionScript.AppendLine("{"); actionScript.AppendLine(" SetParameter_" + ClientID + "(parameter);"); actionScript.AppendLine(" " + ControlsHelper.GetPostBackEventReference(this, "##PARAM##").Replace("'##PARAM##'", "action")); actionScript.AppendLine("}"); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "actionScript" + ClientID, ScriptHelper.GetScript(actionScript.ToString())); // Setup title elements localizeTitle.TitleText = GetString("documentlibrary.localizedocument"); copyTitle.TitleText = GetString("documentlibrary.copydocument"); deleteTitle.TitleText = GetString("documentlibrary.deletedocument"); propertiesTitle.TitleText = GetString("documentlibrary.documentproperties"); permissionsTitle.TitleText = GetString("documentlibrary.documentpermissions"); versionsTitle.TitleText = GetString("LibraryContextMenu.VersionHistory"); // Initialize new file uploader bool uploadVisible = (CurrentUser.IsAuthorizedPerDocument(LibraryNode, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed) && IsAuthorizedToCreate; uploadAttachment.Visible = uploadVisible; if (uploadVisible) { uploadAttachment.Text = GetString("documentlibrary.newdocument"); uploadAttachment.InnerElementClass = "LibraryUploader"; uploadAttachment.NodeParentNodeID = LibraryNode.NodeID; uploadAttachment.ParentElemID = ClientID; uploadAttachment.SourceType = MediaSourceEnum.Content; uploadAttachment.DisplayInline = true; uploadAttachment.IsLiveSite = IsLiveSite; uploadAttachment.NodeGroupID = GroupID; uploadAttachment.DocumentCulture = DocumentContext.CurrentDocumentCulture.CultureCode; uploadAttachment.CheckPermissions = true; uploadAttachment.Width = 100; // Set allowed extensions if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom") { // Load allowed extensions uploadAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], ""); } else { // Use site settings string siteName = SiteContext.CurrentSiteName; uploadAttachment.AllowedExtensions = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSUploadExtensions"); } uploadAttachment.ReloadData(); } // Check permissions, for group document library also group administrator can modify the permissions bool hasModifyPermission = (CurrentUser.IsAuthorizedPerDocument(LibraryNode, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.ModifyPermissions }) == AuthorizationResultEnum.Allowed) || IsGroupAdmin; if (!hasModifyPermission) { btnPermissions.AddCssClass("hidden"); } btnPermissions.Enabled = hasModifyPermission; pnlHeader.Visible = hasModifyPermission || uploadVisible; } }
/// <summary> /// Called by the Visual Studio Shell to notify components of a broadcast message. /// </summary> /// <param name="msg">The message identifier.</param> /// <param name="wParam">First parameter associated with the message.</param> /// <param name="lParam">Second parameter associated with the message.</param> /// <returns>S_OK always.</returns> public int OnBroadcastMessage(uint msg, IntPtr wParam, IntPtr lParam) { switch (msg) { case VSConstants.VSM_VIRTUALMEMORYLOW: case VSConstants.VSM_VIRTUALMEMORYCRITICAL: { if (!_alreadyLogged) { // record that we had hit critical memory barrier Logger.Log(FunctionId.VirtualMemory_MemoryLow, KeyValueLogMessage.Create(m => { // which message we are logging and memory left in bytes when this is called. m["MSG"] = msg; m["MemoryLeft"] = (long)wParam; })); _alreadyLogged = true; } _workspaceCacheService?.FlushCaches(); // turn off full solution analysis only if user option is on. if (ShouldTurnOffFullSolutionAnalysis((long)wParam)) { // turn our full solution analysis option off. // if user full solution analysis option is on, then we will show info bar to users to restore it. // if user full solution analysis option is off, then setting this doesn't matter. full solution analysis is already off. _workspace.Options = _workspace.Options.WithChangedOption(RuntimeOptions.FullSolutionAnalysis, false); if (IsUserOptionOn()) { // let user know full analysis is turned off due to memory concern. // make sure we show info bar only once for the same solution. _workspace.Options = _workspace.Options.WithChangedOption(RuntimeOptions.FullSolutionAnalysisInfoBarShown, true); _workspace.Services.GetService <IErrorReportingService>().ShowGlobalErrorInfo(ServicesVSResources.Visual_Studio_has_suspended_some_advanced_features_to_improve_performance, new InfoBarUI(ServicesVSResources.Re_enable, InfoBarUI.UIKind.Button, () => _workspace.Options = _workspace.Options.WithChangedOption(RuntimeOptions.FullSolutionAnalysis, true)), new InfoBarUI(ServicesVSResources.Learn_more, InfoBarUI.UIKind.HyperLink, () => BrowserHelper.StartBrowser(new Uri(LowVMMoreInfoLink)), closeAfterAction: false)); } } // turn off low latency GC mode. // once we hit this, not hitting "Out of memory" exception is more important than typing being smooth all the time. // once it is turned off, user will hit time to time keystroke which responsive time is more than 50ms. in our own perf lab, // about 1-2% was over 50ms with this off when we first introduced this GC mode. GCManager.TurnOffLowLatencyMode(); break; } } return(VSConstants.S_OK); }
public static int Main(string[] args) { NativeMemory.GetCurrentUnmanagedThreadId = () => (ulong)Pal.rvn_get_current_thread_id(); UseOnlyInvariantCultureInRavenDB(); SetCurrentDirectoryToServerPath(); string[] configurationArgs; try { configurationArgs = CommandLineSwitches.Process(args); } catch (CommandParsingException commandParsingException) { Console.WriteLine(commandParsingException.Message); CommandLineSwitches.ShowHelp(); return(1); } if (CommandLineSwitches.ShouldShowHelp) { CommandLineSwitches.ShowHelp(); return(0); } if (CommandLineSwitches.PrintVersionAndExit) { Console.WriteLine(ServerVersion.FullVersion); return(0); } new WelcomeMessage(Console.Out).Print(); var targetSettingsFile = new PathSetting(string.IsNullOrEmpty(CommandLineSwitches.CustomConfigPath) ? "settings.json" : CommandLineSwitches.CustomConfigPath); var destinationSettingsFile = new PathSetting("settings.default.json"); if (File.Exists(targetSettingsFile.FullPath) == false && File.Exists(destinationSettingsFile.FullPath)) //just in case { File.Copy(destinationSettingsFile.FullPath, targetSettingsFile.FullPath); } var configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath); if (configurationArgs != null) { configuration.AddCommandLine(configurationArgs); } configuration.Initialize(); LoggingSource.UseUtcTime = configuration.Logs.UseUtcTime; LoggingSource.Instance.MaxFileSizeInBytes = configuration.Logs.MaxFileSize.GetValue(SizeUnit.Bytes); LoggingSource.Instance.SetupLogMode( configuration.Logs.Mode, configuration.Logs.Path.FullPath, configuration.Logs.RetentionTime?.AsTimeSpan, configuration.Logs.RetentionSize?.GetValue(SizeUnit.Bytes), configuration.Logs.Compress ); if (Logger.IsInfoEnabled) { Logger.Info($"Logging to {configuration.Logs.Path} set to {configuration.Logs.Mode} level."); } LatestVersionCheck.Instance.Initialize(configuration.Updates); if (Logger.IsOperationsEnabled) { Logger.Operations(RavenCli.GetInfoText()); } if (WindowsServiceRunner.ShouldRunAsWindowsService()) { try { WindowsServiceRunner.Run(CommandLineSwitches.ServiceName, configuration, configurationArgs); } catch (Exception e) { if (Logger.IsInfoEnabled) { Logger.Info("Error running Windows Service", e); } return(1); } return(0); } RestartServer = () => { RestartServerMre.Set(); ShutdownServerMre.Set(); }; var rerun = false; RavenConfiguration configBeforeRestart = configuration; do { if (rerun) { Console.WriteLine("\nRestarting Server..."); configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath); if (configurationArgs != null) { var argsAfterRestart = PostSetupCliArgumentsUpdater.Process( configurationArgs, configBeforeRestart, configuration); configuration.AddCommandLine(argsAfterRestart); configBeforeRestart = configuration; } configuration.Initialize(); } try { using (var server = new RavenServer(configuration)) { try { try { server.OpenPipes(); } catch (Exception e) { if (Logger.IsInfoEnabled) { Logger.Info("Unable to OpenPipe. Admin Channel will not be available to the user", e); } Console.WriteLine("Warning: Admin Channel is not available:" + e); } server.Initialize(); if (CommandLineSwitches.PrintServerId) { Console.WriteLine($"Server ID is {server.ServerStore.GetServerId()}."); } new RuntimeSettings(Console.Out).Print(); if (rerun == false && CommandLineSwitches.LaunchBrowser) { BrowserHelper.OpenStudioInBrowser(server.ServerStore.GetNodeHttpServerUrl()); } new ClusterMessage(Console.Out, server.ServerStore).Print(); var prevColor = Console.ForegroundColor; Console.Write("Server available on: "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{server.ServerStore.GetNodeHttpServerUrl()}"); Console.ForegroundColor = prevColor; var tcpServerStatus = server.GetTcpServerStatus(); if (tcpServerStatus.Listeners.Count > 0) { prevColor = Console.ForegroundColor; Console.Write("Tcp listening on "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{string.Join(", ", tcpServerStatus.Listeners.Select(l => l.LocalEndpoint))}"); Console.ForegroundColor = prevColor; } Console.WriteLine("Server started, listening to requests..."); prevColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("TIP: type 'help' to list the available commands."); Console.ForegroundColor = prevColor; if (configuration.Storage.IgnoreInvalidJournalErrors == true) { var message = $"Server is running in dangerous mode because {RavenConfiguration.GetKey(x => x.Storage.IgnoreInvalidJournalErrors)} was set. " + "It means that storages of databases, indexes and system one will be loaded regardless missing or corrupted journal files which " + "are mandatory to properly load the storage. " + "This switch is meant to be use only for recovery purposes. Please make sure that you won't use it on regular basis. "; if (Logger.IsOperationsEnabled) { Logger.Operations(message); } prevColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(message); Console.ForegroundColor = prevColor; } IsRunningNonInteractive = false; rerun = CommandLineSwitches.NonInteractive || configuration.Core.SetupMode == SetupMode.Initial ? RunAsNonInteractive() : RunInteractive(server); Console.WriteLine("Starting shut down..."); if (Logger.IsInfoEnabled) { Logger.Info("Server is shutting down"); } } catch (Exception e) { string message = null; if (e.InnerException is AddressInUseException) { message = $"{Environment.NewLine}Port might be already in use.{Environment.NewLine}Try running with an unused port.{Environment.NewLine}" + $"You can change the port using one of the following options:{Environment.NewLine}" + $"1) Change the ServerUrl property in setting.json file.{Environment.NewLine}" + $"2) Run the server from the command line with --ServerUrl option.{Environment.NewLine}" + $"3) Add RAVEN_ServerUrl to the Environment Variables.{Environment.NewLine}" + "For more information go to https://ravendb.net/l/EJS81M/4.2"; } else if (e is SocketException && PlatformDetails.RunningOnPosix) { const string extension = ".dll"; var ravenPath = typeof(RavenServer).Assembly.Location; if (ravenPath.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { ravenPath = ravenPath.Substring(0, ravenPath.Length - extension.Length); } message = $"{Environment.NewLine}In Linux low-level port (below 1024) will need a special permission, " + $"if this is your case please run{Environment.NewLine}" + $"sudo setcap CAP_NET_BIND_SERVICE=+eip {ravenPath}"; } if (Logger.IsOperationsEnabled) { Logger.Operations("Failed to initialize the server", e); Logger.Operations(message); } Console.WriteLine(message); Console.WriteLine(); Console.WriteLine(e); return(-1); } } Console.WriteLine("Shutdown completed"); } catch (Exception e) { Console.WriteLine("Error during shutdown"); Console.WriteLine(e); return(-2); } finally { if (Logger.IsOperationsEnabled) { Logger.OperationsAsync("Server has shut down").Wait(TimeSpan.FromSeconds(15)); } ShutdownCompleteMre.Set(); } } while (rerun); return(0); }
public UnionMangasSource(LibraryContext libraryContext, HtmlSourceHelper htmlHelper, BrowserHelper browserHelper) : base(libraryContext, htmlHelper, browserHelper) { }
public virtual void OpenChangelog() { BrowserHelper.TryOpenUrlIntegrated(GetUrl()); }
/// <summary> /// Gets row column content. /// </summary> /// <param name="dr">DataRow</param> /// <param name="dc">DataColumn</param> /// <param name="toCompare">Indicates if comparison will be used for content</param> /// <returns>String with column content</returns> private string GetRowColumnContent(DataRow dr, DataColumn dc, bool toCompare) { if (dr == null) { // Data row was not specified return(string.Empty); } if (!dr.Table.Columns.Contains(dc.ColumnName)) { // Data row does not contain the required column return(string.Empty); } var value = dr[dc.ColumnName]; if (DataHelper.IsEmpty(value)) { // Column is empty return(string.Empty); } var content = ValidationHelper.GetString(value, ""); Func <string> render = () => { if (toCompare) { return(content); } content = TextHelper.EnsureHTMLLineEndings(content); return(content); }; Func <string> standardRender = () => { if (toCompare) { return(content); } if (EncodeDisplayedData) { content = HTMLHelper.HTMLEncode(content); } content = content.Replace("\t", " "); content = "<div style=\"max-height: 300px; overflow: auto;\">" + content + "</div>"; content = TextHelper.EnsureLineEndings(content, "<br />"); return(content); }; // Binary columns if (dc.DataType == typeof(byte[])) { var data = (byte[])dr[dc.ColumnName]; content = string.Format("<{0}: {1}>", GetString("General.BinaryData"), DataHelper.GetSizeString(data.Length)); return(standardRender()); } // DataTime columns if (dc.DataType == typeof(DateTime)) { var dateTime = Convert.ToDateTime(content); var cultureInfo = CultureHelper.GetCultureInfo(MembershipContext.AuthenticatedUser.PreferredUICultureCode); content = dateTime.ToString(cultureInfo); return(standardRender()); } switch (dc.ColumnName.ToLowerCSafe()) { // Document content case "documentcontent": var sb = new StringBuilder(); Action <MultiKeyDictionary <string>, string, string> addItems = (dictionary, titleClass, textClass) => { foreach (DictionaryEntry item in dictionary) { var regionContent = HTMLHelper.ResolveUrls((string)item.Value, SystemContext.ApplicationPath); if (toCompare) { sb.AppendLine((string)item.Key); sb.AppendLine(regionContent); } else { sb.AppendFormat("<span class=\"{0}\">{1}</span>", titleClass, item.Key); sb.AppendFormat("<span class=\"{0}\">{1}</span>", textClass, HTMLHelper.HTMLEncode(regionContent)); } } }; var items = new EditableItems(); items.LoadContentXml(ValidationHelper.GetString(value, "")); // Add regions addItems(items.EditableRegions, "VersionEditableRegionTitle", "VersionEditableRegionText"); // Add web parts addItems(items.EditableWebParts, "VersionEditableWebPartTitle", "VersionEditableWebPartText"); content = sb.ToString(); return(render()); // XML columns case "pagetemplatewebparts": case "webpartproperties": case "reportparameters": case "classformdefinition": case "classxmlschema": case "classformlayout": case "userdialogsconfiguration": case "siteinvoicetemplate": case "userlastlogoninfo": case "formdefinition": case "formlayout": case "uservisibility": case "classsearchsettings": case "graphsettings": case "tablesettings": case "transformationhierarchicalxml": case "issuetext": case "savedreportparameters": // HTML columns case "emailtemplatetext": case "templatebody": case "templateheader": case "templatefooter": case "containertextbefore": case "containertextafter": case "savedreporthtml": case "layoutcode": case "webpartlayoutcode": case "transformationcode": case "reportlayout": if (BrowserHelper.IsIE()) { content = HTMLHelper.ReformatHTML(content, " "); } else { content = HTMLHelper.ReformatHTML(content); } break; // File columns case "metafilename": var metaFileName = HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["MetaFileName"], "")); if (ShowLinksForMetafiles) { var metaFileGuid = ValidationHelper.GetGuid(dr["MetaFileGuid"], Guid.Empty); if (metaFileGuid != Guid.Empty) { var metaFileUrl = ResolveUrl(MetaFileInfoProvider.GetMetaFileUrl(metaFileGuid, metaFileName)); content = string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", metaFileUrl, metaFileName); } } else { content = metaFileName; } return(render()); } return(standardRender()); }
public void OpenLicense() { BrowserHelper.TryOpenUrlIntegrated(GetUrl("license")); }
public override bool TryGetValue(int index, string columnName, out object content) { // REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async? // also, what is cancellation mechanism? var item = GetItem(index); if (item == null) { content = null; return(false); } var data = item.Data; switch (columnName) { case StandardTableKeyNames.ErrorRank: // build error gets highest rank content = ValueTypeCache.GetOrCreate(ErrorRank.Lexical); return(content != null); case StandardTableKeyNames.ErrorSeverity: content = ValueTypeCache.GetOrCreate(GetErrorCategory(data.Severity)); return(content != null); case StandardTableKeyNames.ErrorCode: content = data.Id; return(content != null); case StandardTableKeyNames.ErrorCodeToolTip: content = BrowserHelper.GetHelpLinkToolTip(data); return(content != null); case StandardTableKeyNames.HelpKeyword: content = data.Id; return(content != null); case StandardTableKeyNames.HelpLink: content = BrowserHelper.GetHelpLink(data)?.AbsoluteUri; return(content != null); case StandardTableKeyNames.ErrorCategory: content = data.Category; return(content != null); case StandardTableKeyNames.ErrorSource: content = ValueTypeCache.GetOrCreate(ErrorSource.Build); return(content != null); case StandardTableKeyNames.BuildTool: content = _source.BuildTool; return(content != null); case StandardTableKeyNames.Text: content = data.Message; return(content != null); case StandardTableKeyNames.DocumentName: content = GetFileName(data.DataLocation?.OriginalFilePath, data.DataLocation?.MappedFilePath); return(content != null); case StandardTableKeyNames.Line: content = data.DataLocation?.MappedStartLine ?? 0; return(true); case StandardTableKeyNames.Column: content = data.DataLocation?.MappedStartColumn ?? 0; return(true); case StandardTableKeyNames.ProjectName: content = item.ProjectName; return(content != null); case ProjectNames: var names = item.ProjectNames; content = names; return(names.Length > 0); case StandardTableKeyNames.ProjectGuid: content = ValueTypeCache.GetOrCreate(item.ProjectGuid); return((Guid)content != Guid.Empty); case ProjectGuids: var guids = item.ProjectGuids; content = guids; return(guids.Length > 0); case StandardTableKeyNames.SuppressionState: // Build doesn't support suppression. Contract.ThrowIfTrue(data.IsSuppressed); content = SuppressionState.NotApplicable; return(true); default: content = null; return(false); } }
internal static SPOnlineConnection InstantiateDeviceLoginConnection(string url, bool launchBrowser, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, Action <string> messageCallback, Action <string> progressCallback, Func <bool> cancelRequest, PSHost host, bool disableTelemetry) { SPOnlineConnection spoConnection = null; var connectionUri = new Uri(url); HttpClient client = new HttpClient(); var result = client.GetStringAsync($"https://login.microsoftonline.com/common/oauth2/devicecode?resource={connectionUri.Scheme}://{connectionUri.Host}&client_id={SPOnlineConnection.DeviceLoginAppId}").GetAwaiter().GetResult(); var returnData = JsonConvert.DeserializeObject <Dictionary <string, string> >(result); var context = new ClientContext(url); messageCallback(returnData["message"]); if (launchBrowser) { Utilities.Clipboard.Copy(returnData["user_code"]); messageCallback("Code has been copied to clipboard"); #if !NETSTANDARD2_0 BrowserHelper.OpenBrowser(returnData["verification_url"], (success) => { if (success) { var tokenResult = GetTokenResult(connectionUri, returnData, messageCallback, progressCallback, cancelRequest); if (tokenResult != null) { progressCallback("Token received"); spoConnection = new SPOnlineConnection(context, tokenResult, ConnectionType.O365, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry); } else { progressCallback("No token received."); } } }); #else OpenBrowser(returnData["verification_url"]); messageCallback(returnData["message"]); var tokenResult = GetTokenResult(connectionUri, returnData, messageCallback, progressCallback, cancelRequest); if (tokenResult != null) { progressCallback("Token received"); spoConnection = new SPOnlineConnection(context, tokenResult, ConnectionType.O365, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry); } else { progressCallback("No token received."); } #endif } else { var tokenResult = GetTokenResult(connectionUri, returnData, messageCallback, progressCallback, cancelRequest); if (tokenResult != null) { progressCallback("Token received"); spoConnection = new SPOnlineConnection(context, tokenResult, ConnectionType.O365, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry); } else { progressCallback("No token received."); } } spoConnection.ConnectionMethod = ConnectionMethod.DeviceLogin; return(spoConnection); }
/// <summary> /// Ensures text maximal line length /// </summary> /// <param name="text">Text in which length of line should be ensured</param> private string EnsureMaximumLineLength(string text) { return(TextHelper.EnsureMaximumLineLength(text, 50, BrowserHelper.IsIE() ? "<span></span>" : "<wbr>", false)); }