Sunday, 16 March 2014

Getting Information of logged In Users Community using apex

Salesforce communities allows you to connect your partners,employees and customers directly to the business process.

Salesforce communities Improve customer service and reduce support costs with Communities 

for Service.

Through this blog post my simple aim to is throw light on apex classes that are available to fetch information about logged in User community.

So lets have a look on how to approach the code to find community-Id and then use the community ID to get information about the users community and user detail

So lets explore the above code and find what all details one can infer from this code
CommunityHelper.getCommunityInfo().urlPathPrefix  ---This is sample on how you can use to get urlPathPrefix and this can be effective in using for various URL navigations .

http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_outputs.htm#capi_community_output

The above link is really handy to figure what all info one can obtain from getCommunityInfo() class .

The return will be of connectapi.community class and this class has following variables in below image
















Hope this blog was helpful and looking to blog more on how to use connectAPI more for chatter apps using vf framework .

Tuesday, 28 January 2014

Parsing An XML Data With DOM Parser In Apex

Parsing the XML data in Apex is always pain and there are already very good blogs and links that really help us to design the strategy for parsing XML data of various complexities .

http://www.tgerm.com/2011/01/apex-xmldom-to-fast-xmldom.html

The above blog from Abhinav one of our MVP of sfdc dev commmunity is informational and i suggest everyone to read this on how to use fast XML DOM.

There is a cookbook article as well on how to effectively achieve the parsing of XML using DOM parsers

http://developer.force.com/cookbook/recipe/parsing-xml-using-the-apex-dom-parser

One has to know two system classes a)Document Class b)XMLNode Class
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_xml_dom.htm

Now the question then ,why I am I writing this blog when already there are so much information on web as how to do it.The reason is even after reading all the documents in net ,i struggled to parse an XML as none of the blogs speak on how to parse when we have namespace in the XML.

Here is the sample XML data that i am trying to parse
Now one thing you will observe in the below parser code that i have written ,how i use the namespaces to parse the data.Providing namespace as null will trigger null pointer exceptions

So the idea of this blogpost was just to make one aware on how to parse the XML if there are namespaces .

Hope you enjoyed the blog series .

Sunday, 26 January 2014

Encrypting the XML response from External System In Custom Field Using AES 256 Algorithm

Encrypting the data via crypto classes in apex language is fun and below are the few articles links on developer force that really help us understand better.

http://wiki.developerforce.com/page/Apex_Crypto_Class

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_crypto.htm

Having read the above document one can easily be of opinion thats its too easy with few lines of code to encrypt data using AES 256 and also same can be stored in a field via an apex trigger .It is not so simple when it comes to storing this data into the custom field .

From the above code ,the problem arises when we start thinking on how to store the encrypted  blob data into the field of object .We dont have any field of data type blob in sfdc and thats were my problem  began and hence this blog for people looking for solution around how to store the blog in a Long Text Field and then how to decrypt the same .


The above code will trigger an exception as below





So now the question ,how will i be able to store the encrypted data in string format from the BLOB ?

There are couple of ways to do this ,but shortest ,the best

1)Convert BLOB data to HEX and store in field and then convert HEX back to string.There is lack of methods to do this till date but comming spring 14 release has a new method and much needed for these kind of problem.Once my org will be up with spring 14 i will try this method

Blob blobValue = EncodingUtil.convertFromHex('4A4B4C');

System.assertEquals('JKL', blobValue.toString());


Intresting but its coming in next release

2)Store the data inform of base64Encoded String and later use this and decode and then decrypt



The above code compiles and now lets decrypt and retrieve the original data

The below diagram summarizes the process


Reference:

https://help.salesforce.com/apex/HTViewSolution?urlname=How-do-you-convert-a-Blob-to-string-1327108626373&language=en_US

Sunday, 5 January 2014

MAXIMUM DEBUG LOG SIZE REACHED

*********** MAXIMUM DEBUG LOG SIZE REACHED ***********

Many Times i get frustrated when i want to log something and see the values in debug log and when i encounter an error saying MAXIMUM DEBUG LOG SIZE REACHED.

