• URVASHI
  • NEWBIE
  • 50 Points
  • Member since 2013

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 36
    Questions
  • 64
    Replies

Hi

I am new to Salesforce

I have a bulk api code in C# which reads data from sql server database and imports it to Salesforce.This code works fine in the Visual Studio 2008.

But my requirement is to call the code from Salesforce,so i am using Soap Api for it.

I have created a webservice in C# and in a function named getbulkdata() i have pasted my bulk api code there.

Now this code works fine in the Webservice test client i.e. it imports data from sql server to salesforce.

But now when i m calling the same code from Salesforce it gives me the following error:

 

System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: Unable to connect to the remote server faultcode=a:InternalServiceFault faultactor=

Error is in expression '{!getSaveToObjectPage}'

 

 

 

 

The wsdl2Apex class getbulkdata() method is as below:

 

 public String Getbulkdata(String tablename,String databasename,String Objectname) {
            sqlServerConnector23.Getbulkdata_element request_x = new sqlServerConnector23.Getbulkdata_element();
            sqlServerConnector23.GetbulkdataResponse_element response_x;
            request_x.tablename = tablename;
            request_x.databasename = databasename;
            request_x.Objectname = Objectname;
            Map<String, sqlServerConnector23.GetbulkdataResponse_element> response_map_x = new Map<String, sqlServerConnector23.GetbulkdataResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'http://tempuri.org/IService1/Getbulkdata',
              'http://tempuri.org/',
              'Getbulkdata',
              'http://tempuri.org/',
              'GetbulkdataResponse',
              'sqlServerConnector23.GetbulkdataResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.GetbulkdataResult;
        }

 

The method is called from salesforce in the following way:

 

 public PageReference getSaveToObjectPage() {
     sqlArray23.ArrayOfstring a = new sqlArray23.ArrayOfstring();
     sqlServerConnector23.BasicHttpBinding_IService1 stub = new sqlServerConnector23.BasicHttpBinding_IService1();
     String operation='insert';
     stub.timeout_x = 120000; 
     
       
    String Message= stub.Getbulkdata(tablename,databasename,obj name);
   
           PageReference newpage = new PageReference('/apex/SqlServer2005Login_Import6');
            newpage.setRedirect(false); 
              return newpage;  
     
     }

 

 Can some one please tell me y am i getting the Soap Fault unable to connect to remote server.

As the same code is working fine in webservice (WCF) Test Client.

 

 

Thanks in advance.

Please let me know if you require anythg more like the bulk api code or something else.

 

 

 

 

 

 

 

 

 

 

