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

DLL in Stored Procedure MSSQL

Extended Stored Procedures (MSDN), http://support.microsoft.com/kb/190987

Thread Local Storage in an extended stored procedure (MSDN), http://support.microsoft.com/kb/163449

HTTP Post in C# .Net

Why re-invent the wheel? 😉

See below for a few quick examples from the minds over at csharp-online and codeproject.


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All examples are in C# .Net.

HTTP Post:

using System.Net;
...
string HttpPost (string uri, string parameters)
{ 
   // parameters: name1=value1&name2=value2	
   WebRequest webRequest = WebRequest.Create (uri);
   //string ProxyString = 
   //   System.Configuration.ConfigurationManager.AppSettings
   //   [GetConfigKey("proxy")];
   //webRequest.Proxy = new WebProxy (ProxyString, true);
   //Commenting out above required change to App.Config
   webRequest.ContentType = "application/x-www-form-urlencoded";
   webRequest.Method = "POST";
   byte[] bytes = Encoding.ASCII.GetBytes (parameters);
   Stream os = null;
   try
   { // send the Post
      webRequest.ContentLength = bytes.Length;   //Count bytes to send
      os = webRequest.GetRequestStream();
      os.Write (bytes, 0, bytes.Length);         //Send it
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Request error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   finally
   {
      if (os != null)
      {
         os.Close();
      }
   }
 
   try
   { // get the response
      WebResponse webResponse = webRequest.GetResponse();
      if (webResponse == null) 
         { return null; }
      StreamReader sr = new StreamReader (webResponse.GetResponseStream());
      return sr.ReadToEnd ().Trim ();
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Response error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   return null;
} // end HttpPost 

Intermediate webrequest usage:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
 
namespace BaseClassNameSpace.Web.BaseServices
{

//This base class provides implementation of request 

//and response methods during Http Calls.
      public class HttpBaseClass
      {
 
            private string UserName;
            private string UserPwd;
            private string ProxyServer;
            private int ProxyPort;
            private string Request;
            
            public HttpBaseClass(string HttpUserName, 
              string HttpUserPwd, string HttpProxyServer, 
              int HttpProxyPort, string HttpRequest)
            {
                  UserName = HttpUserName;
                  UserPwd = HttpUserPwd;
                  ProxyServer = HttpProxyServer;
                  ProxyPort = HttpProxyPort;
                  Request = HttpRequest;
            }
 
/// <summary>

// This method creates secure/non secure web
// request based on the parameters passed.
            public virtual HttpWebRequest CreateWebRequest(string uri, 
              NameValueCollection collHeader, 
              string RequestMethod, bool NwCred)
            {
                  HttpWebRequest webrequest = 
                   (HttpWebRequest) WebRequest.Create(uri);
                  webrequest.KeepAlive = false;
                  webrequest.Method = RequestMethod;
 
                  int iCount = collHeader.Count;
                  string key;
                  string keyvalue;
 
                  for (int i=0; i < iCount; i++)
                  {
                        key = collHeader.Keys[i];
                        keyvalue = collHeader[i];
                        webrequest.Headers.Add(key, keyvalue);
                  }
                  
                  webrequest.ContentType = "text/html"; 
                  //"application/x-www-form-urlencoded";

                  if (ProxyServer.Length > 0)
                  {
                     webrequest.Proxy = new 
                      WebProxy(ProxyServer,ProxyPort);
                  }
                  webrequest.AllowAutoRedirect = false;
 
                  if (NwCred)
                  {
                      CredentialCache wrCache = 
                              new CredentialCache();
                      wrCache.Add(new Uri(uri),"Basic",
                        new NetworkCredential(UserName,UserPwd));
                      webrequest.Credentials = wrCache;
                  }
                  //Remove collection elements

                  collHeader.Clear();
                  return webrequest;
            }//End of secure CreateWebRequest

            
            // This method retreives redirected URL from

            // response header and also passes back

            // any cookie (if there is any)

            public virtual string GetRedirectURL(HttpWebResponse 
                 webresponse, ref string Cookie)
            {
                  string uri="";
 
                  WebHeaderCollection headers = webresponse.Headers;
                  
                  if ((webresponse.StatusCode == HttpStatusCode.Found) || 
                    (webresponse.StatusCode == HttpStatusCode.Redirect) ||
                    (webresponse.StatusCode == HttpStatusCode.Moved) ||
                    (webresponse.StatusCode == HttpStatusCode.MovedPermanently))
                  {
                        // Get redirected uri

                        uri = headers["Location"] ;
                        uri = uri.Trim();
                  }
 
                  //Check for any cookies

                  if (headers["Set-Cookie"] != null)
                  {
                        Cookie = headers["Set-Cookie"];  
                  }
                  //                string StartURI = "http:/";

//                if (uri.Length > 0 && uri.StartsWith(StartURI)==false)

//                {

//                      uri = StartURI + uri;

//                }

                  return uri;
            }//End of GetRedirectURL method

            public virtual string GetFinalResponse(string ReUri, 
             string Cookie, string RequestMethod, bool NwCred)
            {
                  NameValueCollection collHeader = 
                        new NameValueCollection();
 
                  if (Cookie.Length > 0)
                  {
                        collHeader.Add("Cookie",Cookie);
                  }
 
                  HttpWebRequest webrequest = 
                    CreateWebRequest(ReUri,collHeader, 
                    RequestMethod, NwCred);
                        
                  BuildReqStream(ref webrequest);
 
                  HttpWebResponse webresponse;
 
                  webresponse = (HttpWebResponse)webrequest.GetResponse();
 
                  Encoding enc = System.Text.Encoding.GetEncoding(1252);
                  StreamReader loResponseStream = new 
                    StreamReader(webresponse.GetResponseStream(),enc);
 
                  string Response = loResponseStream.ReadToEnd();
 
                  loResponseStream.Close();
                  webresponse.Close();
                  
                  return Response;
            }
 
            private void BuildReqStream(ref HttpWebRequest webrequest)
            {
                  byte[] bytes = Encoding.ASCII.GetBytes(Request);
                  webrequest.ContentLength=bytes.Length;
 
                  Stream oStreamOut = webrequest.GetRequestStream();
                  oStreamOut.Write(bytes,0,bytes.Length);
                  oStreamOut.Close();
            }
      }
}//End of HttpBaseClass class

References:
Csharp-online, “HTTP Post”, http://en.csharp-online.net/HTTP_Post
Codeproject, “How to use HttpWebRequest and HttpWebResponse in .NET”, http://www.codeproject.com/KB/IP/httpwebrequest_response.aspx

String Formatting

Snippets below have been condensed from their original sources for brevity. See references for original articles.

All examples are in C# .Net.

My own little function:

   private string DynamicFormat(string dbformatstring, string contentstring)
        {
            foreach (string item in dbformatstring.Split(',')) {
            string propname = item.Split(':')[0];
                string propvalue = item.Split(':')[1];
                contentstring = contentstring.Replace("{"+propname+"}",propvalue);
            }

            return contentstring;
        }

Format With extension method by James Newton-King:

public static string FormatWith(this string format, params object[] args)
{
  if (format == null)
    throw new ArgumentNullException("format");
 
  return string.Format(format, args);
}
 
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
  if (format == null)
    throw new ArgumentNullException("format");
 
  return string.Format(provider, format, args);
}

References
James Newton-King, “FormatWith”,http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx

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

JQuery Grid Themes

Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.

Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html

Datatables.Net:
http://www.datatables.net/styling/themes/smoothness

Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html

Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html

Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables

JQuery and Partial Postbacks

I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.

Javascript (JQuery):

Sys.Application.add_load(startJQuery); 

startJQuery() { 
//do JQ here
}

And alternatively..

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.

RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.

The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel

C#:


int scriptnumber = 1;
string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString());
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath));
            jqueryfileoutput = sr.ReadToEnd();

            upnlBodyContent.Update();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname",
                "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);

