Objective C: UITextField controlling background image/color

If you set
UITextField *tf = [[UITextField alloc] init];
tf.borderStyle = UITextBorderStyleRoundedRect;
you can't control background of text field. To controlling background you need
#import "QuartzCore/QuartzCore.h"
...

UITextField *tf = [[UITextField alloc] init];
tf.borderStyle = UITextBorderStyleDefault;
tf.background = [UIImage imageNamed:@"bg_000000_20.png"];
tf.layer.cornerRadius = 5.0;
tf.layer.masksToBounds = YES;

// for vertical align
tf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

// for border
tf.layer.borderWidth = 1.0;
tf.layer.borderColor = [[UIColor darkGrayColor] CGColor];

// for left padding
tf.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
tf.leftViewMode = UITextFieldViewModeAlways;

Java: Read key from Windows Registry.

After create new windows registry in cmd by:
reg add HKLM\SOFTWARE\Policies\MyApplication\AES /v SecurityKey /d 12345678901234567890123456789012
need read it from java
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

/**
 * @author Oleg Ryaboy, based on work by Miguel Enriquez 
 */
public class WindowsReqistry {

    /**
     * 
     * @param location path in the registry
     * @param key registry key
     * @return registry value or null if not found
     */
    public static final String readRegistry(String location, String key){
        try {
            // Run reg query, then read output with StreamReader (internal class)
            Process process = Runtime.getRuntime().exec("reg query " + 
                    '"'+ location + "\" /v " + key);

            StreamReader reader = new StreamReader(process.getInputStream());
            reader.start();
            process.waitFor();
            reader.join();

            // Parse out the value
            String[] parsed = reader.getResult().split("\\s+");
            if (parsed.length > 1) {
                return parsed[parsed.length-1];
            }
        } catch (Exception e) {}

        return null;
    }

    static class StreamReader extends Thread {
        private InputStream is;
        private StringWriter sw= new StringWriter();

        public StreamReader(InputStream is) {
            this.is = is;
        }

        public void run() {
            try {
                int c;
                while ((c = is.read()) != -1)
                    sw.write(c);
            } catch (IOException e) { 
            }
        }

        public String getResult() {
            return sw.toString();
        }
    }
    public static void main(String[] args) {

        // Sample usage
        String value = WindowsReqistry.readRegistry("HKLM\\SOFTWARE\\Policies\\MyApplication\\AES", "SecurityKey");
        System.out.println(value);
    }
}

Android: Import SSL certificate and use it to SSL connection


  1. First of all you need get SSL certificate. You can obtain certificate (file with .cer extention) from the chain included in the endpoint certificate or from the official site of the issuer (in the Base64 encoded X.509 format).

    Or if you have this certificate installed on you local computer you can obtain it by run "mmc" (Microsoft Management Console) from command line ("Prompt" or "Run"). If you don't have Certificate snap-in go to  File -> Add/Remove Snap-in... -> Select from available snap-ins "Certificates" -> Add to Selected snap-ins -> Ok.

    Find certificate what do you need -> Right click -> All Tasks -> Export -> Select Base-64 encoded X.509 (.CER) -> Save into my_certificate.cer in my_certificate_path place.

    Content of this file look like:
    -----BEGIN CERTIFICATE-----
    MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0B...
    -----END CERTIFICATE-----
    
  2. For create the keystore download latest release of Bouncy Castle provider (bcprov-jdkxx-xxx.jar) and store it in provider_path place. You must have JRE installation for invoke keytool (located under bin folder). You may add path to keytool into CLASSPATH environment variable or use absolute path.
  3. Execute this command for create mykeystore.bks (don't use upper case and "_" for name):
    D:/PROGRA~1/Java/jre7/bin/keytool -importcert -v -trustcacerts -file "my_certificate_pathmy_certificate.cer" -alias myAlias -keystore "my_keystore_path/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "provider_path/bcprov-jdkxx-xxx.jar" -storetype BKS -storepass "my_password"
    
  4. You may verify if the certificate was imported correctly
    D:/PROGRA~1/Java/jre7/bin/keytool -list -keystore "my_keystore_path/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "provider_path/bcprov-jdkxx-xxx.jar" -storetype BKS -storepass "my_password"
    
  5. Paste you mykeystore.bks as a raw resource under res/raw (this generate R.raw.mykeystore resource)
  6. Create a custom HttpClient to use you SSL certificate for HTTPS connection:
    import java.io.InputStream;
    import java.security.KeyStore;
    
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.SingleClientConnManager;
    
    import android.content.Context;
    
    public class MyHttpsClient extends DefaultHttpClient {
      
        final Context context;
     
        public MyHttpsClient(Context context) {
            this.context = context;
        }
     
        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            // Register for port 443 our SSLSocketFactory with our keystore
            // to the ConnectionManager
            registry.register(new Scheme("https", newSslSocketFactory(), 443));
            return new SingleClientConnManager(getParams(), registry);
        }
     
        private SSLSocketFactory newSslSocketFactory() {
            try {
                // Get an instance of the Bouncy Castle KeyStore format
                KeyStore trusted = KeyStore.getInstance("BKS");
                // Get the raw resource, which contains the keystore with
                // your trusted certificates (root and any intermediate certs)
                InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
                try {
                    // Initialize the keystore with the provided trusted certificates
                    // Also provide the password of the keystore
                    trusted.load(in, "my_password".toCharArray());
                } finally {
                    in.close();
                }
                // Pass the keystore to the SSLSocketFactory. The factory is responsible
                // for the verification of the server certificate.
                SSLSocketFactory sf = new SSLSocketFactory(trusted);
                // Hostname verification from certificate
                // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
                sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
                return sf;
            } catch (Exception e) {
                throw new AssertionError(e);
            }
        }
    }
    
  7. Use you custom HttpClient:
    DefaultHttpClient client = new MyHttpsClient(getApplicationContext());
    

