How can I access Whatsapp Web from WebBrowser Control? - c#

Im trying to access Whatsapp Web from my desktop application using a WebBrowser Control, but a message popups, recommending me to use Chrome, Firefox, etc..
How can I avoid this message and get the QR Code? I tried changing the User-Agent this way:
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
private void Form1_Load(object sender, EventArgs e)
{
string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, userAgent, userAgent.Length, 0);
}
But it didn't work. I mean, it changed the User-Agent, but I'm still getting the same message.
I check current User-Agent using this web: http://www.whoishostingthis.com/tools/user-agent/
What can I do? Thanks in advice!

The native WebBrowser control is based on Internet Explorer, which, when embedded, runs in IE7 compatibility mode by Default.
IE is used regardless of the default browser on your system.
Whatsapp Web seems to support no version of IE, so it makes no sense to alter the compatibility mode of the WebBrowser control.
Instead, you should consider using a different browser control, like Chromium.
There are a lot of resources on the web about how to integrate Chromium into a .Net application.

Related

Open website with selenium as an Android device

I want to make a program with opens a website "in mobile view", I don't really know how to call it, but I want that the website thinks I'm using an android phone.
I have tried it using ChromeOptions and changing the user-agent, but somehow it doesn't work.
ChromeOptions options = new ChromeOptions();
options.AddArgument("user-agent=Mozilla/5.0 (Linux; Android 8.1.0; Phone) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.90 Mobile Safari/537.36");
driver = new ChromeDriver("./", options);
This site has detailed documentation of using Mobile Emulation.
Moreover, after ChromeDriver v2.11 has mobileEmulation option.
For C#
Use something like this,
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.EnableMobileEmulation("Pixel 2");
chromeOptions.AddUserProfilePreference("safebrowsing.enabled", true);
chromeOptions.AddUserProfilePreference("credentials_enable_service", false);
chromeOptions.AddUserProfilePreference("profile.password_manager_enabled", false);
ChromeDriverService service = ChromeDriverService.CreateDefaultService(#"C:\chromedriver");
IWebDriver driver = new ChromeDriver(service, chromeOptions);
You can enter the device required like iPhone X, iPad Pro, Samsung s7, etc..
Also remember that,
EnableMobileEmulation("deviceName");
deviceName:
The name of the device to emulate. The device name must be a valid device name
from the Chrome DevTools Emulation panel.
Note: specifying an invalid device name will not throw an exception, but will generate
an error in Chrome when the driver starts. To unset mobile emulation, call this
method with null as the argument.

Downloading a pdf in .NET 3.5 vs .NET 4.6 using C#

I have a third party server url that opens a pdf file in browser. Before one can access the pdf, request must be authenticated, so authentication information is integrated in the url. So It takes the form like:
SERVER_IP:/runReport.jsp?&jrs.cmd=jrs.get_subnodes&jrs.authorization=YWRtaW46YWRtaW4=&jrs.report_sheet$Report=true&jrs.catalog=/cata/catafolder/cataname.cat&jrs.report=/cata/catafolder/container.cls&jrs.result_type=2&jrs.profile=myProfile&jrs.param$InputAD;1_#assignmentId=AD0000695585
jrs.authorization=YWRtaW46YWRtaW4=
is authorization information attached to the URL. I developed two pieces of code.
The one in .NET 4.6 is:
HttpClient client = new HttpClient();
string param= "someparamvalue";
string url = UrlBuilder(param);
HttpResponseMessage message = client.GetAsync(url).Result;
HttpContent content = message.Content;
System.IO.Stream stream = content.ReadAsStreamAsync().Result;
FileStream fs = File.Create($"exported\\{param}.pdf");
stream.CopyTo(fs);
fs.Close();
stream.Close();
And it successfully downloads the pdf in the "exported" folder.
We have a restriction to do it in .NET 3.5 (.NET 4+ cannot be installed immediately on the machine), so I tried it with following code in 3.5:
string param= "someparamvalue";
string url = UrlBuilder(param);
string fileName = $"exported\\{param}.pdf";
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
wc.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
wc.DownloadFile(url, fileName);
but all it downloads, is a pdf that is 1) Cannot be opened with pdf reader (A message appears that says "File is either not supporte or corrupted...") 2) I can still open the downloaded file in "Notepad++", I see the html for login web page. (So even if authorization information is there in URL, it still didn't authenticate the user)
Anything, I am missing on how these 2 pieces of code work differently for same request? What wrong I am doing with 3.5 code ?

Spellcheck in web browser control not working under IE11 emulation

I am trying to have spellcheck work in a Winforms web browser control.
This is my current C# code:
try
{
String appname = Process.GetCurrentProcess().ProcessName + ".exe";
RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", RegistryKeyPermissionCheck.ReadWriteSubTree);
object ieVal = key.GetValue(appname, null);
MessageBox.Show(ieVal.ToString());
if (ieVal == null || (int)ieVal != 11001)
{
key.SetValue(appname, 11001, RegistryValueKind.DWord);
}
key.Close();
}
catch
{
MessageBox.Show("Registry stuff didn't work");
}
MessageBox.Show(webBrowser1.Version.ToString());
webBrowser1.DocumentText = "<html><head><body><div spellcheck=\"true\" style=\"width:100%; height:100%;\" contenteditable=\"true\"></div>"
+"<script>alert(navigator.userAgent);</script>"
+"</body></html>";
So first I set the proper registry key so that the browser emulates IE11
Then I add a div tag with spellcheck attribute set to true.
The version that the MessageBox.Show(webBrowser1.Version.ToString()) shows is:
11.0.9600.18525
The navigator.userAgent that the Javascript displays is:
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
So it seems like the web browser control is using IE11. But when I type the spell check doesn't work.
Note: When I run that html code with the real IE everything works properly.
Also, the navigator.userAgent displayed on the actual browser is:
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko
Note2: When I run my application on Windows 10 machine the spellcheck works. But I need to make it work on Windows 7 machines.
I had very similar problems using a WebBrowser control on a form and found 2 solutions, each with differing effects, which could both be used.
Using spellcheck=true in the HTML:
Adding the attribute spellcheck=true to the HTML or BODY or TEXTAREA tags, depending on where you want it implemented, will allow spelling checking on text input boxes (my tests were on Windows 10).
Note that any EXISTING text in the text boxes was not spell checked - you had to type NEW text in. This caught me out when running test EXEs with a pre-filled text box, which never got the little red underlines on its spelling mistakes.
Registry entry for FEATURE_SPELLCHECK
This did something different. It allowed spell checking in TinyMCE to work in our embedded web browser control. On its own, it did not enable spell checking in text areas.
See the link below for references to a registry key close to the one you were setting. However, it requires a new key and then a value that matches the name of the EXE you're running. In my case, this involved creating the FEATURE_SPELLCHECKING registry key, and then a DWORD with name TEST123.EXE and value 1.
https://msdn.microsoft.com/en-us/library/ee330735%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396#spellchecking
I found this through the page linked below, where someone reports it not working for Windows 7. Note that this person also tries it with a "local user" key, which does not work in my experience:
https://social.msdn.microsoft.com/Forums/ie/en-US/515fa4b1-2b85-46e4-a041-7dc27c4539c4/how-to-enable-spell-checker-in-web-browser-control-for-ie10?forum=ieextensiondevelopment
Use both of the above.
We found that approach 2 above met most of our needs, as we were using TinyMCE. However, in other applications, both 1 and 2 can be used in conjunction to provide the most functionality.

SSRS2008 ASP.NET ServerReport fails on IE11 with OEM UserAgent

I am rendering a SSRS ServerReport to PDF and in the ReportViewer WebForm Control in a ASP.NET 3.5 Application with a SQL Server Report Service 2008.
Some people using Internet Explorer 11 reported that they cannot open generated PDF files or see anything in the viewer.
The rendering fails with this error:
library!ReportServer_0-403!7c8!01/02/2014-11:07:37:: e ERROR: Throwing Microsoft.ReportingServices.Diagnostics.Utilities.InternalCatalogException: , Microsoft.ReportingServices.Diagnostics.Utilities.InternalCatalogException: Interner Fehler beim Berichtsserver. Weitere Informationen finden Sie im Fehlerprotokoll. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: String
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Web.Configuration.HttpCapabilitiesBase.get_MajorVersion()
at Microsoft.ReportingServices.Diagnostics.Utilities.BrowserDetectionUtility.GetBrowserInfoFromRequest(HttpRequest request)
at Microsoft.ReportingServices.Diagnostics.RSRequestParameters.SetBrowserCapabilities(HttpRequest request)
at Microsoft.ReportingServices.Library.RenderReportAction.SetBrowserCapabilities()
at Microsoft.ReportingServices.Library.RenderReportAction.PerformExecution()
at Microsoft.ReportingServices.Library.RenderReportAction.Render()
--- End of inner exception stack trace ---;
I could track these errors down to a OEM string used in the UserAgent of IE11.
Examples:
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MALC; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MATM; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; NP06; rv:11.0) like Gecko
MALC, MATM and NP06 appear to be OEM strings and are not part of the usual IE11 UserAgent.
Removing these strings in IEs developer tools user agent settings makes everything work normally, but is not a solution for the end user.
Things I have tried:
Overriding the UserAgent of the incoming Request in the ASP.NET application, but it appeared to never change regardless what I was setting. (I might have done this wrong, all I found was that I cannot change it so I tried anyway)
Override the header at the Begin-/EndRequest event in the Global.asax
Adding a custom .browser file in the App_Browser directory of the application itself and on the SSRS Server Application
What does work:
Intercepting the request and making a custom Request using HttpWebRequest with a different UserAgent, copying cookies (session id) and request/response headers back and forth.
I feel like this is a horrible solution and should not be done like this.
How can I make SSRS not throw an error while parsing IE11s UserAgent?
Is there a way to disable it or add a custom Regular Expression to parse it manually?
You can override the user agent to the report server by supplying additional device information.
This can be done when calling the Render method of the SOAP API by supplying this XML fragment as a parameter
<DeviceInfo>
<UserAgent>custom_user_agent_here</UserAgent>
</DeviceInfo>
Or using URL access like this
http://<Server Name>/reportserver?/SampleReports/Sales Order Detail&rs:Command=Render&rs:Format=HTML4.0&rc:UserAgent=custom_user_agent_here
.
References
Reporting Services Device Information Settings
http://msdn.microsoft.com/en-us/library/ms155397(v=sql.110).aspx
HTML Device Information Settings
http://msdn.microsoft.com/en-us/library/ms155395(v=sql.110).aspx

