예제 #1
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;
        }
예제 #2
0
        public static void UpdateLastTextDate(SforceService _binding, string LeadID)
        {
            Dealer_Lead__c application = new Dealer_Lead__c();

            application.Id = LeadID;
            application.BRGCaseMail_DateTime_Last_Text__c          = DateTime.Now;
            application.BRGCaseMail_DateTime_Last_Text__cSpecified = true;
            application.BRGCaseMail_Number_Texts_Sent__c           = application.BRGCaseMail_Number_Texts_Sent__c + 1;
            application.BRGCaseMail_Number_Texts_Sent__cSpecified  = true;

            if (application.BRGCaseMail_Number_Texts_Sent__c != null)
            {
                application.BRGCaseMail_Number_Texts_Sent__c += 1;
            }
            else
            {
                application.BRGCaseMail_Number_Texts_Sent__c = 1;
            }

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { application });
        }
예제 #3
0
        public static SalesForceWebReference.Account getBRGCaseMailAccount(SforceService _binding, string UserID, string Password)
        {
            QueryResult qr = null;

            //SalesForceWebReference.Account _account;

            ////qr = _binding.query("select Id, Account__c, Name, FirstName__c, LastName__c, CreatedDate from  from Dealer_Lead_c");

            qr = _binding.query(_accountQuery + " where BRGCaseMail_Password__c = '" + Password + "' and BRGCaseMail_User_ID__c = '" + UserID + "'");

            //List<Account> _accounts = new List<Account>();

            if (qr.records != null)
            {
                if (qr.records.Length > 0)
                {
                    return((Account)qr.records[0]);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
        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);
                }
            }
        }
예제 #5
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
            };
        }
예제 #6
0
        public static List <SalesForceWebReference.Dealer_Lead__c> getApplications(SforceService _binding, string AccountId, string LastName)
        {
            QueryResult qr = null;

            //SalesForceWebReference.Account _account;

            ////qr = _binding.query("select Id, Account__c, Name, FirstName__c, LastName__c, CreatedDate from  from Dealer_Lead_c");

            string _query2 = _appQuery + " where Account__c = '" + AccountId + "' and Name like '%" + LastName + "%' and BRGCaseMail_OK_to_send__c = true  order by CreatedDate desc";

            qr = _binding.query(_query2);

            List <Dealer_Lead__c> _applications = new List <Dealer_Lead__c>();

            if (qr.records != null)
            {
                for (int i = 0; i < qr.records.Length; i++)
                {
                    _applications.Add(((Dealer_Lead__c)qr.records[i]));

                    //Debug.WriteLine(((Account)qr.records[i]).Name);
                }
            }

            return(_applications);
        }
 public void Teardown()
 {
     credentialProvider = null;
     sfClient           = null;
     credentials        = null;
     result             = null;
 }
예제 #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");
            }
        }
예제 #9
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
        }
예제 #10
0
 public void LoginIfRequired()
 {
     if (_binding == null)
     {
         _binding = _salesforceSession.Login();
     }
 }
예제 #11
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);
            }
        }
