Force.com for ASP.NET Developers

Dave Nielsen demonstrates how to create custom Force.com logicthat can be called from within a Force.com application or from within a customASP.NET application hosted outside Salesforce.com.

Dave Nielsen

October 30, 2009

18 Min Read
ITPro Today logo in a gray background | ITPro Today

asp:Feature

 

Force.com for ASP.NET Developers

 

By Dave Nielsen

 

The developer community, including those vested deeply inthe Microsoft .NET platform, has expressed particular interest in usingForce.com Web services to expose data and business logic from the Force.complatform to custom, external applications.

 

This article will show you how to create custom Force.comlogic that you can call from within a Force.com application or from within acustom ASP.NET application hosted outside Salesforce.com.You ll learn how to:

  • Create a custom Force.com function and expose itas a Web service.

  • Create a Visualforce application that calls thecustom Force.com function and displays the results within a Visualforce page.

  • Create a Microsoft ASP.NET Web form thatretrieves data from the Force.com Web service account and displays the resultswithin an ASP.NET Web page.

  • Use an e-mail address to look up a lead in aSalesforce.com account and return the lead s listed mailing address, which canbe used to pre-populate an online order form.

 

When finished with the article, you will understand howto:

  • Use Apex code (a procedural on-demand languagethat is part of the Force.com platform) to expose a Simple Object AccessProtocol (SOAP)-based Web service from within Force.com.

  • Use Visualforce to consume the SOAP-based Web servicein a Force.com application.

  • Use Microsoft Visual Studio 2005 to consume theSOAP-based application from an external ASP.NET Web site.

 

Getting Started

Before we move forward, let s define exactly what callingcustom Force.com logic from Visualforce pages and ASP.NET Web forms actuallylooks like. Figure 1 illustrates how Force.com Apex code, exposed as a Web serviceto an ASP.NET Web form, pulls data out of Salesforce.com and displays it to auser viewing an ASP.NET Web page.

 


Figure 1: Pulling data from aForce.com Web service to an ASP.NET Web form.

 

Several systems must connect to make this process happen:

  • Your lead data stored in Force.com

  • A Force.com Web service, which queries yourForce.com data and exposes it outside the Force.com platform

  • An ASP.NET Web page that retrieves the data fromthe Web service and displays it in a Web browser

 

Assembling Your Tools

For this walk-through, you ll need Visual Studio 2005(using Microsoft Visual Basic) and Visualforce. If you don t already haveVisual Studio, you can get a free copy of Microsoft Visual Web Developer 2005 ExpressEdition. You can use Visualforce to create unique user experiences and datainteractions for use within your Force.com applications. Unlike Visual Studio,Force.com applications are available on-demand, through your Web browser. Thereis no software to install. Of course, you ll need a Salesforce.com DeveloperEdition account with Visualforce enabled.

 

Getting a Free Force.com Developer Edition Account Login

You don t need to use live company data and risk making amess of things: Force.com Developer Edition accounts are free and easy tocreate. By joining the Apex Developer Network (ADN), you get a DeveloperEdition account as well as access to developer forums and other memberbenefits. Sign up for your free Force.com Developer Edition account.

 

Enable the Visualforce Developer Preview

Joining ADN gets you a Developer Edition account, but you llstill need access to the Visualforce Developer Preview. You ll receive anotification that Visualforce has been added to your account.

 

Next, use your new ADN credentials to log in to your Salesforce.comaccount. To enable development mode, click Setup | My Personal Information |Personal Information. Select the Development Mode checkbox, then click Save.

 

To confirm that Visualforce is now enabled, visit https://na2.salesforce.com/apex/LookupAddress1(replace na2 with the sub-domain you see in the URL of your Developer Editionaccount). Note the Salesforce.com message. If the message says Page Sample1does not exist ... Create page LookupAddress1 then Visualforce is enabled. Ifyou do not see this message, then Visualforce is not enabled correctly. Repeatthe process and confirm that the correct settings are selected.

 

