Browse Month: March 2014

PHP Security: HTTP Authentication

You possible have found a web page that you want to open, sudden peep out a dialog window asking for username and password. common example is early page at cpanel (control panel to manage the web server use web based). It use HTTP Authentication.

In protecting web page with HTTP authentication, you have to deliver two header. header WWW-AUTHENTICATE tell to browser that an username and password needed.

Example, create a file named “protectHTTP.php” within wwwphpsecurity.php. Enter following code:

<?php
  // test for username/password
  if(($_SERVER['PHP_AUTH_USER'] == "mia") AND
    ($_SERVER['PHP_AUTH_PW'] == "secret"))
  {
    echo("successfully!<br>n");
  }
  else
  {
    //Send headers to cause a browser to request
    //username and password from user
    header("WWW-Authenticate: " .
    "Basic realm="PHPEveryDay's Protected Area"");

	header("HTTP/1.0 401 Unauthorized");

    //Show failure text, which browsers usually
    //show only after several failed attempts
    print("This page is protected by HTTP ");
  }
?>

PHP creates the PHP_AUTH_USER and PHP_AUTH_PW  elements of the _SERVER array automatically if the browser passes a  username and password.

How to call visualforce page in Salesforce1

Its pretty easy:

<apex:page>
    <script>
        try
        {
            sforce.one.navigateToURL('/apex/myVFPage');
        }
        catch(e)
        {
            window.location.href = '/apex/myVFPage';
        }
    </script>
</apex:page>

But you would come to a problem eventually that the vf page where I wrote above code, suppose testSF1 … how do I call that page?

Here is manual way:

1. Create new visualforce tab for this testSF1 page.

2. Goto Setup -> Mobile Adminstration -> Mobile Navigation -> Add the tab to available list -> Save.

3. Open Salesforce1 app & you’ll find the tab in the left menu list.

 

Here is another way of automatically invoking the visualforce page in salesforce1 format:

1. Create new visualforce tab for this testSF1 page.

2. Goto Setup -> Mobile Adminstration -> Mobile Navigation -> Add the tab to available list -> Save.

3. Open Salesforce1 in mobile browser (e.g. https://na15.salesforce.com/one/one.app). Login & you’ll see similar view as that of app. Now from the left menu, click on your vf page tab.

4. Note the address bar url is changed to something like:

https://na15.salesforce.com/one/one.app#eyJjb21wb25lbnREZWXiOiJvbmU6YWxvaGFQYWdlIiwiYXU0cmlidXRlcyI6eyJ2YWx1ZXMiOnsiYRRkcmVzcyI6Imh0dHBzOi8vZW1haWxjb25uZWN0Lm5hMTUudmlzdXFsLmZvcmNlLmNvbS9hcGV5L0VtYWlsQ29ubmVjdF9DYWxsU0YxP3NmZGMudGFiTmFtZT0wMXJpMDAwMDAwMG9ldDUifX0sInQiOjEzOTU2ODIzMDQwNTJ9

5. Copy this url & you can directly call this URL to open the vf page directly wherever you want.

 

Now here is one very weird behavior of URLs getting generated in Salesforce1:

Suppose your vf page code is:

<apex:page controller="EmailConnect_GotoIdController">
    <script>
        try
        {
            sforce.one.navigateToSObject('{!recId}');
        }
        catch(e)
        {
            window.location.href = '/{!recId}';
        }
    </script>
</apex:page>

Now if you follow my above method of creating/adding tab, opening SF1 in mobile browser & copying the URL …. this I am afraid wont work everytime. Based on the contents the URL dynamically changes if the content is Dynamic. Here is what I mean:

– Suppose {!recId} passed to vf page was 003i000000ZjE8T then URL of tab would be different.

– Suppose {!recId} passed to vf page was 003i000000ERbAg then URL of tab would be different though tab is same.

 

This is really strange & annoying for programmers but seems no solution yet. So to solve this problem, we have devised solution of our own. Contact us through http://www.nanostuffs.com & we’ll be more than delighted to help you.

How to write data into NFC tags in Android?

NFC stands for “Near Field Communication” and, as the name implies, it enables short range communication between compatible devices. This requires at least one transmitting device, and another to receive the signal.  NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.

I was developing an application in which I had to accept the data from a spinner and two edit text fields, combine the data and write it into NFC tag.

I followed  these simple steps to write the data into NFC tag:

1)      Declare an Intent Filter to announce to the system that it’s enabled to work on NFC.

2)      Have a method that Android will call when NFC is detected.