We all know the log levels in SFDC can be configured and hence setting filters as below in debug logs help to solve the problem

  • Database : NONE
  • Workflow : NONE
  • Validation : NONE
  • Callouts : NONE
  • Apex Code : ERROR
  • Apex Profiling : NONE
  • Visualforce : NONE

The above stackexchange link helps to identify how to solve the problems .

But when it comes to the TEST classes sometimes when there are too many test methods even filtering as shown above does not help much .How do we solve the problem then ?

One solution is to comment out all other test methods except the method that's giving trouble or suspected of cause of error .Hence we will be able to display logs for only the method and debug the result .


Sunday, 10 November 2013

Simulating SSO concept using axiom as IDP (An app on heruko) and Salesforce











SSO(Single SIGN ON) is a very vital concept and as a fresher to IT industry many of us struggle to understand the definition and importance. The aim of the blog post is to help you to  understand what SSO is and how easy it is to configure in salesforce.

SSO (Single Sign On) allows the end users to provide their credentials once and obtain access to multiple resources. The key point of the concept is that the users are not prompted for their credentials anew on access to participating resources until the
    active  session is terminated. 

     The participating resources are typically related, but still remain independent. 

    Specifically, each system may have own authorization system, providing system-specific      roles to the end users.

 We will be using an IDP simulator axiom on heruko to simulate federated SSO concept  with salesforce as the service provider .

There are four  ways we can have single sign on with salesforce and get authenticated .

  1. Delegated SSO
  2. Federated SSO
  3. OAUTH
  4. JIT SSO (Just in Time SSO)
I am not going to explain each one of these as this is not the aim of this blog ,having said that i have few good reference link which you can refer to understand the difference between each of them 


The above link is an awesome webinar which explains all the four ways and there advantages and disadvantages 

2)There are some  blog posts on developer.force.com and these blog posts are very interesting read





One of them,(first link a) uses salesforce as IDP and also as a service provider ,so two orgs are connected and explains the concept of SSO.These are valuable resources to spend time reading and configuring .


Now let me take some time to describe Federated SSO at high level .The above diagram will help me explaining the concept of Federated SSO.

In federated SSO uses SAML and we have an IDP(Identity Provider) and a Service Provider(SP).


The user makes a request to Force.com for a specific resource: This request may happen in a variety of ways for a variety of reasons. For example, the user may be following a bookmark, clicking on a link from an email, of allowing their browser to auto-complete.
  • Force.com detects the user needs to authenticate and redirects the user to their SAML Identity Provider: Since the user doesn't present a session cookie, they need to authenticate. An organization-specific hostname allows the user's Org to be discovered, and they are sent over the SAML protocol. Along with a SAML Request, a form parameter called RelayState is passed along to the IDP. This captures the location of the resource the user originally requested
  • The user accesses their IDP and authenticates. This authentication is performed by the IdP giving the customer complete control over the authentication process. A variety of popular techniques may be used, such as LDAP, a web access management system, Integrated Windows Authentication, or a 2-factor system such as SecurID.
  • Once authenticated, the IDP sends a SAML Response back to Force.com. This response happens via the user's browser, and includes the RelayState originally sent by the Service Provider. The echoing of RelayState is critical to the success of the protocol, as this is what allows the user to be returned to the originally requested resource.
  • Force.com processes the SAML assertion and logs the user in. The digital signature applied to the SAML Response allows verification that the message is from the Identity Provider, at which point the user is authenticated. They are granted a session and redirected to their original request.
Now come the actual part of practically simulating 

Here i will be using axiom a heruko app built just  for learning, testing, and troubleshooting single sign-on solutions for Salesforce.com

1)Configuration in Salesforce Environment 

This is very simple and let me go through this step by step with screenshots

a)So first step is to register a domain in my domain and set the redirection policy (Navigate to Domain management>my Domain in your salesforce instance 















b)Next step is to enable SAML 2.0 and configure the parameters for SAML SINGLE SIGN ON Settings

