Showing posts with label SalesForce. Show all posts
Showing posts with label SalesForce. Show all posts

Tuesday, 21 May 2013

SalesForce - Tips

Sales force


 Errors I have encountered while trying to connect without much reading

   LOGIN_MUST_USE_SECURITY_TOKEN: Invalid username, password, security token; or user locked out. Are you at a new location? When accessing Salesforce--either via a desktop client or the API--from outside of your company’s trusted networks, you must add a security token to your password to log in.To receive a new security token, log in to salesforce.com at http://login.salesforce.com and click Setup | My Personal Information | Reset Security Token.
       
  Resolution
      Update password field of your log in with merged password and security token
      var response = sforce.login(LoginUserName, LoginUserPassword + LoginSecurityToken);
       

       


Creating custom fields

 I have used designer to generate custom fields in my object and generated WSDL but my custom field is not present in generated XML.

Solution:

 Go to: Account => Setup =>App Setup=>Objects

Open object you want to edit. Click on field you want to make visible.

 Click on highlighted "Set Field-Level Security"
 

Set appropriate visibility read only levels.











Used references:

reference book
Creating custom fields

Wednesday, 10 April 2013

SalesForce Generation of APEX code


Creating an Apex Class from a WSDL

Available in: Unlimited, Developer, Enterprise, and Database.com Editions

User Permissions Needed
To define, edit, delete, set security, set version settings, show dependencies, and run tests for Apex classes:“Author Apex
An Apex class can be automatically generated from a WSDL document that is stored on a local hard drive or network. Creating a class by consuming a WSDL document allows developers to make callouts to the external Web service in their Apex.
Note
Use Outbound Messaging to handle integration solutions when possible. Use callouts to third-party Web services only when necessary.
To access this functionality:
  1. In the application, click Your Name | Setup | Develop | Apex Classes.
  2. Click Generate from WSDL.
  3. Click Browse to navigate to a WSDL document on your local hard drive or network, or type in the full path. This WSDL document is the basis for the Apex class you are creating.
    Note
    The WSDL document that you specify might contain a SOAP endpoint location that references an outbound port.
    For security reasons, Salesforce restricts the outbound ports you may specify to one of the following:
    • 80: This port only accepts HTTP connections.
    • 443: This port only accepts HTTPS connections.
    • 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.
  4. Click Parse WSDL to verify the WSDL document contents. The application generates a default class name for each namespace in the WSDL document and reports any errors. Parsing will fail if the WSDL contains schema types or schema constructs that are not supported by Apex classes, or if the resulting classes exceed 1 million character limit on Apex classes. For example, the Salesforce SOAP API WSDL cannot be parsed.
  5. Modify the class names as desired. While you can save more than one WSDL namespace into a single class by using the same class name for each namespace, Apex classes can be no more than 1 million characters total.
  6. Click Generate Apex. The final page of the wizard shows which classes were successfully generated, along with any errors from other classes. The page also provides a link to view successfully generated code.
The successfully-generated Apex class includes stub and type classes for calling the third-party Web service represented by the WSDL document. These classes allow you to call the external Web service from Apex. For an example, see the Force.com Apex Code Developer's Guide.
Note the following about the generated Apex:
  • If a WSDL document contains an Apex reserved word, the word is appended with _x when the Apex class is generated. For example, limit in a WSDL document converts to limit_x in the generated Apex class. For a list of reserved words, see the Force.com Apex Code Developer's Guide.
  • If an operation in the WSDL has an output message with more than one element, the generated Apex wraps the elements in an inner class. The Apex method that represents the WSDL operation returns the inner class instead of the individual elements.

Monday, 8 April 2013

SOQL queries salesforce.com

SOQL & SalesForce.com




Get all records for id:

