/// <summary>
        /// Logins current binding.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="token">The token.</param>
        /// <param name="userInfo">The user info.</param>
        /// <returns>Login result.</returns>
        public bool Login(string username, string password, string token, out UserInfo userInfo)
        {
            if (!_loggedIn)
            {
                LoginResult loginResult = _binding.login(username, String.Concat(password, token));

                _binding.Url = loginResult.serverUrl;
                _binding.SessionHeaderValue = new SessionHeader
                {
                    sessionId = loginResult.sessionId
                };

                _salesforceGlobals = _binding.describeGlobal();

                _userInfo = new UserInfo
                {
                    UserSFID         = loginResult.userId,
                    OrganizationSFID = loginResult.userInfo.organizationId,
                    OrganizationName = loginResult.userInfo.organizationName
                };

                userInfo = _userInfo; _loggedIn = true;
            }
            else
            {
                userInfo = null;
            }

            return(_loggedIn);
        }
Beispiel #2
0
        /// <summary>
        /// Logins the specified username.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <exception cref="System.Exception">Salesforce Password has expired</exception>
        private void Login(string username, string password)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            // Create a service object
            _binding = new SforceService {
                Timeout = 15000
            };

            // Try logging in
            var lr = _binding.login(username, password);

            // Check if the password has expired
            if (lr.passwordExpired)
            {
                throw new Exception("Salesforce Password has expired");
            }

            // Set returned service endpoint URL
            _binding.Url = lr.serverUrl;

            /** Now have an instance of the SforceService
             * that is pointing to the correct endpoint. Next, the sample client
             * application sets a persistent SOAP header (to be included on all
             * subsequent calls that are made with SforceService) that contains the
             * valid sessionId for our login credentials. To do this, the sample
             * client application creates a new SessionHeader object and persist it to
             * the SforceService. Add the session ID returned from the login to the
             * session header
             */
            _binding.SessionHeaderValue = new SessionHeader {
                sessionId = lr.sessionId
            };
        }
Beispiel #3
0
 private void getSessionInfo()
 {
     _loginResult = new LoginResult();
     System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
     _loginResult = _sforceRef.login(uname, pwd + securityToken);
     sessionId    = _loginResult.sessionId;
 }
Beispiel #4
0
        public bool Login(SalesForceCredential salesForceCredential)
        {
            try
            {
                _loginResult = _salesforceService.login(salesForceCredential.UserName,
                                                        salesForceCredential.Password + salesForceCredential.SecurityToken);

                var result = !string.IsNullOrEmpty(_loginResult.sessionId) &&
                             !string.IsNullOrEmpty(_loginResult.userId) &&
                             _loginResult.userInfo != null;

                if (!result)
                {
                    return(false);
                }

                _salesforceService.Url = _loginResult.serverUrl;
                _salesforceService.SessionHeaderValue = new SessionHeader {
                    sessionId = _loginResult.sessionId
                };

                return(true);
            }
            catch (Exception exception)
            {
                throw new Exception("There was an error logging into sales force.")
                      {
                          Source = exception.Source
                      };
            }
        }
Beispiel #5
0
        public bool Authenticate()
        {
            binding = new SforceService();
            LoginResult LResult = new LoginResult();
            try
            {
                LResult = binding.login(UserName, Password + SecurityToken);
            }
            catch (SoapException ex)
            {
                logger.Log(NLog.LogLevel.Error, ex.Message);
                return false;
            }
            if (LResult.passwordExpired)
            {
                return false;
            }

            //Change the binding to the new endpoint
            binding.Url = LResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            binding.SessionHeaderValue = new SessionHeader();
            binding.SessionHeaderValue.sessionId = LResult.sessionId;
            GetUserInfoResult userInfo = LResult.userInfo;

            return true;
        }
		public void ConnectToService()
		{
			try
			{
				Client = new SforceService();
                SforceService t = new SforceService();
                

                Client.Url = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.URL;

				_loginResult = Client.login(UserName, Password);
			}
			catch (SoapException ex)
			{
				UnityResolver.UnityContainer.Resolve<ILogger>().LogEvent(() =>
					Config.AppEvents.GainWinServicesExactTarget.ExactTargetInformation,
					"SalesForce SoapException");

				throw new ApiException("SalesForce SoapException", ex);
			}
			catch (Exception ex)
			{
				UnityResolver.UnityContainer.Resolve<ILogger>().LogEvent(() =>
					Config.AppEvents.GainWinServicesExactTarget.ExactTargetInformation,
					"SalesForce Exception");

				throw new ApiException("SalesForce Exception", ex);
			}
		}
        static EventDAL()
        {
            if (SfdcBinding == null)
            {
                string userName;

                string password;
                userName = ConfigurationManager.AppSettings["SalesForceUserName"];
                password = ConfigurationManager.AppSettings["SalesForcePassword"];
                string      securityToken      = ConfigurationManager.AppSettings["SalesForceSecurityToken"];
                LoginResult CurrentLoginResult = null;

                SfdcBinding = new SforceService();
                try
                {
                    CurrentLoginResult = SfdcBinding.login(userName, password + securityToken);
                    //Change the binding to the new endpoint
                    SfdcBinding.Url = CurrentLoginResult.serverUrl;
                    //Create a new session header object and set the session id to that returned by the login
                    SessionHeader sessionHeader = new SessionHeader();
                    SfdcBinding.SessionHeaderValue           = sessionHeader;
                    SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
                }
                catch (Exception e)
                {
                    EventLog.WriteEntry("SalesForcceIntegration", e.Message,
                                        EventLogEntryType.Error);
                }
            }
        }
