Convert part of string to URL when displayed - asp.net-mvc

I browsed around for a solution and I am sure it's a simple question but still not sure how to do that. So, I have a string that contains many words and some times it has links in it. For example:
I like the website http://somesitehere.com/somepage.html and I suggest you try it too.
I want to display the string in my view and have all links automatically converted to URLs.
#Model.MyText
Even StackOverflow gets it.

#Hunter is right.
In addition i found complete implementation in C#: http://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link.aspx.
In case original link goes down
VB.Net implementation
Protected Function MakeLink(ByVal txt As String) As String
Dim regx As New Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\#\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase)
Dim mactches As MatchCollection = regx.Matches(txt)
For Each match As Match In mactches
txt = txt.Replace(match.Value, "<a href='" & match.Value & "'>" & match.Value & "</a>")
Next
Return txt
End Function
C#.Net implementation
protected string MakeLink(string txt)
{
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(txt);
foreach (Match match in mactches) {
txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
}
return txt;
}

One way to do that would be to do a Regular Expression match on a chunk of text and replace that url string with an anchor tag.

Another regex that can be used with KvanTTT answer, and has the added benefit of accepting https urls
https?://([\w+?.\w+])+([a-zA-Z0-9\~!\##\$\%\^\&*()_-\=+\/\?.:\;\'\,]*)?
.net string representation:
"https?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?"

Related

Swift Adding HTML to UIWebView, expression was too complex

I'm adding some HTML content to an UIWebView.
This line:
generatedHtml += "<br><p style=\"font-family:'Chevin-Medium';font-size:12px;color:#505050;padding-top:0px;\">" + newsItem.entry.likes + " like this " + newsItem.entry.comments?.count + " comments</p>"
I get:
expressions was too complex to be solved in reasonable time
I'm just doing a count on an array, i don't know how to make that less complex?
The object looks like this:
public class NewsItem: NSObject {
var entry: EntryObject = EntryObject()
}
public class EntryObject: NSObject {
var comments: [Comment]? = []
}
newsItem.entry.comments?.count is an integer, and you can't add an integer to a string using +, you should use string interpolation with \():
" like this \(newsItem.entry.comments?.count) comments</p>"
Or use the String initializer if you need to keep using +:
" like this " + String(newsItem.entry.comments?.count) + " comments</p>"
If the error "too complex" persists, you'll have to break down the statements and use variables instead of inserting the expressions directly.
Try to do by this way
var countComments : Int = 0
//Validate comment counting
if let cComments = newsItem.entry.comments?.count
{
countComments = cComments
}
//... Some code here ...
//Devide to Conquest.
//If is easy to find... Is not hard to fix
generatedHtml += "<br>"
generatedHtml += "<p style=\"font-family:'Chevin-Medium';font-size:12px;color:#505050;padding-top:0px;\">"
generatedHtml += "\(newsItem.entry.likes) "
generatedHtml += "like this \(countComments) comments" //Here you have a valid value
genetatedHtml += "</p>"
But, why?
Maybe you have a problem with the optional value newsItem.entry.comments?.count that can gets you a nil value. Then, first of all, validate the value and be sure about what was returned. Better "0", a valid value than nil
When you split the string creation, the debug working will be more easy to execute. You will can have a better idea where is happening an error.
Maybe it´s not a definitive solution to your problem, but a good way to help you fix it.

