Blog Archives

Android Launch Browser from App to handle external URLs

Upon googling for this one, I found some good relevant links on stack overflow as well as the android webview documentation, but no singular solution that tied everything together.

First, I created a custom WebViewClient class. Note that this is optional as you can do inline class declarations in this environment.

package com.example.testapp;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;

public class MyWebViewClient extends WebViewClient {
@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && url.startsWith('http://192.168.1.101')) {
            return false;
        } else {
        	view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    }
}

Then, in the main activity, use code within onCreate to support for multiple windows and to set the web view client to your own custom client.

package com.example.testapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.net.Uri;

public class MainActivity extends Activity {

	private WebView webView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	final Context context = this;
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    	webView = (WebView) findViewById(R.id.webView1);
    	webView.getSettings().setJavaScriptEnabled(true);
    	
    	webView.getSettings().setSupportMultipleWindows(true);

    	webView.setWebViewClient(new MyWebViewClient());
    	webView.loadUrl('http://192.168.1.1/login.aspx');
    }

If you want to use an inline class declaration instead of defining a seperate mywebviewclient class, you can also use something like:

    	webView.setWebViewClient(new WebViewClient() {
    	      @Override
    	      public boolean shouldOverrideUrlLoading(WebView view, String url) {
//etc, same code as above
    	      }
});

If you have not already addressed the question of handling the android back button within your webview, the android documentation has a good quick simple code reference on how to accomplish this.

Enjoy. :)

References
StackOverflow, http://stackoverflow.com/questions/5979361/android-open-url-in-a-new-window-without-leaving-app

StackOverflow, http://stackoverflow.com/questions/7028258/launch-browser-from-within-app-how-do-you-get-back-to-the-app

Android Documentation, http://developer.android.com/reference/android/webkit/WebView.html

URL Rewriting/Mapping using Global.asax

Ultimately I wound up using a different method, specified in my other blog post on URL Rewriting on GoDaddy and Shared hosting.

However, the method below is actually very useful if you are trying to do certain validation which cannot be expressed in web.config or RegEx prior to redirect, such as checking if querystring is valid and exists in database values, etc.

        //try out various request types such as absolute path and raw url to see differences
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string originalPath = HttpContext.Current.Request.Path.ToLower();
            //HttpContext.Current.Request.RawUrl.ToLower();
                //HttpContext.Current.Request.Path.ToLower();
            RewritePaths(originalPath);
        }

        private void RewritePaths(string originalPath)
        {
            Rewrite(originalPath, "default", "index");
            Rewrite(originalPath, "home", "index");
            Rewrite(originalPath, "index");
            Rewrite(originalPath, "login");
        }

        private void Rewrite(string path, string page)
        {
            if (path.Contains("/" + page))
            {
                if (!path.Contains(".aspx"))
                {
                    //Context.RewritePath(path.Replace("/" + page, "/" + page + ".aspx"));
                    Context.RewritePath(page + ".aspx");
                }
            }
        }

        private void Rewrite(string path, string frompage, string topage)
        {
            if (path.Contains("/" + frompage))
            {
                if (!path.Contains(".aspx")) {
                //Context.RewritePath(path.Replace("/" + frompage, "/" + topage + ".aspx"));
                Context.RewritePath(topage + ".aspx");
                }
            }
        }

URL Rewriting on GoDaddy and Shared hosting

After doing a lot of searching through google queries, forums and archives, I was finally able to solve the conundrum of using URL rewriting on GoDaddy.

The site in question is also a subdomain in a sub folder off the root site, meaning web.config rules cascade, which complicated things slightly more and was enough to send GD support over the edge.

So my site/domain/DNS setup was as follows:

//--parent
www.parentsite.com
//--and sub
subsite.parentsite.com
//--where sub is actually cname of
test.othersite.com

//--parent points to root folder
/web.config
/default.aspx
//--and sub points to subsite folder
/subsite/web.config
/subsite/default.aspx
//--desired url
/subsite/default //--should point to /subsite/default.aspx

I could not find a single article which presented a complete solution, including my own URL Mapping solution I presented in a previous article.

The simple solution in my previous article only works on GoDaddy servers if the mapping specifies a file extension on both the url and mapped url, such as:

<urlMappings enabled="true">
            <add url="~/default.aspx" mappedUrl="index.aspx"/>
            <add url="~/index.html" mappedUrl="index.aspx"/>
</urlMappings>