Beispiel #8
0
        public void upLoad()
        {
            ServicePointManager.Expect100Continue = true;                       //Enables prolonged use
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12; //Sets needed security level

            var    list = new List <string>();                                  //List to hold case numbers that have been used
            string user = "";                                                   //Test salesforce user
            string pass = "";                                                   //Test salesforce pass

            binding         = new SforceService();                              //Initializs binding object
            binding.Timeout = 60000;                                            //Sets maximum time per binding
            WebReference.LoginResult lr;                                        //lr is my login result
            lr = binding.login(user, pass);                                     //Used lr to create credentials
            string authEndPoint = binding.Url;                                  //Not sure what this does honestly

            binding.Url = lr.serverUrl;                                         //Sets binding to correct server
            binding.SessionHeaderValue           = new SessionHeader();         //Header needed for API format
            binding.SessionHeaderValue.sessionId = lr.sessionId;                //Gives binder the session id

            try
            {
                Case          c     = new Case();
                Case[]        cases = new Case[1];
                CaseComment   com   = new CaseComment();
                CaseComment[] coms  = new CaseComment[1];

                //c.AccountId = "GBS Non Case Events";
                //c.Subject = "API Test";
                //c.Type = "MAC - Non-Billable";
                //c.Case_Product_Category__c = "Project";
                //c.Product_Subcategory__c = "Training";
                //c.Priority = "SLA - 5 - Client Request/Client Created Issue";
                //c.Origin = "Phone";
                //c.Reason = "Test Description";
                //c.Status = "Case Opened";
                //c.OwnerId = "Firaus Odeh";
                //c.ContactId = "";
                //c.Description = "Test";
                //c.IsEscalated = false;
                //c.SuppliedName = "Test Case";
                //c.SuppliedEmail = "";
                //c.SuppliedPhone = "";
                //c.SuppliedCompany = "";
                //SaveResult[] results = binding.create(cases);
                //Debug.WriteLine("valid Data");
                c.Id = "5000g000026SPQ8AAO";
                string      query1 = "Insert into Case (Comments) Value ('Test') Where CaseNumber = '00311360'";
                QueryResult result = binding.query(query1);
                com.Id          = result.ToString();
                c.Subject       = "Test";
                com.CommentBody = "Test comment";
                c.Comments      = "test";
                coms[0]         = com;
                SaveResult[] check = binding.create(coms);
            }
            catch
            {
                Debug.WriteLine("Invalid data");
            }
        }
Beispiel #9
0
        public static void ImageDownload()
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;

            LoginResult   currentLoginResult = null;
            SforceService sfdcBinding        = new SforceService();

            currentLoginResult = sfdcBinding.login(UserName, Password + SecurityToken);

            //Change the binding to the new endpoint
            sfdcBinding.Url = currentLoginResult.serverUrl;
            //Create a new session header object and set the session id to that returned by the login
            sfdcBinding.SessionHeaderValue           = new SessionHeader();
            sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
            string      sfSessionId = currentLoginResult.sessionId;
            QueryResult queryResult = null;

            if (sfdcBinding != null)
            {
                //String SOQL = "SELECT id,IsProfilePhotoActive,FullPhotoUrl,LastName ,FirstName FROM User where isActive = true and IsProfilePhotoActive=true";
                String SOQL = "select Id, name, Phone__c,fee__c,Head_Master__c, City__c, Board__c,Languages_offered__c,State__c from School__c";
                queryResult = sfdcBinding.query(SOQL);
            }
            if (queryResult.size > 0)
            {
                // SFImages(queryResult, sfSessionId);
                SchoolData(queryResult);
            }
        }
Beispiel #10
0
        public HomeController()
        {
            sfdcBinding = new SforceService();


            ///////////// SFDC

            try
            {
                currentLoginResult = sfdcBinding.login(userName, password + securityToken);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                // This is likley to be caused by bad username or password
                sfdcBinding = null;
                throw (ex);
            }
            catch (Exception ex)
            {
                // This is something else, probably comminication
                sfdcBinding = null;
                throw (ex);
            }


            //Change the binding to the new endpoint
            sfdcBinding.Url = currentLoginResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            sfdcBinding.SessionHeaderValue           = new SessionHeader();
            sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;


            //////////// SFDC
        }