Below is the code in C# for Bulk Api.


 

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualBasic;
    using System.Collections;
    using System.Data;
    using System.Diagnostics;
    using System.Xml;
    using System.IO;
    using System.Net;
    
    
    namespace ConsoleApplication7
    {
        class Program
        {
    
           
            private static SForceService.SforceService bindingService { get; set; }
    
    
            private static void QueryUsingBulkAPI()
            {
                string jobId = string.Empty;
                string resultId = string.Empty;
                string batchId = string.Empty;
                //new code
                Console.Write("Enter user name: ");
                string userName = Console.ReadLine();
    
    
                Console.Write("Enter password: ");
                string password = Console.ReadLine();
    
    
    
                ////Provide feed back while we create the web service binding    
                Console.WriteLine("Creating the binding to the web service...");
    
                // Create the binding to the sforce servics
                bindingService = new SForceService.SforceService();
    
                // Set the time out value
                bindingService.Timeout = 60000;
    
                ////Attempt the login giving the user feedback
                Console.WriteLine("LOGGING IN NOW....");
    
    
    
                try
                {
                    SForceService.LoginResult loginRes = bindingService.login(userName, password);
                    Console.WriteLine(loginRes);
                    Console.WriteLine( "The session id is: " + loginRes.sessionId);
                    Console.WriteLine("The new server url is: " + loginRes.serverUrl);
    
                    //Change the binding to the new endpoint
                    bindingService.Url = loginRes.serverUrl;
    
                    //Create a new session header object and set the session id to that returned by the login
                    bindingService.SessionHeaderValue = new SForceService.SessionHeader();
                    bindingService.SessionHeaderValue.sessionId = loginRes.sessionId;
                    Debug.WriteLine(loginRes.sessionId);
                   
                    CreateJob(loginRes.sessionId, "query", "Case", ref jobId);
                    //e.g for inserting contact
                    //Dim jobId As String = CreateJob(loginRes.sessionId, "insert", "Contact")
    
                    byte[] inputFileData = null;
    
                    if ((jobId.Length > 0))
                    {
                        //data loading using a sampe file
                        // Open a file that is to be loaded into a byte array
                        System.IO.FileInfo oFile = null;
                        //oFile = New System.IO.FileInfo("data.csv")
                        oFile = new System.IO.FileInfo("request.txt");
    
                        System.IO.FileStream oFileStream = oFile.OpenRead();
                        long lBytes = oFileStream.Length;
                        int a = (int)lBytes; //modified after conversion
                        if ((lBytes > 0))
                        {
                            byte[] fileData = new byte[lBytes];
                            // Read the file into a byte array
                            oFileStream.Read(fileData, 0, a);   //modified after conversion
                            oFileStream.Close();
    
                            //Get the file where the Query is present
                            inputFileData = fileData;
                        }
    
                        //Adds the batch to SalesForce
                        AddBatch(loginRes.sessionId, inputFileData, jobId, batchId, resultId);
    
                        //Check Status and Get BatchId and ResultsId
                        GetStatusAndRetrieveBatchIdAndResultsId(loginRes.sessionId, jobId, ref batchId, ref resultId);
    
                        //Get Results Id
                        RetrieveResults(loginRes.sessionId, jobId, batchId, resultId);
                    }
                }
                catch (System.Web.Services.Protocols.SoapException e)
                {
                    //// This is likley to be caused by bad username or password
                    Console.Write(e.Message + ", please try again." + "Hit return to continue...");
                    Console.ReadLine();
    
                }
                catch (Exception ex)
                {
                    //// This is something else, probably comminication
                    Console.Write(ex.Message + ", please try again." +   "Hit return to continue...");
                    Console.ReadLine();
    
                }
    
    
    
                //new code end
                //Used to create the Job in SalesForce--
                //the Job can be query, insert, delete etc...This is the operation parameter
                //eg for querying Case
    
    
    
    
    
            }
    
            /// <summary>
            /// Creates a job in Salesforce
            /// </summary>
            /// <param name="sfSessionId"></param>
            /// <param name="sfOperation"></param>
            /// <param name="sfObjectName"></param>
            /// <param name="jobId"></param>
            /// <remarks></remarks>
    
            public static void CreateJob(string sfSessionId, string sfOperation, string sfObjectName, ref string jobId)
            {
                string str = "";
                string reqURL = "";
                byte[] bytes = null;
                XmlDocument reqDoc = null;
                XmlDocument responseXmlDocument = new XmlDocument();
    
                str = "" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<jobInfo xmlns=\"http://www.force.com/2009/06/asyncapi/dataload\">" + "    <operation></operation>" + "    <object></object>" + "    <contentType>CSV</contentType>" + "</jobInfo>";
                //Eg for XML content type
                //"    <contentType>XML</contentType>" &
    
                reqURL = "https://na1.salesforce.com/services/async/28.0/job";
                reqDoc = new XmlDocument();
                reqDoc.LoadXml(str);
                // added XML modifications
                reqDoc.GetElementsByTagName("operation")[0].InnerText = sfOperation;
                reqDoc.GetElementsByTagName("object")[0].InnerText = sfObjectName;
                bytes = System.Text.Encoding.ASCII.GetBytes(reqDoc.InnerXml);
                //bytes = System.Text.Encoding.UTF8.GetBytes(reqDoc.InnerXml)
               
                using (Stream responseStream = Post(bytes, reqURL, sfSessionId, "POST", "text/csv; charset=UTF-8"))
                {
                    responseXmlDocument.Load(responseStream);
                    //Get jobId
                    jobId = ((((responseXmlDocument) != null)) ? responseXmlDocument.GetElementsByTagName("id").Item(0).InnerText : "");
                }
    
            }
    
            /// <summary>
            /// Adds the Batch to SalesForce
            /// </summary>
            /// <param name="sfSessionId"></param>
            /// <param name="fileBytes"></param>
            /// <param name="sfJobId"></param>
            /// <param name="sfBatchId"></param>
            /// <param name="sfResultId"></param>
            /// <remarks></remarks>
    
            public static void AddBatch(string sfSessionId, byte[] fileBytes, string sfJobId, string sfBatchId = null, string sfResultId = null)
            {
                string requestURI = ("https://login.salesforce.com/services/async/23.0/job/" + (sfJobId + "/batch"));
                Post(fileBytes, requestURI, sfSessionId, "POST", "text/csv; charset=UTF-8");
    
            }
    
            /// <summary>
            /// Once the batch is added get the BatchId and then
            /// once the processing is done , get the Results ID
            /// </summary>
            /// <param name="sfSessionId"></param>
            /// <param name="sfJobId"></param>
            /// <param name="batchId"></param>
            /// <param name="resultId"></param>
            /// <remarks></remarks>
    
            public static void GetStatusAndRetrieveBatchIdAndResultsId(string sfSessionId, string sfJobId, ref string batchId, ref string resultId)
            {
    
                XmlDocument responseXmlDocument = new XmlDocument();
                string reqURL = ("https://na1.salesforce.com/services/async/23.0/job/" + sfJobId + "/batch");
                //Get BatchId
                using (System.IO.Stream responseStream = Post(null, reqURL, sfSessionId, "GET", "text/csv; charset=UTF-8"))
                {
                    responseXmlDocument.Load(responseStream);
                    batchId = ((((responseStream) != null)) ? responseXmlDocument.GetElementsByTagName("id").Item(0).InnerText : "");
                }
    
                //Get ResultId
                reqURL = ("https://na1.salesforce.com/services/async/23.0/job/" + (sfJobId + "/batch/" + batchId + "/result"));   
                using (System.IO.Stream responseStream = Post(null, reqURL, sfSessionId, "GET", "text/csv; charset=UTF-8"))
                {
                    responseXmlDocument.Load(responseStream);
                    resultId = ((((responseStream) != null)) ? responseXmlDocument.GetElementsByTagName("result").Item(0).InnerText : "");
                }
    
            }
    
            /// <summary>
            /// Post the rest call with batch id and results id to get the output
            /// </summary>
            /// <param name="sfSessionId"></param>
            /// <param name="sfJobId"></param>
            /// <param name="sfBatchId"></param>
            /// <param name="sfResultId"></param>
            /// <remarks></remarks>
    
            public static void RetrieveResults(string sfSessionId, string sfJobId, string sfBatchId, string sfResultId)
            {
                string reqURL = ("https://na1.salesforce.com/services/async/23.0/job/" + (sfJobId + "/batch/" + sfBatchId + "/result/" + sfResultId));  
                string localFile = "output.csv";
                //Create the output file
                using (System.IO.Stream responseStream = Post(null, reqURL, sfSessionId, "GET", "text/csv; charset=UTF-8"))
                {
                    using (System.IO.FileStream fsOutputFile = new System.IO.FileStream(localFile, FileMode.Create, FileAccess.Write))
                    {
                        byte[] buffer = new byte[2048];
                        int read = 0;
                        do
                        {
                            read = responseStream.Read(buffer, 0, buffer.Length);
                            fsOutputFile.Write(buffer, 0, read);
                        } while (!(read == 0));
                        responseStream.Close();
                        fsOutputFile.Flush();
                        fsOutputFile.Close();
                    }
                    responseStream.Close();
                }
    
            }
    
            /// <summary>
            /// Function to POST the HTTP rest request
            /// </summary>
            /// <param name="bytes"></param>
            /// <param name="reqURL"></param>
            /// <param name="sfSessionId"></param>
            /// <param name="method"></param>
            /// <param name="contentType"></param>
            /// <returns></returns>
            /// <remarks></remarks>
            public static Stream Post(byte[] bytes, string reqURL, string sfSessionId, string method, string contentType)
            {
    
                //Create the request object
                WebRequest requestHttp = WebRequest.Create(reqURL);
                //Assign the type of request POST,GET..
                requestHttp.Method = method;
                //Assign Content Type
                requestHttp.ContentType = contentType;
                //"text/csv; charset=UTF-8" or "application/xml; charset=UTF-8"
                //Assign the session id to the header
                requestHttp.Headers.Add(("X-SFDC-Session: " + sfSessionId));
    
                //Assign byte length
                if ((bytes != null))
                {
                    requestHttp.ContentLength = bytes.Length;
    
                    System.IO.Stream strmHttpContent = requestHttp.GetRequestStream();
                    strmHttpContent.Write(bytes, 0, bytes.Length);
                    strmHttpContent.Close();
    
                }
    
                //Get the response object
              
               String responseFromServer;
              try
                {
                    //Call the service and get the response
                    HttpWebResponse response = (HttpWebResponse)requestHttp.GetResponse();
    
                    if (HttpStatusCode.OK == response.StatusCode)
                    {
                        Stream dataStream = response.GetResponseStream();
                        StreamReader reader = new StreamReader(dataStream);
                       responseFromServer = reader.ReadToEnd();
                        response.Close();
                    }
                }
                catch (WebException e)
                {
                    using (WebResponse response = e.Response)
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)response;
                        responseFromServer = string.Format("Error code: {0}  ", httpResponse.StatusCode);
                        using (Stream data = response.GetResponseStream())
                        {
                            responseFromServer += new StreamReader(data).ReadToEnd();
                         //   return responseFromServer;
                            Console.WriteLine("reponse from server" + responseFromServer);
                        }
                    }
                }
                //Return response Stream
                WebResponse responseHttpRequest = requestHttp.GetResponse();
                return responseHttpRequest.GetResponseStream();
    
    
            }
            static void Main(string[] args)
            {
                QueryUsingBulkAPI();
            }
        }
    }

 


 

