Inject some string to a specific part of string in C# - c#

How to insert some string to a specific part of another string. What i am trying to achieve is i have an html string like this in my variable say string stringContent;
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="Viewport" content="width=320; user-scaleable=no;
initial-scale=1.0">
<style type="text/css">
body {
background: black;
color: #80c0c0;
}
</style>
<script>
</script>
</head>
<body>
<button type="button" onclick="callNative();">Call to Native
Code!</button>
<br><br>
</body></html>
I need to add below string content inside <script> <script/> tag
function callNative()
{
window.external.notify("Uulalaa!");
}
function addToBody(text)
{
document.body.innerHTML = document.body.innerHTML + "<br>" + text;
}
How i can achieve this in C#.

Assuming your content is stored in the string content, you can start by finding the script tag with:
int scriptpos = content.IndexOf("<script");
Then to get past the end of the script tag:
scriptpos = content.IndexOf(">", scriptpos) + 1;
And finally to insert your new content:
content = content.Insert(scriptpos, newContent);
This at least allows for potential attributes in the script tag.

Use htmlString.Replace(what, with)
var htmlString = "you html bla bla where's the script tag? oooups here it is!!!<script></script>";
var yourScript = "alert('HA-HA-HA!!!')";
htmlString = htmlString.Replace("<script>", "<script>" + yourScript);
Note that this will insert yourScript inside all <script> elements.

var htmlString = #"<script>$var1</script> <script>$var2</script>"
.Replace("$var1", "alert('var1')")
.Replace("$var2", "alert('var2')");

var htmlString = "you html bla bla where's the script tag? oooups here it is!!!<script></script>";
var yourScript = "alert('HA-HA-HA!!!')";
htmlString = htmlString.Insert(html.IndexOf("<script>") + "<script>".Length + 1, yourScript);

