public void GenerateRandomAlpha_throws_for_negative_number() { // arrange var utils = new StringUtils(); // act & assert Assert.Throws<Exception>(()=>utils.GenerateRandomAlpha(-1)); }
public CommandHandler() { this.au = new ArrayUtils(); this.su = new StringUtils(); this.nu = new NumericalUtils(); this.pu = new PacketsUtils(); }
public void StringUtils_SimpleStringAndChar_ShouldCountChars() { var stringToScan = "TDD is awesome!"; var charToScan = "e"; var expectedResult = 2; var stringUtil = new StringUtils(); int result = stringUtil.scanOccurance(stringToScan, charToScan); Assert.AreEqual(expectedResult, result); }
public void StringUtils_ComplexStringAndChar_ShouldCountChars() { var stringToScan = "Once is unique, twice is a coincidence, three times is a pattern."; var charToScan = "n"; var expectedResult = 5; var stringUtil = new StringUtils(); int result = stringUtil.scanOccurance(stringToScan, charToScan); Assert.AreEqual(expectedResult, result); }
public void GenerateRandomAlpha_returns_empty_string_for_zero_length() { // arrange var utils = new StringUtils(); string expected = String.Empty; // act var actual = utils.GenerateRandomAlpha(0); // assert Assert.That(actual, Is.EqualTo(expected)); }
public void GenerateRandomAlpha_returns_string_of_correct_length() { // arrange var utils = new StringUtils(); var expected = 8; // act var actual = utils.GenerateRandomAlpha(8); // assert Assert.That(actual.Length, Is.EqualTo(expected)); }
public void GenerateRandomAlpha_returns_string_with_only_ascii_characters() { // arrange var utils = new StringUtils(); // act var actual = utils.GenerateRandomAlpha(8); // assert var regex = new Blobby.Utils.Regex(); var isAscii = regex.IsAscii(actual); Assert.True(isAscii); }
private static bool IsContentTemplateString(string itemType, string itemTypes, ref string templateString, LowerNameValueCollection selectedItems, LowerNameValueCollection selectedValues, PageInfo pageInfo, ContextInfo contextInfo) { if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedCurrent))//当前内容 { if (contextInfo.ContentInfo.Id == pageInfo.PageContentId) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedIsTop))//置顶内容 { if (contextInfo.ContentInfo.IsTop) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedImage))//带图片的内容 { if (!string.IsNullOrEmpty(contextInfo.ContentInfo.GetExtendedAttribute(BackgroundContentAttribute.ImageUrl))) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedVideo))//带视频的内容 { if (!string.IsNullOrEmpty(contextInfo.ContentInfo.GetExtendedAttribute(BackgroundContentAttribute.VideoUrl))) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedFile))//带附件的内容 { if (!string.IsNullOrEmpty(contextInfo.ContentInfo.GetExtendedAttribute(BackgroundContentAttribute.FileUrl))) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedIsRecommend))//推荐的内容 { if (TranslateUtils.ToBool(contextInfo.ContentInfo.GetExtendedAttribute(BackgroundContentAttribute.IsRecommend))) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedIsHot))//热点内容 { if (TranslateUtils.ToBool(contextInfo.ContentInfo.GetExtendedAttribute(BackgroundContentAttribute.IsHot))) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedIsColor))//醒目内容 { if (TranslateUtils.ToBool(contextInfo.ContentInfo.GetExtendedAttribute(BackgroundContentAttribute.IsColor))) { templateString = selectedItems.Get(itemTypes); return true; } } else if (StringUtils.EqualsIgnoreCase(itemType, StlItemTemplate.SelectedChannelName))//带有附件的内容 { if (selectedValues.Count > 0) { var nodeInfo = NodeManager.GetNodeInfo(contextInfo.ContentInfo.PublishmentSystemId, contextInfo.ContentInfo.NodeId); if (nodeInfo != null) { if (selectedValues.Get(nodeInfo.NodeName) != null) { templateString = selectedValues.Get(nodeInfo.NodeName); return true; } } } } else if (IsNumberInRange(contextInfo.ItemContainer.ContentItem.ItemIndex + 1, itemType)) { templateString = selectedItems.Get(itemTypes); return true; } return false; }
public static H3D IdentifyByMagic(Stream Stream, H3DDict <H3DBone> Skeleton, string FileName) { H3D Output = null; if (Stream.Length > 4) { BinaryReader Reader = new BinaryReader(Stream); uint MagicNum = Reader.ReadUInt32(); Stream.Seek(-4, SeekOrigin.Current); string Magic = Encoding.ASCII.GetString(Reader.ReadBytes(4)); Stream.Seek(0, SeekOrigin.Begin); if (Magic.StartsWith("BCH")) { return(H3D.Open(Reader.ReadBytes((int)Stream.Length))); } else if (Magic.StartsWith("MOD") && FileName != null) { return(LoadMTModel(Reader, FileName, Path.GetDirectoryName(FileName))); } else if (Magic.StartsWith("TEX") && FileName != null) { return(new MTTexture(Reader, Path.GetFileNameWithoutExtension(FileName)).ToH3D()); } else if (Magic.StartsWith("MFX")) { MTShader = new MTShaderEffects(Reader); } else if (Magic.StartsWith("CGFX")) { return(Gfx.Open(Stream)); } else if (Magic.StartsWith("CMIF")) { return(new CMIFFile(Stream).ToH3D()); } else { switch (MagicNum) { case GFModel.MagicNum: GFModel Model = new GFModel(Reader, "Model"); Output = Model.ToH3D(); Output.SourceData.Add(Model); break; case GFTexture.MagicNum: //Can be GFShader or GFTexture Reader.BaseStream.Seek(0x8, SeekOrigin.Current); string GFMagicStr = StringUtils.ReadPaddedString(Reader, 8); if (GFMagicStr == GFTexture.MagicStr) { Reader.BaseStream.Seek(-0x10, SeekOrigin.Current); Output = new H3D(); Output.Textures.Add(new GFTexture(Reader).ToH3DTexture()); } else { Reader.BaseStream.Seek(0x8, SeekOrigin.Current); GFMagicStr = StringUtils.ReadPaddedString(Reader, 8); if (GFMagicStr == GFShader.MagicStr) { Reader.BaseStream.Seek(-0x18, SeekOrigin.Current); Output = new H3D(); Output.SourceData.Add(new GFShader(Reader)); } } break; case GFModelPack.MagicNum: if (GFModelPack.IsModelPack(Reader)) { Output = new GFModelPack(Reader).ToH3D(); } break; case GFMotion.MagicNum: if (Skeleton != null) { Output = new H3D(); GFMotion Motion = new GFMotion(Reader, 0); H3DAnimation SklAnim = Motion.ToH3DSkeletalAnimation(Skeleton); H3DMaterialAnim MatAnim = Motion.ToH3DMaterialAnimation(); H3DAnimation VisAnim = Motion.ToH3DVisibilityAnimation(); if (SklAnim != null) { Output.SkeletalAnimations.Add(SklAnim); } if (MatAnim != null) { Output.MaterialAnimations.Add(MatAnim); } if (VisAnim != null) { Output.VisibilityAnimations.Add(VisAnim); } } break; } if (GFMotionPack.IsGFL2MotionPack(Reader)) { GFMotionPack Pack = new GFMotionPack(Reader); Output = Pack.ToH3D(Skeleton); } if (GF1MotionPack.IsGFL1MotionPack(Reader)) { Output = new GF1MotionPack(Reader).ToH3D(Skeleton); } } } return(Output); }
/// <summary> /// Resolves the name of the property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>The property name camel cased.</returns> protected internal override string ResolvePropertyName(string propertyName) { // lower case the first letter of the passed in name return(StringUtils.ToCamelCase(propertyName)); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateFargateProfileRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EKS"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-11-01"; request.HttpMethod = "POST"; if (!publicRequest.IsSetClusterName()) { throw new AmazonEKSException("Request object does not have required field ClusterName set"); } request.AddPathResource("{name}", StringUtils.FromString(publicRequest.ClusterName)); request.ResourcePath = "/clusters/{name}/fargate-profiles"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if (publicRequest.IsSetClientRequestToken()) { context.Writer.WritePropertyName("clientRequestToken"); context.Writer.Write(publicRequest.ClientRequestToken); } else if (!(publicRequest.IsSetClientRequestToken())) { context.Writer.WritePropertyName("clientRequestToken"); context.Writer.Write(Guid.NewGuid().ToString()); } if (publicRequest.IsSetFargateProfileName()) { context.Writer.WritePropertyName("fargateProfileName"); context.Writer.Write(publicRequest.FargateProfileName); } if (publicRequest.IsSetPodExecutionRoleArn()) { context.Writer.WritePropertyName("podExecutionRoleArn"); context.Writer.Write(publicRequest.PodExecutionRoleArn); } if (publicRequest.IsSetSelectors()) { context.Writer.WritePropertyName("selectors"); context.Writer.WriteArrayStart(); foreach (var publicRequestSelectorsListValue in publicRequest.Selectors) { context.Writer.WriteObjectStart(); var marshaller = FargateProfileSelectorMarshaller.Instance; marshaller.Marshall(publicRequestSelectorsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if (publicRequest.IsSetSubnets()) { context.Writer.WritePropertyName("subnets"); context.Writer.WriteArrayStart(); foreach (var publicRequestSubnetsListValue in publicRequest.Subnets) { context.Writer.Write(publicRequestSubnetsListValue); } context.Writer.WriteArrayEnd(); } if (publicRequest.IsSetTags()) { context.Writer.WritePropertyName("tags"); context.Writer.WriteObjectStart(); foreach (var publicRequestTagsKvp in publicRequest.Tags) { context.Writer.WritePropertyName(publicRequestTagsKvp.Key); var publicRequestTagsValue = publicRequestTagsKvp.Value; context.Writer.Write(publicRequestTagsValue); } context.Writer.WriteObjectEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return(request); }
public Topic SanitizeTopic(Topic topic) { topic.Name = StringUtils.SafePlainText(topic.Name); return(topic); }
// // This is an hack, since there can be multiple loggers. // However it's the most common use case and `mtouch` logs // are often the most important to gather and developers expect // a single change (in verbosity) to do the job and be consistent in CI. // // msbuild argument format // -verbosity:<level> Display this amount of information in the event log. // The available verbosity levels are: q[uiet], m[inimal], // n[ormal], d[etailed], and diag[nostic]. (Short form: -v) // static public string GetVerbosityLevel(string commandLine) { const string shortForm = "v:"; const string longForm = "verbosity:"; if (!StringUtils.TryParseArguments(commandLine, out var args, out _)) { return(GetVerbosityLevel(LoggerVerbosity.Normal)); } foreach (var arg in args) { // the minimum length we're looking for is `/v:q` if (arg.Length < 4) { continue; } // msbuild accepts two types of argument separator if (arg [0] != '/' && arg [0] != '-') { continue; } var verbosity = String.Empty; // short and long forms are possible, always case sensitive if (arg.IndexOf(shortForm, StringComparison.Ordinal) == 1) { // skip argument prefix (+1) and the (short) argument to get the verbosity level verbosity = arg.Substring(shortForm.Length + 1); } else if (arg.IndexOf(longForm, StringComparison.Ordinal) == 1) { verbosity = arg.Substring(longForm.Length + 1); } else { continue; } // case sensitive switch (verbosity) { case "q": case "quiet": return(GetVerbosityLevel(LoggerVerbosity.Quiet)); case "m": case "minimal": return(GetVerbosityLevel(LoggerVerbosity.Minimal)); case "n": case "normal": default: return(GetVerbosityLevel(LoggerVerbosity.Normal)); case "d": case "detailed": return(GetVerbosityLevel(LoggerVerbosity.Detailed)); case "diag": case "diagnostic": return(GetVerbosityLevel(LoggerVerbosity.Diagnostic)); } } // nothing is normal return(GetVerbosityLevel(LoggerVerbosity.Normal)); }
/// <summary> /// Add a new permission /// </summary> /// <param name="permission"></param> public void Add(Permission permission) { permission.Name = StringUtils.SafePlainText(permission.Name); _permissionRepository.Add(permission); }
/// <summary> /// Returns a paged amount of searched topics by a string search value /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="amountToTake"></param> /// <param name="searchTerm"></param> /// <returns></returns> public PagedList <Topic> SearchTopics(int pageIndex, int pageSize, int amountToTake, string searchTerm) { var search = StringUtils.SafePlainText(searchTerm); return(_topicRepository.SearchTopics(pageIndex, pageSize, amountToTake, search)); }
public string Serialize(Dictionary <string, string> dict) { return(StringUtils.FormatFromDictionary(Template, dict)); }
/// <summary> /// Writes a new Web specific entry into the log file /// /// Assumes that your log file is set up to be a Web Log file /// </summary> /// <param name="webEntry"></param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">Thrown if the insert operation fails</exception> public bool WriteEntry(WebLogEntry entry) { using (SqlDataAccess data = CreateDal()) { string sql = string.Format(@" insert into [{0}] (Entered,Message,ErrorLevel,Details,ErrorType,StackTrace,IpAddress,UserAgent,Url,QueryString,Referrer,PostData,RequestDuration) values (@Entered,@Message,@ErrorLevel,@Details,@ErrorType,@StackTrace,@IpAddress,@UserAgent,@Url,@QueryString,@Referrer,@PostData,@RequestDuration) select CAST(scope_identity() as integer) ", LogFilename); object result = data.ExecuteScalar(sql, data.CreateParameter("@Entered", entry.Entered, DbType.DateTime), data.CreateParameter("@Message", StringUtils.TrimTo(entry.Message, 255), 255), data.CreateParameter("@ErrorLevel", entry.ErrorLevel), data.CreateParameter("@Details", StringUtils.TrimTo(entry.Details, 4000), 4000), data.CreateParameter("@ErrorType", entry.ErrorType), data.CreateParameter("@StackTrace", StringUtils.TrimTo(entry.StackTrace, 1500), 1500), data.CreateParameter("@IpAddress", entry.IpAddress), data.CreateParameter("@UserAgent", StringUtils.TrimTo(entry.UserAgent, 255)), data.CreateParameter("@Url", entry.Url), data.CreateParameter("@QueryString", StringUtils.TrimTo(entry.QueryString, 255)), data.CreateParameter("@Referrer", entry.Referrer), data.CreateParameter("@PostData", StringUtils.TrimTo(entry.PostData, 2048), 2048), data.CreateParameter("@RequestDuration", entry.RequestDuration) ); // check for table missing and retry if (data.ErrorNumber == 208) { // if the table could be created try again if (CreateLog()) { return(WriteEntry(entry)); } } if (result == null || result == DBNull.Value) { throw new InvalidOperationException("Unable add log entry into table " + LogFilename + ". " + data.ErrorMessage); } // Update id entry.Id = (int)result; return(true); } }
private void InitializeClassificationList_Worker(object sender, DoWorkEventArgs e) { lock (mRequiredClassifications) { ArrayList classifications; ExclusionList = MOG_Filename.GetProjectLibraryClassificationString(); classifications = MOG_DBReports.ClassificationForProperty("", MOG_PropertyFactory.MOG_Sync_OptionsProperties.New_SyncFiles(true), false); mRequiredClassifications.Clear(); if (classifications != null && classifications.Count > 0) { foreach (string classificationName in classifications) { // Do we already have this class? if (!mRequiredClassifications.Contains(classificationName)) { bool excluded = false; if (ExclusionList.Length > 0) { excluded = StringUtils.IsFiltered(classificationName, ExclusionList); } // Is it excluded? if (excluded == false) { //we don't have this classification yet, so add it and give it a container for assets List <string> assetList = new List <string>(); mRequiredClassifications.Add(classificationName, assetList); } } } } if (ShowAssets) { // Enable this if we wnat to show assets in this tree ArrayList assets = MOG_DBAssetAPI.GetAllAssets(true, MOG_ControllerProject.GetBranchName()); // Enable this if we wnat to show assets in this tree if (assets != null && assets.Count > 0) { foreach (MOG_Filename asset in assets) { int index = mRequiredClassifications.IndexOfKey(asset.GetAssetClassification()); if (index >= 0) { List <string> assetList = mRequiredClassifications.GetByIndex(index) as List <string>; if (assetList != null) { bool excluded = false; if (ExclusionList.Length > 0) { excluded = StringUtils.IsFiltered(asset.GetAssetFullName(), ExclusionList); } // Is it excluded? if (excluded == false) { assetList.Add(asset.GetAssetFullName()); } } } } } } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request["protocolo"] != null) { String estado = null; String categoria = null; List <EntQuestionarioEmpresa> listQuestionarioEmpresa = new BllQuestionarioEmpresa().ObterPorProtocolo(Request["protocolo"]); new BllQuestionarioEmpresa().AlterarRelatorioGeradoPorProtocolo(Request["protocolo"], true); if (listQuestionarioEmpresa != null) { List <EntEmpresaCadastro> listEmpresaCadastro = new BllEmpresaCadastro().ObterPorIdPrograma(listQuestionarioEmpresa[0].EmpresaCadastro.IdEmpresaCadastro, StringUtils.ToInt(Request["programaId"])); if (listEmpresaCadastro != null) { Boolean comentarios = ObjectUtils.ToBoolean(Request["comentarios"]); Int32 programaId = ObjectUtils.ToInt(Request["programaId"]); Int32 turmaId = ObjectUtils.ToInt(Request["turmaId"]); Int32 avaliador = ObjectUtils.ToInt(Request["avaliacao"]); Int32 intro = ObjectUtils.ToInt(Request["intro"]); gerarRelatorioPDF(listEmpresaCadastro[0].IdEmpresaCadastro.ToString(), listEmpresaCadastro[0].CPF_CNPJ, listQuestionarioEmpresa[0].IdQuestionarioEmpresa.ToString(), Request["protocolo"], estado, categoria, comentarios, programaId, turmaId, avaliador, intro, false, this.Page); } } } } }
public string GetSelectCommend(int siteId, string logType, string userName, string keyword, string dateFrom, string dateTo) { if (siteId == 0 && (string.IsNullOrEmpty(logType) || StringUtils.EqualsIgnoreCase(logType, "All")) && string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(keyword) && string.IsNullOrEmpty(dateFrom) && string.IsNullOrEmpty(dateTo)) { return(GetSelectCommend()); } var whereString = new StringBuilder("WHERE "); var isWhere = false; if (siteId > 0) { isWhere = true; whereString.AppendFormat("(SiteId = {0})", siteId); } if (!string.IsNullOrEmpty(logType) && !StringUtils.EqualsIgnoreCase(logType, "All")) { if (isWhere) { whereString.Append(" AND "); } isWhere = true; if (StringUtils.EqualsIgnoreCase(logType, "Channel")) { whereString.Append("(ChannelId > 0 AND ContentId = 0)"); } else if (StringUtils.EqualsIgnoreCase(logType, "Content")) { whereString.Append("(ChannelId > 0 AND ContentId > 0)"); } } if (!string.IsNullOrEmpty(userName)) { if (isWhere) { whereString.Append(" AND "); } isWhere = true; whereString.AppendFormat("(UserName = '******')", userName); } if (!string.IsNullOrEmpty(keyword)) { if (isWhere) { whereString.Append(" AND "); } isWhere = true; whereString.AppendFormat("(Action LIKE '%{0}%' OR Summary LIKE '%{0}%')", PageUtils.FilterSql(keyword)); } if (!string.IsNullOrEmpty(dateFrom)) { if (isWhere) { whereString.Append(" AND "); } isWhere = true; whereString.Append($"(AddDate >= {SqlUtils.GetComparableDate(TranslateUtils.ToDateTime(dateFrom))})"); } if (!string.IsNullOrEmpty(dateTo)) { if (isWhere) { whereString.Append(" AND "); } whereString.Append($"(AddDate <= {SqlUtils.GetComparableDate(TranslateUtils.ToDateTime(dateTo))})"); } return("SELECT Id, SiteId, ChannelId, ContentId, UserName, IpAddress, AddDate, Action, Summary FROM siteserver_SiteLog " + whereString); }
public void PreviewMarkdown(MarkdownDocumentEditor editor = null, bool keepScrollPosition = false, bool showInBrowser = false, string renderedHtml = null, int editorLineNumber = -1) { try { // only render if the preview is actually visible and rendering in Preview Browser if (!Model.IsPreviewBrowserVisible && !showInBrowser) { return; } if (editor == null) { editor = Window.GetActiveMarkdownEditor(); } if (editor == null) { return; } var doc = editor.MarkdownDocument; var ext = Path.GetExtension(doc.Filename).ToLower().Replace(".", ""); string mappedTo = "markdown"; if (!string.IsNullOrEmpty(renderedHtml)) { mappedTo = "html"; ext = null; } else { mappedTo = editor.MarkdownDocument.EditorSyntax; } PreviewBrowserInterop interop = null; if (string.IsNullOrEmpty(ext) || mappedTo == "markdown" || mappedTo == "html") { if (!showInBrowser) { if (keepScrollPosition) { interop = new PreviewBrowserInterop(PreviewBrowserInterop.GetWindow(WebBrowser)); } else { Window.ShowPreviewBrowser(false, false); } } if (mappedTo == "html") { if (string.IsNullOrEmpty(renderedHtml)) { renderedHtml = doc.CurrentText; } if (!doc.WriteFile(doc.HtmlRenderFilename, renderedHtml)) { // need a way to clear browser window return; } renderedHtml = StringUtils.ExtractString(renderedHtml, "<!-- Markdown Monster Content -->", "<!-- End Markdown Monster Content -->"); } else { // Fix up `/` or `~/` Web RootPaths via `webRootPath: <path>` in YAML header // Specify a physical or relative path that `\` or `~\` maps to doc.GetPreviewWebRootPath(); bool usePragma = !showInBrowser && mmApp.Configuration.PreviewSyncMode != PreviewSyncMode.None; if (string.IsNullOrEmpty(renderedHtml)) { renderedHtml = doc.RenderHtmlToFile(usePragmaLines: usePragma); } if (renderedHtml == null) { Window.ShowStatusError($"Access denied: {Path.GetFileName(doc.Filename)}"); // need a way to clear browser window return; } // Handle raw URLs to render if (renderedHtml.StartsWith("http") && StringUtils.CountLines(renderedHtml) == 1) { WebBrowser.Navigate(new Uri(renderedHtml)); Window.ShowPreviewBrowser(); return; } renderedHtml = StringUtils.ExtractString(renderedHtml, "<!-- Markdown Monster Content -->", "<!-- End Markdown Monster Content -->"); } if (showInBrowser) { var url = doc.HtmlRenderFilename; mmFileUtils.ShowExternalBrowser(url); return; } WebBrowser.Cursor = Cursors.None; WebBrowser.ForceCursor = true; // if content contains <script> tags we must do a full page refresh bool forceRefresh = renderedHtml != null && renderedHtml.Contains("<script "); if (keepScrollPosition && !mmApp.Configuration.AlwaysUsePreviewRefresh && !forceRefresh) { string browserUrl = WebBrowser.Source.ToString().ToLower(); string documentFile = "file:///" + doc.HtmlRenderFilename.Replace('\\', '/') .ToLower(); if (browserUrl == documentFile) { if (string.IsNullOrEmpty(renderedHtml)) { PreviewMarkdown(editor, false, false); // fully reload document } else { try { try { // scroll preview to selected line if (mmApp.Configuration.PreviewSyncMode == PreviewSyncMode.EditorAndPreview || mmApp.Configuration.PreviewSyncMode == PreviewSyncMode.EditorToPreview || mmApp.Configuration.PreviewSyncMode == PreviewSyncMode.NavigationOnly) { int highlightLineNo = editorLineNumber; if (editorLineNumber < 0) { highlightLineNo = editor.GetLineNumber(); editorLineNumber = highlightLineNo; } if (renderedHtml.Length < 100000) { highlightLineNo = 0; // no special handling render all code snippets } var lineText = editor.GetLine(editorLineNumber).Trim(); if (mmApp.Configuration.PreviewSyncMode != PreviewSyncMode.NavigationOnly) { interop.UpdateDocumentContent(renderedHtml, highlightLineNo); } // TODO: We need to get Header Ids var headerId = string.Empty; // headers may not have pragma lines if (editorLineNumber > -1) { if (lineText.StartsWith("#") && lineText.Contains("# ")) // it's header { lineText = lineText.TrimStart(new[] { ' ', '#', '\t' }); headerId = LinkHelper.UrilizeAsGfm(lineText); } } if (editor.MarkdownDocument.EditorSyntax == "markdown") { interop.ScrollToPragmaLine(editorLineNumber, headerId); } else if (editor.MarkdownDocument.EditorSyntax == "html") { interop.ScrollToHtmlBlock(lineText); } } else { interop.UpdateDocumentContent(renderedHtml, 0); } } catch { /* ignore scroll error */ } } catch { // Refresh doesn't fire Navigate event again so // the page is not getting initiallized properly //PreviewBrowser.Refresh(true); WebBrowser.Tag = "EDITORSCROLL"; WebBrowser.Navigate(new Uri(doc.HtmlRenderFilename)); } } return; } } WebBrowser.Tag = "EDITORSCROLL"; WebBrowser.Navigate(new Uri(doc.HtmlRenderFilename)); return; } // not a markdown or HTML document to preview Window.ShowPreviewBrowser(true, keepScrollPosition); } catch (Exception ex) { //mmApp.Log("PreviewMarkdown failed (Exception captured - continuing)", ex); Debug.WriteLine("PreviewMarkdown failed (Exception captured - continuing): " + ex.Message, ex); } }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateStreamingSessionRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.NimbleStudio"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-08-01"; request.HttpMethod = "POST"; if (!publicRequest.IsSetStudioId()) { throw new AmazonNimbleStudioException("Request object does not have required field StudioId set"); } request.AddPathResource("{studioId}", StringUtils.FromString(publicRequest.StudioId)); request.ResourcePath = "/2020-08-01/studios/{studioId}/streaming-sessions"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if (publicRequest.IsSetEc2InstanceType()) { context.Writer.WritePropertyName("ec2InstanceType"); context.Writer.Write(publicRequest.Ec2InstanceType); } if (publicRequest.IsSetLaunchProfileId()) { context.Writer.WritePropertyName("launchProfileId"); context.Writer.Write(publicRequest.LaunchProfileId); } if (publicRequest.IsSetOwnedBy()) { context.Writer.WritePropertyName("ownedBy"); context.Writer.Write(publicRequest.OwnedBy); } if (publicRequest.IsSetStreamingImageId()) { context.Writer.WritePropertyName("streamingImageId"); context.Writer.Write(publicRequest.StreamingImageId); } if (publicRequest.IsSetTags()) { context.Writer.WritePropertyName("tags"); context.Writer.WriteObjectStart(); foreach (var publicRequestTagsKvp in publicRequest.Tags) { context.Writer.WritePropertyName(publicRequestTagsKvp.Key); var publicRequestTagsValue = publicRequestTagsKvp.Value; context.Writer.Write(publicRequestTagsValue); } context.Writer.WriteObjectEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } if (publicRequest.IsSetClientToken()) { request.Headers["X-Amz-Client-Token"] = publicRequest.ClientToken; } return(request); }
/// <summary> /// Returns a paged amount of topics in a list filtered via tag /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="amountToTake"></param> /// <param name="tag"></param> /// <returns></returns> public PagedList <Topic> GetPagedTopicsByTag(int pageIndex, int pageSize, int amountToTake, string tag) { return(_topicRepository.GetPagedTopicsByTag(pageIndex, pageSize, amountToTake, StringUtils.GetSafeHtml(tag))); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(AssociateVPCWithHostedZoneRequest publicRequest) { var request = new DefaultRequest(publicRequest, "Amazon.Route53"); request.HttpMethod = "POST"; string uriResourcePath = "/2013-04-01/hostedzone/{Id}/associatevpc"; if (!publicRequest.IsSetHostedZoneId()) { throw new AmazonRoute53Exception("Request object does not have required field HostedZoneId set"); } uriResourcePath = uriResourcePath.Replace("{Id}", StringUtils.FromStringWithSlashEncoding(publicRequest.HostedZoneId)); request.ResourcePath = uriResourcePath; var stringWriter = new StringWriter(CultureInfo.InvariantCulture); using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true })) { xmlWriter.WriteStartElement("AssociateVPCWithHostedZoneRequest", "https://route53.amazonaws.com/doc/2013-04-01/"); if (publicRequest.VPC != null) { xmlWriter.WriteStartElement("VPC", "https://route53.amazonaws.com/doc/2013-04-01/"); if (publicRequest.VPC.IsSetVPCRegion()) { xmlWriter.WriteElementString("VPCRegion", "https://route53.amazonaws.com/doc/2013-04-01/", StringUtils.FromString(publicRequest.VPC.VPCRegion)); } if (publicRequest.VPC.IsSetVPCId()) { xmlWriter.WriteElementString("VPCId", "https://route53.amazonaws.com/doc/2013-04-01/", StringUtils.FromString(publicRequest.VPC.VPCId)); } xmlWriter.WriteEndElement(); } if (publicRequest.IsSetComment()) { xmlWriter.WriteElementString("Comment", "https://route53.amazonaws.com/doc/2013-04-01/", StringUtils.FromString(publicRequest.Comment)); } xmlWriter.WriteEndElement(); } try { string content = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(content); request.Headers["Content-Type"] = "application/xml"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2013-04-01"; } catch (EncoderFallbackException e) { throw new AmazonServiceException("Unable to marshall request to XML", e); } return(request); }
/// <summary> /// Return a topic by url slug /// </summary> /// <param name="slug"></param> /// <returns></returns> public Topic GetTopicBySlug(string slug) { return(_topicRepository.GetTopicBySlug(StringUtils.GetSafeHtml(slug))); }
public IRequest Marshall(CreateCacheClusterRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ElastiCache"); request.Parameters.Add("Action", "CreateCacheCluster"); request.Parameters.Add("Version", "2014-09-30"); if (publicRequest != null) { if (publicRequest.IsSetAutoMinorVersionUpgrade()) { request.Parameters.Add("AutoMinorVersionUpgrade", StringUtils.FromBool(publicRequest.AutoMinorVersionUpgrade)); } if (publicRequest.IsSetAZMode()) { request.Parameters.Add("AZMode", StringUtils.FromString(publicRequest.AZMode)); } if (publicRequest.IsSetCacheClusterId()) { request.Parameters.Add("CacheClusterId", StringUtils.FromString(publicRequest.CacheClusterId)); } if (publicRequest.IsSetCacheNodeType()) { request.Parameters.Add("CacheNodeType", StringUtils.FromString(publicRequest.CacheNodeType)); } if (publicRequest.IsSetCacheParameterGroupName()) { request.Parameters.Add("CacheParameterGroupName", StringUtils.FromString(publicRequest.CacheParameterGroupName)); } if (publicRequest.IsSetCacheSecurityGroupNames()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.CacheSecurityGroupNames) { request.Parameters.Add("CacheSecurityGroupNames" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if (publicRequest.IsSetCacheSubnetGroupName()) { request.Parameters.Add("CacheSubnetGroupName", StringUtils.FromString(publicRequest.CacheSubnetGroupName)); } if (publicRequest.IsSetEngine()) { request.Parameters.Add("Engine", StringUtils.FromString(publicRequest.Engine)); } if (publicRequest.IsSetEngineVersion()) { request.Parameters.Add("EngineVersion", StringUtils.FromString(publicRequest.EngineVersion)); } if (publicRequest.IsSetNotificationTopicArn()) { request.Parameters.Add("NotificationTopicArn", StringUtils.FromString(publicRequest.NotificationTopicArn)); } if (publicRequest.IsSetNumCacheNodes()) { request.Parameters.Add("NumCacheNodes", StringUtils.FromInt(publicRequest.NumCacheNodes)); } if (publicRequest.IsSetPort()) { request.Parameters.Add("Port", StringUtils.FromInt(publicRequest.Port)); } if (publicRequest.IsSetPreferredAvailabilityZone()) { request.Parameters.Add("PreferredAvailabilityZone", StringUtils.FromString(publicRequest.PreferredAvailabilityZone)); } if (publicRequest.IsSetPreferredAvailabilityZones()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.PreferredAvailabilityZones) { request.Parameters.Add("PreferredAvailabilityZones" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if (publicRequest.IsSetPreferredMaintenanceWindow()) { request.Parameters.Add("PreferredMaintenanceWindow", StringUtils.FromString(publicRequest.PreferredMaintenanceWindow)); } if (publicRequest.IsSetReplicationGroupId()) { request.Parameters.Add("ReplicationGroupId", StringUtils.FromString(publicRequest.ReplicationGroupId)); } if (publicRequest.IsSetSecurityGroupIds()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.SecurityGroupIds) { request.Parameters.Add("SecurityGroupIds" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if (publicRequest.IsSetSnapshotArns()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.SnapshotArns) { request.Parameters.Add("SnapshotArns" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if (publicRequest.IsSetSnapshotName()) { request.Parameters.Add("SnapshotName", StringUtils.FromString(publicRequest.SnapshotName)); } if (publicRequest.IsSetSnapshotRetentionLimit()) { request.Parameters.Add("SnapshotRetentionLimit", StringUtils.FromInt(publicRequest.SnapshotRetentionLimit)); } if (publicRequest.IsSetSnapshotWindow()) { request.Parameters.Add("SnapshotWindow", StringUtils.FromString(publicRequest.SnapshotWindow)); } } return(request); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateInputRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.MediaLive"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-10-14"; request.HttpMethod = "PUT"; if (!publicRequest.IsSetInputId()) { throw new AmazonMediaLiveException("Request object does not have required field InputId set"); } request.AddPathResource("{inputId}", StringUtils.FromString(publicRequest.InputId)); request.ResourcePath = "/prod/inputs/{inputId}"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if (publicRequest.IsSetDestinations()) { context.Writer.WritePropertyName("destinations"); context.Writer.WriteArrayStart(); foreach (var publicRequestDestinationsListValue in publicRequest.Destinations) { context.Writer.WriteObjectStart(); var marshaller = InputDestinationRequestMarshaller.Instance; marshaller.Marshall(publicRequestDestinationsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if (publicRequest.IsSetInputDevices()) { context.Writer.WritePropertyName("inputDevices"); context.Writer.WriteArrayStart(); foreach (var publicRequestInputDevicesListValue in publicRequest.InputDevices) { context.Writer.WriteObjectStart(); var marshaller = InputDeviceRequestMarshaller.Instance; marshaller.Marshall(publicRequestInputDevicesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if (publicRequest.IsSetInputSecurityGroups()) { context.Writer.WritePropertyName("inputSecurityGroups"); context.Writer.WriteArrayStart(); foreach (var publicRequestInputSecurityGroupsListValue in publicRequest.InputSecurityGroups) { context.Writer.Write(publicRequestInputSecurityGroupsListValue); } context.Writer.WriteArrayEnd(); } if (publicRequest.IsSetMediaConnectFlows()) { context.Writer.WritePropertyName("mediaConnectFlows"); context.Writer.WriteArrayStart(); foreach (var publicRequestMediaConnectFlowsListValue in publicRequest.MediaConnectFlows) { context.Writer.WriteObjectStart(); var marshaller = MediaConnectFlowRequestMarshaller.Instance; marshaller.Marshall(publicRequestMediaConnectFlowsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if (publicRequest.IsSetName()) { context.Writer.WritePropertyName("name"); context.Writer.Write(publicRequest.Name); } if (publicRequest.IsSetRoleArn()) { context.Writer.WritePropertyName("roleArn"); context.Writer.Write(publicRequest.RoleArn); } if (publicRequest.IsSetSources()) { context.Writer.WritePropertyName("sources"); context.Writer.WriteArrayStart(); foreach (var publicRequestSourcesListValue in publicRequest.Sources) { context.Writer.WriteObjectStart(); var marshaller = InputSourceRequestMarshaller.Instance; marshaller.Marshall(publicRequestSourcesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return(request); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(SetVaultAccessPolicyRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Glacier"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-06-01"; request.HttpMethod = "PUT"; string uriResourcePath = "/{accountId}/vaults/{vaultName}/access-policy"; uriResourcePath = uriResourcePath.Replace("{accountId}", publicRequest.IsSetAccountId() ? StringUtils.FromStringWithSlashEncoding(publicRequest.AccountId) : string.Empty); if (!publicRequest.IsSetVaultName()) { throw new AmazonGlacierException("Request object does not have required field VaultName set"); } uriResourcePath = uriResourcePath.Replace("{vaultName}", StringUtils.FromStringWithSlashEncoding(publicRequest.VaultName)); request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); var marshaller = VaultAccessPolicyMarshaller.Instance; marshaller.Marshall(publicRequest.Policy, context); writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return(request); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeInstanceTypesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2"); request.Parameters.Add("Action", "DescribeInstanceTypes"); request.Parameters.Add("Version", "2016-11-15"); if (publicRequest != null) { if (publicRequest.IsSetFilters()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.Filters) { if (publicRequestlistValue.IsSetName()) { request.Parameters.Add("Filter" + "." + publicRequestlistValueIndex + "." + "Name", StringUtils.FromString(publicRequestlistValue.Name)); } if (publicRequestlistValue.IsSetValues()) { int publicRequestlistValuelistValueIndex = 1; foreach (var publicRequestlistValuelistValue in publicRequestlistValue.Values) { request.Parameters.Add("Filter" + "." + publicRequestlistValueIndex + "." + "Value" + "." + publicRequestlistValuelistValueIndex, StringUtils.FromString(publicRequestlistValuelistValue)); publicRequestlistValuelistValueIndex++; } } publicRequestlistValueIndex++; } } if (publicRequest.IsSetInstanceTypes()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.InstanceTypes) { request.Parameters.Add("InstanceType" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if (publicRequest.IsSetMaxResults()) { request.Parameters.Add("MaxResults", StringUtils.FromInt(publicRequest.MaxResults)); } if (publicRequest.IsSetNextToken()) { request.Parameters.Add("NextToken", StringUtils.FromString(publicRequest.NextToken)); } } return(request); }
private void FindRegexDelimiters(StringUtils.UniformWrapper pattern, out int start, out int end) { int i = 0; while (i < pattern.Length && Char.IsWhiteSpace(pattern[i])) i++; if (i == pattern.Length) throw new ArgumentException(LibResources.GetString("regular_expression_empty")); char start_delimiter = pattern[i++]; if (Char.IsLetterOrDigit(start_delimiter) || start_delimiter == '\\') throw new ArgumentException(LibResources.GetString("delimiter_alnum_backslash")); start = i; char end_delimiter; if (start_delimiter == '[') end_delimiter = ']'; else if (start_delimiter == '(') end_delimiter = ')'; else if (start_delimiter == '{') end_delimiter = '}'; else if (start_delimiter == '<') end_delimiter = '>'; else end_delimiter = start_delimiter; int depth = 1; while (i < pattern.Length) { if (pattern[i] == '\\' && i + 1 < pattern.Length) { i += 2; continue; } else if (pattern[i] == end_delimiter) // (1) should precede (2) to handle end_delim == start_delim case { depth--; if (depth == 0) break; } else if (pattern[i] == start_delimiter) // (2) { depth++; } i++; } if (i == pattern.Length) throw new ArgumentException(LibResources.GetString("preg_no_end_delimiter", end_delimiter)); end = i - 1; }
/// <summary> /// 执行分页查询 /// </summary> /// <param name="pWhereConditions">筛选条件</param> /// <param name="pOrderBys">排序</param> /// <param name="pPageSize">每页的记录数</param> /// <param name="pCurrentPageIndex">以0开始的当前页码</param> /// <returns></returns> public PagedQueryResult<TItemTagEntity> PagedQuery(IWhereCondition[] pWhereConditions, OrderBy[] pOrderBys, int pPageSize, int pCurrentPageIndex) { //组织SQL StringBuilder pagedSql = new StringBuilder(); StringBuilder totalCountSql = new StringBuilder(); //分页SQL pagedSql.AppendFormat("select * from (select row_number()over( order by "); if (pOrderBys != null && pOrderBys.Length > 0) { foreach (var item in pOrderBys) { if(item!=null) { pagedSql.AppendFormat(" {0} {1},", StringUtils.WrapperSQLServerObject(item.FieldName), item.Direction == OrderByDirections.Asc ? "asc" : "desc"); } } pagedSql.Remove(pagedSql.Length - 1, 1); } else { pagedSql.AppendFormat(" [ItemTagID] desc"); //默认为主键值倒序 } pagedSql.AppendFormat(") as ___rn,* from [TItemTag] where isdelete=0 "); //总记录数SQL totalCountSql.AppendFormat("select count(1) from [TItemTag] where isdelete=0 "); //过滤条件 if (pWhereConditions != null) { foreach (var item in pWhereConditions) { if(item!=null) { pagedSql.AppendFormat(" and {0}", item.GetExpression()); totalCountSql.AppendFormat(" and {0}", item.GetExpression()); } } } pagedSql.AppendFormat(") as A "); //取指定页的数据 pagedSql.AppendFormat(" where ___rn >{0} and ___rn <={1}", pPageSize * (pCurrentPageIndex-1), pPageSize * (pCurrentPageIndex)); //执行语句并返回结果 PagedQueryResult<TItemTagEntity> result = new PagedQueryResult<TItemTagEntity>(); List<TItemTagEntity> list = new List<TItemTagEntity>(); using (SqlDataReader rdr = this.SQLHelper.ExecuteReader(pagedSql.ToString())) { while (rdr.Read()) { TItemTagEntity m; this.Load(rdr, out m); list.Add(m); } } result.Entities = list.ToArray(); int totalCount = Convert.ToInt32(this.SQLHelper.ExecuteScalar(totalCountSql.ToString())); //计算总行数 result.RowCount = totalCount; int remainder = 0; result.PageCount = Math.DivRem(totalCount, pPageSize, out remainder); if (remainder > 0) result.PageCount++; return result; }
public void IDirectoryRead_AllEntriesAreReturned() { IFileSystem fs = CreateFileSystem(); fs.CreateDirectory("/dir".ToU8Span()); fs.CreateDirectory("/dir/dir1".ToU8Span()); fs.CreateFile("/dir/dir1/file1".ToU8Span(), 0, CreateFileOptions.None); fs.CreateFile("/dir/file1".ToU8Span(), 0, CreateFileOptions.None); fs.CreateFile("/dir/file2".ToU8Span(), 0, CreateFileOptions.None); Assert.Success(fs.OpenDirectory(out IDirectory dir, "/dir".ToU8Span(), OpenDirectoryMode.All)); var entry1 = new DirectoryEntry(); var entry2 = new DirectoryEntry(); var entry3 = new DirectoryEntry(); var entry4 = new DirectoryEntry(); Assert.Success(dir.Read(out long entriesRead1, SpanHelpers.AsSpan(ref entry1))); Assert.Success(dir.Read(out long entriesRead2, SpanHelpers.AsSpan(ref entry2))); Assert.Success(dir.Read(out long entriesRead3, SpanHelpers.AsSpan(ref entry3))); Assert.Success(dir.Read(out long entriesRead4, SpanHelpers.AsSpan(ref entry4))); Assert.Equal(1, entriesRead1); Assert.Equal(1, entriesRead2); Assert.Equal(1, entriesRead3); Assert.Equal(0, entriesRead4); bool dir1Read = false; bool file1Read = false; bool file2Read = false; // Entries are not guaranteed to be in any particular order CheckEntry(ref entry1); CheckEntry(ref entry2); CheckEntry(ref entry3); Assert.True(dir1Read); Assert.True(file1Read); Assert.True(file2Read); void CheckEntry(ref DirectoryEntry entry) { switch (StringUtils.Utf8ZToString(entry.Name)) { case "dir1": Assert.False(dir1Read); Assert.Equal(DirectoryEntryType.Directory, entry.Type); dir1Read = true; break; case "file1": Assert.False(file1Read); Assert.Equal(DirectoryEntryType.File, entry.Type); file1Read = true; break; case "file2": Assert.False(file2Read); Assert.Equal(DirectoryEntryType.File, entry.Type); file2Read = true; break; default: throw new ArgumentOutOfRangeException(); } } }
/// <inheritdoc/> public void Initialize(ITelemetry telemetry) { if (telemetry == null) { return; } var httpContext = _httpContextAccessor.HttpContext; var items = httpContext?.Items; if (items != null) { if ((telemetry is RequestTelemetry || telemetry is EventTelemetry || telemetry is TraceTelemetry || telemetry is DependencyTelemetry || telemetry is PageViewTelemetry) && items.ContainsKey(BotActivityKey)) { if (items[BotActivityKey] is JObject body) { var userId = string.Empty; var from = body["from"]; if (!string.IsNullOrWhiteSpace(from?.ToString())) { userId = (string)from["id"]; } var channelId = (string)body["channelId"]; var conversationId = string.Empty; var sessionId = string.Empty; var conversation = body["conversation"]; if (!string.IsNullOrWhiteSpace(conversation?.ToString())) { conversationId = (string)conversation["id"]; sessionId = StringUtils.Hash(conversationId); } // Set the user id on the Application Insights telemetry item. telemetry.Context.User.Id = channelId + userId; // Set the session id on the Application Insights telemetry item. // Hashed ID is used due to max session ID length for App Insights session Id telemetry.Context.Session.Id = sessionId; var telemetryProperties = ((ISupportProperties)telemetry).Properties; // Set the conversation id if (!telemetryProperties.ContainsKey("conversationId")) { telemetryProperties.Add("conversationId", conversationId); } // Set the activity id https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#id if (!telemetryProperties.ContainsKey("activityId")) { telemetryProperties.Add("activityId", (string)body["id"]); } // Set the channel id https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#channel-id if (!telemetryProperties.ContainsKey("channelId")) { telemetryProperties.Add("channelId", (string)channelId); } // Set the activity type https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#type if (!telemetryProperties.ContainsKey("activityType")) { telemetryProperties.Add("activityType", (string)body["type"]); } } } } }
public static string Parse(PageInfo pageInfo, ContextInfo contextInfo) { var stlAnchor = new HtmlAnchor(); var htmlId = string.Empty; var channelIndex = string.Empty; var channelName = string.Empty; var upLevel = 0; var topLevel = -1; const bool removeTarget = false; var href = string.Empty; var queryString = string.Empty; var host = string.Empty; foreach (var name in contextInfo.Attributes.Keys) { var value = contextInfo.Attributes[name]; if (StringUtils.EqualsIgnoreCase(name, Id.Name)) { htmlId = value; } else if (StringUtils.EqualsIgnoreCase(name, ChannelIndex.Name)) { channelIndex = StlEntityParser.ReplaceStlEntitiesForAttributeValue(value, pageInfo, contextInfo); if (!string.IsNullOrEmpty(channelIndex)) { contextInfo.ContextType = EContextType.Channel; } } else if (StringUtils.EqualsIgnoreCase(name, ChannelName.Name)) { channelName = StlEntityParser.ReplaceStlEntitiesForAttributeValue(value, pageInfo, contextInfo); if (!string.IsNullOrEmpty(channelName)) { contextInfo.ContextType = EContextType.Channel; } } else if (StringUtils.EqualsIgnoreCase(name, Parent.Name)) { if (TranslateUtils.ToBool(value)) { upLevel = 1; contextInfo.ContextType = EContextType.Channel; } } else if (StringUtils.EqualsIgnoreCase(name, UpLevel.Name)) { upLevel = TranslateUtils.ToInt(value); if (upLevel > 0) { contextInfo.ContextType = EContextType.Channel; } } else if (StringUtils.EqualsIgnoreCase(name, TopLevel.Name)) { topLevel = TranslateUtils.ToInt(value); if (topLevel >= 0) { contextInfo.ContextType = EContextType.Channel; } } else if (StringUtils.EqualsIgnoreCase(name, Context.Name)) { contextInfo.ContextType = EContextTypeUtils.GetEnumType(value); } else if (StringUtils.EqualsIgnoreCase(name, Href.Name)) { href = StlEntityParser.ReplaceStlEntitiesForAttributeValue(value, pageInfo, contextInfo); } else if (StringUtils.EqualsIgnoreCase(name, QueryString.Name)) { queryString = StlEntityParser.ReplaceStlEntitiesForAttributeValue(value, pageInfo, contextInfo); } else if (StringUtils.EqualsIgnoreCase(name, Host.Name)) { host = value; } else { ControlUtils.AddAttributeIfNotExists(stlAnchor, name, value); } } var parsedContent = ParseImpl(pageInfo, contextInfo, stlAnchor, htmlId, channelIndex, channelName, upLevel, topLevel, removeTarget, href, queryString, host); return(parsedContent); }
public IRequest Marshall(DescribeLaunchConfigurationsRequest describeLaunchConfigurationsRequest) { IRequest request = new DefaultRequest(describeLaunchConfigurationsRequest, "AmazonAutoScaling"); request.Parameters.Add("Action", "DescribeLaunchConfigurations"); request.Parameters.Add("Version", "2011-01-01"); if (describeLaunchConfigurationsRequest != null) { List <string> launchConfigurationNamesList = describeLaunchConfigurationsRequest.LaunchConfigurationNames; int launchConfigurationNamesListIndex = 1; foreach (string launchConfigurationNamesListValue in launchConfigurationNamesList) { request.Parameters.Add("LaunchConfigurationNames.member." + launchConfigurationNamesListIndex, StringUtils.FromString(launchConfigurationNamesListValue)); launchConfigurationNamesListIndex++; } } if (describeLaunchConfigurationsRequest != null && describeLaunchConfigurationsRequest.IsSetNextToken()) { request.Parameters.Add("NextToken", StringUtils.FromString(describeLaunchConfigurationsRequest.NextToken)); } if (describeLaunchConfigurationsRequest != null && describeLaunchConfigurationsRequest.IsSetMaxRecords()) { request.Parameters.Add("MaxRecords", StringUtils.FromInt(describeLaunchConfigurationsRequest.MaxRecords)); } return(request); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CopyDBParameterGroupRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.RDS"); request.Parameters.Add("Action", "CopyDBParameterGroup"); request.Parameters.Add("Version", "2014-10-31"); if (publicRequest != null) { if (publicRequest.IsSetSourceDBParameterGroupIdentifier()) { request.Parameters.Add("SourceDBParameterGroupIdentifier", StringUtils.FromString(publicRequest.SourceDBParameterGroupIdentifier)); } if (publicRequest.IsSetTags()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.Tags) { if (publicRequestlistValue.IsSetKey()) { request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValue.Key)); } if (publicRequestlistValue.IsSetValue()) { request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValue.Value)); } publicRequestlistValueIndex++; } } if (publicRequest.IsSetTargetDBParameterGroupDescription()) { request.Parameters.Add("TargetDBParameterGroupDescription", StringUtils.FromString(publicRequest.TargetDBParameterGroupDescription)); } if (publicRequest.IsSetTargetDBParameterGroupIdentifier()) { request.Parameters.Add("TargetDBParameterGroupIdentifier", StringUtils.FromString(publicRequest.TargetDBParameterGroupIdentifier)); } } return(request); }
public void GenerateRandomString_returns_single_character_for_single_input() { var utils = new StringUtils(); var result = utils.GenerateRandomString(StringUtils.LOWERCASE_A, StringUtils.LOWERCASE_A, 1); Assert.That(result, Is.EqualTo("a")); }
/// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateLocalGatewayRouteTableVpcAssociationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2"); request.Parameters.Add("Action", "CreateLocalGatewayRouteTableVpcAssociation"); request.Parameters.Add("Version", "2016-11-15"); if (publicRequest != null) { if (publicRequest.IsSetLocalGatewayRouteTableId()) { request.Parameters.Add("LocalGatewayRouteTableId", StringUtils.FromString(publicRequest.LocalGatewayRouteTableId)); } if (publicRequest.IsSetTagSpecifications()) { int publicRequestlistValueIndex = 1; foreach (var publicRequestlistValue in publicRequest.TagSpecifications) { if (publicRequestlistValue.IsSetResourceType()) { request.Parameters.Add("TagSpecification" + "." + publicRequestlistValueIndex + "." + "ResourceType", StringUtils.FromString(publicRequestlistValue.ResourceType)); } if (publicRequestlistValue.IsSetTags()) { int publicRequestlistValuelistValueIndex = 1; foreach (var publicRequestlistValuelistValue in publicRequestlistValue.Tags) { if (publicRequestlistValuelistValue.IsSetKey()) { request.Parameters.Add("TagSpecification" + "." + publicRequestlistValueIndex + "." + "Tag" + "." + publicRequestlistValuelistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValuelistValue.Key)); } if (publicRequestlistValuelistValue.IsSetValue()) { request.Parameters.Add("TagSpecification" + "." + publicRequestlistValueIndex + "." + "Tag" + "." + publicRequestlistValuelistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValuelistValue.Value)); } publicRequestlistValuelistValueIndex++; } } publicRequestlistValueIndex++; } } if (publicRequest.IsSetVpcId()) { request.Parameters.Add("VpcId", StringUtils.FromString(publicRequest.VpcId)); } } return(request); }
private static void ParseRegexOptions(StringUtils.UniformWrapper pattern, int start, out RegexOptions dotNetOptions, out PerlRegexOptions extraOptions) { dotNetOptions = RegexOptions.None; extraOptions = PerlRegexOptions.None; for (int i = start; i < pattern.Length; i++) { char option = pattern[i]; switch (option) { case 'i': // PCRE_CASELESS dotNetOptions |= RegexOptions.IgnoreCase; break; case 'm': // PCRE_MULTILINE dotNetOptions |= RegexOptions.Multiline; break; case 's': // PCRE_DOTALL dotNetOptions |= RegexOptions.Singleline; break; case 'x': // PCRE_EXTENDED dotNetOptions |= RegexOptions.IgnorePatternWhitespace; break; case 'e': // evaluate as PHP code extraOptions |= PerlRegexOptions.Evaluate; break; case 'A': // PCRE_ANCHORED extraOptions |= PerlRegexOptions.Anchored; break; case 'D': // PCRE_DOLLAR_ENDONLY extraOptions |= PerlRegexOptions.DollarMatchesEndOfStringOnly; break; case 'S': // spend more time studying the pattern - ignore break; case 'U': // PCRE_UNGREEDY extraOptions |= PerlRegexOptions.Ungreedy; break; case 'u': // PCRE_UTF8 extraOptions |= PerlRegexOptions.UTF8; break; case 'X': // PCRE_EXTRA PhpException.Throw(PhpError.Warning, LibResources.GetString("modifier_not_supported", option)); break; default: PhpException.Throw(PhpError.Notice, LibResources.GetString("modifier_unknown", option)); break; } } // inconsistent options check: if ( (dotNetOptions & RegexOptions.Multiline) != 0 && (extraOptions & PerlRegexOptions.DollarMatchesEndOfStringOnly) != 0 ) { PhpException.Throw(PhpError.Notice, LibResources.GetString("modifiers_inconsistent", 'D', 'm')); } }
private static bool IsJsonRequest(string request, string contentType) { return(StringUtils.GetExtension(request) == ".json" || StringUtils.IsContentType(Constants.JsonContentType, contentType)); }