Monday, 2 March 2015

Problem VB.Net to salesforce Integration

STREAMING API IN SALESFORCE

STREAMING API IN SALESFORCE

What is Streaming API ?


To put it simple, streaming API is a mechanism which monitors data changes in Salesforce based on the SOQL query you define, and if the condition matches, sends push notifications to all the subscribed clients.

Since Summer ’12, streaming API is available in any API-valid organizations. You can test it to see how it works in the Developer Edition.

Also, push notifications can be received from a page in a Salesforce application, a server and a page outside of Salesforce, and Java client.

For this example, we will use a Visualforce page to receive push notifications.

What is a Push Notification ?


Push notification is the technology that allows you to send information without the clients’ request when an event occurs in the server.

In "pull technology" where information is sent in response to the clients’ request, the page will not be updated unless the user intentionally refreshes or changes the page. Therefore, in order for the client to know an event has occurred in the server, you need to send a page request periodically and receive the result (called polling).

On the server side, a series of processes to generate an HTTP connection, send information, and close the connection by each and every polling is necessary. iI polling is performed by many clients, then it would consume a huge amount of server resources and network bandwidth.

If you use Ajax that sends a request asynchronously by restricting one part of the page, you can reduce some network bandwidth consumption. However, this is not effective as you still need to respond to the requests that are sent regularly regardless of the server event.

I would not recommend you to use polling frequently, especially if you are using Salesforce, because polling from outside of Salesforce, such as SOAP/REST API consumes API request counts.

This is when streaming API becomes useful.

Note : Before going to code we need some java script files 

STEP 1 :  Go through the URL  and download the zip file  (https://github.com/cometd/cometd)

STEP 2 :  Extract the zip file and follow the below process 

              Next, upload the following files as static resources (Your Name > Setup > Develop > Static 

              Resources > New)

                FILE                                                 NAME

             cometd.js                                             cometd
             jquery-1.5.1.js                                      jquery

             json2.js                                                 json2

             jquery.cometd.js                                  jquery_cometd


STEP 3 :  we have to create one push topic on object 
            
            Go to the developer console or workbench copy the below code and executive it 

            PushTopic pushTopic = new PushTopic();
       pushTopic.ApiVersion = 29.0;
       pushTopic.Name = 'pushOnAccout';
       pushTopic.Description = 'All records for the Account object';
       pushtopic.Query = 'SELECT Id, Name,Phone FROM Account';
       insert pushTopic;
       System.debug('Created new PushTopic: '+ pushTopic.Id);

STEP 4 

                Visual force Page :

                
<apex:page controller="StreamingApiController"> 
<apex:includeScript value="{!$Resource.cometd}"/>
<apex:includeScript value="{!$Resource.jquery}"/>
<apex:includeScript value="{!$Resource.json2}"/>
<apex:includeScript value="{!$Resource.jquery_cometd}"/>

<script type="text/javascript">

(function($){
    $(document).ready(function() {

    $.cometd.init({
        url: window.location.protocol+'//'+window.location.hostname+'/cometd/29.0/',
        requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
    });
    $.cometd.subscribe('/topic/pushOnAccout', function(message) {
        var list = new Array();
    list.push(message.channel,message.data.sobject.Name,message.data.sobject.Id,message.data.event.type,message.data.event.createdDate);

Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.StreamingApiController.methodTosendMessage}',list,function(result,event){ 

},{escape:true}); 

    $('#content').append('<p>Notification: ' +
        'Channel: ' + JSON.stringify(message.channel) + '<br></br>' +
        'Record name: ' + JSON.stringify(message.data.sobject.Name) + '<br></br>' + 
        'ID: ' + JSON.stringify(message.data.sobject.Id) + '<br></br>' +
        'Event type: ' + JSON.stringify(message.data.event.type)+'<br></br>' +
       'Created: ' + JSON.stringify(message.data.event.createdDate) + '</p>');
    });
});
})(jQuery)

</script>