WebBrowser control to use IE9

I want that the WebBrowser control to use IE9. IE9 is installed on the computer, but the WebBrowser control is still using IE8.
I verified with http://www.whatbrowser.org/en/. I try to make some changes to the registry (found a solution here) but is not working.
I think it is the user agent string that is being passed to the site. It is misidentifying it as IE8 as it might not be meeting the requirements in their logic to match as IE9. I can see the same thing happen on my box as well. You could specify the user agent string to use if you want. Add this to your project
In your using statements add ...
using System.Runtime.InteropServices;
Within your form class add ....
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
public void ChangeUserAgent(String Agent)
{
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, Agent, Agent.Length, 0);
}
Then just call it somewhere in your code ... maybe the constructor, or the form_load event.
ChangeUserAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
Browsers lie about their "user agent" to give web sites a break. You're running 9, you cannot have 8 and 9 installed at the same time unless you used the beta version. See this blog post for details about the user agent string.
If you want to make sure then look at the DLL version that gets loaded. Project + Properties, Debug, tick "Unmanaged code debugging". Start your program, Debug + Break All. Debug + Windows + Modules and locate ieframe.dll in the list. The version number column should tell you. I'm getting "8.00.7600.16385 (win7_rtm.090713-1255)", the Win7 release version. I don't have IE9 installed yet.
Use this in the HTML head:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Otherwise:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION\yourexename.exe - REG_DWORD = 9000
(decimal)
You can try to add registry value that informs your WebBrowser control witch version of IE you would like to run for your application.
I had similar problem - more here
It seems it might be your page detection script. Try this site (http://www.whatismybrowser.com/). I know other sites gave me the wrong information, but this site correctly identified the browser as the version of IE that was installed on my machine.

Categories

Resources