3)      Create a method to build a NDEF message.

4)      Create a method to write the NDEF message.

________________________________________________________________________________________________________

Manifest :

<uses-feature

android:name=“android.hardware.nfc”

android:required=“false” />

<uses-permission android:name=“android.permission.NFC” />

________________________________________________________________________________________________________

package com.nanostuffs.nfc.activity;

 

import java.io.IOException;

import java.io.UnsupportedEncodingException;

 

import android.app.Activity;

import android.app.AlertDialog;

import android.app.PendingIntent;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.IntentFilter;

import android.nfc.FormatException;

import android.nfc.NdefMessage;

import android.nfc.NdefRecord;

import android.nfc.NfcAdapter;

import android.nfc.Tag;

import android.nfc.tech.Ndef;

import android.os.Bundle;

import android.provider.Settings;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Spinner;

import android.widget.Toast;

 

import com.nanostuffs.nfc.R;

 

public class WriteActivity extends Activity {

private NfcAdapter adapter;

private PendingIntent pendingIntent;

private IntentFilter writeTagFilters[];

private Tag mytag;

private Context ctx;

private Button write;

private String writeTag;

private Spinner selectFarmer;

private EditText noOfBags;

private EditText fuel;

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.write);

initializeComponents();

}

 

private void initializeComponents() {

selectFarmer = (Spinner) findViewById(R.id.sel_farmer_spinner);

noOfBags = (EditText) findViewById(R.id.no_of_bags_edit);

fuel = (EditText) findViewById(R.id.fuel_litres_edit);

write = (Button) findViewById(R.id.write);

ctx = this;

adapter = NfcAdapter.getDefaultAdapter(this);

pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,

getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

IntentFilter tagDetected = new IntentFilter(

NfcAdapter.ACTION_TAG_DISCOVERED);

tagDetected.addCategory(Intent.CATEGORY_DEFAULT);

writeTagFilters = new IntentFilter[] { tagDetected };

}

________________________________________________________________________________________________________

With last 5 rows we create a IntentFilter, so we tell Android that our application is enabled to work on nfc tag (NfcAdapter.ACTION_TAG_DISCOVERED). We could register our app directly with a intentFilter in the Manifest. In this way we couldn’t lunch our Activity like a simple program, but Android will boot it when it detects a tag. In both ways, after detecting and deciding which app has to work on with the tag, Android will call the method onNewIntent and pass the object tag to the activity:

________________________________________________________________________________________________________

@Override

protected void onNewIntent(Intent intent) {

if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {

mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

Toast.makeText(this,

this.getString(R.string.ok_detection) + mytag.toString(),

Toast.LENGTH_SHORT).show();

}

}

________________________________________________________________________________________________________

So now we have the object tag and we have to build the function to create the NDEF message and to write it into the NFC tag.

________________________________________________________________________________________________________

private NdefRecord createRecord(String text)

throws UnsupportedEncodingException {

String lang = “en”;

byte[] textBytes = text.getBytes();

byte[] langBytes = lang.getBytes(“US-ASCII”);

int langLength = langBytes.length;

int textLength = textBytes.length;

byte[] payload = new byte[1 + langLength + textLength];

// set status byte (see NDEF spec for actual bits)

payload[0] = (byte) langLength;

// copy langbytes and textbytes into payload

System.arraycopy(langBytes, 0, payload, 1, langLength);

System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);

NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,