Its returning the following output with Error:

Enter user name: sfuserid
Enter password: paswd+token
Creating the binding to the web service...
LOGGING IN NOW....
ConsoleApplication7.SForceService.LoginResult
The session id is: 00D90000000k6uO!ARoAQH02gPYFrZmt2RDkBNSXKZrEZLQv9jmAh2lXPaqAp
AsEu0zUbpTUC5mDn0FIHk2cCeYMuDjEIJeXnVfn.ccD1jW31IM3
The new server url is: https://ap1.salesforce.com/services/Soap/u/28.0/00D900000
00k6uO
reponse from serverError code: BadRequest  <?xml version="1.0" encoding="UTF-8"?
><error
   xmlns="http://www.force.com/2009/06/asyncapi/dataload">
 <exceptionCode>InvalidSessionId</exceptionCode>
 <exceptionMessage>Invalid session id</exceptionMessage>
</error>
The remote server returned an error: (400) Bad Request., please try again.Hit
return to continue...

Please help me resolve the Error.The bad request is due to invalid session id,but when i am printing the session id it has a valid value.Please tell me where the prblm is in the above code.

Thanks in advance.




Hello,

        I need bulk api code in C#.net.The developer guide gives the code for client java application.I need it for C#.net.or can i convert the same code to C#.I tried it using IKVM,buit couldnot do it successfully.Please help.