JQuery and Frames

Although there is definitely some room for debate in the web development and design community on where the usage of frames is necessary, there are some situations where they cannot be avoided.

Manipulation of data within these frames can be confusing, and dumping frames to page content using ajax or server side code is not always possible. This is especially true if these pages contain their own sub-site navigation.

In these scenarios, JQuery helps us simplify content management within frames using a combination of the “.contents()” method and “find” functionality to locate and update elements.

If “videoframe” is the id of the iframe, the example below changes the background color of a body inside the frame to a specific color.

JS (JQuery):


$('#videoframe').contents().find("body").css("background-color", "#FFFFFF");

References:
JQuery API, http://api.jquery.com/contents

JQuery AJAX Reference

Keep in mind when using code below if requesting a page that requires login/restricted access, users login session is not carried over.

Snippet below is sample code usage illustrating two different methods of achieving similar result. See references for more info and full specifications.

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/',
                            dataType: "text",
                            type: "POST",
                            data: { city: "NewYork"},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/' + data1+ data2,
                            dataType: "text",
                            type: "GET",
                            data: {},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

References:
JQuery Ajax, http://api.jquery.com/jQuery.ajax/

JQuery Is Not Defined

This is a common error for users implementing JQuery UI. Usually if you see this message, this could mean a few things:

– There is a syntax issue or bad link referencing the JQuery (min/full) JS. Use your debuggers to make sure the JS is loading.

– Similar to above this could also mean the JS cannot be loaded due to being contained in a folder which the site does not have permission to.

– If you are debugging locally and referencing the JQuery JS on an external site, make sure you have internet access and that the site which you are referencing to is up.

– The arrangement of script references may be in the wrong order. JS loads on runtime, so dependencies are important in placement of the script reference on the page. JQuery UI depends on JQuery(min), so (min) must be declared first or you will encounter the error.

As always, Firebug and other web development debuggers such as the one’s built into Chrome and IE are great tools to help you identify and resolve issues such as these.

Hope this may lighten someone’s day. 🙂

    <script src="../JQuery/js/jquery-1.4.4.min.js" type="text/javascript"></script>

    <link href="../JQuery/css/smoothness/jquery-ui-1.8.7.custom.css" rel="stylesheet"
        type="text/css" />

    <script src="../JQuery/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>

References:
Firebug, http://getfirebug.com/
JQuery UI, http://jqueryui.com/