Showing posts with label Salesforce. Show all posts
Showing posts with label Salesforce. Show all posts

Saturday, 18 July 2015

Salesforce Security Considerations


Storing data in cloud with no control over it makes many people anxious and really worried but Salesforce comes with really secure data storage capabilities which for enterprises at their own is not achievable or even if it is, it will be really expensive. So relax Salesforce has been audited by many international standards and have acquired following certifications 
  • PCI DSS
  • FISMA
  • ISO/IEC 27001:2005
  • SAS 70 Type II
  • SysTrust
  • EU-US



Salesforce prevents your data from any Physical damages by providing safety from 

  • Humidity & Temperature 
  • Power Loss 
  • Network Loss or Congestion
  • Early Fire Detection & Prevention

To secure your data from intrusions salesforce follows following approach

  • SPI at perimeter firewall : Stateful packet inspection is done at all the packets coming in on the outer firewall, stateful helps in letting network know the connections and sessions and with this technology packets are not only invested for their headers but for their payloads too, thus leaving chances to error at very low probability.
  • Bastion Stations : After the outer firewall screened with SPI packets reach bastion stations, which are specially designed computer to defend any attacks, these are defined and designed with highest possible security parameters to in selfs are enough to prevent any attack
  • TLS/SSL : Cryptographic protocols encrypt all network data transmissions.

And To prevent the application, we have all sort of security features like : Profile, Object Level security, Field Level security and Record level security as per requirement orgs can always enable two factor integration or have third party biometrics installed!


So place your data on Salesforce and worry just about building apps and logic, without worrying about anything related to infrastructure. 

Saturday, 6 July 2013

ICS File In Salesforce

Have you ever tried sending a meeting Invitation from Salesforce using Apex Code. Below is the code to Achieve the Same.

It creates and sends an email. For any Calendar meeting the universal format for file Accepted is .ICS
and it is nothing but a string containing all the information.

I have used this file as the mail attachment and have set the Content type of email as "text/calendar"

Code Below
--------------------------------------------------------------------------------------------------------------------------

String vCal = 'BEGIN:VCALENDAR' + '\n' + 'PRODID:-//Force.com Labs//iCalendar Export//EN' + '\n' +
'VERSION:2.0' + '\n' + 'CALSCALE:GREGORIAN' + '\n' + 'METHOD:REQUEST'+ '\n'+ 'BEGIN:VEVENT'+ '\n' +
'DTSTART:20131008T103000Z' + '\n' + 'DTEND:20131008T113000Z' + '\n' + 'DTSTAMP:20091008T103839Z' + '\n' +
'ORGANIZER;CN=varun.vatsa@gmail.com:mailto:varun.vatsa@gmail.com' + '\n' + 'UID:varun.vatsa@gmail.com'+ '\n' +
'CREATED:20091008T103839Z' + '\n' + 'DESCRIPTION:something' + '\n' + 'LAST-MODIFIED:20091008T103839Z' + '\n' +
'SEQUENCE:0' + '\n' + 'STATUS:CONFIRMED' + '\n' + 'SUMMARY:Test ICS Mail Format' + + '\n' + 'TRANSP:OPAQUE' + '\n' +
'END:VEVENT'+ '\n' + 'END:VCALENDAR';
List<String> toAddresses = new List<String>();
        toAddresses.add('varun.vatsa@gmail.com');
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSubject('Test');
        email.setToAddresses(toAddresses);
        email.setHtmlBody('Test');
        email.setPlainTextBody('Test');
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('rfc2445.ics');
     
        efa.setBody(blob.valueOf(vCal));
        //attachments.add(efa);
        efa.setContentType('text/calendar');
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
         Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Sunday, 23 September 2012

Open Connection SalesForce Rest API

Hi

I have written a sample code in java to make a persistent connection to Salesforce's Rest API, This example uses Oauth Grant_Type ="password" to provide a fresh access_token each time the request is made.

Please find the code below. To make this code work you need to add package <httpcomponents-client> to your classpath. which can easily be downloaded from  http://hc.apache.org/httpcomponents-client-ga/

 


Please find the code :

package connection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONValue;



public class OauthConnection {

    //Variables to be populated after gaining the Access token.
    private String accessToken = null;
    private Map<String, String> oauthLoginResponse;
   
    //Constants to be used in this class.
    private static final String clientId = <Your Client ID>;  
    private static final String clientSecret = <Your Client Secret>;
    private static final String environment = "<SalesForce Instance>";
    private static final String authUrl = "/services/oauth2/token";
    private static final String restUrl = "/services/data/v25.0/";
    private static final String queryUrl = "/services/data/v25.0/query";
    private static final String username = "<Your SFDC USER NAME>";
    private static final String password = <SFDC PASSWORD WITH SECURITY TOKEN>;
   
   
   
