Conditional <br> for address format in C# - c#

I am formatting my application to show the address related to a specific work ticket. Occasionally the address uses a second line. I don't want to use the following:
<%: ticket.ADDRESS2 %><br />
In this scenario, if the object is null or empty I still get the break and then I have a large space that looks funny.
I thought I could generate my own string and then turn it into a literal with something like this:
string str = ((Object)ticket.ADDRESS2 != "").ToString();
string sAdd2 = str + <br />;
myLiteral.Text = sAdd2;
But that doesn't actually help me out if the Object is null or empty (in fact, I don't even know if it works at all.
So then I tried this:
public string sAdd2
{
get
{
Object oAdd2 = ticket.ADDRESS2;
if (oAdd2 != null)
{
string sAdd2 = ((Object)ticket.ADDRESS2 != "").ToString();
}
else
{
string sAdd2 = ((Object)ticket.ADDRESS2 == "").ToString();
}
}
}
With this I get errors at the 'get' (not all code paths return a value). I feel like I am going way out of the way to do a simple thing. I just want to have my page show
Address Line 1
Address Line 2
City, State ZIP
or
Address Line 1
City, State ZIP
Anyone have any pointers? I've looked up "conditional breaks" but didn't get much of a useful return.

Use an if statement
<%if (!string.IsNullOrEmpty(ticket.ADDRESS2)) { %>
<%: ticket.ADDRESS2 %><br />
<%} %>