Beispiel #11
0
        public string update_rma(string id, string finding, string asset_tag, string rci)
        {
            string message = "RMA Info Updated";

            try
            {
                conn.Open();
                MySqlCommand command = conn.CreateCommand();
                command.CommandText = "UPDATE rma set production_finding = '" + finding + "' WHERE ictag = '" + asset_tag + "'";
                command.ExecuteNonQuery();
                conn.Close();


                string userName;
                string password;
                userName = "******";
                password = "******";
                //use default binding and address from app.config
                // string securityToken = "xxxxxxxxxxxxxxx";
                LoginResult   currentLoginResult = null;
                SforceService sfdcBinding        = null;



                sfdcBinding                              = new SforceService();
                currentLoginResult                       = sfdcBinding.login(userName, password);
                sfdcBinding.Url                          = currentLoginResult.serverUrl;
                sfdcBinding.SessionHeaderValue           = new SessionHeader();
                sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
                var update_case = new Case();

                update_case.RCI_Partner_Origin__c = rci;
                update_case.Reviewed_by_Production__cSpecified = true;
                update_case.Reviewed_by_Production__c          = true;
                update_case.Id = id;
                update_case.Production_Findings__c = finding;



                SaveResult[] saveResults = sfdcBinding.update(new sObject[] { update_case });


                if (saveResults[0].success)
                {
                    message = "The update of Lead ID " + saveResults[0].id + " was succesful";
                }
                else
                {
                    message = "There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message;
                }
            }
            catch (Exception e)
            {
                message = e.Message;
                conn.Close();
            }

            return(message);
        }
Beispiel #12
0
        private static void Main(string[] args)
        {
            var pw = "hHAfXhn6t1O3";
            var token = "vH4tFXiEObwH1WotZxK2xEX3z";
            var username = "******";
            var sfs = new SforceService();
            sfs.Timeout = 60000;
            Console.WriteLine("Logging in...");
            var lr = sfs.login(username, pw + token);
            sfs.SessionHeaderValue = new SessionHeader();
            sfs.SessionHeaderValue.sessionId = lr.sessionId;
            string authEndPoint = sfs.Url;
            sfs.Url = lr.serverUrl;

            string content =
                File.ReadAllText(
                    @"C:\Users\Dana\Documents\GitHub\NWEA_Bridge_Importer\NWEABridgeImporter\productmapping.csv");

            var lines = content.Split(new char[] {'\r'});
            var bridgeFactory = new BridgeFactory(sfs);
            bool isFirst = true;
            foreach (var line in lines)
            {
                if (isFirst)
                {
                    isFirst = false;
                    continue;
                }
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                string pId = string.Empty;
                string prpcId = string.Empty;
                var l = line.Trim();
                l = l.TrimEnd(new char[] {','});

                var parts = l.Split(',');
                if (parts.Length != 2)
                {
                    Console.WriteLine("invalid bridge: " + line);
                    continue;
                }
                pId = parts[0];
                prpcId = parts[1];

                if (string.IsNullOrWhiteSpace(pId) || string.IsNullOrWhiteSpace(prpcId))
                {
                    Console.WriteLine("invalid line: " + line);
                    continue;
                }
                Console.WriteLine("bridging {0} to {1} ...", pId, prpcId);
                bridgeFactory.Bridge(pId, prpcId);
            }
            Console.ReadKey();
        }
Beispiel #13
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string user  = txtUserName.Text;
            string key   = txtpassword.Password;
            string token = txtSecToken.Text;

            if (string.IsNullOrWhiteSpace(user))
            {
                MessageBox.Show("Username is empty");
                return;
            }
            else if (string.IsNullOrWhiteSpace(key))
            {
                MessageBox.Show("Password is empty");
                return;
            }
            else if (string.IsNullOrWhiteSpace(token))
            {
                MessageBox.Show("Security Token is empty");
                return;
            }

            key = key + token;

            //Authentication With Salesforce
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            SforceService SfdcBinding        = null;
            LoginResult   CurrentLoginResult = null;

            SfdcBinding = new SforceService();
            try
            {
                CurrentLoginResult                       = SfdcBinding.login(user, key);
                SfdcBinding.Url                          = CurrentLoginResult.serverUrl;
                SfdcBinding.SessionHeaderValue           = new SessionHeader();
                SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;

                //Open Next Form on Success
                ODataConf odataconf = new ODataConf(SfdcBinding);
                //Datasource datasourceWin = new Datasource(SfdcBinding);
                odataconf.WindowStartupLocation = WindowStartupLocation.Manual;
                odataconf.Top  = this.Top;
                odataconf.Left = this.Top;
                odataconf.Show();
                this.Close();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                SfdcBinding = null;
                MessageBox.Show("Invalid Credentials:" + ex.Message);
            }
            catch (Exception ex)
            {
                SfdcBinding = null;
                MessageBox.Show("Error: " + ex.Message);
            }
        }
Beispiel #14
0
        private LoginResult Login(string userName, string password)
        {
            LoginResult result = salesforceSoapService.login(userName, password);

            salesforceSoapService.Url = result.serverUrl;
            salesforceSoapService.SessionHeaderValue = new SessionHeader {
                sessionId = result.sessionId
            };
            return(result);
        }
