Browse Month: March 2013

How to retrieve installed application list and permissions

In this short post i will show you how use the PackageManager class to retrieve the list of installed applications and associated permissions on your android device .

Starting from the your Activity context you can obtain an instance of PackageManager through the method called getPackageManager(). Using that class is it possible to get a list of ApplicationInfo objects containing details about apps such as MetaData, Permissions, Services or Activities.

Useful data are for example the name of the app, the packageName used to retrieve additional information with PackageManager methods and the publicSourceDir that represent a simple way to identify system or user applications.

The following code gets first of all the PackageManager object, retrieves ApplicationInfos of available apps and for each of them loads the list of permissions and the associated icon as Drawable object.

PackageManager pm = getPackageManager();
List packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo applicationInfo : packages) {
Log.d(TAG, "App:"+applicationInfo.name+" Package :" + applicationInfo.packageName);
try {

PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);

//Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;

if(requestedPermissions != null)
{
for (int i = 0; i < requestedPermissions.length; i++) {
Log.d(TAG,requestedPermissions[i]);
}
}

//Get Application Icon
Drawable appIcon = pm.getApplicationIcon(applicationInfo.packageName);

} catch (NameNotFoundException e) {
e.printStackTrace();
}
}

How to create object in salesforce through Web-Service using Apex Metadata API

Hi All,
many times we required to create objects into Salesforce through web services i.e. using Metadata API. Here is a sample code by which we can create such custom object into the Salesforce.

for the Apex Metadata Api please refer
Apex Metadata API this link.

// Visualforce Page code

<apex:page controller="MetadataUse" action="{!createObject}">

</apex:page>

// Apex code

public with sharing class MetadataUse
{
    public static void createObject()
    {
      MetadataService.CustomObject customeObject = new MetadataService.CustomObject();
      MetadataService.MetadataPort service = MetadataService.createService();
      customeObject.fullName = 'metadataObject__c';
      customeObject.label = 'Metadata Object';
      customeObject.pluralLabel = 'Metadata Objects';
      customeObject.nameField = new MetadataService.customField();
      customeObject.nameField.type_x = 'Text';
      customeObject.nameField.label = 'Sample Record';
      customeObject.deploymentStatus = 'Deployed';
      customeObject.sharingModel = 'ReadWrite';
      MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata>{customeObject});
      }
}

Steps :

1] to create custom object just create one Visualforce page and use the above mentioned visualforce code in it.

2] Create new Apex class and use above mentioned Apex code in it. You can change the object names as per your convenience.

3] If you get an error saying that no createService() method in MetadataService class then add the following code into it

public static MetadataService.MetadataPort createService()
        {
            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
            service.SessionHeader = new MetadataService.SessionHeader_element();
            service.SessionHeader.sessionId = UserInfo.getSessionId();
            return service;
        }

and save it.

after this execute the apex page and check whether new object created or not. Surely new object get created.

Hope this post will be helpful to you.

Thanks

Detect User Language With PHP

This function uses php server variables to detect the “possible” language of the browser of the connected user. This let you show information with the correct language.
Since the HTTP_ACCEPT_LANGUAGE variable contains many information there is some dirty job to do with regular expression to clean the variable and determine the most important value from the ones contained.
The HTTP_ACCEPT_LANGUAGE contains language and q factor. This “q factor” indicates the importance of the language. The bigger is q factor the most important is the language, so the function split the variable, detect q factor and sort to extract the most important.

function getUserLanguage() {
$langs = array();
if (isset($_SERVER[‘HTTP_ACCEPT_LANGUAGE’])) {
// break up string into pieces (languages and q factors)
preg_match_all(‘/([a-z]{1,8}(-[a-z]{1,8})?)s*(;s*qs*=s*(1|0.[0-9]+))?/i’,
$_SERVER[‘HTTP_ACCEPT_LANGUAGE’], $lang_parse);
if (count($lang_parse[1])) {
// create a list like “en” => 0.8
$langs = array_combine($lang_parse[1], $lang_parse[4]);
// set default to 1 for any without q factor
foreach ($langs as $lang => $val) {
if ($val === ”) $langs[$lang] = 1;
}
// sort list based on value
arsort($langs, SORT_NUMERIC);
}
}
//extract most important (first)
foreach ($langs as $lang => $val) { break; }
//if complex language simplify it
if (stristr($lang,”-“)) {$tmp = explode(“-“,$lang); $lang = $tmp[0]; }
return $lang;
}

Web Services and PHP – SOAP vs XML-RPC vs REST

What is web services?

In a typical web surfing scenario, a visitor visits a website and use the functionality provided by that particular website.HTTP request is send to server from web browsers and server responses are translated by browser to display the desired result of the visitor. But, this scenario has been changed in the recent days. You don’t need to visit the particular website to use their service and functionality if they are providing web services. Web services are set of platform independent exposed APIs(functions) which can be used used from remote server over the Internet. There are basically two parties involved in this, one which provides a set of exposed APIs and the another one ,commonly know as web services consumers,is the party which uses the functionality and services provided by web services providing party.

There are different method for providing web services but the most common are SOAPXML-RPC and REST .

SOAP

SOAP was the acronym of Simple Object Access Protocal but this acronym was dropped in the version of 1.2 of SOAP. It is method for exchanging XML based message over the Internet for providing and consuming web services. SOAP message are transferred forming the SOAP-Envelope.You can view the typical SOAP Message articture from here. SOAP is widely criticized for it’s design complexity.