<body>
<div id="content">
<p>Notifications should appear here...</p>
</div>
</body>
</apex:page>

           Controller : 

            public class StreamingApiController {
                @Remoteaction()
                public static void methodTosendMessage(List<String> streamData){
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(new string[] {'xxxxxxxxx@gmail.com'});
                    mail.setCcAddresses(new string[] {'xxxxxxx@gmail.com'});
                    mail.setSubject('Record ' + streamData[3]);
                    mail.setPlainTextBody('Record Details ' + streamData);
                    mail.setReplyTo('xxxxxxxxxx@gmail.com');
                    mail.setSenderDisplayName(UserInfo.getUserEmail());
                    Messaging.SendEmailResult[] res = Messaging.sendEmail(new             
                    Messaging.SingleEmailMessage[] { mail });       
               }
           }
SALESFORCE INTEGRATION WITH .NET USING SOAP API
SALESFORCE INTEGRATION WITH .NET USING SOAP API  PART - 1
Required :
1. .Net end point (or) WSDL wile
NOTE : If client provides WSDL file no need to follow STEP 1
STEP 1 :
Copy the .Net Endpoint given by the client (https://xxxxxxxxxxxx/gw/xxxx/nextgencrm/ldap.getpicture.dev)
Go to the web browser open new tap paste it and add (?wsdl)
EX: https://xxxxxxxxxxxx/gw/xxxx/nextgencrm/ldap.getpicture.dev?wsdl
Copy the XML data and paste in notepad or notepad++
Remove one binding and related port in that XML because sales force support only one binding
EX:
Remove second binding and related port
Binding:
-------
<wsdl:binding name="LdapSoap12" type="tns:LdapSoap">
.
.
.</wsdl:binding>
Port:
-----
<wsdl:port2 name="LdapSoap" binding="tns:LdapSoap">
<soap:address location="xxxxxxxxxxxx" />
</wsdl:port2>
Save the file as MyService.wsdl on your desktop
STEP 2:
Login in to your sales force account
Go to setup > Build > Develop > Apex
Click on Generated Apex
Browser and select MyService.wsdl file and Parse it
If successfully parse Change the name of class as MyDotnetService and save it
STEP 3 :
Open the class MyDotnetService it look like below example
EX:
public class MyDotnetService {
public class HelloWorld_element {
private String[] apex_schema_type_info = new String[]{'http://tempuri.org/','true','false'};
private String[] field_order_type_info = new String[]{};
}
public class HelloWorldResponse_element {
public String HelloWorldResult;
private String[] HelloWorldResult_type_info = new String[]{'HelloWorldResult','http://tempuri.org/',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://tempuri.org/','true','false'};
private String[] field_order_type_info = new String[]{'HelloWorldResult'};
}
public class LdapSoap {
public String endpoint_x = 'https://xxxxxxxxxxxxxxxxxxxxxx/gw/xxxxxxxxxx/nextgencrm/ldap.getpicture.dev';
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://tempuri.org/', 'MyDotnetService'};
public String HelloWorld() {
MyDotnetService.HelloWorld_element request_x = new MyDotnetService.HelloWorld_element();
MyDotnetService.HelloWorldResponse_element response_x;
Map<String, MyDotnetService.HelloWorldResponse_element> response_map_x = new Map<String, MyDotnetService.HelloWorldResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://tempuri.org/HelloWorld',
'http://tempuri.org/',
'HelloWorld',
'http://tempuri.org/',
'HelloWorldResponse',
'MyDotnetService.HelloWorldResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.HelloWorldResult;
}
}
}
STEP 4 :
Go > setup > Administer > Security Controls > Remote Site Settings > New Remote Site
Add Endpoint URL given by client
If client given WSDL file , Go to generated class ( MyDotnetService )
MyDotnetService > LdapSoap > endpoint_x
copy the end point and paste in remote site settings
STEP 5 :
Open the workbench or developer console
Copy class Name , sub class name , and method name like below example
EX:
MyDotnetService.LdapSoap ldap = new MyDotnetService.LdapSoap();
String response = ldap.HelloWorld();
System.debug('response--------'+response);
NOTE :
If time out error came, Add below code
ldap.TimeOut_x = 60000;
Now you successfully integrated sales force with .Net using SOAP API
NOTE : This process is works only when client end point has no Authorization

SALESFORCE INTEGRATION WITH .NET USING SOAP API