예제 #12
0
        public void UpateSalesForceLead(Lead lead)
        {
            SforceService SfdcBinding = SalesForceSession();
            Lead          sfdcLead    = new Lead();

            sfdcLead = lead;
            try
            {
                //Campaign compaign = new Campaign();
                //compaign.Name="IndiaHicks";
                //sfdcLead.c = compaign;

                SaveResult[] saveResults = SfdcBinding.update(new sObject[] { sfdcLead });
                if (saveResults[0].success)
                {
                    string Id = "";
                    Id = saveResults[0].id;
                }
                else
                {
                    string result = "";
                    result = saveResults[0].errors[0].message;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #13
0
        public int SalesForceLeadsCount(String FirstLastName)
        {
            try
            {
                QueryResult qr = new QueryResult();

                int       Leadcount = 0;
                DataTable dt        = new DataTable();
                using (var PubsConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["IHCharity"].ConnectionString.ToString()))
                {
                    SqlCommand testCMD = new SqlCommand("SalesForceBannerLeadFlag", PubsConn);
                    testCMD.CommandType = CommandType.StoredProcedure;
                    testCMD.Parameters.Add(new SqlParameter("@Name", FirstLastName));
                    PubsConn.Open();
                    SqlDataReader myReader = testCMD.ExecuteReader();
                    dt.Load(myReader);
                    PubsConn.Close();
                }
                if (dt.Rows.Count == 0)
                {
                    SforceService SfdcBinding     = SalesForceSession();
                    int           SalesForcecount = 0;
                    string        strQuery        = ("SELECT Id from Lead where Sponsor__c ='" + FirstLastName + "'");
                    qr = SfdcBinding.query(strQuery);
                    SalesForcecount = qr.records.Count();
                    if (SalesForcecount > 0)
                    {
                        using (var PubsConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["IHCharity"].ConnectionString.ToString()))
                        {
                            SqlCommand testCMD = new SqlCommand("InsertSalesForceLeadCount", PubsConn);
                            testCMD.CommandType = CommandType.StoredProcedure;
                            testCMD.Parameters.Add(new SqlParameter("@Name", FirstLastName));
                            testCMD.Parameters.Add(new SqlParameter("@Count", SalesForcecount));
                            PubsConn.Open();

                            SqlDataReader myReader = testCMD.ExecuteReader();
                            dt = new DataTable();
                            dt.Load(myReader);

                            PubsConn.Close();
                            foreach (DataRow row in dt.Rows)
                            {
                                Leadcount = int.Parse(row["Leads"].ToString());
                            }
                            return(Leadcount);
                        }
                    }
                    return(SalesForcecount);
                }
                foreach (DataRow row in dt.Rows)
                {
                    Leadcount = int.Parse(row["CountDiffernece"].ToString());
                }
                return(Leadcount);
            }
            catch (Exception)
            {
                return(0);
            }
        }
예제 #14
0
        public void CreateSalesForceQualifiedAmbassador(Ambassador__c QualifiedAmbassador)
        {
            SforceService SfdcBinding = SalesForceSession();

            try
            {
                //Campaign compaign = new Campaign();
                //compaign.Name="IndiaHicks";
                //sfdcLead.c = compaign;

                SaveResult[] saveResults = SfdcBinding.create(new sObject[] { QualifiedAmbassador });
                if (saveResults[0].success)
                {
                    string Id = "";
                    Id = saveResults[0].id;
                }
                else
                {
                    string result = "";
                    result = saveResults[0].errors[0].message;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #15
0
        public string GetSalesForceQualifiedAmbassadorsID(string Sponsorid = "")
        {
            QueryResult   qr          = new QueryResult();
            string        Ambassador  = string.Empty;
            SforceService SfdcBinding = SalesForceSession();

            try
            {
                string strQuery = (@"select id from Ambassador__c where AmbassadorID__c ='" + Sponsorid + "'");
                qr = SfdcBinding.query(strQuery);
                Common.SforceServices.sObject[] records = qr.records;
                if (records != null)
                {
                    foreach (Ambassador__c node in records)
                    {
                        Ambassador = node.Id;
                        break;
                    }
                }
                return(Ambassador);
            }
            catch (Exception)
            {
                return(Ambassador);
            }
        }
예제 #16
0
        public QueryResult GetSalesForceQualifiedAmbassadorslist(string whereClause = "")
        {
            QueryResult   qr          = new QueryResult();
            SforceService SfdcBinding = SalesForceSession();

            try
            {
                if (!string.IsNullOrEmpty(whereClause))
                {
                    whereClause = whereClause.Replace("QualifiedAmbassadorID", "AmbassadorID__c");
                    whereClause = whereClause.Replace("ReceivedLeads", "Available_To_Receive_Leads__c");
                    whereClause = whereClause.Replace("Zip", "Zip_Code__c");
                    whereClause = whereClause.Replace("Email", "Q_Ambassador_Email__c");
                    whereClause = whereClause.Replace("Mobile", "Mobile_Phone__c");
                    whereClause = whereClause.Replace("Phone", "Phone__c");
                    whereClause = whereClause.Replace("Sponsorid", "SponsorID__c");
                    whereClause = whereClause.Replace("LeaveDate", "LeaveDate__c");
                    whereClause = whereClause.Replace("JoinDate", "JoinDate__c");
                    whereClause = whereClause.Replace("''", "'");
                }
                string strQuery = (@"select id, Name, AmbassadorID__c, Mobile_Phone__c, Phone__c,JoinDate__c,LeaveDate__c, SponsorID__c, Q_Ambassador_Email__c, Zip_Code__c, Available_To_Receive_Leads__c, CreatedById from Ambassador__c where id !='' " + whereClause + @" order by AmbassadorID__c ");
                qr = SfdcBinding.query(strQuery);
                return(qr);
            }
            catch (Exception)
            {
                return(qr);
            }
        }
예제 #17
0
		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);
			}
		}
예제 #18
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);
        }