In PHP 5, there is built-in extension for the providing and consuming web services. But, I personally prefer Nusoap toolkit of PHP for providing and consuming web services using SOAP in PHP.

XML-RPC

XML-RPC (remote procedure call) another way of providing and consuming web services. It uses XML to encode and decode the remote procedure call along with it’s parameter. Compared to the articture of SOAP, it has simpler architecture. You can even define data type of parameters of procedure in XML-RPC. You can visit the official website www.xmlrpc.com to know more about XML-RPC.

In PHP, there is extension which contain various functions for facilating XML-RPC request and response. But the functions xmlrpc_encode_request() and xmlrpc_decode_request() available in PHP is very useful for when it comes to encode and decode XML-RPC request and response.

REST

Representational State Trasfer(REST) is comparatively simpler method for providing and consuming web services. Nowadays, this method is becoming popular in the arena of web services. Unlike above two method, it is not necessary to use XML as a data interchange format in REST. REST architecture is basically focused on two things : Resources and Interface. RESTful is another term to define REST web services .

Resources are application’s state and functionality which is represented by a unique URL. The resources share a uniform interface to transfer the state between the client and server.

For example the URL, http://example.com/product/11 can be a resource.Suppose, GET method is used to retrieve product detail from that URL, POST method is used to modify the production information and DELETE method can be used to delete the product from the same URL. Here, the HTTP methods works as a interface to access the resources.

Talking about PHP, the format of information(representation) returned can be in XML, JSON or even in HTML format. DOM functions, SimpleXML functions and JSON functions comes handy when you are handling RESTful interfaces in PHP.

How to make UITextField’s text selected programmatically ?

 

Hi,

For making UITextField’s text selected programmatically you need to set the UITextField’s delegate linke below :

txt.delegate = self;

and then put following code in textFieldDidBeginEditing

-(void)textFieldDidBeginEditing:(UITextField *)textField
        {
           [textField selectAll:self];

         }

And don’t forget to add delegate in .h

@interface ViewController : UIViewController <UITextFieldDelegate>

Hope this will help somebody.

Happy Coding !!!

 

Zbar SDK is not working well in iOS6

To solved the problem follow the steps:

  1. Go to the ZBar homepage and navigate to the mercurial repository (direct link)
  2. Download the zbar repository as zip.
  3. Unzip the file and navigate to the subfolder named “iphone”.
  4. Open the XCode project.
  5. Delete the “Examples” folder (the folder caused a build error on my machine).
  6. Hit “CMD + B” and build the source.
  7. Find your new libzbar.a file. (User/Library/Developer/Xcode/DerivedData/zbar…)
  8. Replace the old libzbar.a file in your project with the new one.
  9. Hit “CMD + R” and you are good to go.

 

How to access passes from passbook in app?

Create AppId which is similar to passTypeIdentifier. For example if your passTypeIdentifier is pass.abc.xyz then your AppId must be com.abc.xyz .While creating provisioning profile make use of this appId and make use of this provisioning profile for your app. Then only you will be able to distinguish passes available in your passbook.

Also, Keep in mind that the App ID you signing your code with should be Enable for Passes on the Provisioning portal as well.

 

How to add non glossy icon to iOS application?

Hi all,

Let us see how to add non glossy icon to iPhone/iPad applications.

It’s very simple step to follow,

Open Info.plist for your target and add the following property :

Icon already includes gloss effects : YES

Setting this property to YES, shows the non glossy icon.

 

How to compress Image in gzip format

Some times the Size of images are too large and in some of the applications images are needed to save on particular server but because off large size it takes lots off time to save into server.If we compress that image into a particular format then we can save some space of server.

Step 1 – Create one Category and add libz.dylib library.

Step 2 – in .h file i.e in interface file mention the list of methods.

here the name of category is GZIP.

@interface NSData (GZIP)

and mention the list of methods.

– (NSData *)gzippedDataWithCompressionLevel:(float)level;

– (NSData *)gzippedData;

and end the interface using

@end

Step 3 – in .m file i.e in implementation file

#import <zlib.h>

#define CHUNK_SIZE 16384

add the implementation of listed methods.

@implementation NSData (GZIP)

– (NSData *)gzippedDataWithCompressionLevel:(float)level{

if ([self length]){

z_stream stream;

stream.zalloc = Z_NULL;

stream.zfree = Z_NULL;

stream.opaque = Z_NULL;

stream.avail_in = (uint)[self length];

stream.next_in = (Bytef *)[self bytes];

stream.total_out = 0;

stream.avail_out = 0;

int compression = (level < 0.0f)? Z_DEFAULT_COMPRESSION: (int)roundf(level * 9);

if (deflateInit2(&stream, compression, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK){

NSMutableData *data = [NSMutableData dataWithLength:CHUNK_SIZE];

while (stream.avail_out == 0){

if (stream.total_out >= [data length]){

data.length += CHUNK_SIZE;

}

stream.next_out = [data mutableBytes] + stream.total_out;

stream.avail_out = (uint)([data length] – stream.total_out);

deflate(&stream, Z_FINISH);

}

deflateEnd(&stream);

data.length = stream.total_out;

return data;

}

}

return nil;

}

– (NSData *)gzippedData{

return [self gzippedDataWithCompressionLevel:-1.0f];

}

@end

Step 4 – import category where we want to compress image

#import “NSData+GZIP.h”

Step 5 – Convert image into NSData

NSData *userFile = UIImageJPEGRepresentation(img, 1.0f);

Step 6 – call the gzippedData method.

NSData *compressedData = [userFile gzippedData];

Now Compressed image is in compressedData variable.

 

Thank You.