Tag Archives: .Net

Connecting .NET Console Application to Salesforce via Enterprise WSDL

This was something I had done while doing POC around 2 years back. At that I had whole team to work with. Since I don’t have much idea about .NET, so I was contributing on Salesforce end and other guys proficient in .NET were mainly working. But we didn’t take much time to connect to Salesforce and make the connection working properly.

Few days back, I decided to do that myself. Because of my inadequate knowledge of .NET, it took me full  two days  to make it working. In this blogpost, I’m giving all steps(with code) to make the connection up and running. We’ll use Enterprise WSDL tO make describeGlobal call and return all objects present in SFDC

Step 1 : Install ‘VS Express 2013 for web. VS is Visual Studio. It is available for free  on the internet.

Step 2:  Once installed, Click File Menu to create New Project as shown below:

New Project in .NET Application

Create New Project in .NET Application

Step 3 :  In New Project window,  Select ‘Windows’ Application under Visual C# Option’.  Give Name to application something like ‘ConnectToSFDC or ConsoleSFDC etc ‘. see Screenshot below

Select Windows Application under Visual C# option

Select Windows Application under Visual C# option

Step 4:   After you click ‘OK’. Visual studio will create New Project with name you’ve provided.  There are multiple Frames in the project.  Right Side frame  is called Solution Explorer. Right click the name of the project and give ‘Output Type’ as ‘Console application’. Close the tab having same name as Project name. Step 5:  Your main project window will look like this :

Project Main Window

Project Main Window

Step 6:  Now we’ll have to add Enterprise WSDL so that we can Query, Create/Update records in SFDC For this login into SFDC,  Go to Setup | Develop | API . Download Enterprise WSDL.

Step 7: We now have to add WSDL in .NET Application  Right click name of the  Project and click  Add | Service Reference | Advanced..(option at bottom of the new popup)  |  Add Web reference. if you’ve correctly added the WSDL, then two things happen : 1. Window will show ‘SforceService’ Description window showing methods available in webservice to work with .For e.g  onvertLead, Create, delete etc. 2. Right side of web reference window will say ‘ Web services found at this URL’ with name of WSDL file. Showing this in below screen shot.  It will also give option to change the name of Webreference. Change it to sfdcConnect .Click Ok  in all the windows which have been opened and return back to Project Window

Step 8:  In the Code window, add name space

using System.Web.Services.Protocols;

Step 9: Now under Class1. which is default crated by .NET. Add following code . showing screen shot also

Main Code Window

Main Code Window

 
private connectToSFDC.SfdcConnect.SforceService binding;
    
    
    [STAThread]
        static void Main(string[] args)
        {
            Class1 sample = new Class1();
            sample.run();
        }

        public void run()
        {
            // Make a login call

            if (login())
            {
                // Do a describe global
                describeGlobalSample();
                // Describe an account object
                // describeSObjectsSample();
                // Retrieve some data using a query
                //querySample();
                // Log out
                //logout();
            }
        }
        private bool login()
        {
            Console.Write("Enter username: ");
            string username = Console.ReadLine();
            Console.Write("Enter password: ");
            string password = Console.ReadLine();
            // Create a service object
            binding = new connectToSFDC.SfdcConnect.SforceService();
            // Timeout after a minute
            binding.Timeout = 60000;
            // Try logging in
            connectToSFDC.SfdcConnect.LoginResult lr;
            try
            {
                Console.WriteLine("\nLogging in...\n");
                lr = binding.login(username, password);
            }
            // ApiFault is a proxy stub generated from the WSDL contract when
            // the web service was imported
            catch (SoapException e)
            {
                // Write the fault code to the console
                Console.WriteLine(e.Code);
                // Write the fault message to the console
                Console.WriteLine("An unexpected error has occurred: " + e.Message);



                // Write the stack trace to the console
                Console.WriteLine(e.StackTrace);
                // Return False to indicate that the login was not successful
                return false;
            }
            // Save old authentication end point URL
            String authEndPoint = binding.Url;
            // Set returned service endpoint URL
            binding.Url = lr.serverUrl;

         binding.SessionHeaderValue = new connectToSFDC.SfdcConnect.SessionHeader();
         binding.SessionHeaderValue.sessionId = lr.sessionId;
         printUserInfo(lr, authEndPoint);
            // Return true to indicate that we are logged in, pointed
            // at the right URL and have our security token in place.
            return true;

        }
private void printUserInfo(connectToSFDC.SfdcConnect.LoginResult lr, String authEP)
        {
            try
            {
                connectToSFDC.SfdcConnect.GetUserInfoResult userInfo = lr.userInfo;
                Console.WriteLine("\nLogging in ...\n");
                Console.WriteLine("UserID: " + userInfo.userId);

                Console.WriteLine();
                Console.WriteLine("SessionID: " + lr.sessionId);
                Console.WriteLine("Auth End Point: " + authEP);
                Console.WriteLine("Service End Point: " + lr.serverUrl);
                Console.WriteLine();
                Console.ReadLine();

            }

            catch (SoapException e)
            {
              Console.WriteLine("An unexpected error has occurred: " + e.Message +
              " Stack trace: " + e.StackTrace);
            }

        }

        private void describeGlobalSample()
        {
            try
            {

                SfdcConnect.DescribeGlobalResult dgr = binding.describeGlobal();
                Console.WriteLine("\nDescribe Global Results:\n");
                // Loop through the array echoing the object names to the console
                for (int i = 0; i < dgr.sobjects.Length; i++)
                {
                    Console.WriteLine(dgr.sobjects[i].name);
                }
            }
            catch (SoapException e)
            {
                Console.WriteLine("An exception has occurred: " + e.Message +
                "\nStack trace: " + e.StackTrace);
            }

            Console.ReadLine();
        }

Important :  Make sure that Visual Studio Editor shouldn’t be showing errors in the form of red line under code expressions.One of the main source of error is, if WSDL is not properly added as web reference. In case you face any problem. try deleting and adding web reference again. Try to check name of reference added and name used in your class code.

Step 10: As a next step, click on debug tab on top bar of VS editor and click ‘Start Debugging’. This will build the application and open and new window asking you to enter username and password, meant to connect to Salesforce.

once done it will provide list of all objects, which shows connection is working properly.