Beispiel #15
0
 private string LogIn()
 {
     using (var sfClient = new SforceService())
     {
         var username           = _appSettings.Get(AppSettingKeys.Username);
         var password           = _appSettings.Get(AppSettingKeys.Password) + _appSettings.Get(AppSettingKeys.SecurityToken);
         var currentLoginResult = sfClient.login(username, password);
         return(currentLoginResult.sessionId);
     }
 }
        static public LoginResult LoginAtEnvironment(this SforceService svc, string username, string password, string environment)
        {
            string url = svc.Url;

            svc.Url = "https://" + environment + ".salesforce.com/services/Soap/u/29.0";
            LoginResult loginResult = svc.login(username, password);

            svc.Url = url;
            return(loginResult);
        }
        public void CheckSandboxConnection()
        {
            credentials               = new SalesforceCredentials();
            credentials.UserName      = "******";
            credentials.Password      = "******";
            credentials.SecurityToken = "dif5imP71pxuepPz4OM7aEMJX";

            result = sfClient.login(credentials.UserName, credentials.Password + credentials.SecurityToken);
            Assert.AreEqual(true, result.sandbox);
        }
Beispiel #18
0
        public List <Case> search_rma()
        {
            string userName;
            string password;

            userName = "******";
            password = "******";
            //use default binding and address from app.config
            // string securityToken = "xxxxxxxxxxxxxxx";

            SforceService sfdcBinding        = null;
            LoginResult   currentLoginResult = null;

            sfdcBinding = new SforceService();
            try
            {
                currentLoginResult = sfdcBinding.login(userName, password);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                // This is likley to be caused by bad username or password
                sfdcBinding = null;
                throw (ex);
            }
            catch (Exception ex)
            {
                // This is something else, probably comminication
                sfdcBinding = null;
                throw (ex);
            }


            //Change the binding to the new endpoint
            sfdcBinding.Url = currentLoginResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            sfdcBinding.SessionHeaderValue           = new SessionHeader();
            sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;

            QueryResult queryResult = null;
            String      SOQL        = "";
            List <Case> case_result = new List <Case>();

            // SOQL = "SELECT Id,Return_Resolution__c,Description ,CaseNumber,IC_Barcodes__c,RMA_number__c,Production_Findings__c,Channel__c,CreatedDate FROM case where CreatedDate >=2017-01-01T12:00:00Z AND CreatedDate  <=2017-05-31T12:00:00Z";
            SOQL        = "SELECT Id,Return_Resolution__c,Description,CaseNumber,IC_Barcodes__c,RMA_number__c,Production_Findings__c,Channel__c,CreatedDate FROM case where CreatedDate = YESTERDAY";
            queryResult = sfdcBinding.query(SOQL);
            for (int i = 0; i < queryResult.size; i++)
            {
                case_result.Add((Case)queryResult.records[i]);
            }



            return(case_result);
        }
        //Create a new record
        public static void connectWithTridionAndWriteDataInSF(List <SalesforceIntegrationWithSDLWeb8.DAL.Model.Lead> cmsLeadData)
        {
            SforceService SfdcBinding        = null;
            LoginResult   CurrentLoginResult = null;

            SfdcBinding = new SforceService();
            try
            {
                CurrentLoginResult = SfdcBinding.login(ConfigurationManager.AppSettings["uName"].ToString(), ConfigurationManager.AppSettings["pWD"].ToString());
                //Change the binding to the new endpoint
                SfdcBinding.Url = CurrentLoginResult.serverUrl;

                //Create a new session header object and set the session id to that returned by the login
                SfdcBinding.SessionHeaderValue           = new SessionHeader();
                SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
                com.salesforce.ap2.Lead sfLead = new com.salesforce.ap2.Lead();

                //string firstName = "Hem";
                //string lastName = "Kant";
                //string email = "*****@*****.**";
                //string company = "ABC Corp.";
                foreach (var item in cmsLeadData)
                {
                    sfLead.FirstName = item.FName.Text;
                    sfLead.LastName  = item.LName.Text;
                    sfLead.Email     = item.EmaiID.Text;
                    sfLead.Company   = item.Company.Text;

                    SaveResult[] saveResults = SfdcBinding.create(new sObject[] { sfLead });

                    if (saveResults[0].success)
                    {
                        string Id = "";
                        Id = saveResults[0].id;
                    }
                    else
                    {
                        string result = "";
                        result = saveResults[0].errors[0].message;
                    }
                }
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                throw (e);
            }
            catch (Exception e)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                throw (e);
            }
        }
        public bool Login()
        {
            string username = ConfigurationManager.AppSettings["SForce_Username"];
            string password = ConfigurationManager.AppSettings["SForce_Password"];
            // Create a service object
            binding = new SforceService();
            // Timeout after a minute
            binding.Timeout = 60000;
            // Try logging in
            LoginResult lr;
            try
            {
                Debug.WriteLine("LOGGING IN NOW...");
                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
                Debug.WriteLine(e.Code);
                // Write the fault message to the console
                Debug.WriteLine("An unexpected error has occurred: " + e.Message);
                // Write the stack trace to the console
                Debug.WriteLine(e.StackTrace);
                // Return False to indicate that the login was not successful
                return false;
            }
            // Check if the password has expired
            if (lr.passwordExpired)
            {
                throw new Exception("An error has occurred. Your salesforce password has expired. Unable to log in.");
            }
            /** Once the client application has logged in successfully, it will use
             * the results of the login call to reset the endpoint of the service
             * to the virtual server instance that is servicing your organization
             */
            binding.Url = lr.serverUrl;
            /** This client application now has an instance of the SforceService
             * that is pointing to the correct endpoint. Next, this client
             * application sets a persistent SOAP header (to be included on all
             * subsequent calls that are made with SforceService) that contains the
             * valid sessionId for our login credentials. To do this, the sample
             * client application creates a new SessionHeader object and persist it to
             * the SforceService. Add the session ID returned from the login to the
             * session header
             */
            binding.SessionHeaderValue = new SessionHeader();
            binding.SessionHeaderValue.sessionId = lr.sessionId;
            // Return true to indicate that we are logged in, pointed
            // at the right URL and have our security token in place.

            return true;
        }