Creating Visualforce pages is similar to creating a new ADNwiki page. Simply enter the URL you want to create and Visualforce offersto create the page for you!

 

Force.com Web Services

Code that is written in a Microsoft .NET language (such asVisual Basic.NET or C#) is compiled into a Microsoft .NET assembly (a file withan.exe or .dll extension). Microsoft .NET assemblies are hosted by theMicrosoft .NET Runtime, which must be installed on your computer (or Webserver, if your application is an ASP.NET Web application). This Microsoft .NETruntime provides services to your application, manages memory and security tothe user s computer, and so forth.

 

Similarly, Force.com pages are hosted by the Force.complatform, which provides services such as security and memory management toyour application. The primary difference between these two approaches is thatyou don t need to set up any servers or configure any software to begin codingwith Force.com. Salesforce.com does all the set up and configuration for you.Furthermore, Salesforce.com handles future upgrades, so you don t have to worryabout software updates, patches, or service packs.

 

Apex code, the procedural language that is a part of theForce.com platform, is very rigorous. You host your code in the Force.complatform, which in turn is hosted by Salesforce.com, so the code is checked forconsistency and syntax when it is compiled for you. The code runs onSalesforce.com servers and therefore is multi-tenant and automaticallyupgradeable. Your custom methods and objects get all the scalability of theForce.com platform. Your Apex code won t break when Salesforce.com introduces anew release of Force.com.

 

You don t need to know how Force.com works internally tobe productive and build applications quickly ... but a little knowledge won thurt. For more information about the Force.com platform, visit the Platform page andread the Force.com whitepaper.

 

Using Apex Code to Create a Force.com Web Service

You have two choices to expose business logic fromForce.com to your application:

  • You can create a Force.com class object.

  • You can create a Force.com Web service.

 

You ll use the Apex Class Editor in either option, but aForce.com Web service provides the additional benefit of letting externalapplications access your Force.com business logic and data.

 

Fortunately, you can take advantage of both options simplyby adding the global keyword in front of the class name, as Figure 2 shows. Inthis article, I ll show you how to use the global keyword with your class soyour service can be available to your Visualforce application, as well as tothe ASP.NET Web page that we ll create by using Visual Studio .NET.

 


Figure 2: Apex class with globalkeyword.

 

Creating Your First Apex Class

To create a Force.com Web service, you must first createan Apex class. To create an Apex class, log in to your Developer Editionaccount, click Setup | App Setup | Build | Code, then click New. Next, add thefollowing code into the body of the Apex Class Editor:

 

global class getLeadInfo {

}

 

Click Save.

 

Creating a Custom Apex Method

You put your Force.com business logic into a custom Apexmethod. To create your method, you ll use Apex code, which runs within theForce.com platform and is available within other Force.com classes. As Figure 3shows, this code contains a method called getLeadAddressByEmail, which usesSalesforce Object Query Language (SOQL) to look up a lead record based on an e-mailaddress. The query returns a lead object with only the Street, City, State, andPostalCode attributes.

 


Figure 3: Apex Class withgetLeadAddressByEmail method.

 

Creating a Force.com Web Service from Your Apex Class

To expose the methods in your Apex class as a Force.comWeb Service, all you need to do is use the webService annotation within aglobal class. Also, be sure to use the static keyword, which is required forall Force.com Web services. And of course, you ll need to write the Web servicecode. The following code is the same as in the previous sample:

global class getLeadInfo {

 WebService static LeadgetLeadAddressByEmail(string LeadEmail) {

   Lead c = [SELECT Street, City, State, PostalCode from Lead WHEREEmail = :LeadEmail];

   Lead l = newLead(Street = c.Street, City = c.City, State = c.State, PostalCode =c.PostalCode);

  return l;

 }

}

 

Once you ve created your Force.com Web Service, you cangenerate the Web Service Definition Language (WSDL) document that describes theWeb Service. This document will come in handy later in the process, when youuse the Visual Studio Web Reference wizard to access the Force.com Web Service.

 

Visualforce

During Dreamforce 2007, Salesforce.com announcedVisualforce: a new tool to create custom user interfaces and data interactionsfor the Force.com platform. Visualforce is a feature that developers can use tocreate a customized application user interface. You can use Visualforce toshape the presentation of your Force.com applications by combining data frommultiple Force.com objects. You also can use Visualforce to blend data from Webservices into your applications so you can create special-purpose mash-upapplications.

 

Let s create a Visualforce page that enables you to use ane-mail address to look up a lead in Salesforce.com and return the lead smailing address. We will use the Force.com Apex Class ( getLeadInfo ) wecreated in the previous section. Figure 4 illustrates how a Force.com Web service,exposed to a Visualforce page, pulls data out of Salesforce.com and displays itto the user.

 


Figure 4: Pulling data from aForce.com Web Service to a Visualforce page.

 

Creating Your First Visualforce Page

To get started, create a Web page. As I mentioned earlier,creating a Force.com page within Visualforce is easy. Just type in the URL ofthe page you want to create, for example,https://na2.salesforce.com/apex/leadLookup1 (again, replace na2 with thesubdomain that you see when you are logged into salesforce.com). You should seea page similar to Figure 5.

 


Figure 5: Visualforce creates pagesfor you.

 

Click Create page leadLookup1 to create your page. You llsee a page similar to the one in Figure 6. Drag the top of the lower frame afew inches higher to see the Visualforce Page Editor.

 


Figure 6: Your first Visualforcepage.

 

In the lower frame, the Visualforce Page Editor shows youthe code that makes up your page; in the upper frame, you ll see a preview ofthe page. As you can see from the Visualforce Page Editor, a page is acombination of standard HTML elements and Apex tags. Visualforce also supportsJavaScript, style sheets, Cascading Style Sheets (CSS), and most othercapabilities with which Web developers are familiar, such as those available inAdobe Flash and Microsoft Silverlight.

 

Understanding Model-View-Controller

To understand Visualforce, it is helpful to understand theModel-View-Controller (MVC) design pattern. MVC is a common way of architectingapplications and is used in a variety of application development frameworks.Many developers will find this pattern familiar.

 

At the heart of MVC is the idea of separating the userexperience into three component roles:

  • The Model role, which represents the data usedby the application.

  • The View role, which represents the applicationdisplay of that data.

  • The Controller role, which handles the businesslogic that decides how the application behaves when it is engaged by the user.

 

For those of you familiar with ASP.NET, the role of Modelis often played by a DataSet or DataTable. A typed ASP.NET DataSet, forexample, can play the Model role by representing the data in your database. TheView and Controller roles, however, can be translated only loosely intoASP.NET. The View role, for example, is usually handled by the .aspx file, andthe role of Controller is partially handled by the code-behind page (e.g.,.aspx.vb).

 

In Visualforce, the MVC roles are clearer. Standard andcustom Salesforce objects play the Model role. The Visualforce page handles theView role. And the Visualforce Controller handles the Controller role.

 

Note that in an October 2007 blog post, Scott Guthrie discussed the announcement that Microsoft isin the process of creating an ASP.NET MVC framework for developers to usewithin Visual Studio. While this framework won t be on-demand like Visualforce,it may make it easier for developers to switch back and forth between the twoenvironments.

 

Calling Your Force.com Web Service from Your Visualforce Page

To access your Apex class (which has been exposed as a Webservice) from within Visualforce, you first need to create an entry page. Let suse the leadLookup1 page you created in the previous section. Next, add thefollowing code to your Page Editor:

 

 

   

   :

   

   

     

       

     

   

   

 

 

Each Apex tag represents a Visualforce Component. Forexample, an outputLabel is an HTML control used to display a label for anothercomponent, such as the inputText. An inputText is an HTML control that acts asan input box for submitting information, such as the searchString variable. AcommandButton is a control similar to an HTML button and can be set to submit,reset, or image. For a list of all Visualforce Components, click ComponentReference (in the same Web page section as Save).

 

This code sample also includes a reference to the pagecontroller. To create a controller, add the controller attribute to the Apex pagetag, as follows:

 

 

As soon as you click Save, you ll receive an error messagestating Error: Apex class leadLookupController does not exist . This isexpected behavior. Click Create Apex class leadLookupController . You ll getanother error message stating Error: Unknown property leadLookupController1.searchString .Again, this is expected behavior. Click Create Apex method leadLookupController1.getSearchString .You ll get a third error message stating Error: Unknown method leadLookupController1.step2 .Once again, this is expected behavior. Click Create Apex method leadLookupController1.step2 .Your controller, searchString property, and step2 method all will be created.

 

Click the new Controller button (next to Page Editor) tosee the code within the leadLookupController class. Next, add the code for theController:

 

'''public class''' leadLookupController {

private String emailString;

'''public''' void setSearchString(String val) {

emailString = val;

}

'''public''' String getSearchString() {

  return emailString ;

}

 '''public''' LeadgetLead() {

 Lead lead =getLeadInfo.getLeadAddressByEmail(emailString);

 '''return''' lead;

 }

 '''public''' PageReferencestep2() {

 '''return''' Page.leadLookup2;

}

}

 

The getLead method calls the getLeadAddressByEmail methodyou created earlier as a part of the getLeadInfo class, then returns an objectof type Lead.

 

The PageReference step2 method redirects the applicationto leadLookup2 to display the search results. However, leadLookup2 doesn texist yet; you ll need to add it. Follow the same steps you used to createleadLookup1. Paste the following code into your Visualforce Page Editor:

 

 

   :

   

   :

   

   :

   

   :

   

   :

   

 

 

The code uses the outputLabel values to output the resultsfrom the e-mail search by displaying the results from the getLeadAddressByEmailmethod of the getLeadInfo class.

 

Now you understand how to call your custom Force.com logicfrom within Visualforce. But as mentioned earlier, you may not be able to moveyour existing application and logic to Force.com overnight. In this nextsection, I ll show you how to call your Force.com code from an external ASP.NETWeb application.

 

Create an ASP.NET Web Form

For the purposes of this article, we re going to keep theWeb form simple: a standard ASP.NET Web form in an ASP.NET Web site. Later, youcan convert this Web form to an AJAXwidget or business object. To create your Web form, first create a new ASP.NETWeb site called SFLeadLookup.

 

Verify that the Default.aspx Web form has been generated.If you add a new Web form, make sure that the Place code in separate filecheckbox is selected.

 

Next, add to your form a textbox, named txtEmail, and itsassociated label. This field will be used to look up the lead according to e-mailaddress. Then, add to your form textboxes named txtAddress, txtCity, txtState,and txtZip, along with the associated labels. These fields will be prefilledwhen the provided e-mail address is found.

 

Add a button to the form. Name the button cmdSubmit. Youare now ready to add the functionality to use a lead s e-mail to look up thelead s address. This process requires the custom business logic that youcreated earlier. To access this custom business logic from ASP.NET, make surethat the class object is a global class and the service is identified asstatic, as Figure 3 shows.

 

You can confirm and update as necessary by using Setup |App Setup | Build | Code and clicking Edit for the getLeadInfo class. Yourbusiness functionality is now ready to be accessed by your ASP.NET applicationor by any external application that has the appropriate credentials.

 

Web Service Enabling Your Web Form

To access your Force.com Web service, your applicationmust provide the user ID and password from a valid Salesforce.com account thathas API access enabled. For this example, you ll use your existing DeveloperEdition account because the API Enabled option is already selected. Forproduction, you should create a custom profile to use only for accessing theAPI; this profile should have the API Only User property selected.

 

Your application must also pass a session ID string witheach Web service call. A session ID is a temporary ID provided by Salesforce.By default, session ID is valid for two hours. With Administration privileges,you can change the session expiration timeout through the Setup |Administration Setup | Security Controls | Session Settings interface.

 

Obtaining a session ID can be a challenge. Your ASP.NETWeb form can request a session ID by making a Web service call from Salesforce,using the user ID and password from your API-enabled account. This session IDcan be stored locally in a database, text file, or application-level variable.It can be re-used by your application until the session expires, at which timeyour API-enabled user ID and password account may generate another session ID.

 

Obtaining a Session ID

To obtain a session ID, your application must query thelog-in method of the Salesforce.com API. The log-in method will return asession ID, which your application will use to access your custom Force.com Webservice. To access the Salesforce.com API by using ASP.NET, you must create aWeb Reference.

 

To create a Web Reference from your ASP.NET application tothe Salesforce.com API, you first must export the application s WSDL document.To do this, visit Setup | App Setup | Integrate | API and click DownloadEnterprise WSDL. You ll see the XML that describes this Web service API. Youcan use the Enterprise WSDL document to access data directly fromSalesforce.com, but for now, you ll use this service to create a session ID.

 

Next, create a Web Reference within your Visual Studioproject. Right-click the project name (e.g., SFLeadLookup) and select Add WebReference. In the Add Web Reference dialog box there is a textbox labeled URL.Type (or paste) the enterprise.wsdl file path into the URL textbox, then clickGo. You should see the SForceService description displayed in the Add WebReference window, along with many methods. Change the Web Reference name tosforce and click Add Reference. You ll see the sforce proxy library createdwithin your project s Web References folder.

 

Next, you must add code to your Web form to access theSForceService log-in method and retrieve the session ID. The following codeuses the sforce proxy object you created to obtain a session ID:

 

Imports sforce

Partial Class _Default

  InheritsSystem.Web.UI.Page

  Private _userId AsString = "[email protected]"

  Private _password As String= "mypassword"

  Private _sessionId AsString

  Private _serverUrl AsString

  Private _nextLoginTimeAs DateTime

  Protected SubcmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)Handles cmdSubmit.Click

      ' See if Session IDexists

      _sessionId =IIf(Application("_sessionId") Is Nothing,Application("_sessionId"), "")

      _serverUrl =IIf(Application("_serverUrl") Is Nothing,Application("_serverUrl"), "")

      _nextLoginTime =IIf(Application("_nextLoginTime") Is Nothing,Application("_nextLoginTime"),   #1/1/2000#)

      If (NotisConnected()) Then

          getSessionInfo()

      End If

  End Sub

  Public FunctionisConnected() As Boolean

      If _sessionId <>"" And _sessionId <> Nothing Then

          If Now() > _nextLoginTime Then

              isConnected= False

          Else

              isConnected= True

          End If

      Else

          isConnected =False

      End If

  End Function

  Sub getSessionInfo()

      Dim lr As sforce.LoginResult

      Dim ss Assforce.SforceService = New sforce.SforceService

      lr =ss.login(_userId, _password)

      _sessionId =lr.sessionId

      Application("_sessionId") = lr.sessionId

      _serverUrl =lr.serverUrl

      Application("_serverUrl")= lr.serverUrl

      Application("_nextLoginTime") = Now()

  End Sub

End Class

 

Creating a Force.com Web Service Reference

The process of creating a Web Reference from your ASP.NETapplication to your Force.com Web service is similar to creating a Web Referenceto the Salesforce.com API. First, you must export the WSDL document for thegetLeadInfo class. Visit Setup | App Setup | Build and click WSDL (next togetLeadInfo). You ll see the XML that describes the Web service. Save thedocument to a location on your computer s hard drive (e.g.,c:getLeadInfo.wsdl).

 

Next, create a Web Reference within your Visual Studioproject. Right-click your project name and select Add Web Reference. In the AddWeb Reference dialog box, type (or paste) the getLeadInfo.wsdl file path in tothe URL textbox, then click Go. You should see your getLeadInfoServicedisplayed in the Add Web Reference window, along with the getLeadAddressByEmailmethod. To make the Web Reference name more descriptive, change it to getLeadInfoand click Add Reference. You ll see the getLeadInfo proxy library createdwithin the project s Web References folder.

 

Getting a Mailing Address from an E-mail Address

The connection from your Web form to your custom Force.comWeb service is almost complete. The following code sample uses the getLeadInfoproxy object you created to query your custom Force.com Web service with thelead s e-mail address (e.g., [email protected]). If the lead is found, the codedisplays the address (street, city, state, and ZIP code) for the lead. To keepthings simple, no error trapping has been provided. Add the following code toyour Default.aspx code-behind page:

 

Imports sforce

Imports getLeadInfo

Partial Class _Default

  InheritsSystem.Web.UI.Page

  Private _userId AsString = "[email protected]"

  Private _password AsString = "mypassword"

  Private _sessionId AsString

  Private _serverUrl AsString

  Private _nextLoginTimeAs DateTime

  Private _leadEmail AsString

  Protected SubcmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdSubmit.Click

      ' Confirm Lead EmailExists

      _leadEmail =Me.txtEmail.Text

      ' See if Session IDexists

      _sessionId =IIf(Application("_sessionId") Is Nothing, Application("_sessionId"),"")

      _serverUrl =IIf(Application("_serverUrl") Is Nothing,Application("_serverUrl"), "")

      _nextLoginTime =IIf(Application("_nextLoginTime") Is Nothing,Application("_nextLoginTime"), #1/1/2000#)

      If (NotisConnected()) Then

          getSessionInfo()

      End If

      ' Call getLeadInfoWeb Service

      Dim getLeadInfo AsgetLeadInfoService = New getLeadInfoService

      getLeadInfo.SessionHeaderValue = New getLeadInfo.SessionHeader

      getLeadInfo.SessionHeaderValue.sessionId = Me._sessionId

      DimgetLeadInfoResponse As getLeadInfo.Lead

      getLeadInfoResponse= getLeadInfo.getLeadAddressByEmail(_leadEmail)

      Me.txtAddress.Text =getLeadInfoResponse.Street.ToString

      Me.txtCity.Text =getLeadInfoResponse.City.ToString

      Me.txtState.Text =getLeadInfoResponse.State.ToString

      Me.txtZip.Text =getLeadInfoResponse.PostalCode.ToString

  End Sub

  Public FunctionisConnected() As Boolean

      If _sessionId <>"" And _sessionId <> Nothing Then

          If Now() >_nextLoginTime Then

              isConnected= False

          Else

              isConnected= True

          End If

      Else

          isConnected =False

      End If

  End Function

  Sub getSessionInfo()

      Dim lr As sforce.LoginResult

      Dim ss Assforce.SforceService = New sforce.SforceService

      lr =ss.login(_userId, _password)

      _sessionId =lr.sessionId

      Application("_sessionId") = lr.sessionId

      _serverUrl =lr.serverUrl

      Application("_serverUrl") =lr.serverUrl

      Application("_nextLoginTime") = Now()

  End Sub

End Class

 

Putting It All Together

Now that you ve completed the coding, the only thing leftto do is to build and run your project. The URL to your project will looksomething like the following: http://localhost:3187/SFLeadLookup/default.aspx. Theinput and output will look like the Web form in Figure 7.

 


Figure 7: ASP.NET Web form in action.

 

Conclusion

With the release of the Force.com platform, Salesforce isdemonstrating its commitment and ability toprovide a complete development environment for building and deliveringapplications on the Force.com PaaS. You can take full advantage of the platformand build complete applications upon it or, as demonstrated in this article,you can extend the power of the Force.com platform to your ASP.NET Webapplications.

 

The code samples forthis article are available for download.

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like