예제 #19
0
        public static List <SalesForceWebReference.Account> getAccounts(SforceService _binding, string Id, string DealerName, bool ActiveOnly)
        {
            QueryResult qr = null;

            //SalesForceWebReference.Account _account;

            ////qr = _binding.query("select Id, Account__c, Name, FirstName__c, LastName__c, CreatedDate from  from Dealer_Lead_c");
            string query = _accountQuery;

            if (DealerName.Length > 0 || Id.Length > 0 || ActiveOnly == true)
            {
                query += " Where ";

                if (DealerName.Length > 0)
                {
                    query += " Name like '%" + DealerName + "%' ";

                    if (Id.Length > 0)
                    {
                        query += " AND Id = '" + Id + "' ";
                    }
                    if (ActiveOnly)
                    {
                        query += " AND BRGCaseMail_Active__c = true";
                    }
                }
                else if (Id.Length > 0)
                {
                    query += " Id = '" + Id + "' ";

                    if (ActiveOnly)
                    {
                        query += " AND BRGCaseMail_Active__c = true";
                    }
                }
                else if (ActiveOnly)
                {
                    query += " BRGCaseMail_Active__c = true ";
                }
            }

            query += " order by Name asc";

            qr = _binding.query(query);

            List <Account> _accounts = new List <Account>();

            if (qr.records != null)
            {
                for (int i = 0; i < qr.records.Length; i++)
                {
                    _accounts.Add(((Account)qr.records[i]));

                    //Debug.WriteLine(((Account)qr.records[i]).Name);
                }
            }
            return(_accounts);
        }
예제 #20
0
 /// <summary>
 /// constructor for credential provider
 /// </summary>
 internal Salesforce_credential_provider()
 {
     // initialize the service client
     this.salesforceServiceClient = new SforceService();
     logger            = LogManager.GetLogger("Trace");
     trineoCredentials = new Credentials();
     sfCredentials     = new SalesforceCredentials();
     sfLoginResult     = null;
 }
예제 #21
0
파일: Program.cs 프로젝트: ngoloc/NWEA
        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();
        }
예제 #22
0
 public SalesForceInterface()
 {
     _loginResult                   = null;
     _salesforceService             = new SforceService();
     _accountToPocketVoucherMapper  = new AccountToPocketVoucherMapper();
     _accountFieldsMapper           = new AccountFieldsMapper();
     _salesForceCommunicationHelper = new SalesForceCommunicationHelper(_salesforceService);
     ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return(true); };
 }
예제 #23
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);
            }
        }
예제 #24
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);
        }
        //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);
            }
        }