Hi,

I have an example of bulk api from bulk api developer guide:

 

http://www.salesforce.com/us/developer/docs/api_asynch/

inside section walkthrough sample code.(in java)

 

But i am not able to access the connection to salesforce due to some proxy settings.How do i pass the proxy settings in the same code.

 

Error while accessing salesforce:

Failed to send request to https://login.salesforce.com/services/Soap/u/26.0

 

Please help

Thanks :)

Hi,

Can any one explain Bulk api with a small sample code.

I know bulk api is used for processing large amounts of data and is being used with apex data loader but what if some wants to impliment bulk api without the apex dataloader.

 

Please help with an example.

 

Thanks.

hi,

can some help me

 List<SObject> ObjectContents;

String query=Select name from contact;

 ObjectContents = database.query(query);

 

if my query returns 2 rows then size of objectcontents wll be how much?

 

Thanks.

Hi can some help.

 

I wana pass a value to a vf page select list but with setredirect as true.

 

I tried using

public PageReference DatabaseSelectionPage() //true tha
 {
       PageReference newpage = new PageReference('/apex/connection1?dbname='+selectedValue);
           newpage.setRedirect(true);
                newpage.getParameters().put('dbname',selectedValue);
         selectedValue=ApexPages.currentPage().getParameters().get(selectedValue);
        
             return newpage;  
    }
   

 But its passing the value in url.