Objective C: Detect start of bouncing effect for UIScrollView

For detect bouncing of UIScrollView (or UITableView ...) using UIScrollViewDelegate:
static BOOL _draggingView = NO;

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
 _draggingView = YES;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
 _draggingView = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
 NSInteger pullingDetectFrom = 50;
 if (self.contentOffset.y < -startDetecting) {
  _draggingView = NO;
  NSLog(@"Pull Down");
 } else if (self.contentSize.height <= self.frame.size.height && self.contentOffset.y > startDetecting) {
  _draggingView = NO;
  NSLog(@"Pull Up");
 } else if (self.contentSize.height > self.frame.size.height && 
       self.contentSize.height-self.frame.size.height-self.contentOffset.y < -startDetecting) {
  _draggingView = NO;
  NSLog(@"Pull Up");
 }
}

Objective C: Sort array of objects

If we have array of some objects:
@interface SimpleObject : NSObject {
 NSInteger key;
 NSString *name;
        . . .
}
and we need to sort this array by "name" property of SimpleObject. Use NSSortDescriptor:
// declare array with SimpleObject instances
self.simpleObjectsArray = . . .

NSSortDescriptor *sortDescriptor =
        [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
NSArray *sortDescriptors = 
        [NSArray arrayWithObject:sortDescriptor];
// array contained all instances sorted by "name" field
NSArray *sortedArray = 
        [self.simpleObjectsArray sortedArrayUsingDescriptors:sortDescriptors];

Objective C: Bring back user to your application during/after he End the Call

Sometime you need come back to application after phone call initiated by your own application.
Exist two options (each from them not 100% that do you want), but if no choice..

  1. After starting phone call you getting local notification alert with two option
    • Cancel (stay on call screen)
    • Return (back to application during your call)
    NSURL *phoneSchemaURL = [NSURL URLWithString:@"tel://123456789"];
     
    [[UIApplication sharedApplication] openURL:phoneSchemaURL];
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    if (localNotification != nil) {
     NSDate *notificationDate = [[NSDate alloc] initWithTimeIntervalSinceNow: 3];
      
     localNotification.fireDate = notificationDate;
     [notificationDate release];
      
     localNotification.alertBody = @"Stay in app";
     localNotification.alertAction = @"Return";
      
     localNotification.soundName = UILocalNotificationDefaultSoundName;
      
     [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
    [localNotification release];
    
  2. After ending phone call your application retrieve focus.
    NSURL *phoneSchemaURL = [NSURL URLWithString:@"tel://123456789"];
     
     NSString *osVersion = [[UIDevice currentDevice] systemVersion];
     
    if([osVersion compare: @"3.1" options: NSNumericSearch] >= NSOrderedSame ) {
     UIWebView *webview = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
     //or if you just want to call and back to application
     //UIWebView *webview = [[UIWebView alloc] init];
    
     [webview loadRequest:[NSURLRequest requestWithURL:phoneSchemaURL]];
      
     //if you just want to call and back to application remark code below, but don't forget release webview
     [self.view addSubview:webview];
     [webview release];
    } else {
     // On 3.0 and below, dial as usual
     [[UIApplication sharedApplication] openURL: phoneSchemaURL];          
    }
    

Objective C: Basic HTTP Authorization


  1.  First version of "Authorization":
    NSString *loginString = [NSString stringWithFormat:@"%@:%@", [self userName], [self password]];
    NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];  
    NSString *base64LoginData = [NSString stringWithFormat:@"Basic %@",encodedLoginData];
    
    NSURL *url=[NSURL URLWithString:@"http://my_url.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                    timeoutInterval:10.0];
    
    [request setHTTPMethod:@"POST"];
    
    [request setValue:base64LoginData forHTTPHeaderField:@"Authorization"];
    
    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
  2. Second version of "Authorization":
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:10.0];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    NSURLConnection Delegates
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
        if ([challenge previousFailureCount] == 0) {
            NSLog(@"received authentication challenge");
            NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
                                                                        password:@"PASSWORD"
                                                                     persistence:NSURLCredentialPersistenceForSession];
            NSLog(@"credential created");
            [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
            NSLog(@"responded to authentication challenge");    
        }
        else {
            NSLog(@"previous authentication failure");
        }
    }