Mobile Device detection using asp.net and C# - mobile

I have to detect mobile browser and if detect as mobile browser then I have to show some content on the web page.
I am using Request.Browser.IsMobileDevice but it fails for iPhone like handsets.

I don't really know if that can help you but, few months ago i used driveInfo to detect USB device
maybe that can work for detect your iPhone
try to take a look here: http://msdn.microsoft.com/en-us/library/system.io.driveinfo.isready.aspx
And for the event you can try this:
static ManagementEventWatcher w = null;
private static void USBHandler(){
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
q = new WqlEventQuery();
q.EventClassName = "__InstanceCreationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += USBInserted;
w.Start();
}
private static void USBInserted(object sender, EventArgs e){
System.Windows.MessageBox.Show("USB inserted");
}

take a look at http://51degrees.mobi/ You can download their nuget package into your project it works well to detect mobile devices

Related

AxInterop.ShockwaveFlashObjects missing in COM objects

I am trying to run SWF game in my WPF application. This game accepts some variables which should be constantly updated (about 100 times a second). I did some research and I know that basically there are 2 possibilities to run SWF in WPF:
Embed WebBrowser and pass path to the SWF file.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// fixes warning about ActiveX security
string C_Drive_local = "file://127.0.0.1/c$/";
// path of the flash file, here its in C:\DemoContent\bounce.swf
Uri swfPath = new Uri( C_Drive_local + "DemoContent/bounce.swf");
// load it in the browser
MySWFBrowser.Source = swfPath;
}
Use WindowsFormsHost to host an AxShockwaveFlash control
private void FlashLoaded(object sender, RoutedEventArgs e)
{
WindowsFormsHost formHost = new WindowsFormsHost();
AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlash();
formHost.Child = axShockwaveFlash;
mainGrid.Children.Add(formHost);
string flashPath = Environment.CurrentDirectory;
flashPath += #"\game.swf";
axShockwaveFlash.Movie = flashPath;
}
I would like to try with AxShockwaveFlash since it provides methods for setting variables but in my COM objects I can not see AxInterop.ShockwaveFlashObjects.dll
I tried to install several different versions of Flash Player but without success. I cannt find any information about it. How can I get AxInterop.ShockwaveFlashObjects.dll ? What should I install to have it?

Accessing document elements when using Windows.Forms.WebBrowser