After speaking with GoDaddy support on 3 separate occasions, including callbacks from higher tiers, they informed me the mappings “work” and deferred to the above example..

So I dropped the simple approach of using URL Mappings, and stepped it up to URL Rewriting. According to GoDaddy kbase article, Microsoft URL Rewriting is supported, although for some reason they don’t include any examples..

I was able to at least get this working as intended after a little tweaking and reading through some of the references listed further below.

The configuration I am using is IIS7 with .Net 3.5. Haven’t tested it on 4.0 though this should work as well.

The solution:

(see code snippets above for domain structure in my scenario)

(( make sure you don't place modules or system.webServer in your web.config more than once.. you'll get a server 500 error :P ))

	<modules runAllManagedModulesForAllRequests="true">

<system.webServer>
    <rewrite>
      <rewriteMaps>
        <rewriteMap name="StaticRedirects">
<!-- this is similar to url mapping, but the user would actually see the aspx extension in the url -->
          <!-- <add key="/subsitefoldername/pagename" value="/pagename.aspx"/> -->
        </rewriteMap>
      </rewriteMaps>
      <rules>
        <rule name="RedirectRule" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{StaticRedirects:{REQUEST_URI}}" pattern="(.+)" />
          </conditions>
          <action type="Redirect" url="http://test.othersite.com{C:1}" appendQueryString="True" redirectType="Permanent" />
        </rule>
          <rule name="default">
            <match url="default" />
            <action type="Rewrite" url="default.aspx" /> <!-- this hides the extension as intended -->
          </rule>
        <rule name="login">
          <match url="login" />
          <action type="Rewrite" url="login.aspx" />
        </rule>
      </rules>
    </rewrite>

Unfortunately however, the above example can break page validation/viewstate, but that’s a topic for another article. :P

There is one other alternative to note that I also tried which also worked on my local server but not on GoDaddy was using Global.asax context rewrite. To avoid lengthiness, see deferred post on URL Rewriting/Mapping using Global.asax.

References
“Simple URL Rewriting/Mapping in IIS7″, http://ronniediaz.com/2011/04/06/simple-url-rewritingmapping-in-iis7/
Learn IIS, http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-7-integrated-pipeline/, http://learn.iis.net/page.aspx/465/url-rewrite-module-configuration-reference/, http://learn.iis.net/page.aspx/761/provide-url-rewriting-functionality/
Stackoverflow, http://stackoverflow.com/questions/416727/url-rewriting-under-iis-at-godaddy
Rackspacecloud, http://cloudsites.rackspacecloud.com/index.php/How_do_I_rewrite_URLs_from_ASP/.NET%3F
Godaddy kbase, http://help.godaddy.com/topic/623/article/5443

URL Decode in WPF

Crossing from web to forms development you may notice System.Web is not available. You could extract it from the GAC, but would suffer from having to manually update it moving forward.

One solution on the web suggested using Microsoft.XSS library (which is up to version 4.0 at the time of this article).

This would work, but there are some differences in string conversion, especially regarding the “+” and “~” character between using the Web UrlEncode/UrlDecode found in the XSS library or using the Uri method illustrated below.

See references for links to XSS and/or information regarding the differences on how these strings are encoded differently with each method.

Uri videouri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "../../Videos/directory/player.htm");

            string videourl = Uri.UnescapeDataString(videouri.ToString());

            webBrowser1.Navigate(videourl); //can actually accept uri or string

References
Microsoft Anti-XSS Library 4.0, http://www.microsoft.com/downloads/en/details.aspx?FamilyID=F4CD231B-7E06-445B-BEC7-343E5884E651
Nerdbank, http://blog.nerdbank.net/2009/05/uriescapedatapath-and.html
StackOverflow, http://stackoverflow.com/questions/36315/alternative-to-httputility-for-net-3-5-sp1-client-framework

URL Encode in .Net

C#: (ASP .Net)

System.Web.HttpUtility.UrlEncode()

C#: (Client/Server Environment)

Uri.EscapeUriString()

References
MSDN, WebUtility Classhttp://msdn.microsoft.com/en-us/library/system.net.webutility.aspx
MSDN, Uri Classhttp://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx
MSDN blogs, http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

Get Current URL in Javascript

JS (JQuery):

$(document).ready(function() {
    $(location).attr('href');
});

JS (standard):

function CurrentURL() {
    var currenturl = window.location.pathname;
return currenturl;
}
Follow

Get every new post delivered to your Inbox.