예제 #27
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);
        }
        public ODataEntitySelect(ODataClientSettings settings, ODataClient client, SforceService SFDCBinding)
        {
            partNumber = 1;
            InitializeComponent();
            this.settings    = settings;
            this.client      = client;
            this.SFDCBinding = SFDCBinding;

            //Set baseURL Configured in previous step
            txtBaseURL.Text = settings.BaseUri.ToString();
        }
예제 #29
0
        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;
        }
예제 #30
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);
        }
예제 #31
0
        private Salesforce.Helpers.sForceService.SforceService sfLogin(String sfUserID, String sfUserPwd)
        {
            bool reqlogin = true;

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            Salesforce.Helpers.sForceService.SforceService binding;

            // Create a service object if needed
            if (_binding == null)
            {
                binding  = new SforceService();
                reqlogin = true;
            }
            else
            {
                reqlogin = false;
                binding  = _binding;
                try
                {
                    GetUserInfoResult result = binding.getUserInfo();
                }
                catch (SoapException uef)
                {
                    //                 if (uef.ExceptionCode == ExceptionCode.INVALID_SESSION_ID)
                    {
                        reqlogin = true;
                    }
                }
            }
            if (reqlogin)
            {
                LoginResult lr;
                lr = binding.login(sfUserID, sfUserPwd);

                /**
                 * The login results contain the endpoint of the virtual server instance
                 * that is servicing your organization. Set the URL of the binding
                 * to this endpoint.
                 */
                // Save old authentication end point URL
                String authEndPoint = binding.Url;
                // Set returned service endpoint URL
                binding.Url = lr.serverUrl;

                /** Get the session ID from the login result and set it for the
                 * session header that will be used for all subsequent calls.
                 */
                binding.SessionHeaderValue           = new SessionHeader();
                binding.SessionHeaderValue.sessionId = lr.sessionId;
                _binding = binding;
            }
            return(binding);
        }
 public SalesforceManager(string Username, string Password, string Token)
 {
     //setting up our class level sForceService
     _sfs = SalesforceLogin(Username, Password, Token);
     if (_sfs == null)
     {
         LoggedIn = false;
     }
     else
     {
         LoggedIn = true;
     }
 }
 public SalesforceManager(string Username, string Password, string Token)
 {
     //setting up our class level sForceService 
     _sfs = SalesforceLogin(Username, Password, Token);
     if (_sfs == null)
     {
         LoggedIn = false;
     }
     else
     {
         LoggedIn = true;
     }
 }
예제 #34
0
        public static void ChangePassword(SforceService _binding, string Id, string NewPassword)
        {
            Account _account = new Account();

            _account.Id = Id;
            _account.BRGCaseMail_Password__c = NewPassword;

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { _account });
        }
예제 #35
0
        public void UpdateLeadEvent(Common.SforceServices.Event evnt)
        {
            SforceService SfdcBinding = SalesForceSession();

            SaveResult[] results = null;
            try
            {
                results = SfdcBinding.update(new Event[] {
                    evnt
                });
            }
            catch (Exception ce)
            {
            }
        }
예제 #36
0
        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;
            }
        }
        /// <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;
        }
		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);
			}
		}
예제 #39
0
 public BridgeFactory(SforceService svc)
 {
     _svc = svc;
 }
예제 #40
0
        private static void loginToSF(string userName, string password)
        {
            try
            {
                if (sforceSvc == null)
                {
                    sforceSvc = new SforceService();
                }

                loginResult = sforceSvc.login(userName, password);

                if (loginResult != null)
                {
                    sforceSvc.Url = loginResult.serverUrl;

                    SessionHeader sessionHeader = new SessionHeader();

                    sessionHeader.sessionId = loginResult.sessionId;

                    sforceSvc.SessionHeaderValue = sessionHeader;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error logging in to Salesforce.com   Error: {0}\nInnerException: {1}",
                    ex.Message,
                    ex.InnerException != null ? ex.InnerException.Message : string.Empty);
            }
        }
예제 #41
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;
        }