What I have done in the past – in an MVC project, but could easily be in code behind for WebForms – is:
var lines = new [] {
contact.Name,
contact.AddressLine1,
contact.AddressLine2,
contact.AddressLine3,
contact.PostCode
};
var address = String.Join("<br/>", lines.Where(l => !String.IsNullOrWhitespace(l));
and then use the appropriate method to write out address as a raw string.

Remove blank lines, then use string.Join() to add newlines.
// Get the address lines to be displayed
string[] lines = new string[]
{
ticket.Address1,
ticket.Address2,
ticket.Address3,
ticket.Address4,
ticket.ZipCode,
};
// Remove blank lines
IEnumerable<string> filledLines = lines.Where(s => !string.IsNullOrWhitespace(s));
// Add newlines between each line
string html = string.Join(#"<br />", filledLines);

Related

How to check a text contains a certain character within selenium

I have a method below where I retrieve a HTML tag:
public void CheckEmailDisplayed()
{
var email = _driver.FindElement(ConfirmationResponsiveElements.ViewEmail);
}
ViewEmail is below:
public static By ViewEmail => By.ClassName("confirmation-banner__text");
The HTML it corresponds to is:
<div class="confirmation-banner__text firefinder-match">
<p>
We've sent an email to
<strong>firstname#xxx.com</strong>
</p>
<p>
</div>
What I want to do is be able to use the variable email to check that the text contains an #. This is to help determine an email address is displayed. How can this be achieved?
Thanks
Option 1: Check for the # symbol
string email = "test#domain.com";
if (email.Contains("#"))
{
// code here
}
Option 2: Validate Email Address
public static bool IsEmail(string emailToValidate)
{
if (string.IsNullOrEmpty(emailToValidate)) return true;
return Regex.IsMatch(emailToValidate, #"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
How to use option 2:
string email = "test#domain.com";
if (IsEmail(email))
{
// valid email address
}
else
{
// not a valid email address
}
You can add another definition
public static By ViewEmailAddress => By.TagName("strong");
Then use
var emailAddress = emai.FindElement(ConfirmationResponsiveElements.ViewEmailAddress);
var emailAddressText = emailAddress.Text;
And then you can do different operations that you want on emailAddressText. Like validating it having # or doing more complex validations like a email pattern check
You can use IndexOf method
bool found = Value1.IndexOf("abc", 0, 7) != -1;
OR
You can also use regular expressions (less readable though)
string regex = "^.{0,7}abc";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
string Value1 = "sssddabcgghh";
Console.WriteLine(reg.Match(Value1).Success);
Source :-
How to determine if string contains specific substring within the first X characters

Return true only if there is existing match, but it's not first one

I think I already wrote what I want to do in title, so now to the point:
I have a .txt file with url links and their source code will be parsed by regex expression.
Source code of every link is scraped by this:
public static string getSourceCode(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string sourceCode = sr.ReadToEnd();
sr.Close();
resp.Close();
return sourceCode;
}
Each source code contains these text:
..code..
..code..
<p class="content">
exampleexampleexample
</p>
..code..
..code..
<p class="content">
example
</p>
..code..
..code..
There are more elements of content elements.
I get content content by this:
Regex k = new Regex(#"<p class=""question-content"">[\r\n\s]*(\S.*)");
var g = k.Matches(sourceCode);
Now I can easly extract every match:
g[1].ToString() <-- first match
g[2].ToString() <-- second match
g[3].ToString() <-- thirdmatch
etc.
But what I want to do is to extract these links where: first match does not contains XYZ, but there is XYZ in at least other matches.
For example:
First link's source code contains XYZ in first and third match <-- wrong
Second link's source code contains XYZ only in first match <-- wrong
Third link's source code contains XYZ only in third match <-- success!
Solution
I get Every match colletion from this:
MatchCollection b1 = Regex.Matches(sourceCode, #"<p class=""content"">[\r\n\s]*(\S.*)");
What I do next is
checking if first match does not contain "example" by this:
if (!b1[0].ToString().Contains("example"))
And checking the result of this function:
bool checkAnother(int amount, MatchCollection m)
{
for (int i=1; i<=amount-1; i++)
{
if (m[i].ToString().Contains("example"))
return true;
}
return false;
}
So that is the code:
MatchCollection b1 = Regex.Matches(sourceCode, #"<p class=""content"">[\r\n\s]*(\S.*)");
if ((!b1[0].ToString().Contains("example")) && (checkAnother(b1.Count, b1)))
{dataGridView1.Rows[i].Cells[2].Value = "GOOD";
}
What you are trying to do is not suitable for regular expressions.
It's probably possible with multiline matching, capture groups and look-arounds, but IMO it's not worthwhile to put lots of effort into an unmaintainable solution.
Try to verify the found matches in a post-processing step instead. Assuming you grab the matches like so:
var g = k.Matches(sourceCode);
...you can easily achieve that with something like:
var isFirstOk = !g[0].Value.Contains("XYZ");
var areAllOk = isFirstOk && g.Cast<Match>().Skip(1).Any(m => m.Value.Contains("XYZ"));

How to get onyl part of the URL in c#

I am creating a module using C# which will need to refer the URL
So i have 2 example URLs for you here.
http://www.website.com/ProductDetail/tabid/86/rvdsfpid/1gb-dual-port-iscsi-8660/rvdsfmfid/qlogic-174/Default.aspx
&&
http://www.website.com/ProductDetail/tabid/86/rvdsfpid/49950/default.aspx
Now what i need from both the URls is the product ID which in the first case is 8660 & the second case is 49950. I cannot change the way these URls are generated. The easiest way would have been
http://www.website.com/ProductDetail/tabid/86/default.aspx?rvdsfpid=49950
and then i could do the following and life would be easy.
string Pid= Request.Querystring["rvdsfpid"];
However since i dont have control on the way the URL is generatyed how can i catch the URL and fetch only the productId.
Assuming that's the URL format you're being passed and there's nothing else you can do....You're going to need to get the full url and then split it. Here's the basic, you're going to have to add some extra checks and stuff in there;
string url = "http://www.website.com/ProductDetail/tabid/86/rvdsfpid/1gb-dual-port-iscsi-8660/rvdsfmfid/qlogic-174/Default.aspx"
//string url = "http://www.website.com/ProductDetail/tabid/86/rvdsfpid/49950/default.aspx";
url = url.Replace("http://", ""); //get rid of that, add code to check for https?
string[] x = url.Split('/');
string productCode = x[5]; //assuming the product code is always the 6th item in the array!
string code = "";
if (productCode.IndexOf("-") > -1)
{
code = productCode.Substring(productCode.LastIndexOf("-")+1);
}
else
{
code = productCode;
}

Simple text to HTML conversion

I have a very simple asp:textbox with the multiline attribute enabled. I then accept just text, with no markup, from the textbox. Is there a common method by which line breaks and returns can be converted to <p> and <br/> tags?
I'm not looking for anything earth shattering, but at the same time I don't just want to do something like:
html.Insert(0, "<p>");
html.Replace(Enviroment.NewLine + Enviroment.NewLine, "</p><p>");
html.Replace(Enviroment.NewLine, "<br/>");
html.Append("</p>");
The above code doesn't work right, as in generating correct html, if there are more than 2 line breaks in a row. Having html like <br/></p><p> is not good; the <br/> can be removed.
I know this is old, but I couldn't find anything better after some searching, so here is what I'm using:
public static string TextToHtml(string text)
{
text = HttpUtility.HtmlEncode(text);
text = text.Replace("\r\n", "\r");
text = text.Replace("\n", "\r");
text = text.Replace("\r", "<br>\r\n");
text = text.Replace(" ", " ");
return text;
}
If you can't use HttpUtility for some reason, then you'll have to do the HTML encoding some other way, and there are lots of minor details to worry about (not just <>&).
HtmlEncode only handles the special characters for you, so after that I convert any combo of carriage-return and/or line-feed to a BR tag, and any double-spaces to a single-space plus a NBSP.
Optionally you could use a PRE tag for the last part, like so:
public static string TextToHtml(string text)
{
text = "<pre>" + HttpUtility.HtmlEncode(text) + "</pre>";
return text;
}
Your other option is to take the text box contents and instead of trying for line a paragraph breaks just put the text between PRE tags. Like this:
<PRE>
Your text from the text box...
and a line after a break...
</PRE>
Depending on exactly what you are doing with the content, my typical recommendation is to ONLY use the <br /> syntax, and not to try and handle paragraphs.
How about throwing it in a <pre> tag. Isn't that what it's there for anyway?
I know this is an old post, but I've recently been in a similar problem using C# with MVC4, so thought I'd share my solution.
We had a description saved in a database. The text was a direct copy/paste from a website, and we wanted to convert it into semantic HTML, using <p> tags. Here is a simplified version of our solution:
string description = getSomeTextFromDatabase();
foreach(var line in description.Split('\n')
{
Console.Write("<p>" + line + "</p>");
}
In our case, to write out a variable, we needed to prefix # before any variable or identifiers, because of the Razor syntax in the ASP.NET MVC framework. However, I've shown this with a Console.Write, but you should be able to figure out how to implement this in your specific project based on this :)
Combining all previous plus considering titles and subtitles within the text comes up with this:
public static string ToHtml(this string text)
{
var sb = new StringBuilder();
var sr = new StringReader(text);
var str = sr.ReadLine();
while (str != null)
{
str = str.TrimEnd();
str.Replace(" ", " ");
if (str.Length > 80)
{
sb.AppendLine($"<p>{str}</p>");
}
else if (str.Length > 0)
{
sb.AppendLine($"{str}</br>");
}
str = sr.ReadLine();
}
return sb.ToString();
}
the snippet could be enhanced by defining rules for short strings
I understand that I was late with the answer for 13 years)
but maybe someone else needs it
sample line 1 \r\n
sample line 2 (last at paragraph) \r\n\r\n [\r\n]+
sample line 3 \r\n
Example code
private static Regex _breakRegex = new("(\r?\n)+");
private static Regex _paragrahBreakRegex = new("(?:\r?\n){2,}");
public static string ConvertTextToHtml(string description) {
string[] descrptionParagraphs = _paragrahBreakRegex.Split(description.Trim());
if (descrptionParagraphs.Length > 0)
{
description = string.Empty;
foreach (string line in descrptionParagraphs)
{
description += $"<p>{line}</p>";
}
}
return _breakRegex.Replace(description, "<br/>");
}

Show new lines from text area in ASP.NET MVC

I'm currently creating an application using ASP.NET MVC. I got some user input inside a textarea and I want to show this text with <br />s instead of newlines. In PHP there's a function called nl2br, that does exactly this. I searched the web for equivalents in ASP.NET/C#, but didn't find a solution that works for me.
The fist one is this (doesn't do anything for me, comments are just printed without new lines):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace("\r\n", "<br />\r\n");
%>
<%= comment %>
The second one I found was this (Visual Studio tells me VbCrLf is not available in this context - I tried it in Views and Controllers):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
Try (not tested myself):
comment = comment.Replace(System.Environment.NewLine, "<br />");
UPDATED:
Just tested the code - it works on my machine
UPDATED:
Another solution:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringReader sr = new System.IO.StringReader(originalString);
string tmpS = null;
do {
tmpS = sr.ReadLine();
if (tmpS != null) {
sb.Append(tmpS);
sb.Append("<br />");
}
} while (tmpS != null);
var convertedString = sb.ToString();
to view html tags like a DisplayFor
you need to use another method , in fact the mvc dosent allowed you to view tags in page
but you can used this to ignore this option
#Html.Raw(model => model.text)
good luck
If you have a Razor-based view , string with line breaks and want to show that text with the line-breaks intact in your view, you can do this without replacing all \r\n with "html br"-tags. Instead present the text in an element that has the style property white-space set to pre-line. You should really add a class like:
<span class="line-breaks">#Model.MyText</span>
.line-breaks {
white-space:pre-line;
}
Original Found #
https://kaliko.com/blog/text-line-breaks-in-asp.net-mvc-razor-view/
Please have a look this answer Replace Line Breaks in a String C# here.
#Html.Raw(#Model.Comment.RestoreFormatting())
and than...
public static class StringHelper
{
public static string RestoreFormatting(this string str)
{
return str.Replace("\n", "<br />").Replace("\r\n", "<br />");
}
}
I have the same issue and above all answer given the hint, not exactly help, that's why given the answer to help.
Replace "\n" strign with '', '\r\n','\n', nothing help and finally when replace "\r\n", it will work. (in display it like \n, but in database it store as \\n)
Old code
#Html.TextArea("MEPat_textPatNote", Model.MedicationPatCur, 4, 4, new { #class = "k-textbox", style = "width: 100%;", maxlength = "300" })
New code
#Html.TextArea("MEPat_textPatNote", Model.MedicationPatCur.PatNote== null? "": Model.MedicationPatCur.PatNote.Replace("\\n","\r\n"), 4, 4, new { #class = "k-textbox", style = "width: 100%;", maxlength = "300" })

Categories

Resources