Once you enable SAML 2.0 as in below screenshot,the next step will be to download the certificate from axiom tool and upload in the SAML single sign on settings .Here are the screen shots to help you 











































So i hope screen shots are clear to understand .So its basicallyits feeding the entity Id and SSO start page got from the axiom screen back to the salesforce and then in the below video i am going to demonstrate how easy it is now to simulate the whole behavior.Its no point more speaking in words i felt instead decided to put a video






Monday, 4 November 2013

Using Change sets Effectively For Enterprise Application Deployment For Force.com Projects

Deployments in force.com can be a headache specially if you are new to platform ,in fact you may mess up if you use changesets and have no experience before doing this or if you have come up from java/.NET background where you have used ANT for deployments and now asked to use change sets of salesforce

The aim of this blog-post is share some of the tips and tricks for using the changeset effectively for deployment.

So i assume here that we generally go through salesforce document and we are ready after going through salesforce document to explore some tips and tricks that i generally use for deployments when using change set

http://help.salesforce.com/HTViewHelpDoc?id=changesets.htm&language=en_US
https://help.salesforce.com/apex/HTViewHelpDoc?id=changesets_best_practices.htm&language=en

The above links is must read before you start reading the tips i have for using changesets effectively

Problem 1:The field level security and permissions of objects and fields are not obeyed once i deploy fields and objects using changesets 

http://salesforce.stackexchange.com/questions/15238/change-sets-including-custom-objects-and-custom-fields

So the solution is quite simple we forget that profiles and permission sets should be migrated along with migration of fields,objects,apex classes,visualforce,record types etc to apply the permissions 

Problem 2:Reports and Dashboards don't migrate properly

Reports and Dashboards do get migrated well with changesets .All that we need to ensure is to include the folders also that are necessary along with these dashboards .

There are two specific problems that i encountered 

i)In deploying folders or dashboard we get error saying the user with given mail ID don't exist in destination org 

Solution is simple, either we will have to remove the running user from the dashboard of  current org from which we are deploying or other way around to temporarily form  the user mail id in the destination org or may be create folders not deploying manually

ii)I received internal sever error when migrating reports and dashboards .

Internal server errors are meant for salesforce support but here is something that comes by luck sometimes




 If the destination organisation does not have folder sharing enabled then we cant deploy reports we receive internal salesforce errors.Manually enable in destination org to resolve this issue 

Problem 3:Deployed email templates in one go and in next go i deployed letter head and there was no association between email template and letter head 

This particular thing i noticed and looks like a bug but nevertheless,we must be careful in deploying email templates and letterheads .Its better to include both together to avoid such complains .

Problem 4:Its difficult adding fields to changesets when i have large number of fields or components 

For this lets hack a salesforce a bit .

































So from the above pictures we will need to follow these to make our life simpler .First we will sort the fields by Type and then click on the "more" link found at the bottom.

Now the fields looks little better organised for the selection.Lets make it more easier .


si=-2&lsr=0&entityType=CustomFieldDefinition&rowsperpage=260


So observing the url once we click more, at the end of the URL we find a parameter called rowsperpage.This parameter holds no of rows that is displayed when forming the changesets .Now if we increase the rows per page from 260 to some large number 50000 we find we avoided pagination and now sorting on type again ,we find the interface is really selective and we need not paginate lot to add components into changeset.


si=-2&lsr=0&entityType=CustomFieldDefinition&rowsperpage=50000


Increasing rowsperpage avoids pagination and we can scroll at bottom to greater extent and avoids us to one more iteration to add components into changesets 



Disadvantages of Changesets 

Some of the disadvantages of changesets are as follows which needs some attention in future from salesforce

1)For standard fields and objects we will need to manually check permissions and field level security(manual activity or use force.com IDE)

2)Removing components from changeset is painful..yes its painful due to bad user interface and with no sorter available and pagination rendering is ajax one making more slower

Few Interesting tips 