NdefRecord.RTD_TEXT, new byte[0], payload);

return recordNFC;

}

private void write(String text, Tag tag) throws IOException,

FormatException {

NdefRecord[] records = { createRecord(text) };

NdefMessage message = new NdefMessage(records);

// Get an instance of Ndef for the tag.

Ndef ndef = Ndef.get(tag);

// Enable I/O

ndef.connect();

// Write the message

ndef.writeNdefMessage(message);

// Close the connection

ndef.close();

}

________________________________________________________________________________________________________

Now we have to check if the device supports the NFC feature and if it is enabled.If so ,write the data.

________________________________________________________________________________________________________

@Override

public void onResume() {

super.onResume();

writeModeOn();

}

private void writeModeOn() {

if (adapter != null) {

adapter.enableForegroundDispatch(this, pendingIntent,

writeTagFilters, null);

write.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

writeTag = selectFarmer.getSelectedItemId()+1005 + “~”

+ noOfBags.getText() + “~” + fuel.getText();

try {

if (mytag == null) {

Toast.makeText(ctx,

ctx.getString(R.string.error_detected),

Toast.LENGTH_LONG).show();

} else {

write(writeTag, mytag);

Toast.makeText(ctx,

ctx.getString(R.string.ok_writing),

Toast.LENGTH_LONG).show();

}

} catch (IOException e) {

Toast.makeText(ctx,

ctx.getString(R.string.error_writing),

Toast.LENGTH_LONG).show();

e.printStackTrace();

} catch (FormatException e) {

Toast.makeText(ctx,

ctx.getString(R.string.error_writing),

Toast.LENGTH_LONG).show();

e.printStackTrace();

}

}

});

if (!adapter.isEnabled()) {

new AlertDialog.Builder(this)

.setPositiveButton(“Update Settings”,

new DialogInterface.OnClickListener() {

 

public void onClick(DialogInterface arg0,int arg1) {

Intent setnfc = new Intent(Settings.ACTION_WIRELESS_SETTINGS);

startActivity(setnfc);

}

})

.setOnCancelListener(

new DialogInterface.OnCancelListener() {

public void onCancel(DialogInterface dialog) {

finish();

}

}).create().show();

}

} else {

Toast.makeText(getApplicationContext(),

“Sorry, No NFC Adapter found.”, Toast.LENGTH_SHORT).show();

}

 

}

________________________________________________________________________________________________________

If the user exits the application disable the NFC adapter.

________________________________________________________________________________________________________

@Override

public void onPause() {

super.onPause();

writeModeOff();

}

private void writeModeOff() {

if (adapter != null) {

adapter.disableForegroundDispatch(this);

 

}

}

}

How to post custom facebook stories to timeline

1.Create a facebook app & setup app id with your project.
2.create your own story from facebook app opengraph section by creating action & object.
3.Post one story to app owner timeline & submit it to the facebook review team so that it will be become public for app user & can be seen publicaly on timeline
follwing code shows the how to post the story.

-(void)Poststory
{
NSString *itemname=@””;
NSString *link=@””;
NSString *url=@””;
NSString *description=@””;

NSMutableDictionary *object =
[FBGraphObject openGraphObjectForPostWithType:@”appnamespace:objectname” title:itemname
image:link
url:url
description:description];

[FBRequestConnection startForPostOpenGraphObject:object
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {

NSString *objectId = [result objectForKey:@”id”];

NSMutableDictionary *action = [FBGraphObject graphObject];
action[@”objectname”] = objectId;
action[@”fb:explicitly_shared”]=@”true”;//allows on timeline
[FBRequestConnection startForPostWithGraphPath:@”me/appnamespace:actionname”
graphObject:action
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
// handle the result

}];
}];
}

Creating the custom story in opengraph
FOR MORE DETAIL REFER THE LINK

Moving view along with fingure touch

You can move any view inside your viewcontroller simply adding pangestureRecogniser