Beispiel #21
0
        public bool update_rma(string rma_num, string finding)
        {
            bool   sucessful = false;
            string userName;
            string password;

            userName = "******";
            password = "******";
            //use default binding and address from app.config
            // string securityToken = "xxxxxxxxxxxxxxx";
            LoginResult   currentLoginResult = null;
            SforceService sfdcBinding        = null;

            var edit_case = (from t in db.rma where t.rma_number == rma_num select t).FirstOrDefault();

            using (var db = new db_a094d4_icdbEntities1())
            {
                db.Database.ExecuteSqlCommand("Update rma set production_finding = '" + finding + "' where rma_number ='" + rma_num + "'");
            }


            sfdcBinding                              = new SforceService();
            currentLoginResult                       = sfdcBinding.login(userName, password);
            sfdcBinding.Url                          = currentLoginResult.serverUrl;
            sfdcBinding.SessionHeaderValue           = new SessionHeader();
            sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
            var update_case = new Case();

            update_case.Reviewed_by_Production__c          = true;
            update_case.Reviewed_by_Production__cSpecified = true;
            update_case.Id = edit_case.id;
            update_case.Production_Findings__c = finding;



            SaveResult[] saveResults = sfdcBinding.update(new sObject[] { update_case });

            string result = "";

            if (saveResults[0].success)
            {
                sucessful = true;
                result    = "The update of Lead ID " + saveResults[0].id + " was succesful";
            }
            else
            {
                sucessful = false;
                result    = "There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message;
            }



            return(sucessful);
        }
        public SaleForceConnect(String username, String password, String serverUrl)
        {
            //sfService = new SforceService();
            //Si vamos a conectar a una Sandbox, descomentar la linea siguiente (el valor por defecto es a login.salesforce, para ambientes Dev/Production)
            sfService.Url = serverUrl;

            LoginResult CurrentLoginResult = sfService.login(username, password);

            //Change the binding to the new endpoint
            sfService.Url = CurrentLoginResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            sfService.SessionHeaderValue           = new SessionHeader();
            sfService.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
        }
        static void Main(string[] args)
        {
            SforceService SfdcBinding        = null;
            LoginResult   CurrentLoginResult = null;

            SfdcBinding = new SforceService();
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                CurrentLoginResult                       = SfdcBinding.login(Constants.USERNAME, Constants.PASSWORD + Constants.TOKEN);
                SfdcBinding.Url                          = CurrentLoginResult.serverUrl;
                SfdcBinding.SessionHeaderValue           = new SessionHeader();
                SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
                QueryResult queryResult = null;
                String      SOQL        = "";
                SOQL        = "select FirstName, LastName, Phone from Lead LIMIT 10";
                queryResult = SfdcBinding.query(SOQL);
                if (queryResult.size > 0)
                {
                    for (int i = 0; i < queryResult.records.Length; i++)
                    {
                        Lead   lead          = (Lead)queryResult.records[i];
                        string firstName     = lead.FirstName;
                        string lastName      = lead.LastName;
                        string businessPhone = lead.Phone;
                        Console.WriteLine("First Name " + firstName + ", Last Name " + lastName + ", Phone " + businessPhone);
                    }
                }
                else
                {
                    Console.WriteLine("No records returned.");
                }
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                Console.WriteLine("SOAP Exception occured " + e.Message.ToString());
            }
            catch (Exception e)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                Console.WriteLine("Exception occured " + e.Message.ToString());
            }
        }
Beispiel #24
0
        public Response <bool> LogIn(string username, string password)
        {
            var result = new Response <bool>();

            // try catch add error please
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            binding         = new SforceService();
            binding.Timeout = 60000;
            LoginResult lr           = binding.login(username, password);
            String      authEndPoint = binding.Url;

            binding.Url = lr.serverUrl;
            binding.SessionHeaderValue           = new SessionHeader();
            binding.SessionHeaderValue.sessionId = lr.sessionId;
            result.Data = true;
            return(result);
        }
