Showing posts with label Web Service. Show all posts
Showing posts with label Web Service. Show all posts

Tuesday, June 26, 2012

.Net Web Service with Salesforce.com

Part 1 – Update Salesforce Recod using .Net Application
  • Step 1:
    • Create a field TestAccount [Text] in Account.
    • Step 2:
      • Create a .Net application that extracts salesforce's objects records (In this case, Accounts) and update TestAccount field with its Parent Account field.
      • You have to add Web Reference of your enterprise WSDL in this .Net Application.
      • To generate WSDL:  Setup | Develop | API| Generate Enterprise WSDL | Generate.
      • Right Click on it and Save Enterprise WSDL and Import into you .net Application using Webrefernce.
        • If you don't know how to add Webrefernce. (Click here)
  • Now Refer to "Walk Through the Sample Code" in Web Services API Developer's Guide :http://www.salesforce.com/us/developer/docs/api/apex_api.pdf
  • This Walkthorugh Application is a very simple app you can easily query data from the querySample() method. So Query that record by passing a hardcoded record Id e.g. :
    • QueryResult qr = null;
    • string recordId = "01pP00000004kUC"; //SampleID
    • qr = binding.query("SELECT Id, Name, ParentId FROM Account where Id = '" + recordId + "'");
  • In The 2nd part of this App we will update this recordId which will get Id from Outbound Message.
  • To update record we need to use SaveResult and sObject to Update. Here is a sample code to update it. This will Update TestAccount field and populate the Value of ParentId into it.
    • for (int i = 0; i < qr.records.Length; i++)
    • {
    •    Account acc = (Account)qr.records[i];
    •    acc.TestAccount__c = acc.ParentId;
    •    SaveResult[] saveResults = binding.update(new sObject[] { acc }); // updating results in salesforce.
    • }
  • Now Run and Test it whether it is Updating that record or not.
  • How to Import WSDL into .net APP
    • In Solution Explorer Right Click on Application name and click on Add Service Reference.
    • Now Click Advanced a new window will pop up and Now Click on Add Web Reference.
    • Again a window will pop up here you need to specify the path of you Enterprise WSDL e.g. : C:\Users\Administrator\Desktop\enterprise.wsdl
    • Now Click on Add reference and that's it your webrefernce is added into you App.
    • In order to use it you have to add a name space e.g. :  using ApplicationName.WebserviceName;
Part 2 – Outbound Message to invoke .Net Application
Step 3:
Create a Web Service that calls your .Net Application.
Add reference of your .Net application to the Web Service.
Sample Code:
Below is the code of web service file .asmx that implements class WebService in namespace testWebservice
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" %>
Below is the code of a Class Webservice
using System;  using System.Collections.Generic;  using System.Web;  using System.Web.Services;  using ConsoleApplication5;    namespace testWebservice  {      [WebService(Namespace = "http://theinsidecloud.org/")]      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]      public class WebService : System.Web.Services.WebService      {          public WebService()          {              //Uncomment the following line if using designed components              //InitializeComponent();          }          [WebMethod]          public void HelloWorld(String id)          {              Program app = new Program();              app.Accountid = id;              app.run();          }      }  }

Step 4:
  • Now host this Web Service.
Step 5:
  • Create a workflow to send an outbound message that will send Account Id. Specify end point URL where you have hosted your web service.
  • Select a field to be sent as a parameter for the Web Service.
Step 6: 
  • After saving the out bound message you will have its detail page. Click on Click for WSDL.
  • Add web reference of this WSDL in your Web Service.
  • After Adding WSDL to your WebService , Host the updated application to the Web.
So whenever your Workflow fires, it will hit the hosted Web Service with some parameter (in this case Id). Web Service will call .Net application and update a particular record that matches with the parameter.

Friday, June 1, 2012

Web service method call from Custom Button


Technical Requirement:
We have enhancement request in our project and requirements are select number of records in View and change the owner of the selected record.
Description:
As above technical requirement we want to create action from Button and update the records.
Steps to solve above requirement:
1. Create Custom button or Link Named Assign and behavior execute JavaScript.
Code on button:
{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")} // declare the Js connection
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")} // declare the Js apex
{!REQUIRESCRIPT("/js/dojo/0.4.1/dojo.js")} // declare the Js dojo
var ids='';
for(j=0;j< document.forms.length;j++)
{
for (i = 0;i
{
if((document.forms[j].elements[i].name=='ids') && document.forms[j].elements[i].checked)
{
ids+=document.forms[j].elements[i].value+',';
}
}
}// end of loop
if(ids==''){
alert('No requests selected !!!');
}else{
var returnFlag = '';
returnFlag = sforce.apex.execute("CheckClass" , "methode ", {ids:ids} );
if(returnFlag== ‘true’){
window.location = '/apex/PageName;
}else if(returnFlag== ‘false){
alert('You do not have permission to do this!')
}
--------------End of Code--------------------
2. Apex class:
global class CheckClass{
WebService static Boolean methode(){
Write the Logic
Return Boolean value
}
}

WebService Fuctions


WebService Methods
Apex class methods can be exposed as custom Force.comWeb services API calls. This allows an external application to invoke an Apex web service to perform an action in Salesforce.com. Use the webService keyword to define these methods. For
Example:
global class MyWebService {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id);
insert c;
return c.id;
}
}
A developer of an external application can integrate with an Apex class containing webService methods by generating a WSDL for the class.To generate a WSDL from an Apex class detail page:
1. In the application navigate to Your Name  Setup  Develop  Apex Classes.
2. Click the name of a class that contains web Service methods.
3. Click Generate WSDL.

Considerations for Using the WebService Keyword:
  • You cannot use the webService keyword when defining a class. However, you can use it to define top-level, outer class methods, and methods of an inner class.
  • You cannot use the webService keyword to define an interface, or to define an interface's methods and variables.
  • System-defined enums cannot be used in Web service methods.
  • You cannot use the webService keyword in a trigger because you cannot define a method in a trigger.
  • All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer, top-level class must also be defined as global.
  • Methods defined with the webService keyword are inherently global. These methods can be used by any Apex script that has access to the class. You can consider the webService keyword as a type of access modifier that enables more access than global.
  • You must define any method that uses the webService keyword as static.
  • You cannot deprecate webService methods or variables in managed package code.
  • Because there are no SOAP analogs for certain Apex elements, methods defined with the webService keyword cannot take the following elements as  parameters.While these elements can be used within the method, they also cannot be marked as return values.
    • Maps
    • Sets
    • Pattern objects
    • Matcher objects
    • Exception objects
  • You must use the webService keyword with any member variables that you want to expose as part of a Web service. You should not mark these member variables as static.
  • Salesforce.com denies access to Web service and execute anonymous requests from an AppExchange package that has restricted access.
  • Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String value that is too long for the field.

Monday, March 26, 2012

HTTP Callout from Apex Class

public class simpleHTTPCallOut {
public simpleHTTPCallOut(ApexPages.StandardController controller)
{
}
String ErrorMessage;
public void Login() {
 ErrorMessage='';
 final string baseUrl = 'https://login.salesforce.com/';
 final string username = 'test@test.com';
 final string password = 'test@123';
 Http h = new Http();
 HttpRequest req = new HttpRequest();
 req.setMethod('GET');
 req.setEndpoint(baseUrl + '?loginType=&un='+username+'&pw='+password);
 HttpResponse res = h.send(req);
  
 req.setEndpoint(baseUrl + 'apex/EndPOINTPAGE');
 res = h.send(req);
 if (res.getBody().indexOf('success=true')>-1) {
  system.debug('Success');
 } 
}
}