I want my selectedvalue to be passed to my select list on connection1 page.

Can any one please help?

 

Thanks.

Hi can anyone help.

i have 2 pages

firstpage

secondpage

the first page has a next button on which i call the second page

next button code:

PageReference newpage = new PageReference('/apex/secondpage');
            newpage.setRedirect(false);
              
              return newpage;  

 

 the second page has a previous button which calls back the first page.

previous button code:

PageReference newpage = new PageReference('/apex/firstpage');
            newpage.setRedirect(false);
              
              return newpage;  

 Now the problem i am facing is when i click on previous button.it again calls the page n i get the data in my drop down list 2 times instead of once.

like if my firstpage has a drop down list with dynamic values like a,b,c

when i click on previous i get a,b,c,a,b,c in drop down.

and i need to keep setRedirect false as i want default value of drop down to be the one(when i click on previous button),which the user had clicked while navigating from the first page to the second.Can some please help.

 

Please help

Thanks.

 i need to pass selected value with ' ' in the following string but i am unable to do so

 String query='select column_name from information_schema.COLUMNS where table_name ='+ selectedValue1;

 my debug log shows the below mentioned statement

select column_name from information_schema.COLUMNS where table_name =RegistrationTable

 but the actual required statement should be 

select column_name from information_schema.COLUMNS where table_name ='RegistrationTable'

 how do i prepare my string variable. As Sfdc is not allowing me to use "" to prepare the string.

hi,

Can someone please help.

I am new to webservice can someone help?

I have created a custom webservice in asp.net

its link is for example:

http://localhost:8732/Design_Time_Addresses/Calc/Service1/

 

i wana add this link to my

Security controls-->remote site settings

as I am using the wsdl generated from the page.

 

how do i specify the remote site url which should not give me error while making callouts for the webservice.

 

 

Thanks.

 

Hi -

 

I'm doing some work with the Bulk API.  I am able to get my CSV file uploaded and the job to process successfully.  I am, however, having a problem obtaining the status of the job. Here is the code I am using which is based on the example provided...

 

BatchInfo[] statusList = connection.getBatchInfoList(job.getId()).getBatchInfo();

 

I am passing it a valid job ID, which has been successfully submitted.  The error I am receiving is...

 

java.lang.IllegalArgumentException: input stream can not be null
at com.sforce.ws.parser.MXParser.setInput(MXParser.java:522)
at com.sforce.ws.parser.XmlInputStream.setInput(XmlInputStream.java:64)
at com.sforce.async.RestConnection.parseAndThrowException(RestConnection.java:112)
at com.sforce.async.RestConnection.doHttpGet(RestConnection.java:283)
at com.sforce.async.RestConnection.getBatchInfoList(RestConnection.java:190)

 

Any help would be greatly appreciated,

 

Thanks,

 

Jeff Podlogar