Beispiel #25
0
        public bool Validate(SalesForceCredentials creds)
        {
            try
            {
                var loginResult = binding.login(creds.UserName, creds.Password + creds.SecurityToken);
                binding.Url = loginResult.serverUrl;

                binding.SessionHeaderValue = new SessionHeader {
                    sessionId = loginResult.sessionId
                };
                return(true);
            }
            catch (SoapException)
            {
                return(false);
            }
        }
        public bool Validate(SalesForceCredentials creds)
        {
            try
            {
                LoginResult lr;
                lr = binding.login(creds.UserName, creds.Password + creds.SecurityToken);
                var authEndPoint = binding.Url;
                binding.Url = lr.serverUrl;

                binding.SessionHeaderValue           = new SessionHeader();
                binding.SessionHeaderValue.sessionId = lr.sessionId;
                return(true);
            }
            catch (SoapException)
            {
                return(false);
            }
        }
        public ISalesforceSession Create([CallerMemberName] string CallerMemberName = "", [CallerFilePath] string CallerFilePath = "", [CallerLineNumber] int CallerLineNumber = 0)
        {
            //TODO: Salesforce logging.
            DebugLogger.Log($"Salesforced called by: {CallerMemberName}, File: {CallerFilePath}, Line Number {CallerLineNumber}");
            var username = Configuration.Username;
            var password = string.Concat(Configuration.Password, Configuration.Token);
            var service  = new SforceService
            {
                Url     = Configuration.Url,
                Timeout = Configuration.Timeout
            };

            var result = service.login(username, password);

            return(new SalesforceSession
            {
                Id = result.sessionId
            });
        }
Beispiel #28
0
        public SforceService Login()
        {
            SforceService service = new SforceService();

            service.Url = _credentials.SalesforceUrl;


            LoginResult loginResult;

            try
            {
                loginResult = service.login(_credentials.SalesforceLogin, _credentials.SalesforcePassword);
            }
            catch (SoapException ex)
            {
                logger.Error(string.Format("error during attempted login for {0}", _credentials.SalesforceLogin), ex);
                throw ex;
            }

            /**
             * Once the client application has logged in successfully, it will use
             * the results of the login call to reset the endpoint of the service
             * to the virtual server instance that is servicing your organization
             */
            service.Url = loginResult.serverUrl;

            /**
             * The client application now has an instance of the SforceService
             * that is pointing to the correct endpoint. Next, the sample client
             * application sets a persistent SOAP header (to be included on all
             * subsequent calls that are made with SforceService) that contains the
             * valid sessionId for our login credentials. To do this, the
             * client application creates a new SessionHeader object and persists it to
             * the SforceService. Add the session ID returned from the login to the
             * session header.
             */
            service.SessionHeaderValue           = new SessionHeader();
            service.SessionHeaderValue.sessionId = loginResult.sessionId;

            logger.DebugFormat("Successful login for {0}", _credentials.SalesforceLogin);

            return(service);
        }
Beispiel #29
0
        private SforceService Login(string username, string password, string token)
        {
            var binding = new SforceService();

            binding.Timeout = 60000; // 1 min

            LoginResult lr;

            lr = binding.login(username, password + token); // can throw SoapExeption

            if (lr.passwordExpired)
            {
                throw new AuthenticationException("Password Expired!");
            }

            binding.Url = lr.serverUrl;
            binding.SessionHeaderValue           = new SessionHeader();
            binding.SessionHeaderValue.sessionId = lr.sessionId;

            return(binding);
        }
        private bool Login(string username, string password, string securityToken)
        {
            try
            {
                using (SforceService service = new SforceService())
                {
                    LoginResult loginResult =
                        service.login(username, String.Concat(password, securityToken));

                    this.SessionID = loginResult.sessionId;
                    this.ServerUrl = loginResult.serverUrl;
                }

                return true;
            }
            catch (Exception excpt)
            {
                ErrorMessage = excpt.Message;
                return false;
            }
        }