-(void)ViewDidLoad
{
//add pangesture recognise to your moving view
UIPanGestureRecognizer *mSwipeUpRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handletapgesture:)];
[mSwipeUpRecognizer setMaximumNumberOfTouches:1];
[mSwipeUpRecognizer setMaximumNumberOfTouches:1];

[Yourview addGestureRecognizer:mSwipeUpRecognizer];

}
-(void)handletapgesture:(id )recognizer
{
UIPanGestureRecognizer *gesture=(UIPanGestureRecognizer*)recognizer;

[self.view bringSubviewToFront:gesture.view];

switch (gesture.state) {
case UIGestureRecognizerStateBegan:
{
//do something when touch identified
NSLog(@”Received a pan gesture”);
panCoord = [gesture locationInView:gesture.view];

}
break;

case UIGestureRecognizerStateChanged:
{
//change the view frame
CGPoint newCoord = [gesture locationInView:gesture.view];
float dX = newCoord.x-panCoord.x;
float dY = newCoord.y-panCoord.y;

gesture.view.frame = CGRectMake(0, gesture.view.frame.origin.y+dY, gesture.view.frame.size.width, gesture.view.frame.size.height);
}
break;
case UIGestureRecognizerStateEnded:
{
if (gesture.view.frame.origin.y<=originalheight && directionUp==0)
{
//if Uiview position down move it to Up
[UIView animateWithDuration: 0.4
delay: 0
options: (UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionCurveEaseOut)
animations:^{
UpDownview.frame=CGRectMake(0,newheight, 320,325);

}
completion:^(BOOL finished) {
directionUp=1;

}];

}
else
{
//if Uiview position up move it to down
[UIView animateWithDuration: 0.4
delay: 0
options: (UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionCurveEaseOut)
animations:^{
UpDownview.frame=CGRectMake(0, originalheight, 320, 200);

}
completion:^(BOOL finished) {
directionUp=0;
// return;

}];
}
}

break;
default:
break;
}

}

Handling Push Notification in iOS

The push notification is quite complex part to handle. Get it done in only Three easy steps

1] Register for push notification

2] Get Device token

3] Implement delegate methods to handle push notification

 

1] Register for push notification

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

// register for remote notification

[[UIApplication sharedApplication]

registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |

UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert )];

 

//handling push notification: when app is not in running state either in background or foreground

if ([[launchOptions allKeys] containsObject:UIApplicationLaunchOptionsRemoteNotificationKey])

{

NSLog(@”received notification: %@”,launchOptions); //handle notification here with launchOptions dictionary

}

}

2] Get Device token

Receive token in delegate method

– (void)application:(UIApplication *)app

didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken

{

NSString *tokenStr = [devToken description]; //here is the device token needed for Push notification

}

 

//delegate method for getting failure error of registering device

– (void)application:(UIApplication *)app

didFailToRegisterForRemoteNotificationsWithError:(NSError *)err

{

NSLog(@”Error in registration. Error: %@”, err);

}

 

3] Implement delegate methods to handle push notification

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

{

//called when application is running either in foreground or background

NSLog(@”received notification: %@”,userInfo); //handle notification here with userinfo dictionary

}

 

 

 

 

 

 

How to add Activity History while sending emails in Salesforce

Hi Friends, many of you know the Salesforce SingleEmailMessage method,In fact you have used it in your apex code. But when we send mail through this method by default it doesn’t add mail into related list of recipient’s activity history.
If you are stuck with this type of issue, then below I’m providing the solution for this.

setSaveAsActivity(true);

Add this method into your code which will add sent mail to the activity History related List.

