Blog Archives

heroku cheat sheet quick start

#note requires java 8. add the ppa repo for oracle and install this if you dont have it already. check your local with: java -version

#create auth token for subsequent commands
heroku login

#from within a local git cloned app root, to create a new dyno
heroku create

git push heroku master

#check if dyno is running
heroku ps:scale web=1

#shortcut to open the dyno. if you are running these in a remote SSH you will need to X11 forward for this to work
#or simply, just open the address indicated after you push
#this uri is also visible using the logs command below
heroku open

#tail logs for running dyno. refresh the browser while you are viewing the app to verify new log entries added
heroku logs --tail

#procfile declares what command is executed at start of app. this is likely web.
#for windows: this is different. see heroku docs and make and use heroku -f

#general note regarding the “free-ness” of heroku on your first app
“By default, your app is deployed on a free dyno. Free dynos will sleep after a half hour of inactivity and they can be active (receiving traffic) for no more than 18 hours a day before going to sleep. If a free dyno is sleeping, and it hasn’t exceeded the 18 hours, any web request will wake it. This causes a delay of a few seconds for the first request upon waking. Subsequent requests will perform normally”

#pom.xml specifies dependencies in the case of java determines version of java to use

#pull in dependencies to target/dependency and store this in pom.xml
mvn clean install

#to start heroku locally
heroku local web

#install add-ons
heroku addons:create papertrail

#list add-ons
heroku addons

#open add-on logs
heroku addons:open papertrail

#test a command on a one-off dyno, e.g. run bash in local dyno
heroku run bash

#set environment variables
heroku config:set ENERGY="20 GeV"

#view environment variables
heroku config

#show database info, e.g. postgres
heroku pg

#run tsql commands
heroku pg:psql


directory info get files show directories C# .Net

There is sometimes a misunderstanding between a “file” and a “folder” in filesystems. In C# .Net the following is often used to list all “files” in a folder.

DirectoryInfo di = new DirectoryInfo("yourpath");

foreach (FileInfo fi in di.GetFiles()) {
//do work

However, even though you can specify to search containing subdirectories, the above function will not inherently list folders. If you are looking for the equivalent to “dir” or “ls”, instead use “GetFileSystemInfos()”.

            DirectoryInfo di = new DirectoryInfo("yourpath");
//note the difference here with getfilesysteminfos
		foreach (dynamic d in di.GetFileSystemInfos()) {

Note the usage of dynamic in the above example compared to the first example. This avoids any potential issues with inheritance and choosing the right class for your temp iterator variable for unboxing etc.

android app cannot connect to internet

To allow your custom app to connect to the internet, add the following in your AndroidManifest.xml file right before (outside) the application tag.

<uses-permission android:name="android.permission.INTERNET" />

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.content.Context;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;

public class MyWebViewClient extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null &amp;amp;&amp;amp; url.startsWith('')) {
            return false;
        } else {
                    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.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;

public class MainActivity extends Activity {

	private WebView webView;
    public void onCreate(Bundle savedInstanceState) {
    	final Context context = this;

    	webView = (WebView) findViewById(;

    	webView.setWebViewClient(new MyWebViewClient());

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() {
    	      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. :)



Android Documentation,

Get Current Directory in Objective-C

Since Mac OS X is a unix based system, you can always use “getcwd” from the standard C library, but in general if you want to stick within the context of Objective-C/Cocoa, see the examples below.

Here’s one snippet you will probably Google quickly, but ultimately not the solution I chose.

(original code from stackoverflow see reference below)

NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];


Using the “bundle path” rather than “executable path” turned out to work much better in my instance:

NSString *currentpath = [[[[NSBundle mainBundle] bundlePath] stringByDeletingPathExtension] stringByDeletingLastPathcomponent];
NSString *fileName = [NSString stringWithFormat:@"%@/%@/",currentpath,@"filename.pdf"];

References,, “NSFileManager”,, “Working with Directories in Objective c”,
Macrumors Forums,
stackoverflow, “Find Parent Directory of a path”,

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.

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;
   { // 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 );
      if (os != null)
   { // 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"; 

                  if (ProxyServer.Length > 0)
                     webrequest.Proxy = new 
                  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

                  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)
                  HttpWebRequest webrequest = 
                    RequestMethod, NwCred);
                  BuildReqStream(ref webrequest);
                  HttpWebResponse webresponse;
                  webresponse = (HttpWebResponse)webrequest.GetResponse();
                  Encoding enc = System.Text.Encoding.GetEncoding(1252);
                  StreamReader loResponseStream = new 
                  string Response = loResponseStream.ReadToEnd();
                  return Response;
            private void BuildReqStream(ref HttpWebRequest webrequest)
                  byte[] bytes = Encoding.ASCII.GetBytes(Request);
                  Stream oStreamOut = webrequest.GetRequestStream();
}//End of HttpBaseClass class

Csharp-online, “HTTP Post”,
Codeproject, “How to use HttpWebRequest and HttpWebResponse in .NET”,

URL Encode in .Net

C#: (ASP .Net)


C#: (Client/Server Environment)


MSDN, WebUtility Class
MSDN, Uri Class
MSDN blogs,

Quick .Net Encryption Reference

The code below represents a very basic .NET encryption class which has been tested and should work in your application – simply plug and play. :)

Contains two static methods that can be called without needing to instantiate the class.

Keep in mind the initialization vector below (indicated by rgbIV) is generic, and you will need to come up with your own. Remember not to share this. Even if the password is compromised, the attacker would also need to know the initialization vector to crack your value.

Also note the code which has been commented out. This illustrates cases where passwords and/or IV can be statically set in the class and/or shared based on value passed in for password parameter.

Sharing IV and password or storing either statically is a security risk and could cause errors depending on byte differences of the values. If you statically store these values, you will still create secure cipher text, but it will be much easier to crack.

Enjoy. ;)

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace AIS.Common.Crypto

public static class Rijndael
    public static string Encrypt(string ClearText,string password)

        byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);


        return Convert.ToBase64String(ms.ToArray());

    public static string Decrypt(string EncryptedText, string password)
        byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

        MemoryStream ms = new MemoryStream();

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),

        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);


        return Encoding.UTF8.GetString(ms.ToArray());



Wikipedia – Encryption,

Get Current URL in Javascript

JS (JQuery):

$(document).ready(function() {

JS (standard):

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

JQuery Grid Themes

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







Get every new post delivered to your Inbox.

Join 27 other followers