Beispiel #31
0
        private static SforceService SalesForceSession()
        {
            string userName;
            string password;
            string SecurityToken;

            userName      = ConfigurationManager.AppSettings["SalesForceEmail"];
            password      = ConfigurationManager.AppSettings["SalesForcePassword"];
            SecurityToken = ConfigurationManager.AppSettings["SalesForceSecurityToken"];
            //password =  password+securityToken
            password = password + SecurityToken;//"786allah8SEZFhlgUY05CgtgmylgMR3m";
            SforceService SfdcBinding        = null;
            LoginResult   CurrentLoginResult = null;

            SfdcBinding = new SforceService();
            try
            {
                CurrentLoginResult = SfdcBinding.login(userName, password);
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                throw (e);
            }

            catch (Exception e)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                throw (e);
            }
            //Change the binding to the new endpoint
            SfdcBinding.Url = CurrentLoginResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            SfdcBinding.SessionHeaderValue           = new SessionHeader();
            SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
            return(SfdcBinding);
        }
    /// <summary>Page's load event</summary>
    /// <param name="sender">Loaded page</param>
    /// <param name="e">Event's arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["Navigation"] = null;
        if (this.Request.UserLanguages != null)
        {
            this.languageBrowser = this.Request.UserLanguages[0];
        }

        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls12;
        var           url     = ConfigurationManager.AppSettings["SalesForceUrl"].ToString();
        SforceService binding = new SforceService(url);

        try
        {
            var user        = ConfigurationManager.AppSettings["SalesForceUser"].ToString();
            var token       = ConfigurationManager.AppSettings["SalesForceToken"].ToString();
            var loginResult = binding.login(user, token);
            Session["SForceSessionId"] = loginResult.sessionId;
            Session["SForceWsUrl"]     = loginResult.serverUrl;
            binding.Url = loginResult.serverUrl;
            binding.SessionHeaderValue = new SessionHeader
            {
                sessionId = loginResult.sessionId
            };

            Session["SForceConnection"] = binding;
        }
        catch (Exception ex)
        {
            ExceptionManager.Trace(ex, "Salesforce login");
        }

        this.ip = this.GetUserIP();
        Session["ColectivosASPAD"]     = Colectivo.AllASPAD;
        Session["ColectivosASPADJson"] = Colectivo.JsonList(Session["ColectivosASPAD"] as ReadOnlyCollection <Colectivo>);
        Session["ProductosASPAD"]      = Producto.AllASPAD;
        Session["PreciosASPAD"]        = AspadLandFramework.Item.Acto.AllASPAD;
    }
Beispiel #33
0
        private void button2_Click(object sender, EventArgs e)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            string userName = "******";
            string password = "******";

            LoginResult CurrentLoginResult = null;

            try
            {
                CurrentLoginResult = SfdcBinding.login(userName, password);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                throw (ex);
            }
            catch (Exception ex)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                throw (ex);
            }
            if (CurrentLoginResult != null)
            {
                lblstatus.Text = "Connected as: " + CurrentLoginResult.userInfo.userFullName;
            }
            else
            {
                lblstatus.Text = "Connection failed!";
            }

            SfdcBinding.Url = CurrentLoginResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            SfdcBinding.SessionHeaderValue           = new SessionHeader();
            SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
        }
Beispiel #34
0
        loginToSalesforce(
            SalesforceCredentials sfCredentials,
            out LoginResult loginResult)
        {
            bool result = false;

            try
            {
                loginResult = salesforceServiceClient.login(
                    sfCredentials.UserName,
                    sfCredentials.Password + sfCredentials.SecurityToken);

                result = !string.IsNullOrEmpty(loginResult.sessionId) &&
                         !string.IsNullOrEmpty(loginResult.userId) &&
                         loginResult.userInfo != null;

                if (result)
                {
                    // assign the endpoint to the virtual server which serves for this application
                    string authenticationUri = salesforceServiceClient.Url;
                    salesforceServiceClient.Url = loginResult.serverUrl;

                    // set the session id in the header
                    salesforceServiceClient.SessionHeaderValue           = new SessionHeader();
                    salesforceServiceClient.SessionHeaderValue.sessionId = loginResult.sessionId;
                }
            }
            catch (Exception ex)
            {
                loginResult = null;
                logger.ErrorException(
                    "Salesforce login failed",
                    ex);
                result = false;
            }

            return(result);
        }
        /// <summary>
        /// For expeidency we are currently using:
        /// Usernmae: "*****@*****.**"
        /// Password: "******"
        /// Token: "hlY0jOIILtogz3sQlLUtmERlu"
        ///  combo: 8f9C3AyqhlY0jOIILtogz3sQlLUtmERlu
        /// We want to get an account assigned to us SPECIFICIALLY just for connecting to the API in the future.
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        private SforceService SalesforceLogin(string Username, string Password, string Token)
        {
            SforceService sfs = new SforceService();
            // Need to append password and security token together since we're logging in through the
            // Salesforce API
            string      passwordPlusSecurityToken = string.Format("{0}{1}", Password, Token);
            LoginResult loginResult;

            try
            {
                loginResult = sfs.login(Username, passwordPlusSecurityToken);
            }
            catch (SoapException ex)
            {
                // Write the fault code to the console
                Console.WriteLine(ex.Code);

                // Write the fault message to the console
                Console.WriteLine("An unexpected error has occurred: " + ex.Message);

                // Write the stack trace to the console
                Console.WriteLine(ex.StackTrace);

                // Return False to indicate that the login was not successful
                return(null);
            }
            //now that you are logged in you must change the url from login to the server
            sfs.Url = loginResult.serverUrl;
            //make readable from the outside
            _salesforceUrl = sfs.Url;

            //required so we can work with our session
            sfs.SessionHeaderValue           = new SessionHeader();
            sfs.SessionHeaderValue.sessionId = loginResult.sessionId;

            return(sfs);
        }
        /// <summary>
        /// For expeidency we are currently using:
        /// Usernmae: "*****@*****.**" 
        /// Password: "******" 
        /// Token: "hlY0jOIILtogz3sQlLUtmERlu"
        ///  combo: 8f9C3AyqhlY0jOIILtogz3sQlLUtmERlu
        /// We want to get an account assigned to us SPECIFICIALLY just for connecting to the API in the future.
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        private SforceService SalesforceLogin(string Username, string Password, string Token)
        {
            SforceService sfs = new SforceService();
            // Need to append password and security token together since we're logging in through the 
            // Salesforce API
            string passwordPlusSecurityToken = string.Format("{0}{1}", Password, Token);
            LoginResult loginResult;
            try
            {
                loginResult = sfs.login(Username, passwordPlusSecurityToken);
            }
            catch (SoapException ex)
            {
                // Write the fault code to the console 
                Console.WriteLine(ex.Code);

                // Write the fault message to the console 
                Console.WriteLine("An unexpected error has occurred: " + ex.Message);

                // Write the stack trace to the console 
                Console.WriteLine(ex.StackTrace);

                // Return False to indicate that the login was not successful 
                return null;
            }
            //now that you are logged in you must change the url from login to the server 
            sfs.Url = loginResult.serverUrl;
            //make readable from the outside
            _salesforceUrl = sfs.Url;

            //required so we can work with our session
            sfs.SessionHeaderValue = new SessionHeader();
            sfs.SessionHeaderValue.sessionId = loginResult.sessionId;

            return sfs;
        }
