Getting String Definitions To Accept Multiple Lines? - c#

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>
";

Related

Webview2 SetVirtualHostNameToFolderMapping not allowed to load local resource

Hey all I am using the new WebView2 with my WinForms app. I can get it to display my dynamic html that I create but it has the "" when it tries to load the images for the page.
The image tag looks like this:
<div id="animation1" style="display: inline-flex;">
<img src="file:///C:\Users\admin\source\repos\wCondictions\bin\x86\Debug\Resources/nice.gif" style="height: 110px; width: 110px;">
<span class="imgWeather">Nice</span>
</div>
The code I am currently using is this:
fileNames = new DirectoryInfo(resourcePath)
.GetFiles()
.OrderBy(p => Path.GetFileNameWithoutExtension(p.Name))
.Select(fi => fi.Name)
.ToArray();
string blah = Path.Combine(Application.StartupPath, "Resources");
string fullHtml = string.Empty;
string HeaderHtml = "<!DOCTYPE html>\n" +
"<html>\n" +
"<style>\n" +
".imgW {\n" +
"position: absolute;\n" +
"z-index: 10;\n" +
"color: red;\n" +
"width: 110px;\n" +
"height:30px;\n" +
"text-align: center;\n" +
"vertical-align: middle;\n" +
"top: 88px;\n" +
"background-color: aquamarine;\n" +
"font-family: Arial;\n" +
"font-size: small;\n" +
"}\n" +
"</style>\n" +
"<body style=\"background-color: #00000;\">";
string dynamixImg = "<div id=\"animation1\" style=\"display: inline-flex;\">\n" +
"<img src=\"file:///" + blah + "/{0}\" style=\"height: 110px; width: 110px;\" />\n" +
"<span class=\"imgW\">{1}</span>\n" +
"</div>";
string FooterHtml = "</body>" +
"</html>";
for (int a = 0; a < fileNames.Count(); a++)
{
fullHtml += string.Format(
dynamixImg,
fileNames[a],
fileNames[a]
.Replace(".gif", "")
.Replace("&", "&&")
) + "\n";
}
await webView21.EnsureCoreWebView2Async();
webView21.CoreWebView2.SetVirtualHostNameToFolderMapping(
"Resources",
#"C:\Users\admin\source\repos\wCondictions\bin\x86\Debug\Resources\",
CoreWebView2HostResourceAccessKind.Allow
);
webView21.NavigateToString(HeaderHtml + fullHtml + FooterHtml);
I've seen many places where it says to use the SetVirtualHostNameToFolderMapping but even with that it still says the same error.
So I am not sure what I am missing or misunderstanding about how to use the SetVirtualHostNameToFolderMapping in order to allow the images to load locally?
Ok, I will try again, my first answer was confusing.
You get the error because you use the file:// protocol.
It seems you have not fully understood the the use of SetVirtualHostNameToFolderMapping.
Once you have set the virtual server by calling SetVirtualHostNameToFolderMapping you should use that virtual server just as you use any other server on the internet. Do NOT use file://!
So all you have to do is edit your HeaderHtml and your <img src.
The HeaderHtml should include a <base> tag, which should point to your virtual server root:
<html>
<head>
<base href="http://Resources" />
</head>
That makes it very easy to build you dynamic <ìmg> tags, the source is simply the file name:
<img src="image.png" />
Now WebView2will translate it into a file path and fetch the image!
As a side note, you can also include files from sub-folder by adding the folder name in front of the file name, like this:
<img src="/subfolder/image.png" />

Inject some string to a specific part of string in 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);

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);
}
}

how to know which browser my .net application is running on?

I want to apply different css on different browsers.
I want to run one css when it is safari and second for all others.
How can I detect that and apply css according to that?
You can use CSS browser selectors for this. There are different solutions available for this on the net.
For example:
CSS Browser Selector
The CSS Browser Selector is a small JavaScript library which allows you to include different cascading style sheets (CSS) for each browser.
An example:
<style type="text/css">
.ie .example {
background-color: yellow
}
.ie7 .example {
background-color: orange
}
.opera .example {
background-color: green
}
.webkit .example {
background-color: black
</style>
If you Google for "different css per browser" you'll find other solutions as well, but most of them boil down to similar solutions.
Another way would be to detect the browser type and capabilities in ASP.NET so that you can render the appropriate HTML / CSS / ...etc. You can find more information on that topic here:
http://msdn.microsoft.com/en-us/library/3yekbd5b.aspx
For example:
private void Button1_Click(object sender, System.EventArgs e)
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform;
TextBox1.Text = s;
}
The Browser property of the Request returns a HttpBrowserCapabilities object. It contains information on the capabilities of the browser that is running on the client.
http://msdn.microsoft.com/en-us/library/system.web.httpbrowsercapabilities.aspx
You can examine the UserAgent property of the Request object.
Inside the page head tag
<%# Request.UserAgent.ToLower().Contains("safari") ?
"<link rel='stylesheet' type='text/css' href='safari.css' />" :
"<link rel='stylesheet' type='text/css' href='other.css' />" %>
Use below things....in your control...and you can set different style...to asp.net textbox control for different browser.
<asp:TextBox ID="TestTextBox" runat="server" ie:Text="You are in Internet explorer." mozilla:Text="You are in Firefox." Text="You are in other browser." ie:CssClass="IEStyle" mozilla:CssClass="FFStyle" CssClass="DefaultStyle" />
using Using the Request.Browser you can determine the browser user is using your
You can check it from javascript like:
if (navigator.appName == 'Microsoft Internet Explorer') {
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}

Categories