I'm new to automating webpage access, so forgive what is probably a remedial question. I'm using C#/Windows.Forms in a console app. I need to programmatically enter the value of an input on a webpage that I cannot modify and that is running javascript. I have successfully opened the page (triggering WebBrowser.DocumentCompleted). I set browser emulation mode to IE11 (in registry), so scripts run without errors. When DocumentCompleted() triggers, I am unable to access the document elements without first viewing the document content via MessageBox.Show(), which is clearly not acceptable for my unattended app.
What do I need to do so that my document elements are accessbile in an unattended session (so I can remove MessageBox.Show() from the code below)? Details below. Thank you.
The input HTML is:
<input class="input-class" on-keyup="handleKeyPress($key)" type="password">
My DocumentCompleted event handler is:
private static void LoginPageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = ((WebBrowser)sender);
var document = wb.Document;
// I'm trying to eliminate these 3 lines
var documentAsIHtmlDocument = (mshtml.IHTMLDocument)document.DomDocument;
var content = documentAsIHtmlDocument.documentElement.innerHTML;
MessageBox.Show(content);
String classname = null;
foreach (HtmlElement input in document.GetElementsByTagName("input"))
{
classname = input.GetAttribute("className");
if (classname == "input-class")
{
input.SetAttribute("value", password);
break;
}
}
}
The problem for me was that the page I'm accessing is being created by javascript. Even though documentComplete event was firing, the page was still not completely rendered. I have successfully processed the first page by waiting for the document elements to be available and if not available, doing Application.DoEvents(); in a loop until they are, so I know now that I'm on the right track.
This SO Question helped me: c# WebBrowser- How can I wait for javascript to finish running that runs when the document has finished loading?
Note that checking for DocumentComplete does not accurately indicate the availability of the document elements on a page generated by javascript. I needed to keep checking for the elements and running Application.DoEvents() until they became available (after the javascript generated them).
If the problem comes from the creation of a STAThread, necessary to instantiate the underlying Activex component of WebBrowser control, this is
a modified version of Hans Passant's code as shown in the SO Question you linked.
Tested in a Console project.
class Program
{
static void Main(string[] args)
{
NavigateURI(new Uri("[SomeUri]", UriKind.Absolute), "SomePassword");
Console.ReadLine();
}
private static string SomePassword = "SomePassword";
private static void NavigateURI(Uri url)
{
Thread thread = new Thread(() => {
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate(url);
Application.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
protected static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = ((WebBrowser)sender);
if (browser.Url == e.Url)
{
while (browser.ReadyState != WebBrowserReadyState.Complete)
{ Application.DoEvents(); }
HtmlDocument Doc = browser.Document;
if (Doc != null)
{
foreach (HtmlElement input in Doc.GetElementsByTagName("input"))
{
if (input.GetAttribute("type") == "password")
{
input.InnerText = SomePassword;
//Or
//input.SetAttribute("value", SomePassword);
break;
}
}
}
Application.ExitThread();
}
}
}

WinForms - Show notification count in app launcher Icon

In my WinForms application, I want to display the notifications count in the app launcher icon.
How can this be achieved ?
I believe this is what you're asking for, unfortunately it is in WPF. Winforms doesn't provide a way to do that. You need to P/Invoke manually.
Download Windows 7 API Code Pack - Shell
and use the following.
private void SetTaskBarOverlay()
{
string notificationCount = "3"; //To do: Add this as a parameter
var bmp = new Bitmap(32, 32);
using (Graphics g = Graphics.FromImage(bmp))
{
g.FillEllipse(Brushes.Blue, new Rectangle(Point.Empty, bmp.Size));
g.DrawString(notificationCount, new Font("Sans serif", 25, GraphicsUnit.Point),
Brushes.White, new Rectangle(Point.Empty, bmp.Size));
}
var overlay = Icon.FromHandle(bmp.GetHicon());
TaskbarManager.Instance.SetOverlayIcon(overlay, "");
}
private void RemoveTaskBarOverlay()
{
TaskbarManager.Instance.SetOverlayIcon(null, "");
}
You may alter the painting code to achieve the desired effect.

Silverlight Application.InstallState - Incorrect

I'm using the pattern Tim Heuer outlines here for my Silverlight 4 OOB installation pattern:
http://timheuer.com/blog/archive/2009/08/12/silverlight-out-of-browser-force-install-pattern.aspx
Here is my app's *Application_Startup* method:
private void Application_Startup(object sender, StartupEventArgs e)
{
//string _USERID = e.InitParams["UserAccount"];
if ((App.Current.InstallState == InstallState.Installed) && (!App.Current.IsRunningOutOfBrowser))
{
this.RootVisual = new Installed();
}
else if (!App.Current.IsRunningOutOfBrowser)
{
this.RootVisual = new Installer();
}
else
{
this.RootVisual = new MainPage();
}
ShowBusy(false);
}
The problem is that even when the app is installed and running App.Current.InstallState returns NotInstalled and App.Current.IsRunningOutOfBrowser is false - so my control Installed never shows, it always show the Installer control.
This is the case in both my dev and deployed environments.
I'm stumped on this one, anyone have thoughts?
I have seen problems with this when the browser is in private browsing mode.
UPDATE: Red Herring - refer comments
Have the same problem.
I've heard that this only works proper when the application has been code-signed. Don't know if this is true as I cannot test to verify.
This might relate: http://msdn.microsoft.com/en-us/library/dd550721(v=vs.95).aspx

Managing cookies in a WPF WebBrowser control?

Is there a way to read/write the cookies that a WebBrowser control uses?
I am doing something like this...
string resultHtml;
HttpWebRequest request = CreateMyHttpWebRequest(); // fills http headers and stuff
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
resultHtml = sr.ReadToEnd();
}
WebBrowser browser = new WebBrowser();
browser.CookieContainer = request.CookieContainer; // i wish i could do this :(
browser.NavigateToString(resultHtml);
One of the potentially confusing things about the WebBrowser control and cookies is that at a first glance, it often looks like your app gets a separate cookie store. For example, if you log into a site that stores a persistent cookie to identify you, then whether you appear to be logged in for that site from inside an app hosting the control will be independent of whether you seem to be logged in via Internet Explorer.
In fact, you can even be logged in with different identities.
However, although it might be natural to draw the conclusion that each app hosting the WebBrowser therefore gets its own cookies, in fact that's not true. There are merely two sets of cookies: the ones used in 'low integrity' mode (which is what IE runs in by default), and the other set, which is what you'll get in a normal app that hosts the WebBrowser and also what you'll get if you run IE elevated.
the webbrowser control uses WinInet for networking, specifically use the InternetSetCookie(Ex) and InternetGetCookie(Ex) functions for Cookie management. There isn't a WinInet wrapper in .Net, but you can p-invoke.
Yes you are right, InternetGetCookieEx is the only way to retrieve HttpOnly cookies and it is the preferred way to grab cookie from WebBrowser control.
I posted a complete example here
You can use Application.GetCookie and Application.SetCookie methods.
Although Application is more or less related to WPF, you can use these methods in any desktop .NET code. In fact, they are wrappers on InternetGetCookieEx and InternetSetCookieEx Windows APIs.
I faced the same issue few days ago.
Besides the examples of the previous answers, here is a Win32 wrapper for the WebBrowser control. The advantage of this implementation is that it exposes more options that the default WebBrowser control.
Unfortunately if It's not WPF native, so you will have to create a wrapper if you're planning to use it in WPF.
http://code.google.com/p/csexwb2/
Here is sample from [link][1]
> public static class WinInetHelper
{
public static bool SupressCookiePersist()
{
// 3 = INTERNET_SUPPRESS_COOKIE_PERSIST
// 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
return SetOption(81, 3);
}
public static bool EndBrowserSession()
{
// 42 = INTERNET_OPTION_END_BROWSER_SESSION
return SetOption(42, null);
}
static bool SetOption(int settingCode, int? option)
{
IntPtr optionPtr = IntPtr.Zero;
int size = 0;
if (option.HasValue)
{
size = sizeof(int);
optionPtr = Marshal.AllocCoTaskMem(size);
Marshal.WriteInt32(optionPtr, option.Value);
}
bool success = InternetSetOption(0, settingCode, optionPtr, size);
if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
return success;
}
[System.Runtime.InteropServices.DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(
int hInternet,
int dwOption,
IntPtr lpBuffer,
int dwBufferLength
);
}

Resources