SQL CLR User Defined Function (C#) adds null character (\0) in between every existing character in String being returned

This one has kept me stumped for a couple of days now.
It's my first dabble with CLR & UDF ...
I have created a user defined function that takes a multiline String as input, scans it and replaces a certain line in the string with an alternative if found. If it is not found, it simply appends the desired line at the end. (See code)
The problem, it seems, comes when the final String (or Stringbuilder) is converted to an SqlString or SqlChars. The converted, returned String always contains the Nul character as every second character (viewing via console output, they are displayed as spaces).
I'm probably missing something fundamental on UDF and/or CLR.
Please Help!!
Code (I leave in the commented Stringbuilder which was my initial attempt... changed to normal String in a desperate attempt to find the issue):
[Microsoft.SqlServer.Server.SqlFunction]
[return: SqlFacet(MaxSize = -1, IsFixedLength = false)]
//public static SqlString udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
public static SqlChars udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
if (omaIn == null || omaIn.ToString().Length <= 0) return new SqlChars("");
String[] lines = Regex.Split(omaIn.ToString(), "\r\n");
Regex JobTag = new Regex(#"^JOB=.+$");
//StringBuilder buffer = new StringBuilder();
String buffer = String.Empty;
bool matched = false;
foreach (var line in lines) {
if (!JobTag.IsMatch(line))
//buffer.AppendLine(line);
buffer += line + "\r\n";
else {
//buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber + "\r\n");
matched = true;
}
}
if (!matched) //buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber) + "\r\n";
//return new SqlString(buffer.ToString().Replace("\0",String.Empty)) + "blablabla";
// buffer = buffer.Replace("\0", "|");
return new SqlChars(buffer + "\r\nTheEnd");
}
I know in my experiences, the omaIn parameter should be of type SqlString and when you go to collect its value/process it, set a local variable:
string omaString = omaIn != SqlString.Null ? omaIn.Value : string.empty;
Then when you return on any code path, to rewrap the string in C#, you'd need to set
return omaString == string.empty ? new SqlString.Null : new SqlString(omaString);
I have had some fun wrestling matches learning the intricate hand-off between local and outbound types, especially with CLR TVFs.
Hope that can help!

Naming a text file on CSHTML (Razor)

I have a page with a text area for title input and body input.
Saving a text file with those things is easy, the question is, how can I make the file to be named after whatever was placed in the title input?
I tried this:
#{
var result = "";
if (IsPost)
{
var title = Request["title"];
var body = Request["body"];
var filedata = title + "," + body + Environment.NewLine;
var dataFile = Server.MapPath("/App_Data/Request["title"]");
File.WriteAllText(#dataFile, filedata);
result = "Information saved.";
}
}
(Note that var title = Request["title"]; means that its requesting from a text input named "title"). What I want to get is that the input will also be the name of the file its saving.
But it seems that this area:
var dataFile = Server.MapPath("/App_Data/Request["title"]");
is not the correct way.
What is the correct way to do it?
Couple of pointers; firstly this sort of logic should be in a Controller, not in a View. Your Views are supposed to display information about your model, your Controllers carry out operations.
Secondly, the following should do the trick (in a Controller!):
[HttpPost]
public ActionResult SaveFile(string title, string body)
{
var fileData = title + "," + body + Environment.NewLine;
var fileSavePath = Path.Combine(
Server.MapPath("~/TextFiles"),
title.Replace(" ", "_") + ".txt");
File.WriteAllText(fileSavePath, fileData);
return this.RedirectToAction("SaveSuccessful");
}
Of note:
Server.MapPath("~/TextFiles") gives you the path to a TextFiles directory in the root of your web application where the files will be stored.
I've replaced spaces in the title which has been input with underscores.
This method redirects the user to an Action named SaveSuccessful on the same Controller
Of course you need error handling and all sorts of other things in there, but hopefully that helps.

Getting cleaned HTML in text from HtmlCleaner

I want to see the cleaned HTML that we get from HTMLCleaner.
I see there is a method called serialize on TagNode, however don't know how to use it.
Does anybody have any sample code for it?
Thanks
Nayn
Here's the sample code:
HtmlCleaner htmlCleaner = new HtmlCleaner();
TagNode root = htmlCleaner.clean(url);
HtmlCleaner.getInnerHtml(root);
String html = "<" + root.getName() + ">" + htmlCleaner.getInnerHtml(root) + "</" + root.getName() + ">";
Use a subclass of org.htmlcleaner.XmlSerializer, for example:
// get the element you want to serialize
HtmlCleaner cleaner = new HtmlCleaner();
TagNode rootTagNode = cleaner.clean(url);
// set up properties for the serializer (optional, see online docs)
CleanerProperties cleanerProperties = cleaner.getProperties();
cleanerProperties.setOmitXmlDeclaration(true);
// use the getAsString method on an XmlSerializer class
XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);
String html = xmlSerializer.getAsString(rootTagNode);
XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);
String html = xmlSerializer.getAsString(rootTagNode);
the method above has a problem,it will trim content in html label, for example,
this is paragraph1.
will become
this is paragraph1.
and it is getSingleLineOfChildren function does the trim operation. So if we fetch data from website and want to keep the format like tuckunder.
PS:if a html label has children label,the parent label contetn will not be trimed,
for example <p> this is paragraph1. <a>www.xxxxx.com</a> </p> will keep whitespace before "this is paragraph1"

JQUERY call to Controller Action: String Parameter truncated if containing 'space' character

I have a view that accepts 2 string parameters and 2 date values. User hits search button and they get filtered output to the screen. This all works perfectly well until a user inputs a string with a space. i.e. they can search for 'waste' but not 'waste oil'.
Interestingly, in the latter, the parameter is ok from Javascript before the call is made. But on entering the controller code it goes form being 'waste oil' on client to 'waste'. When this happens the other parameters get set to NULL crashing the system.
I've tried replacing the spaces if present with '#' character then stripping out and putting back in ' ' on the controller side. This is a messy fudge and only appears to work with one parameter.
There must be a simple explanation for this parameter data loss, any comments much appreciated
Not sure a code example is needed but here it is anyway if it help:
My controller header :
public ActionResult IndexSearch(int? page, string searchText,string searchTextSite,string StartDate,string EndDate)
{
My HTML Javascript :
function Search(sSearchText,sSite) {
sSearchText = sSearchText.toString().replace(" ", "#");
sSite = sSite.toString().replace(" ", "#");
debugger;
alert($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val());
$("#ResultsList").load($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val(),
function() {
$('#LoadingGif').empty();
});
$('#LoadingGif').empty().html('<img src="' + $("#AbsolutePath").val() + 'Content/images/ajax-loader.gif" alt="Loading image" />');
}
You are not URL encoding your parameters when sending the AJAX request because you are using string concatenations when building the url. You could use the following technique in order to have properly encoded values:
var url = $('#AbsolutePath').val() + 'Waste.mvc/IndexSearch';
var data = {
searchText: sSearchText,
searchTextSite: sSite ,
StartDate: $('#StartDate').val(),
EndDate: $('#EndDate').val()
};
$('#ResultsList').load(url, data, function() {
$('#LoadingGif').empty();
});
Now you will get correct values on the server.

Resources