    public static void main(String[] args){
        try{
       
            OauthConnection oc = new OauthConnection();
            oc.oAuthSessionProvider();
           
            oc.executeQuery();
       
        }catch(Exception e){
            e.printStackTrace();
        }
      }
       
    public void oAuthSessionProvider()
            throws HttpException, IOException
    {
        // Set up an HTTP client that makes a connection to REST API.
        DefaultHttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);

        // Set the SID.
        System.out.println("Logging in as " + username + " in environment " + environment);
        String baseUrl = environment + authUrl;
       
        // Send a post request to the OAuth URL.
        HttpPost oauthPost = new HttpPost(baseUrl);
       
        // The request body must contain these 5 values.
        List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
        parametersBody.add(new BasicNameValuePair("grant_type", "password"));
        parametersBody.add(new BasicNameValuePair("username", username));
        parametersBody.add(new BasicNameValuePair("password", password));
        parametersBody.add(new BasicNameValuePair("client_id", clientId));
        parametersBody.add(new BasicNameValuePair("client_secret", clientSecret));
        oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));

        // Execute the request.
        System.out.println("POST " + baseUrl + "...\n");
      
        HttpResponse response = client.execute(oauthPost);
        int code = response.getStatusLine().getStatusCode();
      
        System.out.println("Code >> " +code);
       
        //populate Response map to fetch ACCESS TOKEN for any future call.
        this.oauthLoginResponse = (Map<String, String>)JSONValue.parse(EntityUtils.toString(response.getEntity()));
       
        System.out.println("OAuth login response");
       
        for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet())
        {
            System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
        }
       
        //Populate Access Token 
        this.accessToken = oauthLoginResponse.get("access_token");
        System.out.println("");
    }
   
    public void executeQuery(){
         DefaultHttpClient httpClient = new DefaultHttpClient();
       
        List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
        qsList.add(new BasicNameValuePair("q", "Select a.ParentId, a.OwnerId, a.Name, a.IsPrivate,  a.Id, a.Description, a.ContentType, a.BodyLength, a.Body " +
                "                                From Attachment a where  a.ParentId = '00390000006DEGb'"));
       
        String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
        HttpGet get = new HttpGet(environment + queryUrl+"?"+queryString);
        get.setHeader("Authorization", "OAuth " + accessToken);
        try{
            HttpResponse queryResponse = httpClient.execute(get);
           
            System.out.println(queryResponse.getStatusLine().getReasonPhrase());
              Map<String, Object> querynfo = (Map<String, Object>)
                        JSONValue.parse(EntityUtils.toString(queryResponse.getEntity()));
             
              System.out.println("Query response");
                for (Map.Entry<String, Object> entry : querynfo.entrySet())
                {
                    System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
                }
                System.out.println("");
             
        }catch(Exception e){
            e.printStackTrace();
        }
       
    }
 }

Friday, 2 March 2012

Tool for SalesForce Profile Comparison, Field Level Security

Hi many a time while working in Salesforce we get the boring and mechanical task of comparing profiles, and out of this worst part is field level security. This task gets worse when we have some objects with large number of custom fields. So to sort this out I have written a java code that will read files from two different folders(Download profiles in your eclipse and pass the path of the Profile folders from two different project) or if you want to compare just two files, put them in two folders and provide the path of those two folders.

After comparison, the code will generate a parent directory, containing children directories named on the profile, the children directories will contain two csv files each one for object comparison and other for Field level security comparison.

To execute this code, you just need eclipse of core java libraries, and change the path mentioned in the class to that of your system specific path, and get the results.

please find the code below.



Tuesday, 31 January 2012

Problem: failed to create task or type antlib:com.salesforce:deploy

Hi, Today while trying to deploy my org's metadata on production using Salesforce's migration tool I faced the error "Problem: failed to create task or type antlib:com.salesforce:deploy".

I was using Ubuntu 11.04 (It should be useful in MAC systems as well), so i discovered the solution to this problem is we need to download the salesforce migration tool from our deployment org's Your Name | Setup | Develop | Tools.

After downloading the zip file on your drive, extract the content and copy the ant-salesforce.jar to /usr/share/ant/lib/ 

This should resolve the particular error.





Monday, 30 January 2012

Download Salesforce Attachments on Drive.

Many a times in salesforce we need to download selective attachments, in that case the SFDC's Data Export tool doesn't seem helpful as it will download all the attachments (yes you can select objects but not the records in that object). So for this purpose i have written a small Java code, that will take help of the enterprise wsdl of the org from which i need to extract the data.

