• 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.

when i am running the client application of bulk api in java.I am getting the following error:

Anyone there to help:

I took the client application from the bulk api developer guide.

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

Sample client application using java.


com.sforce.ws.ConnectionException: Failed to send request to https://login.salesforce.com/services/Soap/u/28.0
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.login(PartnerConnection.java:791)
    at com.sforce.soap.partner.PartnerConnection.<init>(PartnerConnection.java:315)
    at com.jeffdouglas.BulkLoader.getRestConnection(BulkLoader.java:278)
    at com.jeffdouglas.BulkLoader.runJob(BulkLoader.java:160)
    at com.jeffdouglas.BulkLoader.run(BulkLoader.java:57)
    at com.jeffdouglas.BulkLoader.main(BulkLoader.java:42)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:132)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:78)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Failed to send request to https://login.salesforce.com/services/Soap/u/28.0

 

Please help me i am stuck.

Thanks.:)

  • September 27, 2013
  • Like
  • 0

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 :)

  • September 26, 2013
  • Like
  • 0

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 :)

  • September 26, 2013
  • Like
  • 0

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.

  • September 23, 2013
  • Like
  • 0

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.

  • September 03, 2013
  • Like
  • 0

Hi,

Can anyone help.

 

I want use a extension with custom controller

<apex:page controller="MyApexClass" extensions="MyExtClass"...> ... </apex:page>
public with sharing class MyExtClass {
  private MyApexClass ctrl;
  public MyExtClass(MyApexClass controllerParam){
      ctrl = controllerParam;
  }
}

I have used in similar manner but now,if i have a vf page with select list and its getter and setter method are in MyExtClass(extension) then how do i use that variable value in my controller MyApexClass.

 

like for example:

How do i use selectedvalue3 in my controller MyApexClass.

Is there any way to do this?

public with sharing class MyExtClass {
public string selectedValue3{get;set;} private MyApexClass ctrl; public MyExtClass(MyApexClass controllerParam){ ctrl = controllerParam; } }

Hello,

Below is the code for vf page:

<apex:repeat id="repeat" value="{!InnerList}" var="in">
  
  <apex:selectList value="{!in.selectedValue1}" id="value1" required="true" multiselect="false" style="width:200px;" size="1">
        
     <apex:selectOptions id="options" value="{!Header}"/>
             
  </apex:selectList>
          
          
  <apex:selectList value="{!in.selectedValue2}" id="value2" multiselect="false" required="true" style="width:200px;" size="1">
     
     <apex:selectOptions id="options1" value="{!FieldList}"/>
           
   </apex:selectList>
        
</apex:repeat>

     <apex:actionRegion >   
  
    <apex:commandButton id="Next" value="SavetoObject"  action="{!saveToObject}" immediate="true" />
       </apex:actionRegion>
             
           

 Here if i don use immediate=true,i get validation error like:

 j_id0:j_id2:j_id33:repeat:0:value1: Validation Error: Value is not valid

 

and when i use immediate=true validation error disappears but it doesnot capture my user input.

I found a solution some where that using action region i can make it capture my user input.

Can any one explain me.

Above is the link for action region solution.

http://salesforce.stackexchange.com/questions/8574/problem-in-commandbutton-with-immediate-true

http://www.tgerm.com/2010/09/visualforce-actionregion-deep-dive.html

 

 

but i don know how to use it in my context.

Can some one please help.

 

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.

Hello,

Can anyone pls help.

I wana make callout to a function whose return type is ArrayOfArrayOfstring

 