Beispiel #37
0
        private bool login()
        {
            Console.Write("Enter username: "******"Enter password: "******"password+securityToken";

            // Create a service object
            binding = new SforceService();

            // Timeout after a minute
            binding.Timeout = 60000;

            // Try logging in
            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;
            }

            // Check if the password has expired
            if (lr.passwordExpired)
            {
                Console.WriteLine("An error has occurred. Your password has expired.");
                return false;
            }

            /** Once the client application has logged in successfully, it will use
             * the results of the login call to reset the endpoint of the service
             * to the virtual server instance that is servicing your organization
             */
            // Save old authentication end point URL
            String authEndPoint = binding.Url;
            // Set returned service endpoint URL
            binding.Url = lr.serverUrl;

            /** The sample client application now has an instance of the SforceService
             * that is pointing to the correct endpoint. Next, the sample client
             * application sets a persistent SOAP header (to be included on all
             * subsequent calls that are made with SforceService) that contains the
             * valid sessionId for our login credentials. To do this, the sample
             * client application creates a new SessionHeader object and persist it to
             * the SforceService. Add the session ID returned from the login to the
             * session header
             */
            binding.SessionHeaderValue = new 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;
        }
		public void PreSend(List<DataForAPI> listToSend)
		{
			//			CreateNewJob();
			//
			//			AddBatchesToTheJob();

			try
			{
				var salesForceService = new SforceService();

				var userName = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.Login;
				var securityToken = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.SecurityToken;
				var password = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.Password + securityToken;

				var loginResult = salesForceService.login(userName, password);

				if (!loginResult.passwordExpired)
				{
					salesForceService.Url = loginResult.serverUrl;
					salesForceService.SessionHeaderValue = new SessionHeader { sessionId = loginResult.sessionId };

					var sObjectArraysList = RegularizeList(listToSend);
					foreach (var sObjectArray in sObjectArraysList)
					{
						var elqaMarketingActivityArray = CreateTransferObjectsArray(sObjectArray);
						var saveResults = salesForceService.create(elqaMarketingActivityArray);
						for (int i = 0; i < saveResults.Length; i++)
						{
							if (saveResults[i].success)
							{
								sObjectArray[i].DataBaseAccess.UpdateEntity(sObjectArray[i].SourceEntity, true, string.Empty);
							}
							else
							{
								sObjectArray[i].DataBaseAccess.UpdateEntity(sObjectArray[i].SourceEntity, false, saveResults[i].errors[0].statusCode + " " + saveResults[i].errors[0].message);
							}
							switch (sObjectArray[i].ProcessType)
							{
								case Enums.ProcessType.JPMarginCall:
									sObjectArray[i].DataBaseAccess.UpdateMarginCall(sObjectArray[i].SourceEntity);
									break;
								case Enums.ProcessType.JPInactivityDeletion:
									sObjectArray[i].DataBaseAccess.UpdateJapanInactivity(sObjectArray[i].SourceEntity);
									break;
								case Enums.ProcessType.AUHKMarginUtilization:
									sObjectArray[i].DataBaseAccess.UpdateHighMarginThresholdBreachesToEloqua(sObjectArray[i].SourceEntity);
									break;
							}
						}
					}
				}
				else
				{
					_logger.LogEvent(() => Config.AppEvents.GainWinServicesExactTarget.ExactTargetWarning, "Password Expired. Login: "******" Password: "******"SalesForceApi.PreSend " + e);
			}
		}