To generate code stub from enterprise wsdl you need WSC jar, which can be downloaded easily from net, once you get it, go to command prompt and paste the below mentioned command, with your own directory structure and it will generate the required jar to make connections to your org.

java -classpath  < YOUR PATH OF WSC JAR>\wsc-20.jar com.sforce.ws.tools.wsdlc  <PATH where you have kept your enterprise wsdl> \enterprise.wsdl  <PATH where you want to genrate the jar> \Enterprise.jar

Include this newly generated jar into your Java(Eclipse's) build path, and you are ready to make connection to your org.

This code will also create a CSV file to relate the parent with that to its attachment(s).


package com.mypackage;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Attachment;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class ExportAttachments {
 
  static final String USERNAME = "<YOUR USER NAME>";
  static final String PASSWORD = "<YOUR PASSWORD>";
  static EnterpriseConnection connection;
  static final String ATTACHIDS ="00P50000007HYMJEA4,00P50000007HmAjEAK,00P50000004CmZ3EAK";
  static final String AccountIds = "0015000000SQSmIAAX,0015000000bBP1pAAG,0015000000bCfjTAAS,0015000000LKHCFAA5";
 
  static List<String> str = new ArrayList<String>();
  static List<String> stracct = new ArrayList<String>();
  static Map<String,String> idMap = new HashMap<String,String>();
  static Map<String,String> csvMap = new HashMap<String,String>();
 

  public static void main(String[] args) {

    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    //config.setTraceMessage(true);
    str = Arrays.asList(ATTACHIDS.split(","));
    stracct = Arrays.asList(AccountIds.split(","));
    for(String s:stracct){
        idMap.put(s,s);
    }
    try {
     
      connection = Connector.newConnection(config);
     
      // display some current settings
      System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
      System.out.println("Service EndPoint: "+config.getServiceEndpoint());
      System.out.println("Username: "+config.getUsername());
      System.out.println("SessionId: "+config.getSessionId());
   
      queryAccounts();
      createCSV();
      queryAttachments();
     
    } catch (ConnectionException e1) {
        e1.printStackTrace();
    } 

  }
 
 private static void queryAccounts() {
       
        
        try {
          for(String s:idMap.keySet()){
          // query for the 5 newest contacts     
          QueryResult queryResults = connection.query("SELECT Id, VSX_ID__c " +
                  "FROM Account WHERE Id in ('"+s+"')");
          if (queryResults.getSize() > 0) {
            for (int i=0;i<queryResults.getRecords().length;i++) {
              // cast the SObject to a strongly-typed Account
              Account a = (Account)queryResults.getRecords()[i];
              csvMap.put(a.getId(),a.getVSX_ID__c());
            }
          }
           }
        } catch (Exception e) {
          e.printStackTrace();
        }   
       
      }
 
  private static void queryAttachments() {
      try{
          for(String s:str){
           QueryResult queryResults = connection.query("Select Id, ParentId, Name, ContentType, Body " +
            "From Attachment WHERE id in('"+s+"')");
       
           if (queryResults.getSize() > 0) {
               for (int i=0;i<queryResults.getRecords().length;i++) {
                  // cast the SObject to a strongly-typed Contact
                    Attachment a = (Attachment)queryResults.getRecords()[i];
                    writeOnDisk(a.getId()+"-"+a.getName(),a.getBody());
                    System.out.println("Id: " + a.getId() + " - Name: "+a.getName()+" "+" - Account: "+a.getParentId());
                }
              }
          }
      }catch (Exception e) {
          e.printStackTrace();
        }   
     
     
  }
 
  private static void writeOnDisk(String fileName, byte[] bdy){
      try
      {
          String filePath = "C://Documents and Settings//varun//Desktop//JavaExport//"+fileName;
          FileOutputStream fos = new FileOutputStream(filePath);//File OutPutStream is used to write Binary Contents like pictures
          fos.write(bdy);
          fos.close();
      }
      catch (IOException e)
      {
      System.out.println(e.getMessage());
      }
  }
 
  private static void createCSV(){
      try
      {   
          String toWrite="";
   
          if(csvMap!=null){
              for(String s:csvMap.keySet()){
                  toWrite +="\""+s+"\""+","+"\""+csvMap.get(s)+"\"\n";
              }
         
          System.out.println(toWrite);
          String file_name = "C://Documents and Settings//varun//Desktop//JavaExport/AccountVSX.csv";
          FileWriter file = new FileWriter(file_name);
          BufferedWriter out = new BufferedWriter (file);
          out.write(toWrite);
          out.close();
          }
      }
      catch (IOException e)
      {
          System.out.println(e.getMessage());
      }
  }


}