In order to create a fully functional ASP.net WebServices integration with Salesforce. We need the following.
1.Visual Studio 2010
2. Salesforce Account
3.SOAPUI
Most of the code/logic will be in the Visual Studio 2010, mainly for the ASP.net program. You might need an active Salesfroce account for the successful integration with the WSDL file of Salesforce. The SOAPUI is a testing tool that is used to test if the webservices is working and mainly to debug any errors in the logic.
1. Finding the WSDL file in the Salesforce Account.
In order, for a successful integration with the salesforce account, we need the wsdl file that is located in the Setup--> Searchbox-->API---> Enterprise WSDL --> Generate WSDLfile.
After that click on generate, we then get an XML file of the web page.
After finding the WSDL file save the file in your local machine.
2. Connecting the WSDL file to Visual Studio project.
Once you have the wsdl file, we need to connect the wsdl file to the Visual Studio. Create a new project and then add a new web services then attach the wsdl file to it.
Hence, I have created a project called Test. From that project I can attach the wsdl file by right clicking on the Test ---> Service Reference ---> Add Web Reference.
It will direct you to salesforce authentication. Click Ok to all. I have changed the WebService name to Salesforce_mdmdev.
3. Connection to Salesforce
Once the wsdl file is attached to your project, we need a logic to get connected to your Salesforce account.
Create a class SFConnecton, where in that class write the logic as stated below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using Test.SalesforceAdaptor.Salesforce_mdmDev;
/// <summary>
/// Summary description for SFConnection
/// </summary>
public class SFConnection
{
private string username;
private string password;
private string securitytoken;
private SforceService sfService;
//the Constructor
public SFConnection(string currentEnvironment)
{
if (currentEnvironment.ToUpper() == "DEV")
{
username = ConfigurationManager.AppSettings["SF_DEV_USER"].ToString();
password = ConfigurationManager.AppSettings["SF_DEV_PASSWORD"].ToString();
securitytoken = ConfigurationManager.AppSettings["SF_DEV_SECURITYTOKEN"].ToString();
}
else if (currentEnvironment.ToUpper() == "QA")
{
username = ConfigurationManager.AppSettings["SF_QA_USER"].ToString();
password = ConfigurationManager.AppSettings["SF_QA_PASSWORD"].ToString();
securitytoken = ConfigurationManager.AppSettings["SF_QA_SECURITYTOKEN"].ToString();
}
else if (currentEnvironment.ToUpper() == "PROD")
{
username = ConfigurationManager.AppSettings["SF_PROD_USER"].ToString();
password = ConfigurationManager.AppSettings["SF_PROD_PASSWORD"].ToString();
securitytoken = ConfigurationManager.AppSettings["SF_PROD_SECURITYTOKEN"].ToString();
}
try
{
sfService = new SforceService();
LoginResult res = sfService.login(username, password + securitytoken);
SessionHeader sh = new SessionHeader();
sh.sessionId = res.sessionId;
sfService.SessionHeaderValue = new SessionHeader();
sfService.SessionHeaderValue.sessionId = sh.sessionId;
sfService.Url = res.serverUrl;
}
catch (Exception ex)
{
throw new Exception("Error occured while connecting to Salesforce: " + ex.Message);
}
}
}
4. Testing it with SOAPUI
While connecting to the SOAPUI. We can add the WSDL file of the Visual force project that you have created which is the asmx.cs file. After running the project write the URL as the
" ?WSDL"
Save this file and go to SOAPUI and create a new project and add this file to it.
While creating the new project we can see all the logic that we have created on the Visual force "asmx.cs " file been replicated to the SOAPUI.
As you can see above, the code from the "SLXCustomer.asmx.cs" file from the Visual Studio is reflected to the SOAPUI and to the page.
From here you can code in and test if the web services is working or not.
5. Things to be Noted in the WSDL file.
There are certain modifications that needs to be included in the WSDL file via Reference.cs file and wsdl file, from the link below. These changes must be included in order to make the WebServices logic to be fully functional.
Whenever you make any changes in the Salesforce platform, we need to keep Updating the WSDL file. Simply by clicking the Service References and then click the Update Reference or delete the file and add the WSDL file again. But while updating it, we need to keep updating the Reference.cs file and the wsdl file form the link given above.
6. Get Data from the Salesforce Account.
In order to fetch the data form the Salesforce Account, we have created a logic that would match all the fields name form the Salesforce Account fields.
We have 4 classes.
1. SLXCustomer.asmx.cs
2. Account.cs
3. SFConnection.cs
4. Transcation Handler.cs
The SLXCustomer.cs file is the main page class, where the file is executed. The Account class hold all the account details. SFConnection page is where the Connection is made to Salesfroce Account. The transcation Handler is the controller.
The code is shown below for Getting data from the Salesforce Account.
// Disctionary.cs
public struct EducationCustomer
{
/// <summary> The customer account. </summary>
public Account CustomerAccount;
/// <summary> The customer addresses. </summary>
public List<Address> CustomerAddresses;
/// <summary> Identifier for the request log. </summary>
public int RequestLogID;
}
//SLXCustomer.asmx.cs
public EducationCustomer GetEducationCustomer(string DSName, string TargetID, string SLXID, ExtraFields ExtraFields)
{
if (string.IsNullOrEmpty(DSName))
DSName = "";
requestLog.AccountID = SLXID;
requestLog.Action = "Get Education Customer";
requestLog.RequestDate = createDate;
requestLog.setRequestXML();
requestLog.Username = DSName;
if (TargetID.ToUpper().Equals("DEBUG_LOG"))
{
requestLog.Insert();
}
EducationCustomer response = new EducationCustomer();
response.CustomerAccount = new Account();
response.CustomerAddresses = new List<Address>();
/*
if (Authentication == null)
{
if (TargetID.ToUpper().Equals("DEBUG_LOG"))
{
requestLog.Message = "No credentials provided. Cannot authenticate user." + " ##RequestLogID - " + requestLog.id + "## GetEducationCustomerResponse";
requestLog.SuccessFlag = 0;
requestLog.Update();
}
throw new Exception("No credentials provided. Cannot authenticate user." + " ##RequestLogID - " + requestLog.id + "## GetEducationCustomerResponse");
}
*/
try
{
if (ADAuthentication.IsAuthenticated(Authentication.Username, Authentication.Password))
{
transactionHandler = new TransactionHandler(currentEnvironment);
Accounts c = transactionHandler.GetEducationCustomer(SLXID, ref requestLog);
response.CustomerAccount.MDMID = c.mdmID;
response.CustomerAccount.MDRPID = c.mdrPID;
response.CustomerAccount.SLXID = c.slxID;
response.CustomerAccount.CustomerName = c.customerName;
response.CustomerAccount.CustomerType = c.customerType;
response.CustomerAccount.CustomerStatus = c.customerStatus;
response.CustomerAccount.CustomerStatusReason = c.customerStatusReason;
response.CustomerAccount.EnrollmentCount = c.enrollmentCount;
response.CustomerAccount.LowGrade = c.lowGrade;
response.CustomerAccount.HighGrade = c.highGrade;
response.CustomerAccount.Email = c.email;
response.CustomerAccount.Fax = c.fax;
response.CustomerAccount.MainPhone = c.mainPhone;
response.CustomerAccount.TollFreePhone = c.tollFreePhone;
response.CustomerAccount.WebAddress = c.webAddress;
response.CustomerAccount.ParentSLXID = c.parentSLXID;
//response.CustomerAccount.ParentMDMID = c.ParentMDMID;
response.CustomerAccount.SECCODEID = c.secCODEID;
response.CustomerAccount.SLXPrimaryAddressID = c.slxPrimaryAddressID;
response.CustomerAccount.SLXShippingAddressID = c.slxShippingAddressID;
response.CustomerAccount.Language = c.language;
response.CustomerAccount.SchoolType = c.schoolType;
response.CustomerAccount.AlternativeProgram = c.alternativeProgram;
response.CustomerAccount.AdultEducationProgram = c.adultEducationProgram;
response.CustomerAccount.SpecialEducationProgram = c.specialEducationProgram;
response.CustomerAccount.CharterSchool = c.charterSchool;
response.CustomerAccount.CatholicSchool = c.catholicSchool;
response.CustomerAccount.CanadianBIASchool = c.canadianBIASchool;
//response.RequestLogID = requestLog.id;
Address a = new Address();
a.AddressStatus = "Active";
a.AddressType = "Physical";
a.AddressLine1 = c.physAddressLine1;
a.AddressLine2 = c.physAddressLine2;
a.City = c.physCity;
a.County = c.physCounty;
a.State = c.physState;
a.PostalCode = c.physZip;
a.Country = c.physCountry;
response.CustomerAddresses.Add(a);
Address b = new Address();
b.AddressStatus = "Active";
b.AddressType = "Mailing";
b.AddressLine1 = c.mailAddressLine1;
b.AddressLine2 = c.mailAddressLine2;
b.City = c.mailCity;
b.County = c.mailCounty;
b.State = c.mailState;
b.PostalCode = c.mailZip;
b.Country = c.mailCountry;
response.CustomerAddresses.Add(b);
}
else
{
throw new Exception("Cannot authenticate user. Cannot get customer details.");
}
}
catch (Exception ex)
{
if (TargetID.ToUpper().Equals("DEBUG_LOG"))
{
requestLog.Message = "An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "## GetEducationCustomerResponse";
requestLog.SuccessFlag = 0;
if (TargetID.ToUpper().Equals("DEBUG_LOG"))
{
requestLog.Update();
}
}
throw new Exception("An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "## GetEducationCustomerResponse");
}
finally
{
//always close connections and dispose of objects
XmlSerializer xsSubmit = new XmlSerializer(typeof(EducationCustomer));
//var subReq = new MyObject();
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, response);
requestLog.ResponseXml = sww.ToString();
requestLog.setResponseXML(response);
if (TargetID.ToUpper().Equals("DEBUG_LOG"))
{
requestLog.Update();
}
requestLog.disconnect();
}
return response;
}
//TranscationHandler.cs
public Accounts GetEducationCustomer(String AccountID, ref RequestLog requestLog)
{
try
{
if (!string.IsNullOrEmpty(AccountID))
{
Account = Accounts.getAccount(AccountID, sfConn);
if (string.IsNullOrEmpty(Account.slxID))
throw new Exception("Account does not exist.");
}
else
{
throw new Exception("Account ID not provided.");
}
if (requestLog.id > 0) // this means this is not a sceduled get education customer request
{
requestLog.Message = "Successfully retrieved customer data.";
requestLog.SuccessFlag = 1;
requestLog.Update();
}
}
catch (Exception ex)
{
requestLog.Message = "Error getting customer data. " + ex.Message;
requestLog.SuccessFlag = 0;
if (requestLog.id > 0) // this means this is not a sceduled get education customer request
{
requestLog.Update();
}
throw ex;
}
return Account;
}
//Account.cs
public static Accounts getAccount(string strSLxID, SFConnection sfConn)
{
DiscoveryEducation.MDM.SalesforceAdaptor.Salesforce_mdmDev.QueryResult queryResult;
DiscoveryEducation.MDM.SalesforceAdaptor.Salesforce_mdmDev.Account sfAccount;
Accounts myAccount = new Accounts (sfConn);
try
{
var strQuery = "SELECT Id, SLX_ID__c, PID__c, MDMROWID__c, "
+ "Name, Type, Status__c, Customer_Status_Reason__c, High_Grade__c, Low_Grade__c, Enrollment__c, "
+ "GradeLevelCategory__c, Language__c, "
+ "Phone, Fax, Website, Toll_Free_Phone__c, Email__c,"
+ "SLX_Parent_Account__c, Merged_SurviAccount__c, Split_Source_Account__c, "
+ "BillingStreet, BillingCity, BillingState, Billing_County__c, BillingPostalCode, BillingCountry,"
+ "ShippingStreet, ShippingCity, ShippingState, Shipping_County__c, ShippingPostalCode, ShippingCountry "
+ "From Account where SLX_ID__c ='"
+ strSLxID + "'";
queryResult = myAccount.sfConn.Query(strQuery);
var x = queryResult.size;
sfAccount = (DiscoveryEducation.MDM.SalesforceAdaptor.Salesforce_mdmDev.Account)queryResult.records[0];
myAccount.mapObject(sfAccount);
}
catch (Exception ex)
{
throw new Exception("No Record located for sales force ID or no connection established for " + strSLxID
+ " " + ex.Message);
}
return myAccount;
}
As you can see from the above code, When we try to execute in the SOAPUI and addd the SLXID we get the details of the Salesforce Account through the response.
In this example, we will insert values to the SOAPUI and it will be reflected in the Salesforce Database.
The following is the list of code.
//SLXCustomer.cs
public EducationCustomer InsertCustomer(string DSName, string TargetID, Account1 Account, List<Address> Addresses, ExtraFields ExtraFields)
{
if (string.IsNullOrEmpty(DSName))
{
DSName = "";
}
/*
int requestLogID = 0;
SqlCommand mdmCmd = SLXMDMConnect(); //get database connection object here.
requestLogID = RequestLog.insertRequestXMLIntoLog("Create customer", mdmCmd);
RequestLog requestLog = new RequestLog(requestLogID, DSName, "Create customer");
*/
RequestLog requestLog = new RequestLog("DEV");
// requestLog.AccountID = Account.SLXID;
EducationCustomer responseValues = new EducationCustomer();
responseValues.CustomerAccount = new Account();
responseValues.CustomerAddresses = new List<Address>();
/*
responseValues.PhysicalAddresses = new List<PhysicalAddress>();
responseValues.MailingAddresses = new List<MailingAddress>();
*/
if (Authentication != null)
{
username = Authentication.Username;
password = Authentication.Password;
}
else
{
requestLog.Message = "No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be created." + " ##RequestLogID - " + requestLog.id + "##";
requestLog.SuccessFlag = 0;
requestLog.Insert();
//Log.LogRequest("Create customer", "No credentials provided. Cannot authenticate user.", Account.CustomerName, "", username, mdmCmd);
throw new Exception("No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be created." + " ##RequestLogID - " + requestLog.id + "##");
}
try
{ /*
authenticated = ADAuthentication.IsAuthenticated(username, password, mdmCmd);
if (authenticated)
{ */
string AccountSurvivor = ExtraFields.ExtraField1;
transactionHandler = new TransactionHandler(currentEnvironment);
Accounts customer = null;
transactionHandler.InsertCustomer(Account, Addresses, ref requestLog, DSName);
customer = transactionHandler.Account;
/*
Customer.Username = username;
Customer customer = Customer.CreateCustomer(Account, Addresses, requestLogID, DSName);
*/
responseValues.CustomerAccount.MDMID = customer.mdmID;
responseValues.CustomerAccount.MDRPID = customer.mdrPID;
responseValues.CustomerAccount.SLXID = customer.slxID;
responseValues.CustomerAccount.CustomerName = customer.customerName;
responseValues.CustomerAccount.CustomerType = customer.customerType;
responseValues.CustomerAccount.CustomerStatus = customer.customerStatus;
responseValues.CustomerAccount.CustomerStatusReason = customer.customerStatusReason;
responseValues.CustomerAccount.EnrollmentCount = customer.enrollmentCount;
responseValues.CustomerAccount.LowGrade = customer.lowGrade;
responseValues.CustomerAccount.HighGrade = customer.highGrade;
responseValues.CustomerAccount.Email = customer.email;
responseValues.CustomerAccount.Fax = customer.fax;
responseValues.CustomerAccount.MainPhone = customer.mainPhone;
responseValues.CustomerAccount.TollFreePhone = customer.tollFreePhone;
responseValues.CustomerAccount.WebAddress = customer.webAddress;
responseValues.CustomerAccount.ParentSLXID = customer.parentSLXID;
//response.CustomerAccount.ParentMDMID = c.ParentMDMID;
responseValues.CustomerAccount.SECCODEID = customer.secCODEID;
responseValues.CustomerAccount.SLXPrimaryAddressID = customer.slxPrimaryAddressID;
responseValues.CustomerAccount.SLXShippingAddressID = customer.slxShippingAddressID;
responseValues.CustomerAccount.Language = customer.language;
responseValues.CustomerAccount.SchoolType = customer.schoolType;
responseValues.CustomerAccount.AlternativeProgram = customer.alternativeProgram;
responseValues.CustomerAccount.AdultEducationProgram = customer.adultEducationProgram;
responseValues.CustomerAccount.SpecialEducationProgram = customer.specialEducationProgram;
responseValues.CustomerAccount.CharterSchool = customer.charterSchool;
responseValues.CustomerAccount.CatholicSchool = customer.catholicSchool;
responseValues.CustomerAccount.CanadianBIASchool = customer.canadianBIASchool;
//response.RequestLogID = requestLog.id;
Address a = new Address();
a.AddressStatus = "Active";
a.AddressType = "Physical";
a.AddressLine1 = customer.physAddressLine1;
a.AddressLine2 = customer.physAddressLine2;
a.City = customer.physCity;
a.County = customer.physCounty;
a.State = customer.physState;
a.PostalCode = customer.physZip;
a.Country = customer.physCountry;
responseValues.CustomerAddresses.Add(a);
Address b = new Address();
b.AddressStatus = "Active";
b.AddressType = "Mailing";
b.AddressLine1 = customer.mailAddressLine1;
b.AddressLine2 = customer.mailAddressLine2;
b.City = customer.mailCity;
b.County = customer.mailCounty;
b.State = customer.mailState;
b.PostalCode = customer.mailZip;
b.Country = customer.mailCountry;
responseValues.CustomerAddresses.Add(b);
/*
responseValues.SLXID = customer.Account.AccountID;
responseValues.RequestLogID = requestLogID;
foreach (AccountAddress a in customer.Addresses)
{
if (a.AddressType.ToUpper().Equals("PHYSICAL"))
{
PhysicalAddress physAddr = new PhysicalAddress();
physAddr.AddressMDMID = a.AddressMDMID;
physAddr.AddressSLXID = a.AddressID;
responseValues.PhysicalAddresses.Add(physAddr);
}
else if (a.AddressType.ToUpper().Equals("MAILING"))
{
MailingAddress mailAddr = new MailingAddress();
mailAddr.AddressMDMID = a.AddressMDMID;
mailAddr.AddressSLXID = a.AddressID;
responseValues.MailingAddresses.Add(mailAddr);
}
}
*/
/*
}
else
{
throw new Exception("No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be created.");
} */
}
catch (Exception ex)
{
throw new Exception("Customer object cannot be created.");
/*
requestLog.Message = "An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "##";
requestLog.SuccessFlag = 0;
requestLog.Insert();
throw new Exception("An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "##");
*/
}
finally
{
//always close connections and dispose of objects
/* if ((mdmConn != null) && (mdmConn.State == ConnectionState.Open))
SLXMDMDisconnect();
if (mdmCmd != null)
mdmCmd.Dispose();*/
}
return responseValues;
}
//TranscationHandler.cs
public void InsertCustomer(Account1 sAccount, List<Address> sAddresses, ref RequestLog requestLog, string dsname)
{
// Accounts existingAcc = Accounts.getAccount(sAccount.SLXID, sfConn);
// existingAcc.parseCustomerType();
// Account sAccount;
// var tstSalesForceId = Accounts.GetSalesforceId(sAccount.SLXID, sfConn);
try
{
/*
// if (!string.IsNullOrEmpty(existingAcc.slxID))
if (!string.IsNullOrEmpty(sAccount.SLXID))
{
throw new Exception("Customer object cannot be created.");
}
else
{*/
Account = new Accounts(sfConn);
mapDataToCustomerAccount1(sAccount, sAddresses);
// Account.parseCustomerType();
// Account.buildCustomerType();
int sequencenumber = 5;
Account.slxID = String.Format("A6UJ" + "{0:d}",sequencenumber.ToString().PadLeft(7, '0'));
sequencenumber++;
//String.Format("A6UJ" + "{0:d}", (DateTime.Now.Ticks / 10) % 10000000);
//Path.GetRandomFileName();
//Account.slxID = Account.slxID.Replace(".", "");
// Account.slxID.Substring(0, 6);
// sAccount.SLXID = Path.GetRandomFileName();
// sAccount.SLXID = sAccount.SLXID.Replace(".", "");
//sAccount.SLXID.Substring(0, 6);
// Account.sfID = existingAcc.sfID;
sfConn.CreateAccounts(Account);
/*
mdmNote = new MDM_Note
{
accountID = sAccount.SLXID,
sfID = existingAcc.sfID,
accountName = sAccount.CustomerName,
description = "MDM Account Update",
userName = dsname
};
mdmNote.setNotes(generateLongNotes(existingAcc, Account));
sfConn.Create(mdmNote);
if (!string.IsNullOrEmpty(sAccount.DSNotes))
{
var requestMdmNote = new MDM_Note
{
accountID = sAccount.SLXID,
sfID = existingAcc.sfID,
accountName = sAccount.CustomerName,
description = "MDM Account DS Notes Update",
userName = dsname
};
requestMdmNote.setNotes(sAccount.DSNotes);
sfConn.Create(requestMdmNote);
}
requestLog.Message = "Successfully updated customer. " + longNotes;
requestLog.SuccessFlag = 1;
requestLog.Update();
*/
// }
}
catch (Exception ex)
{ /*
requestLog.Message = ex.Message;
requestLog.SuccessFlag = 0;
requestLog.Insert();
*/
throw new Exception(ex.Message);
}
}
//SFConnection.cs
public bool CreateAccounts(Accounts creacc)
{
SaveResult[] creResult;
Account createacc = new Account();
createacc.Id = creacc.sfID;
createacc.Name = creacc.customerName;
createacc.Phone = creacc.mainPhone;
createacc.Fax = creacc.fax;
createacc.Type = creacc.customerType;
createacc.Website = creacc.webAddress;
createacc.BillingStreet = creacc.mailAddressLine1;
createacc.BillingState = creacc.mailState;
createacc.BillingCity = creacc.mailCity;
createacc.BillingPostalCode = creacc.mailZip;
createacc.BillingCountry = creacc.mailCounty;
createacc.Billing_County__c = creacc.mailCounty;
createacc.ShippingStreet = creacc.physAddressLine1;
createacc.ShippingState = creacc.physState;
createacc.ShippingPostalCode = creacc.physZip;
createacc.ShippingCity = creacc.physCity;
createacc.ShippingCountry = creacc.physCountry;
createacc.Shipping_County__c = creacc.physCounty;
createacc.High_Grade__c = creacc.highGrade;
createacc.Low_Grade__c = creacc.lowGrade;
createacc.Enrollment__c = Convert.ToDouble(creacc.enrollmentCount);
createacc.SLX_ID__c = creacc.slxID;
createacc.Status__c = creacc.customerStatus;
createacc.Toll_Free_Phone__c = creacc.tollFreePhone;
createacc.Customer_Status_Reason__c = creacc.customerStatusReason;
try
{
sfService = new SforceService();
LoginResult res = sfService.login(username, password + securitytoken);
SessionHeader sh = new SessionHeader();
sh.sessionId = res.sessionId;
sfService.SessionHeaderValue = new SessionHeader();
sfService.SessionHeaderValue.sessionId = sh.sessionId;
sfService.Url = res.serverUrl;
//update account
creResult = sfService.create(new sObject[] { createacc });
if (!creResult[0].success)
{
throw new Exception("Error occured while Update to Salesforce: " + creResult[0].errors[0].message);
}
}
catch (Exception ex)
{
throw new Exception("Error occured while connecting to Salesforce: " + ex.Message);
}
return creResult[0].success;
}
In order to remove certain request from the SOAPUI, re format the Account Struct like this:
//Dictionary.cs
[Serializable]
public struct Account1
{
public string CustomerName;
/// <summary> The second customer name. </summary>
public string CustomerName2;
/// <summary> Type of the customer. </summary>
public string CustomerType;
/// <summary> The customer status. </summary>
public string CustomerStatus;
/// <summary> The customer status reason. </summary>
public string CustomerStatusReason;
/// <summary> Number of enrollments. </summary>
public string EnrollmentCount;
/// <summary> The low grade. </summary>
public string LowGrade;
/// <summary> The high grade. </summary>
public string HighGrade;
/// <summary> The district classification. </summary>
public string DistrictClassification;
/// <summary> Type of the school. </summary>
public string SchoolType;
/// <summary> The language. </summary>
public string Language;
/// <summary> The alternative program. </summary>
public string AlternativeProgram;
/// <summary> The magnet program. </summary>
public string MagnetProgram;
/// <summary> The adult education program. </summary>
public string AdultEducationProgram;
/// <summary> The special education program. </summary>
public string SpecialEducationProgram;
/// <summary> The charter school. </summary>
public string CharterSchool;
/// <summary> The catholic school. </summary>
public string CatholicSchool;
/// <summary> The canadian bia school. </summary>
public string CanadianBIASchool;
/// <summary> The virtual school. </summary>
public string VirtualSchool;
/// <summary> The special education services. </summary>
public string SpecialEducationServices;
/// <summary> The ds notes. </summary>
public string DSNotes;
/// <summary> Identifier for the slx primary address. </summary>
public string SLXPrimaryAddressID;
/// <summary> Identifier for the slx shipping address. </summary>
public string SLXShippingAddressID;
/// <summary> The email. </summary>
public string Email;
/// <summary> The fax. </summary>
public string Fax;
/// <summary> The main phone. </summary>
public string MainPhone;
/// <summary> The toll free phone. </summary>
public string TollFreePhone;
/// <summary> The web address. </summary>
public string WebAddress;
/// <summary> The parent mdmid. </summary>
public string ParentMDMID;
/// <summary> The parent slxid. </summary>
public string ParentSLXID;
/// <summary> The seccodeid. </summary>
public string SECCODEID;
/// <summary> Identifier for the state. </summary>
public string StateID;
/// <summary> Identifier for the assessment. </summary>
public string AssessmentID;
/// <summary> The first additional field. </summary>
public string AdditionalField1;
/// <summary> The second additional field. </summary>
public string AdditionalField2;
/// <summary> The third additional field. </summary>
public string AdditionalField3;
/// <summary> The fourth additional field. </summary>
public string AdditionalField4;
/// <summary> The fifth additional field. </summary>
public string AdditionalField5;
}
which had these values before
/// <summary> The mdmid. </summary>
public string MDMID;
/// <summary> The mdrpid. </summary>
public string MDRPID;
/// <summary> The slxid. </summary>
public string SLXID;
/// <summary> Name of the customer. </summary>
and with the help of this code.
When ever we push the request we get a new SLXID which is unique and having constant "A6UJ"
Account.slxID = String.Format("A6UJ" + "{0:d}",sequencenumber.ToString().PadLeft(7, '0'));
8. Upsert Data into the Salesforce Account
In order to upset the data in to the Salesforce Account, we would require the ID for the customer account for updating any changes. This is the SLXID.
Below is the code for it.
//SLXCustomer.ws
public CustomerResponse UpdateCustomer(string DSName, string TargetID, Account Account, List<Address> Addresses, ExtraFields ExtraFields)
{
if (string.IsNullOrEmpty(DSName))
{
DSName = "";
}
//RequestLog requestLog = new RequestLog(currentEnvironment);
requestLog.AccountID = Account.SLXID;
requestLog.Action = "Get Education Customer";
requestLog.RequestDate = createDate;
requestLog.setRequestXML();
requestLog.Username = DSName;
requestLog.Insert();
responseValues.SLXID = Account.SLXID;
responseValues.RequestLogID = requestLog.id;
responseValues.MailingAddresses = null;
responseValues.PhysicalAddresses = null;
if (Authentication != null)
{
username = Authentication.Username;
password = Authentication.Password;
}
else
{
requestLog.Message = "No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be updated." + " ##RequestLogID - " + requestLog.id + "##";
requestLog.SuccessFlag = 0;
requestLog.Update();
throw new Exception("No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be updated." + " ##RequestLogID - " + requestLog.id + "##");
}
try
{
if (ADAuthentication.IsAuthenticated(username, password))
{
// The ExtraField1 will have the SLx ID for the survivor for the account being updated
// if the updated account status is Inactive and reason code is Merged
string AccountSurvivor = ExtraFields.ExtraField1;
transactionHandler = new TransactionHandler(currentEnvironment);
requestLog.Action = "Update customer";
requestLog.Username = DSName;
requestLog.AccountID = Account.SLXID;
transactionHandler.UpdateCustomer(Account, Addresses, ref requestLog, DSName, AccountSurvivor, OperationType.Update);
// Accounts customer = transactionHandler.Account;
requestLog.SuccessFlag = 1;
requestLog.Message = "Successfully updated customer.";
XmlSerializer xsSubmit = new XmlSerializer(typeof(CustomerResponse));
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, responseValues);
requestLog.ResponseXml = sww.ToString();
requestLog.Update();
}
else
{
throw new Exception("Cannot authenticate user. Account '" + Account.CustomerName + "' could not be updated.");
}
}
catch (Exception ex)
{
requestLog.Message = "An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "##";
requestLog.SuccessFlag = 0;
requestLog.Update();
throw new Exception("An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "##");
}
finally
{
requestLog.setResponseXML(responseValues);
requestLog.Update();
requestLog.disconnect();
}
return responseValues;
}
//TranscationHandler.cs
public void UpdateCustomer( Account sAccount, List<Address> sAddresses, ref RequestLog requestLog, string dsname, string accountSurvivor, OperationType updateSource)
{
Accounts existingAcc = Accounts.getAccount(sAccount.SLXID, sfConn);
// existingAcc.parseCustomerType();
//Check if status changed
if (!existingAcc.customerStatus.Equals(sAccount.CustomerStatus))
{
if (sAccount.CustomerStatus.ToUpper().Equals("NA"))
{
sAccount.CustomerName = "##INACTIVE - CLOSED##" + sAccount.CustomerName;
}
else if (sAccount.CustomerStatus.Equals("Temporarily Active"))
{
// sAccount.CustomerName = "##INACTIVE - CLOSED##" + sAccount.CustomerName;
}
else if (sAccount.CustomerStatus.ToUpper().Equals("INACTIVE"))
{
//sAccount.CustomerName = sAccount.CustomerName.Replace("##INACTIVE - CLOSED##", "");
sAccount.CustomerName = "##INACTIVE - CLOSED##" + sAccount.CustomerName;
}
else if (sAccount.CustomerStatus.ToUpper().Equals("ACTIVE"))
{
sAccount.CustomerName = sAccount.CustomerName.Replace("##INACTIVE - CLOSED##", "") ;
}
else{
throw new Exception("Invalid customer status.");
}
}
var tstSalesForceId = Accounts.GetSalesforceId(sAccount.SLXID, sfConn);
try
{
if (!string.IsNullOrEmpty(existingAcc.slxID))
{
Account = new Accounts(sfConn);
mapDataToCustomerAccount(sAccount, sAddresses);
//Account.parseCustomerType();
//Account.buildCustomerType();
Account.sfID = existingAcc.sfID;
sfConn.Update(Account);
mdmNote = new MDM_Note
{
accountID = sAccount.SLXID,
sfID = existingAcc.sfID,
accountName = sAccount.CustomerName,
description = "MDM Account Update",
userName = dsname
};
//mdmNote.setNotes(generateLongNotes(existingAcc, Account));
mdmNote.setNotes(generateFieldUpdateText("updated", dsname));
sfConn.Create(mdmNote);
if (!string.IsNullOrEmpty(sAccount.DSNotes))
{
var requestMdmNote = new MDM_Note
{
accountID = sAccount.SLXID,
sfID = existingAcc.sfID,
accountName = sAccount.CustomerName,
description = "MDM Account DS Notes Update",
userName = dsname
};
requestMdmNote.setNotes(sAccount.DSNotes);
sfConn.Create(requestMdmNote);
}
requestLog.Message = "Successfully updated customer. " + longNotes;
requestLog.SuccessFlag = 1;
requestLog.Update();
}
else
{
throw new Exception("Customer object cannot be created for update. Account does not exist.");
}
}
catch (Exception ex)
{
requestLog.Message = ex.Message;
requestLog.SuccessFlag = 0;
requestLog.Update();
throw new Exception(ex.Message);
}
}
//SFConnection.cs
public bool Update(Accounts updAcct)
{
SaveResult[] result;
Account acc = new Account(); // Salesforce account
acc.Id = updAcct.sfID;
acc.Name = updAcct.customerName;
acc.Phone = updAcct.mainPhone;
acc.Fax = updAcct.fax;
acc.Type = updAcct.customerType;
acc.Website = updAcct.webAddress;
acc.BillingStreet = updAcct.mailAddressLine1;
acc.BillingState = updAcct.mailState;
acc.BillingCity = updAcct.mailCity;
acc.BillingPostalCode = updAcct.mailZip;
acc.BillingCountry = updAcct.mailCountry;
acc.Billing_County__c = updAcct.mailCounty;
acc.ShippingStreet = updAcct.physAddressLine1;
acc.ShippingState = updAcct.physState;
acc.ShippingPostalCode = updAcct.physZip;
acc.ShippingCity = updAcct.physCity;
acc.ShippingCountry = updAcct.physCountry;
acc.Shipping_County__c = updAcct.physCounty;
acc.High_Grade__c = updAcct.highGrade;
acc.Low_Grade__c = updAcct.lowGrade;
acc.Enrollment__c = Convert.ToDouble(updAcct.enrollmentCount);
acc.SLX_ID__c = updAcct.slxID;
acc.Status__c = updAcct.customerStatus;
acc.Toll_Free_Phone__c = updAcct.tollFreePhone;
acc.Customer_Status_Reason__c = updAcct.customerStatusReason;
acc.Enrollment__cSpecified = true;
acc.Language__c = updAcct.language;
acc.Email__c = updAcct.email;
acc.MDMROWID__c = updAcct.mdmID;
acc.GradeLevelCategory__c = updAcct.schoolType;
try
{
//update account
result = sfService.update(new sObject[] { acc });
if (!result[0].success)
{
throw new Exception("Error occured while Update to Salesforce: " + result[0].errors[0].message);
}
}
catch (Exception ex)
{
throw new Exception("Error occured while connecting to Salesforce: " + ex.Message);
}
return result[0].success;
}
With the help of the SOAPUI. We can see the updated result.
In order to upset the data in to the Salesforce Account, we would require the ID for the customer account for updating any changes. This is the SLXID.
Below is the code for it.
//SLXCustomer.ws
public CustomerResponse UpdateCustomer(string DSName, string TargetID, Account Account, List<Address> Addresses, ExtraFields ExtraFields)
{
if (string.IsNullOrEmpty(DSName))
{
DSName = "";
}
//RequestLog requestLog = new RequestLog(currentEnvironment);
requestLog.AccountID = Account.SLXID;
requestLog.Action = "Get Education Customer";
requestLog.RequestDate = createDate;
requestLog.setRequestXML();
requestLog.Username = DSName;
requestLog.Insert();
responseValues.SLXID = Account.SLXID;
responseValues.RequestLogID = requestLog.id;
responseValues.MailingAddresses = null;
responseValues.PhysicalAddresses = null;
if (Authentication != null)
{
username = Authentication.Username;
password = Authentication.Password;
}
else
{
requestLog.Message = "No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be updated." + " ##RequestLogID - " + requestLog.id + "##";
requestLog.SuccessFlag = 0;
requestLog.Update();
throw new Exception("No credentials provided. Cannot authenticate user. Account '" + Account.CustomerName + "' could not be updated." + " ##RequestLogID - " + requestLog.id + "##");
}
try
{
if (ADAuthentication.IsAuthenticated(username, password))
{
// The ExtraField1 will have the SLx ID for the survivor for the account being updated
// if the updated account status is Inactive and reason code is Merged
string AccountSurvivor = ExtraFields.ExtraField1;
transactionHandler = new TransactionHandler(currentEnvironment);
requestLog.Action = "Update customer";
requestLog.Username = DSName;
requestLog.AccountID = Account.SLXID;
transactionHandler.UpdateCustomer(Account, Addresses, ref requestLog, DSName, AccountSurvivor, OperationType.Update);
// Accounts customer = transactionHandler.Account;
requestLog.SuccessFlag = 1;
requestLog.Message = "Successfully updated customer.";
XmlSerializer xsSubmit = new XmlSerializer(typeof(CustomerResponse));
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, responseValues);
requestLog.ResponseXml = sww.ToString();
requestLog.Update();
}
else
{
throw new Exception("Cannot authenticate user. Account '" + Account.CustomerName + "' could not be updated.");
}
}
catch (Exception ex)
{
requestLog.Message = "An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "##";
requestLog.SuccessFlag = 0;
requestLog.Update();
throw new Exception("An error occurred. " + ex.Message + " ##RequestLogID - " + requestLog.id + "##");
}
finally
{
requestLog.setResponseXML(responseValues);
requestLog.Update();
requestLog.disconnect();
}
return responseValues;
}
//TranscationHandler.cs
public void UpdateCustomer( Account sAccount, List<Address> sAddresses, ref RequestLog requestLog, string dsname, string accountSurvivor, OperationType updateSource)
{
Accounts existingAcc = Accounts.getAccount(sAccount.SLXID, sfConn);
// existingAcc.parseCustomerType();
//Check if status changed
if (!existingAcc.customerStatus.Equals(sAccount.CustomerStatus))
{
if (sAccount.CustomerStatus.ToUpper().Equals("NA"))
{
sAccount.CustomerName = "##INACTIVE - CLOSED##" + sAccount.CustomerName;
}
else if (sAccount.CustomerStatus.Equals("Temporarily Active"))
{
// sAccount.CustomerName = "##INACTIVE - CLOSED##" + sAccount.CustomerName;
}
else if (sAccount.CustomerStatus.ToUpper().Equals("INACTIVE"))
{
//sAccount.CustomerName = sAccount.CustomerName.Replace("##INACTIVE - CLOSED##", "");
sAccount.CustomerName = "##INACTIVE - CLOSED##" + sAccount.CustomerName;
}
else if (sAccount.CustomerStatus.ToUpper().Equals("ACTIVE"))
{
sAccount.CustomerName = sAccount.CustomerName.Replace("##INACTIVE - CLOSED##", "") ;
}
else{
throw new Exception("Invalid customer status.");
}
}
var tstSalesForceId = Accounts.GetSalesforceId(sAccount.SLXID, sfConn);
try
{
if (!string.IsNullOrEmpty(existingAcc.slxID))
{
Account = new Accounts(sfConn);
mapDataToCustomerAccount(sAccount, sAddresses);
//Account.parseCustomerType();
//Account.buildCustomerType();
Account.sfID = existingAcc.sfID;
sfConn.Update(Account);
mdmNote = new MDM_Note
{
accountID = sAccount.SLXID,
sfID = existingAcc.sfID,
accountName = sAccount.CustomerName,
description = "MDM Account Update",
userName = dsname
};
//mdmNote.setNotes(generateLongNotes(existingAcc, Account));
mdmNote.setNotes(generateFieldUpdateText("updated", dsname));
sfConn.Create(mdmNote);
if (!string.IsNullOrEmpty(sAccount.DSNotes))
{
var requestMdmNote = new MDM_Note
{
accountID = sAccount.SLXID,
sfID = existingAcc.sfID,
accountName = sAccount.CustomerName,
description = "MDM Account DS Notes Update",
userName = dsname
};
requestMdmNote.setNotes(sAccount.DSNotes);
sfConn.Create(requestMdmNote);
}
requestLog.Message = "Successfully updated customer. " + longNotes;
requestLog.SuccessFlag = 1;
requestLog.Update();
}
else
{
throw new Exception("Customer object cannot be created for update. Account does not exist.");
}
}
catch (Exception ex)
{
requestLog.Message = ex.Message;
requestLog.SuccessFlag = 0;
requestLog.Update();
throw new Exception(ex.Message);
}
}
//SFConnection.cs
public bool Update(Accounts updAcct)
{
SaveResult[] result;
Account acc = new Account(); // Salesforce account
acc.Id = updAcct.sfID;
acc.Name = updAcct.customerName;
acc.Phone = updAcct.mainPhone;
acc.Fax = updAcct.fax;
acc.Type = updAcct.customerType;
acc.Website = updAcct.webAddress;
acc.BillingStreet = updAcct.mailAddressLine1;
acc.BillingState = updAcct.mailState;
acc.BillingCity = updAcct.mailCity;
acc.BillingPostalCode = updAcct.mailZip;
acc.BillingCountry = updAcct.mailCountry;
acc.Billing_County__c = updAcct.mailCounty;
acc.ShippingStreet = updAcct.physAddressLine1;
acc.ShippingState = updAcct.physState;
acc.ShippingPostalCode = updAcct.physZip;
acc.ShippingCity = updAcct.physCity;
acc.ShippingCountry = updAcct.physCountry;
acc.Shipping_County__c = updAcct.physCounty;
acc.High_Grade__c = updAcct.highGrade;
acc.Low_Grade__c = updAcct.lowGrade;
acc.Enrollment__c = Convert.ToDouble(updAcct.enrollmentCount);
acc.SLX_ID__c = updAcct.slxID;
acc.Status__c = updAcct.customerStatus;
acc.Toll_Free_Phone__c = updAcct.tollFreePhone;
acc.Customer_Status_Reason__c = updAcct.customerStatusReason;
acc.Enrollment__cSpecified = true;
acc.Language__c = updAcct.language;
acc.Email__c = updAcct.email;
acc.MDMROWID__c = updAcct.mdmID;
acc.GradeLevelCategory__c = updAcct.schoolType;
try
{
//update account
result = sfService.update(new sObject[] { acc });
if (!result[0].success)
{
throw new Exception("Error occured while Update to Salesforce: " + result[0].errors[0].message);
}
}
catch (Exception ex)
{
throw new Exception("Error occured while connecting to Salesforce: " + ex.Message);
}
return result[0].success;
}
With the help of the SOAPUI. We can see the updated result.
No comments:
Post a Comment