List<id> listaToTrue=newList<id>();
for(Account a : [select id from Account where ParentId in:addAccountsActivate]){
    listaParaActivar.add(a.id);
}
 
 
    private SforceService binding;

        public SalesForceTest()
        {
            ProcessConnection();

        }

        public bool ProcessConnection()
        {
            Boolean success = false;
            // Create a service object
            binding = new SforceService();
            LoginResult lr;
            try
            {
                Console.WriteLine("\nLogging in...\n");
                lr = binding.login(LoginUserName, LoginUserPassword + LoginSecurityToken);
                /**
                * The login results contain the endpoint of the virtual server instance
                * that is servicing your organization. Set the URL of the binding
                * to this endpoint.
                */
                // Save old authentication end point URL
                String authEndPoint = binding.Url;
                // Set returned service endpoint URL
                binding.Url = lr.serverUrl;
                /** Get the session ID from the login result and set it for the
                * session header that will be used for all subsequent calls.
                */
                binding.SessionHeaderValue = new SessionHeader();
                binding.SessionHeaderValue.sessionId = lr.sessionId;
                // Print user and session info
                GetUserInfoResult userInfo = lr.userInfo;
                Console.WriteLine("UserID: " + userInfo.userId);
                Console.WriteLine("User Full Name: " +
                                  userInfo.userFullName);
                Console.WriteLine("User Email: " +
                                  userInfo.userEmail);
                Console.WriteLine();
                Console.WriteLine("SessionID: " +
                                  lr.sessionId);
                Console.WriteLine("Auth End Point: " +
                                  authEndPoint);
                Console.WriteLine("Service End Point: " +
                                  lr.serverUrl);
                Console.WriteLine();
                // Return true to indicate that we are logged in, pointed
                // at the right URL and have our security token in place.
                success = true;
            }
            catch (SoapException e)
            {
                Console.WriteLine("An unexpected error has occurred: " +
                                  e.Message + "\n" + e.StackTrace);
            }
            return success;
        }

        public void CloseConnection()
        {
            binding.invalidateSessions(new[] {binding.SessionHeaderValue.sessionId});
            Console.WriteLine("Closed connection");
        }


        public void GetQuery()
        {
            QueryResult qResult = null;

            String soqlQuery = "SELECT ID, FirstName, LastName FROM Contact";
            qResult = binding.query(soqlQuery);
            Boolean done = false;
            if (qResult.size > 0)
            {
                Console.WriteLine("Logged-in user can see a total of "
                                  + qResult.size + " contact records.");
                while (!done)
                {
                    sObject[] records = qResult.records;
                    for (int i = 0; i < records.Length; ++i)
                    {
                        Contact con = (Contact) records[i];
                        String fName = con.FirstName;
                        String lName = con.LastName;
            
                        Console.WriteLine("Contact " + (i + 1) + ": ID:" + con.Id +" "+fName +" " + lName);
                        
                    }
                    if (qResult.done)
                    {
                        done = true;
                    }
                    else
                    {
                        qResult = binding.queryMore(qResult.queryLocator);
                    }
                }
            }
            else
            {
                Console.WriteLine("No records found.");
            }
            Console.WriteLine("\nQuery succesfully executed.");
            
        }

        public List<string> CustomSelect()
        {
            var list= new List<string>();
            QueryResult qResult = null;

            String soqlQuery = "SELECT ID,firstName__c,LastName__c FROM ContactPerson__c";
            qResult = binding.query(soqlQuery);
            Boolean done = false;
            if (qResult.size > 0)
            {
                Console.WriteLine("Logged-in user can see a total of "
                                  + qResult.size + " contact records.");
                while (!done)
                {
                    sObject[] records = qResult.records;
                    for (int i = 0; i < records.Length; ++i)
                    {
                        var con = (ContactPerson__c) records[i];
                        String fName = con.FirstName__c;
                        String lName = con.LastName__c;
                        list.Add(con.Id);
                        Console.WriteLine("Contact " + (i + 1) + ": ID:" + con.Id +" "+fName +" " + lName);
                        
                    }
                    if (qResult.done)
                    {
                        done = true;
                    }
                    else
                    {
                        qResult = binding.queryMore(qResult.queryLocator);
                    }
                }
            }
            else
            {
                Console.WriteLine("No records found.");
            }
            Console.WriteLine("\nQuery succesfully executed.");
            return list;
        }

        public void Insert()
        {
            var contactPerson = new ContactPerson__c();
            contactPerson.FirstName__c = string.Format("{0}{1}", "testFirstName", DateTime.Now.ToShortTimeString());
            contactPerson.LastName__c = string.Format("{0}{1}", "testLastName", DateTime.Now.ToShortTimeString());
            contactPerson.Email__c = string.Format("{0}{1}", DateTime.Now.ToString("ddMMhhmm"), "@gmail.com");
            contactPerson.LandLine__c = string.Format("{0}{1}", "01225", DateTime.Now.ToShortTimeString());
            contactPerson.CreatedDate = DateTime.Now;

            var saveResult = binding.create(new[] {contactPerson});
            if (saveResult.Length == 0)
            {
                Console.WriteLine("Failed to save");
            }
            foreach (var result in saveResult)
            {
                Console.WriteLine("id:{0} success:{1} errors:{2}", result.id, result.success,
                                  (result.errors != null) ? result.errors.Length : 0);
                if (result.errors != null)
                    foreach (var error in result.errors)
                    {
                        Console.WriteLine("Error: {0} Field: {1}", error.message, error.fields);
                    }
            }
        }

        public bool UpdateRecord(string recordId)
        {
            try
            {
                sObject[] sObjects = binding.retrieve("ID, FirstName__c,LastName__c,Email__c,LandLine__c", "ContactPerson__c",new[] { recordId });
                // Verify that some objects were returned.
                // Even though we began with valid object IDs,
                // someone else might have deleted them in the meantime.

                // Cast the SObject into an ContactPerson__c object
                ContactPerson__c contactPerson = (ContactPerson__c)sObjects.First();
                if (contactPerson != null)
                {
                    Console.WriteLine("contact person found");

                    ContactPerson__c con = (ContactPerson__c) contactPerson;
                    con.FirstName__c = DateTime.Today.ToShortDateString();

                    var saveResult = binding.update(new[] { con });
                    if (saveResult.Length == 0)
                    {
                        Console.WriteLine("Failed to save");
                    }
                    foreach (var result in saveResult)
                    {
                        Console.WriteLine("id:{0} success:{1} errors:{2}", result.id, result.success,
                                          (result.errors != null) ? result.errors.Length : 0);
                        if (result.errors != null)
                            foreach (var error in result.errors)
                            {
                                Console.WriteLine("Error: {0} Field: {1}", error.message, error.fields);
                            }
                    }
                }
                else
                {
                    Console.WriteLine("Nof Found contact person");
                }
            }
            catch (SoapException e)
            {
                Console.WriteLine("An unexpected error has occurred: " +
                                  e.Message + "\n" + e.StackTrace);
            }
            return false;
        }


        /// <summary>
        /// Deletes the record.
        /// </summary>
        /// <param name="recordId">The record id.</param>
        public void DeleteRecord(string recordId)
        {
            try
            {
                DeleteResult[] deleteResults = binding.delete(new[] { recordId });
                for (int i = 0; i < deleteResults.Length; i++)
                {
                    DeleteResult deleteResult = deleteResults[i];
                    if (deleteResult.success)
                    {
                        Console.WriteLine("Deleted Record ID: " + deleteResult.id);
                    }
                    else
                    {
                        // Handle the errors.
                        // We just print the first error out for sample purposes.
                        Error[] errors = deleteResult.errors;
                        if (errors.Length > 0)
                        {
                            Console.WriteLine("Error: could not delete " + "Record ID "
                                  + deleteResult.id + ".");
                            Console.WriteLine("   The error reported was: ("
                                  + errors[0].statusCode + ") "
                                  + errors[0].message + "\n");
                        }
                    }
                }
            }
            catch (SoapException e)
            {
                Console.WriteLine("An unexpected error has occurred: " +
                                        e.Message + "\n" + e.StackTrace);
            }
        }