Follow the example given for better understanding:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{‘Receipient’s Email’};
String[] ccAddresses = new String[] {‘Additional Receipient’};
mail.setTargetObjectId(receipient.id); // Put setTargetobjectid value as per your requirement.
mail.setCcAddresses(ccAddresses);
mail.setSenderDisplayName(‘SalesforceLogin Test’);
mail.setSubject(‘Subject Test’);
mail.setSaveAsActivity(true); //add mail to the activity history
mail.setBccSender(false);
mail.setUseSignature(false);
mail.setHtmlBody(‘Hi! Salesforce user’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Hope this post Helps You!

 

Adding multiple uicontrollers on view

If we create multiple controllers programmatically, we generally use for loop but we can add the same controllers by using the methods,

example:

1. By using for loop

 

for (int i = 0; i < 3; i++)

{

UITextField *textField= [[UITextField alloc] initWithFrame:CGRectMake(50, 20+40*i, 117, 30)];

textField.borderStyle = UITextBorderStyleRoundedRect;

textField.font = [UIFont systemFontOfSize:15];

textField.placeholder = @”enter text”;

textField.autocorrectionType = UITextAutocorrectionTypeNo;

textField.keyboardType = UIKeyboardTypeDefault;

textField.returnKeyType = UIReturnKeyDone;

textField.clearButtonMode = UITextFieldViewModeWhileEditing;

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

textField.delegate = self;

textField.tag = i;

[self.view addSubview:textField];

}

here, we have to get controllers by tags or by array outside the loop and bit difficult to set position, if controllers are not be aligned

 

2. By using methods

 

We can create the method like this

-(UITextField *)getTextField:(CGRect)frame

{

UITextField *textField= [[UITextField alloc] initWithFrame:frame];

textField.borderStyle = UITextBorderStyleRoundedRect;

textField.font = [UIFont systemFontOfSize:15];

textField.placeholder = @”enter text”;

textField.autocorrectionType = UITextAutocorrectionTypeNo;

textField.keyboardType = UIKeyboardTypeDefault;

textField.returnKeyType = UIReturnKeyDone;

textField.clearButtonMode = UITextFieldViewModeWhileEditing;

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

textField.delegate = self;

return textField;

}

and just call the above method as

UITextField *firstName = [self getTextField:CGRectMake(167, 20, 117, 30)];

[self.view addSubview:firstName];

UITextField *lastName = [self getTextField:CGRectMake(167, 60, 117, 30)];

[self.view addSubview:lastName];

UITextField *phoneNo = [self getTextField:CGRectMake(167, 100, 117, 30)];

[phoneNo setKeyboardType:UIKeyboardTypePhonePad];

[self.view addSubview:phoneNo];

 

Second method is also helpful when we add more controllers later..

 

 

 

 

 

Show/Hide fields as Picklist value changes using Deluge script in Zoho

Sometimes we need to show/hide  certain fields as picklist value changes for example  there is field called ‘Reason’ and we want to hide this field as picklist ‘Product type’ changes to ‘Research’.

We can achieve this by configuring fields action in deluge script.

steps

  • Go to the field on which you want to add action ,in above example ‘Product type’.
  • Field Deluge Name is the name of the field we’ll refer in the deluge script.
  • Select->field properties->Configure field action.
  • Select Field Actions -> Type -> On User input block in Script builder.This action will be executed when user changes field value.

  • Drag if-else condition statement.
  • add logic as below image& save the script

The ‘Reason’ field will be hide as picklist ‘Product type’ changes to ‘Research’, as shown below.

 

How to Create a subform in Zoho

A subform is a form that is inserted into another form. In a one-to-many relationship, each parent record associates itself with multiple children. Using Subforms, users can display the parent and child records in one place without having to switch between forms.

Zoho have field type ‘subform’ which you can insert blank form /existing form in the main form.
To add the subform in the main form

1]Edit the main form ->add new subform(field type is present in the left panel)->Drag-n-drop subform where you want on the main form.
2]On the adding subform it’ll ask you for the new blank form or existing form.
3]Add new fields in the subform and save the changes.

After adding form you can add records in subform  using ‘add new’ button as shown in below image.

The Main Form report will display all the records with the values of the selected subform fields

The ‘Column property’ in the main form report allows you to customize the sub form report also.

Hope this helps you!
Thank You!


  • 1
  • 2