This can be done in another (safer) way, using HTML Agility Pack (open source project http://htmlagilitypack.codeplex.com). It helps you to parse and edit html without you having to worry about malformed tags (<br/>, <br />, < br / > etc). It includes operations to make it easy to insert elements, like AppendChild.
If you are dealing with HTML, this is the way to go.

For this you can read the html file into string by using File.ReadAllText method. Here For example, i have used sample html string. After that, by some string operations you can add tags under script like follows.
string text = "<test> 10 </test>";
string htmlString =
#" <html>
<head>
<script>
<tag1> 5 </tag1>
</script>
</head>
</html>";
int startIndex = htmlString.IndexOf("<script>");
int length = htmlString.IndexOf("</script>") - startIndex;
string scriptTag = htmlString.Substring(startIndex, length) + "</script>";
string expectedScripTag = scriptTag.Replace("<script>", "<script><br>" + text);
htmlString = htmlString.Replace(scriptTag, expectedScripTag);

Related

How do I insert a script tag in to the top/beginning of head tag using BHO?

I am using this code in c# for inject js into html page.this is working fine.
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)document.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject3 = (IHTMLScriptElement)document.createElement("script");
scriptObject3.type = #"text/javascript";
scriptObject3.text = System.IO.File.ReadAllText(Environment.CurrentDirectory + #"\all.js");
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject3);
but i want to be this as first element in head tag.
<head>
//INSERT SCRIPT HERE
<script type="text/javascript" src="common.js"></script>
<script type="text/javascript" src="omni-controls.js"></script></head>
how this could be done in c#.
You can do this:
if (!ClientScript.IsStartupScriptRegistered("youScriptName"))
{
ClientScript.RegisterStartupScript(GetType(), "youScriptName",
#"<script type=""text/javascript"" src=""yourpath/script.js""></script>");
}
You should do it in the Page_Load
Get the first child of HEAD and use it as second parameter of the Element's method insertBefore.

Select meta tag using c#?

This is Xml where i want to select meta tag
<meta charset="utf-8">
<title>Gmail: Email from Google</title>
<meta name="description" content="10+ GB of storage, less spam,
and mobile access. Gmail is email that's intuitive, efficient, and
useful. And maybe even fun.">
<link rel="icon" type="image/ico" href="//mail.google.com/favicon.ico">
I am doing this
string texturl = textBox2.Text;
string Url = "http://" + texturl;
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(Url);
var SpanNodes = doc.DocumentNode.SelectNodes("//meta");
if (SpanNodes != null)
{
foreach (HtmlNode SN in SpanNodes)
{
string text = SN.InnerText;
MessageBox.Show(text);
}
Its not actually selecting any text from there............what i am doing wrong please help
meta elements are self-closing elements, meaning they have no text children (InnerText). I believe you want to get the value of the content attribute. I believe you do that using something like SN["content"], but I don't know HtmlAgilityPack.

What's the easiest way to generate an HTML file?

I'm working on a console application that's supposed to spit out an html document that contains a table and maybe some javascript.
I thought about writing the html by hand:
streamWriter.WriteLine("<html>");
streamWriter.WriteLine("<body>");
streamWriter.WriteLine(GetHtmlTable());
streamWriter.WriteLine("</body>");
streamWriter.WriteLine("</html>");
... but was wondering if there is a more elegant way to do it. Something along these lines:
Page page = new Page();
GridView gridView = new GridView();
gridView.DataSource = GetDataTable();
gridView.DataBind();
page.Controls.Add(gridView);
page.RenderControl(htmlWriter);
htmlWriter.Flush();
Assuming that I'm on the right track, what's the proper way to build the rest of the html document (ie: html, head, title, body elements) using the System.Web.UI.Page class? Do I need to use literal controls?
It would be a good idea for you to use a templating system to decouple your presentation and business logic.
Take a look at Razor Generator which allows the use of CSHTML templates within non ASP.NET applications.
http://razorgenerator.codeplex.com/
I do a lot of automated HTML page generation. I like to create an HTML page template with custom tags where to insert the dynamic controls, data, or literals. I then read template file into a string and replace the custom tag with the generated HTML like you are doing above and write the HTML file back out of the string. This saves me the time of creating all the tedious support HTML for the design template, css, and supporting JS.
Template File Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<CUSTOMHEAD />
</head>
<body>
<CUSTOMDATAGRID />
</body>
</html>
Create HTML From Template File loaded into string Example
private void GenerateHTML(string TemplateFile, string OutputFileName)
{
string strTemplate = TemplateFile;
string strHTMLPage = "";
string strCurrentTag = "";
int intStartIndex = 0;
int intEndIndex = 0;
while (strTemplate.IndexOf("<CUSTOM", intEndIndex) > -1)
{
intStartIndex = strTemplate.IndexOf("<CUSTOM", intEndIndex);
strHTMLPage += strTemplate.Substring(intEndIndex,
intStartIndex - intEndIndex);
strCurrentTag = strTemplate.Substring(intStartIndex,
strTemplate.IndexOf("/>", intStartIndex) + 6 - intStartIndex);
strCurrentTag = strCurrentTag.ToUpper();
switch (strCurrentTag)
{
case "<CUSTOMHEAD />":
strHTMLPage += GenerateHeadJavascript();
break;
case "<CUSTOMDATAGRID />":
StringWriter sw = new StringWriter();
GridView.RenderControl(new HtmlTextWriter(sw));
strHTMLPage += sw.ToString();
sw.Close();
break;
case "<CUSTOMANYOTHERTAGSYOUMAKE />":
//strHTMLPage += YourControlsRenderedAsString();
break;
}
intEndIndex = strTemplate.IndexOf("/>", intStartIndex) + 2;
}
strHTMLPage += strTemplate.Substring(intEndIndex);
try
{
StreamWriter swHTMLPage = new System.IO.StreamWriter(
OutputFileName, false, Encoding.UTF8);
swHTMLPage.Write(strHTMLPage);
swHTMLPage.Close();
}
catch (Exception ex)
{
// AppendLog("Write File Failed: " + OutputFileName + " - " + ex.Message);
}
}

Getting String Definitions To Accept Multiple Lines?

For some reason, the syntax highlighting below is working how I'd like it to, but this is not how it interprets the code in Visual Studio. When I try to assign multiple lines to a string, it won't let me. Is there a way i can make the following work without combining all of my code into one line or using a += for each new line?
string HtmlCode = "";
HtmlCode =
"
<head>
<style>
*{margin: 0px;padding: 0px;font-family: Microsoft Sans Serif;font-size: 11px;}
</style>
</head>
";
Use verbatim string by prefixing your string with #
string HtmlCode = "";
HtmlCode =
#"
<head>
<style>
*{margin: 0px;padding: 0px;font-family: Microsoft Sans Serif;font-size: 11px;}
</style>
</head>
";
Use literal strings:
string HtmlCode = #"
<head>
<style>
*{margin: 0px;padding: 0px;font-family: Microsoft Sans Serif;font-size: 11px;}
</style>
</head>";
Prefix the string with an "#"
string HtmlCode = "";
HtmlCode =
#"
<head>
<style>
*{margin: 0px;padding: 0px;font-family: Microsoft Sans Serif;font-size: 11px;}
</style>
</head>
";

ASP.NET - How to write some html in the page? With Response.Write?

I need that some html in the area in the asp.net page that i am coding, is changed according to a string variable.
I was thinking about creating a label, and then change the text on it.
But the string variable contains something like:
<h2><p>Notify:</p> alert</h2>
So, I don't feel that give this to a label text is a good idea
How i can do?
Using response.write?
If I use response.write, my added code will be at the beginning of the html source, how i can tell him to add it in a specific ?
Thank you
If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
why don't you give LiteralControl a try?
myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";
If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:
Markup:
<span runat="server" id="FooSpan"></span>
Code:
FooSpan.Text = "Foo";
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
Use a literal control and write your html like this:
literal1.text = "<h2><p>Notify:</p> alert</h2>";
You should really use the Literal ASP.NET control for that.
You can go with the literal control of ASP.net or you can use panels or the purpose.
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]
public static string showTxtbox(string name)
{
return showResult(name);
}
public static string showResult(string name)
{
Database databaseObj = new Database();
DataTable dtObj = databaseObj.getMatches(name);
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +
"<tr>" +
"<td><b>Name</b></td>" +
"<td><b>Company Name</b></td>" +
"<td><b>Phone</b></td>"+
"</tr>";
for (int i = 0; i < dtObj.Rows.Count; i++)
{
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+
"</tr>";
}
result += "</table>";
return result;
}
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function.
Result is displayed in the form of table.

Categories