1)The components in changesets are the very latest version components at that particular instance in the organisation.What i meant by this is say you formed a changeset at an hour before and one of the trigger got deactivated later ,say 10 minutes before you deployed into next instance .The trigger will appear deactivated in destination org as the current instance and code or build is taken during deployment .So make sure to form these only at time of deployment 

2)Approval process are available ,groups and queues can be deployed .If any issue its better to form queues and groups manually as this is simpler than debugging issue 

3)Be extra careful in adding metadata to changeset that have recently modified by salesforce during salesforce API release .An example to quote ,in winter 14 release only my sandbox was updated to 29 and my production was still on 28.0 and salesforce made some changes to Topics object and some unknown error was received during deployment .In order to avoid this i preferred removing that permission sets .

4)If some components is not getting deployed and if its config build and small effort prefer manually creating and removing same from changesets .Good thing about changesets is changesets can be cloned .

Hope this was interesting post!!Happy deployments and coding !




Thursday, 24 October 2013

Battling CPU time out limit in apex sfdc



As per winter 14 release a new Limit was introduced for apex transactions which was brought in instead of number of script statements (2,00,000 script statement was maximum script statements allowed ).If you are guessing its CPU time out limit i am blogging on ..you are right .Its this new feature which asks for developer to be more smart and more thoughtful in designing and approaching any apex design going forward 


One question that quickly came to my mind when this was announced is what will happen to previous code which took more than 10s (Please note for synchronous transactions 10 seconds is the CPU limit ) ?


I found answer to this in my favorite community that i spent lot of my time in(Yes its the salesforce.stackexchange.com) 


http://salesforce.stackexchange.com/questions/18244/how-do-sf-calculate-the-cpu-limit


Read the technical  discussion that went deep to exploring OS concepts in computer science .So the answer why the previous code wont break is because salesforce analyzed all their previous code and for each org they took the maximum CPU time that a code took to execute and have set the time out equal to that .Example assume before winter 14 i have an org A and that had a code which did not hit script execution limit but took 15 seconds of CPU time in that case for org A the CPU time limit is 15 seconds .



It wont be fair if i dont explain whats this CPU time of apex transaction here.


CPU Time :Read the below blog link from apex product manager himself to dig deeper .


http://blogs.developerforce.com/engineering/2013/09/script-limits-begone.html


The time taken by the apex transaction in a context including validations,workflows apex code and  excluding time taken in DML,queries,callouts is called CPU time .

Lets be once more clear on whats counted in CPU time and whats not


What's counted:

- All Apex code
- Library functions exposed in Apex
- Workflow execution
What's not counted:

- Database operations, e.g. DML, SOQL
- SOSL
- HTTP callouts


Now lets discuss some of the best practices  in code which will help to reduce the CPU time out 


1)Using Map Based Query 

Very clear this was taught to us when we had to reduce script statements ,well same best practice is also useful when you want to reduce the CPU time

2)Explore option to see if your business scenario allows you to do the operation asynchronously 

In some cases business process may not be real time and hence if there is a chance to make code execute in @future ,this will break the context and also the CPU time out limit for asynchronous process is 60seconds(6X of synchronous process).So do consider a thought on this if you are in trouble of hitting this limit


3)Aggregate SOQL usage 


Since the database time is not calculated in CPU time its always better to explore the usage of aggregate SOQL for your business use case .


Say you want summation of field value  of some records ,if you use normal for loop to get these obvious you have spent CPU time there .Instead try to push your calculation using SUM,AVG aggregate functions at the database layer itself so that you have reduced CPU time and have pushed the process on database layer itself.Explore options to group by or create some sort of filtering at database layer and push your calculations at database layer to reduce chances of hitting CPU time out issue .


4)Make sure you take only necessary data and run a loop .


This is essential now to filter only specific data while doing a for on a list of records as too much looping will increase CPU time .Same held good when we had no of script statements limit .


So conclusion is clear some of best practices we used to reduce script statements still hold good and its essential to follow these .


If you have come across any other techniques in apex to reduce the CPU time consumed please post below and i am happy to learn and share .


Happy coding !





Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...