C# WebBrowser control not displaying custom HTML - c#

I have a web browser control that for some reason isn't loading my HTML:
string updatingChatHTML = ""
+ "<HTML> "
+ "<head>"
+ "<style>"
+ "body {"
+ " margin: 0px;"
+ " padding: 0px;"
+ " background: " + chatBackground + ";\n"
+ " Font-Family: Arial;"
+ " font-size: 11px; "
+ " text-align: left;"
+ "}"
+ "</style>"
+ "</head>"
+ "<body>";
txtChat.DocumentText = updatingChatHTML + "</body></HTML>";
(txtChat is my WebBrowser Control).
The weird thing is, it was working before I changed something, but I can't figure out what I changed that caused it to stop working.
I have a breakpoint set to just after the last line above, and I can see that updatingChatHTML has the proper value it's meant to, but txtChat.DocumentText still has a value of <HTML></HTML>\0.
I thought maybe it was an initialisation thing, so I added txtChat.Navigate("about:blank"); prior to any assignment, but it still doesn't work.
This event actually gets fired quite often though, and the first time/two times, it doesn't work, but after the form is finished loading it seems to, but it's already the last thing to happen on my Form_Load.
Any suggestions?

Attempting to set the DocumentText property when
no document is loaded
or the browser control is not in a ready state (e.g. currently loading a document)
will cause the property assignment to fail silently.
After calling the Navigate function you should monitor the DocumentCompleted event for notification of when the navigation operation completes.

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

Gmap looses GListener after refresh

I have a Gmap Control where i add lots of points(markers) via c# code.
Directly after i add the marker i add a GListener to all the markers.
Now i have a few buttons on the web page that when a user clicks one of them the map gets refreshed to show only relative markers.
Everything works fine when the user clicks the first button but when the user clicks on any other button the Glistener just doesnt work but the markers does change accordingly.
Here is some code where i add the markers and listeners.
marker = new GMarker(new GLatLng(lat, lng), new GIcon(Gicon));
clicklistener = new GListener(marker.ID, GListener.Event.click, string.Format(#"function(){{var w=new google.maps.InfoWindow();w.setContent('<center><b>{0}</b></center></br><center>{3}</center></br><center>{4}</center></br><center>{5}</center></br><center>{6}</center>');w.open({1}, {2});}}", SName + " , " + FacType, GMap1.GMap_Id, marker.ID, "Printer Status: " + PrinterStatus.ToString() + ", Battery: " + Sbat + "V Signal: " + SSignal + "%", "Scanner Status: " + ScannerStatus.ToString(), "SMS Received: " + Sreceived + " , SMS Sent: " + Ssent, "Last SMS Date: " + SsmsDate.ToString() + " , Last Comms Date: " + ScommsDate.ToString()));
The Marker and clicklistener is globally defined and gets added to the map via gmap1.add(marker) and gmap1.add(clicklistener)
any ideas?
Regards
Patrick
Sorted.
All that needed to be done is a complete reset of the whole map like so:
GMap1.reset();
and then just add the new markers and listeners as necessary :)

how to preview a html file from database to a browser using C#

I have HTML code stored in a database and would like to display (render) it onto a view.
I wanted to show it as a normal text page.
eg: **HTML:** <h3 style="font-weight: bold">Usage:</h3>
<p style="text-decoration: underline">Viewing of Form -</p>
Should be shown as: Usage:
Viewing of Form -
I have a button as view and when clicked, it should show me the page.
I am using entity frame work so i have written,
string url = ("view.aspx?id = " + page.ID + "&Text=" + page.Text);
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open( '" + url + "', null, 'height=500,width=800,status=yes,toolbar=yes,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=yes' );", true);
and i have created a new page view.aspx and tried to use System.Web.HttpUtility.HtmlDecode(Request.QueryString["Text"]) to render the file.
But i am getting a blank page.
Please help me.
Thanks,
Can you confirm that page.Text has a value when it's being rendered?
If you are certain that the value page.Text is populated correctly (I'm assuming something like "view.aspx?id=1&Text=<h3>example post<h3>") then you may want to try encoding the string for the URL before returning it to the client.
string url = ("view.aspx?id = " + page.ID + "&Text=" + System.Web.HttpUtility.UrlEncode(page.Text));
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open( '" + url + "', null, 'height=500,width=800,status=yes,toolbar=yes,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=yes' );", true);
Then make sure that you are getting encoded characters in your links on the client.

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

AJAX Control Toolkit's combobox + IE are too slow

I have problems with optimizing AJAX Control Toolkit. The specific problem is that 4800 records take about 30 seconds to bind in Internet Explorer (only 2 seconds in Opera & Firefox). I've tried anything, but I still can't improve the load time in IE.
I've already enabled compression and caching, I'm using ToolkitScriptManager instead of ScriptManager. I've tried setting LoadScriptsBeforeUI and EnablePartialRendering to false, but it still doesn't help.
This is the query I use for binding.
var osoba =
from o in db.osobas
orderby o.osoba_prezime
select new {
o.osoba_id,
person = o.osoba_prezime + " " +
o.osoba_ime + " | " +
o.tijelo.tijelo_naziv + " | " +
o.radno_mjesto.rm_naziv_m
};
cb1.DataSource = osoba;
cb1.DataTextField = "person";
cb1.DataValueField = "osoba_id";
cb1.DataBind();
cb1.Items.Insert(0, " ");
Any help would be appreciated. Thank you!
Do you happen to have the developer toolbar open? I've had speed issues in IE when the toolbar is running, and when it's closed, load times are considerably faster.

Categories