public class sqlArray {
    public class ArrayOfstring {
        public String[] string_x;
        private String[] string_x_type_info = new String[]{'string','http://www.w3.org/2001/XMLSchema','string','0','-1','true'};
        private String[] apex_schema_type_info = new String[]{'http://schemas.microsoft.com/2003/10/Serialization/Arrays','true','false'};
        private String[] field_order_type_info = new String[]{'string_x'};
    }
    public class ArrayOfArrayOfstring {
        public sqlArray.ArrayOfstring[] ArrayOfstring;
        private String[] ArrayOfstring_type_info = new String[]{'ArrayOfstring','http://schemas.microsoft.com/2003/10/Serialization/Arrays','ArrayOfstring','0','-1','true'};
        private String[] apex_schema_type_info = new String[]{'http://schemas.microsoft.com/2003/10/Serialization/Arrays','true','false'};
        private String[] field_order_type_info = new String[]{'ArrayOfstring'};
    }
}

 

 and this is my function

 public sqlArray.ArrayOfArrayOfstring outputForSelect(String query,String databasename) {
            Connect6.outputForSelect_element request_x = new Connect6.outputForSelect_element();
            Connect6.outputForSelectResponse_element response_x;
            request_x.query = query;
            request_x.databasename = databasename;
            Map<String, Connect6.outputForSelectResponse_element> response_map_x = new Map<String, Connect6.outputForSelectResponse_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/outputForSelect',
              'http://tempuri.org/',
              'outputForSelect',
              'http://tempuri.org/',
              'outputForSelectResponse',
              'Connect6.outputForSelectResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.outputForSelectResult;
        }

 

 

Please help.

 

Thanks.

Urvashi.

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.

 

How to specify multilple content type in <apex:page> tag.

i wana save two files on load of a page.

One file i can specify in content type but where to specif the other file.

Is it possible thru contenttype

 

<apex:page sidebar="false" showHeader="false" controller="Con" cache="true" contentType="text/csv#abc.csv" language="en-US">

 If i wana specify xyz.csv also along with abc.csv.How do i achieve this?

Hi any anyone explain me the concept of 2 array using list<list<String>>.

How to access individual elements of both the list.

 

if suppose i have

 List<List<String>> HeaderDataC = new List<List<String>>();
    List<String> list1 = new List<String>();
    List<String> list2 = new List<String>();

list1.add('val1');

list1.add('val2');

list2.add('1');

list2.add('2');

 

    HeaderDataC.add(list1);
    HeaderDataC.add(list2);

 

but here what represents row data n what represents column data.

and if suppose i wana insert value in specific row of specific column,how do i achive it?

like HeaderDataC[2][3]?

 

Thanks in advance.

hi i need help

Below is my code:

VF page:

<apex:page sidebar="false" showHeader="false" controller="communityCon1234" cache="true" contentType="text/csv#Error.csv" language="en-US">


<apex:repeat value="{!HeaderXLS}" var="a">

<apex:outputText value="{!a}">
</apex:outputText>

</apex:repeat>
<br/>
<apex:repeat value="{!fileLine}" var="b">
<apex:outputText value="{!b}"></apex:outputText>

</apex:repeat>
<br/>
</apex:page>

 

Controller:

 

 public List<String> getHeaderXLS()
    {
      List<String> listString1 = new List<String>();
     listString1.add('phnnumber');
      listString1.add('name');
   
      return  listString1;
    }
    public List<String> getFileLine()
    { List<String> listString = new List<String>();
     listString.add('123456');
      listString.add('urvashi');
      return listString;
      
    }

 MY problem here is i wana display the values of listString and listString1 in different columns in excel file.

like

phnnumber    name

123456           urvashi

 

The the size of listString is not fixed.It varies depending upon the code.

How do i do this?
Please help.

And how do i insert<br/> tag in btwn vf page so that it doesnot come in the excel file.

Hello,

 I Wanna write data to the CSV file, and i have the values of those variables in my controller.

 

How do i di it.

 

<apex:page controller="comm" cache="true" contentType="text/csv#File.csv" language="en-US">
</apex:page>

 I know the above method to create a file as File.csv.

But how do i write data to CSV.

 

Thanks.

Can anyone help.

If i am doing an operation of inserting some values in an object using a loop.

Account a=new Account();
for(Integer j=0;j<5;j++)
 {
 a.put(l[j],inputvalues[j]);
 }  
Here inputvalues and l array contains the following values:
l[j]                inputvalues[j]
Name                 Neha 
Accountnumber        5023   

If suppose there occurs some error during "put" operation then i get the error in Visual Force page
Instead of this i want an error in some other resource like a variable or list item and my operation of insert should not stop.
Anyone has a solution to this.
Please help with some sample code.

 

Thanks.

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 :)

  • September 26, 2013
  • Like
  • 0

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.

  • September 23, 2013
  • Like
  • 0

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.

  • September 03, 2013
  • Like
  • 0

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