Exemple #1
0
        public async Task <IActionResult> OnPostImportAsync()
        {
            IsAuthenticated      = true;
            SalesForceCredential = new SalesForceCredential
            {
                InstanceUrl  = TempData.Peek("InstanceUrl") as string,
                RefreshToken = TempData.Peek("RefreshToken").ToString(),
                Token        = TempData.Peek("Token").ToString(),
                ApiVersion   = TempData.Peek("ApiVersion").ToString()
            };

            if (!QueryParams.Company && !QueryParams.Email && !QueryParams.Name)
            {
                ModelState.AddModelError("QueryParams.Name", "You must choose at least one search criteria.");
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (QueryParams.ImportFile.Length > 0)
            {
                Accounts = await _importService.Import(QueryParams, SalesForceCredential);

                return(_exportService.ExportResults(Accounts, Path.GetFileNameWithoutExtension(QueryParams.ImportFile.FileName)));
            }

            var lookupPerson = new Person();

            Accounts = await _lookup.LookupContact(QueryParams, lookupPerson, SalesForceCredential);

            return(Page());
        }
Exemple #2
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
                      };
            }
        }
Exemple #3
0
 public void OnGet()
 {
     if (TempData.Peek("Token") == null)
     {
         IsAuthenticated = false;
         ReturnUrl       =
             Common.FormatAuthUrl(
                 _config["Salesforce:AuthUrl"], // if using sandbox org then replace login with test
                 ResponseTypes.Code,
                 _config["Salesforce:ConsumerKey"],
                 HttpUtility.UrlEncode(_config["CallBackUrl"]),
                 DisplayTypes.Popup);
     }
     else
     {
         IsAuthenticated      = true;
         SalesForceCredential = new SalesForceCredential
         {
             InstanceUrl  = TempData.Peek("InstanceUrl") as string,
             RefreshToken = TempData.Peek("RefreshToken").ToString(),
             Token        = TempData.Peek("Token").ToString(),
             ApiVersion   = TempData.Peek("ApiVersion").ToString()
         };
     }
 }
 /// <summary>
 /// Cancel the edit.
 /// </summary>
 /// <param name="sender">Object that raised the event.</param>
 /// <param name="e">Event arguments.</param>
 private void buttonCancel_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         _credential  = null;
         DialogResult = false;
         Close();
     }
     catch (Exception err)
     {
         App.HandleException(err);
     }
 }
Exemple #5
0
        /// <summary>
        /// Create a new local project.
        /// </summary>
        public override void Execute()
        {
            SalesForceCredential credential = null;

            // get credentials for new project.
            EditSalesForceCredentialWindow dlg = new EditSalesForceCredentialWindow();

            dlg.Title = "New Project";
            while (App.ShowDialog(dlg))
            {
                try
                {
                    using (App.Wait("Verifying credentials..."))
                    {
                        credential = dlg.Credential;
                        SalesForceClient.TestLogin(credential);
                    }
                    break;
                }
                catch (Exception err)
                {
                    App.MessageUser(err.Message, "Login Failed", MessageBoxImage.Error, new string[] { "OK" });

                    dlg            = new EditSalesForceCredentialWindow();
                    dlg.Title      = "New Project";
                    dlg.Credential = credential;
                }
            }

            // create the new project or open an existing project that has the same credentials
            if (credential != null)
            {
                Project project = null;
                if (Project.ProjectExists(credential.Username))
                {
                    project            = Project.OpenProject(credential.Username);
                    project.Credential = credential;
                }
                else
                {
                    project = new Project(credential);
                }

                project.Save();

                App.Instance.SalesForceApp.OpenProject(project);
            }
        }
        public SalesForceCredential Create()
        {
            try
            {
                var configurationFileUrl = Helper.Instance.SystemFileURI(ConfigurationFileName);

                if (File.Exists(configurationFileUrl))
                {
                    byte[] decryptedFileBytes = null;
                    MMEncrypt.Instance.Decrypt(configurationFileUrl, EncryptAttributes.Instance.Password, ref decryptedFileBytes);

                    var xmlFileContent = Encoding.Default.GetString(decryptedFileBytes);

                    if (xmlFileContent.IndexOf('<') == -1)
                    {
                        throw new Exception("Credentials file missing the xml start tag");
                    }

                    int startIndex = xmlFileContent.IndexOf('<');
                    int length     = xmlFileContent.LastIndexOf('>') + 1 - startIndex;
                    xmlFileContent = xmlFileContent.Substring(startIndex, length);

                    var xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(xmlFileContent);

                    var salesForceCredential = new SalesForceCredential
                    {
                        UserName      = "******",
                        Password      = "******",        //"Menu1203mate@SF",
                        SecurityToken = "oLbdKUyN9j6k9T15ocIx4ZZz" // "JAznA5075w7OdVZG8UTTztUyt"
                    };

                    return(salesForceCredential);
                }
                //return null;
            }
            catch (Exception exception)
            {
                ServiceLogger.LogException("Exception in UpdateSalesForceVersion", exception);
            }
            return(null);
        }
        /// <summary>
        /// Save the edit.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ValidateUserInput())
                {
                    _credential = new SalesForceCredential(
                        Domain,
                        Username,
                        Password,
                        Token);

                    DialogResult = true;
                    Close();
                }
            }
            catch (Exception err)
            {
                App.HandleException(err);
            }
        }
Exemple #8
0
        /// <summary>
        /// Open the project with the given name.
        /// </summary>
        /// <param name="projectName">The name of the project to open.</param>
        /// <returns>The project with the given name.</returns>
        public static Project OpenProject(string projectName)
        {
            if (String.IsNullOrWhiteSpace(projectName))
            {
                throw new ArgumentException("projectName is null or whitespace.", "projectName");
            }

            string fileName = Path.Combine(ROOT_FOLDER, projectName);

            fileName = Path.Combine(fileName, String.Format("{0}.sfdcProject", projectName));
            if (!File.Exists(fileName))
            {
                throw new Exception("Couldn't find project: " + projectName);
            }

            XmlReaderSettings xmlSettings = new XmlReaderSettings();

            xmlSettings.IgnoreComments   = true;
            xmlSettings.IgnoreWhitespace = true;

            Project project = null;

            using (FileStream stream = File.OpenRead(fileName))
            {
                using (XmlReader xml = XmlReader.Create(stream, xmlSettings))
                {
                    if (!xml.ReadToFollowing("project"))
                    {
                        throw new Exception("Invalid xml.  No 'project' element found.");
                    }

                    if (!xml.ReadToDescendant("credential"))
                    {
                        throw new Exception("Invalid xml.  No 'credential' element found.");
                    }

                    CryptoContainer <SalesForceCredential> cryptoCredential = new CryptoContainer <SalesForceCredential>();
                    cryptoCredential.ReadXml(xml);
                    SalesForceCredential credential = cryptoCredential.GetData(PROJECT_PASSWORD);

                    SimpleRepository repository = null;
                    if (xml.IsStartElement("repository"))
                    {
                        CryptoContainer <SimpleRepository> cryptoRepository = new CryptoContainer <SimpleRepository>();
                        cryptoRepository.ReadXml(xml);
                        repository = cryptoRepository.GetData(PROJECT_PASSWORD);
                    }

                    xml.Close();

                    project = new Project(credential);

                    if (repository != null)
                    {
                        repository.WorkingPath = project.RepositoryFolder;
                        project.Repository     = repository;
                    }
                }

                stream.Close();
            }

            return(project);
        }
Exemple #9
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="credential">The credential for the project.</param>
        public Project(SalesForceCredential credential)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            Credential    = credential;
            ProjectFolder = Path.Combine(ROOT_FOLDER, credential.Username);
            ProjectFile   = Path.Combine(ProjectFolder, String.Format("{0}.sfdcProject", credential.Username));

            DeployFolder = Path.Combine(ProjectFolder, "Deploy");
            if (!Directory.Exists(DeployFolder))
            {
                Directory.CreateDirectory(DeployFolder);
            }

            ManifestFolder = Path.Combine(DeployFolder, "Manifest");
            if (!Directory.Exists(ManifestFolder))
            {
                Directory.CreateDirectory(ManifestFolder);
            }
            UpgradeManifestFiles();

            PackageFolder = Path.Combine(DeployFolder, "Package");
            if (!Directory.Exists(PackageFolder))
            {
                Directory.CreateDirectory(PackageFolder);
            }

            SymbolsFolder = Path.Combine(ProjectFolder, "Symbols");
            if (!Directory.Exists(SymbolsFolder))
            {
                Directory.CreateDirectory(SymbolsFolder);
            }

            SnippetsFolder = Path.Combine(ProjectFolder, "Snippets");
            if (!Directory.Exists(SnippetsFolder))
            {
                Directory.CreateDirectory(SnippetsFolder);
            }

            RepositoryFolder = Path.Combine(ProjectFolder, "Repository");
            if (!Directory.Exists(RepositoryFolder))
            {
                Directory.CreateDirectory(RepositoryFolder);
            }

            Repository             = new SimpleRepository();
            Repository.WorkingPath = RepositoryFolder;

            SearchFolder = Path.Combine(ProjectFolder, "Search");
            if (!Directory.Exists(SearchFolder))
            {
                Directory.CreateDirectory(SearchFolder);
            }

            Language = new LanguageManager(SymbolsFolder);

            _symbolsDownloaded = new EventWaitHandle(true, EventResetMode.ManualReset);
        }
        /// <summary>
        /// Open a new project.
        /// </summary>
        /// <param name="project">The project to open.</param>
        public void OpenProject(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            // check for existing project
            if (CurrentProject != null)
            {
                if (App.MessageUser("The current project must be closed before opening a new one.  Do you want to close the current project?",
                                    "Close Project",
                                    MessageBoxImage.Warning,
                                    new string[] { "Yes", "No" }) != "Yes")
                {
                    return;
                }

                CloseProject();
            }

            // test the credential
            SalesForceCredential credential = project.Credential;

            while (true)
            {
                try
                {
                    using (App.Wait("Verifying credentials..."))
                        SalesForceClient.TestLogin(credential);

                    using (App.Wait("Initializing project..."))
                    {
                        project.Repository.AuthorName  = project.Client.User.Name;
                        project.Repository.AuthorEmail = project.Client.UserEmail;
                        project.LoadSymbolsAsync(false);
                    }

                    break;
                }
                catch (Exception err)
                {
                    App.MessageUser(err.Message, "Login Failed", MessageBoxImage.Error, new string[] { "OK" });

                    EditSalesForceCredentialWindow dlg = new EditSalesForceCredentialWindow();
                    dlg.Credential = credential;
                    dlg.Title      = "Enter credentials";

                    if (!App.ShowDialog(dlg))
                    {
                        return;
                    }

                    credential         = dlg.Credential;
                    project.Credential = credential;
                    project.Save();
                }
            }

            // open the project
            using (App.Wait("Opening project..."))
            {
                CurrentProject            = project;
                App.Instance.SessionTitle = project.Credential.Username;

                App.Instance.Navigation.Nodes.Add(new SourceFolderNode(project));
                App.Instance.Navigation.Nodes.Add(new DataFolderNode(project));
                App.Instance.Navigation.Nodes.Add(new LocalFolderNode(project));

                App.Instance.Menu.UpdateFunctions();
                App.Instance.ToolBar.UpdateFunctions();

                App.Instance.GetFunction <InsertSnippetContainerFunction>().Refresh(App.Instance.Menu);
            }
        }
Exemple #11
0
        public async Task <List <Person> > Import(QueryParameters queryParameters, SalesForceCredential sfdcCredential)
        {
            //Get file
            var newFile = new FileInfo(queryParameters.ImportFile.FileName);

            //Establish import and error objects
            var importObj = new List <Person>();

            //Check if file is an Excel File
            if (!newFile.Extension.Contains(".xls"))
            {
                throw new Exception("File must be in Excel format.");
            }

            //Create an excel package
            using (var package = new ExcelPackage(queryParameters.ImportFile.OpenReadStream()))
            {
                //Get the first worksheet in the file
                var worksheet = package.Workbook.Worksheets.First();

                //Set rowcount, colcount and variables for the required columns
                var rowCount         = worksheet.Dimension.Rows;
                var colCount         = worksheet.Dimension.Columns;
                var emailColumn      = 0;
                var companyColumn    = 0;
                var firstNameColumn  = 0;
                var lastNameColumn   = 0;
                var nameColumn       = 0;
                var titleColumn      = 0;
                var unsubColumn      = 0;
                var searchByFullName = false;
                //Loop through columns to identify the column number for each of the required columns
                for (var col = 1; col <= colCount; col++)
                {
                    var columnValue = Convert.ToString(worksheet.Cells[1, col].Value);
                    if (columnValue.ToLower().Contains("first"))
                    {
                        firstNameColumn = col;
                    }
                    else if (columnValue.ToLower().Contains("last"))
                    {
                        lastNameColumn = col;
                    }
                    else if (columnValue.ToLower().Contains("name"))
                    {
                        nameColumn       = col;
                        searchByFullName = true;
                    }
                    else if (columnValue.ToLower().Contains("email"))
                    {
                        emailColumn = col;
                    }
                    else if (columnValue.ToLower().Contains("company"))
                    {
                        companyColumn = col;
                    }
                    else if (columnValue.ToLower().Contains("title"))
                    {
                        titleColumn = col;
                    }
                    else if (columnValue.ToLower().Contains("unsubscribe"))
                    {
                        unsubColumn = col;
                    }
                }

                //Loop through the rows of the worksheet, skipping row 1 (header row)
                for (var row = 2; row <= rowCount; row++)
                {
                    //If first field is blank exit the for loop
                    if (worksheet.Cells[row, 1].Value == null)
                    {
                        break;
                    }

                    //Create temporary person object
                    var lookupPerson = new Person
                    {
                        LookupEmail       = worksheet.Cells[row, emailColumn].Value != null ? worksheet.Cells[row, emailColumn].Value.ToString() : "",
                        LookupAccountName = worksheet.Cells[row, companyColumn].Value == null ? "" : worksheet.Cells[row, companyColumn].Value.ToString()
                    };

                    if (titleColumn > 0)
                    {
                        lookupPerson.LookupTitle = worksheet.Cells[row, titleColumn].Value == null
                            ? ""
                            : worksheet.Cells[row, titleColumn].Value.ToString();
                    }
                    if (unsubColumn > 0)
                    {
                        lookupPerson.LookupOptOut = worksheet.Cells[row, unsubColumn].Value != null;
                    }

                    if (searchByFullName)
                    {
                        lookupPerson.LookupName = worksheet.Cells[row, nameColumn].Value != null ? worksheet.Cells[row, nameColumn].Value.ToString() : "";
                    }
                    else
                    {
                        lookupPerson.LookupFirst = worksheet.Cells[row, firstNameColumn].Value != null ? worksheet.Cells[row, firstNameColumn].Value.ToString() : "";
                        lookupPerson.LookupLast  = worksheet.Cells[row, lastNameColumn].Value != null ? worksheet.Cells[row, lastNameColumn].Value.ToString() : "";
                        lookupPerson.LookupName  = $"{lookupPerson.LookupFirst} {lookupPerson.LookupLast}";
                    }

                    var personResult = await _lookup.LookupContact(queryParameters, lookupPerson, sfdcCredential);

                    if (personResult != null && personResult.Count > 0)
                    {
                        foreach (var found in personResult)
                        {
                            var obu = string.IsNullOrWhiteSpace(found.Originating_Business_Unit__c)
                                ? "No OBU"
                                : found.Originating_Business_Unit__c;

                            var foundPerson = new Person
                            {
                                Name                  = found.Name,
                                Email                 = found.Email,
                                AccountId             = $"{found.AccountId}",
                                AccountName           = $"{found.AccountName} ({found.AccountId})",
                                CompanyNameMatchCount = personResult.Count,
                                Id = $"{found.Id}",
                                Originating_Business_Unit__c = $"{obu}",
                                Direct_Phone__c      = $"{found.Direct_Phone__c}",
                                Email_Invalid__c     = found.Email_Invalid__c,
                                HasOptedOutOfEmail   = found.HasOptedOutOfEmail,
                                Industry_Vertical__c = $"{found.Industry_Vertical__c}",
                                LeadSource           = $"{found.LeadSource}",
                                Title             = $"{found.Title}",
                                Description       = $"{found.Description}",
                                LookupName        = lookupPerson.LookupName,
                                LookupFirst       = lookupPerson.LookupFirst,
                                LookupLast        = lookupPerson.LookupLast,
                                LookupEmail       = lookupPerson.LookupEmail,
                                LookupAccountName = lookupPerson.LookupAccountName,
                                LookupTitle       = lookupPerson.LookupTitle,
                                LookupOptOut      = lookupPerson.LookupOptOut
                            };

                            importObj.Add(foundPerson);
                        }
                    }
                    else
                    {
                        var notFoundPerson = new Person
                        {
                            Name                         = lookupPerson.Name,
                            Email                        = lookupPerson.Email,
                            Id                           = "NOT FOUND",
                            CompanyNameMatch             = false,
                            NameMatch                    = false,
                            EmailMatch                   = false,
                            AccountId                    = "",
                            AccountName                  = lookupPerson.AccountName,
                            CompanyNameMatchCount        = 0,
                            Originating_Business_Unit__c = "NONE",
                            Direct_Phone__c              = "",
                            Email_Invalid__c             = false,
                            HasOptedOutOfEmail           = lookupPerson.HasOptedOutOfEmail,
                            Industry_Vertical__c         = "",
                            LeadSource                   = "",
                            Title                        = lookupPerson.Title,
                            Description                  = "",
                            LookupName                   = lookupPerson.LookupName,
                            LookupFirst                  = lookupPerson.LookupFirst,
                            LookupLast                   = lookupPerson.LookupLast,
                            LookupEmail                  = lookupPerson.LookupEmail,
                            LookupAccountName            = lookupPerson.LookupAccountName,
                            LookupTitle                  = lookupPerson.LookupTitle,
                            LookupOptOut                 = lookupPerson.LookupOptOut
                        };
                        importObj.Add(notFoundPerson);
                    }
                } // End For Loop
                return(importObj);
            }
        }
Exemple #12
0
        public async Task <List <Person> > LookupContact(QueryParameters queryParams, Person lookupPerson, SalesForceCredential sfdCredential)
        {
            var client = new ForceClient(sfdCredential.InstanceUrl, sfdCredential.Token,
                                         sfdCredential.ApiVersion);

            var lookupEmail = lookupPerson.LookupEmail.Replace("'", @"\'");

            var query  = "SELECT id, name, email, AccountId, Account.Name, Direct_Phone__c, Email_Invalid__c, HasOptedOutOfEmail, Industry_Vertical__c, LeadSource, Title, Description, Originating_Business_Unit__c FROM Contact";
            var useAnd = false;

            if (queryParams != null)
            {
                if (queryParams.Name)
                {
                    useAnd = true;
                    query  = $"{query} WHERE name LIKE '%{lookupPerson.LookupName}%'";
                }

                if (queryParams.Email)
                {
                    if (useAnd)
                    {
                        query = $"{query} AND email LIKE '%{lookupEmail}%'";
                    }
                    else
                    {
                        useAnd = true;
                        query  = $"{query} WHERE email LIKE '%{lookupEmail}%'";
                    }
                }

                if (queryParams.Company)
                {
                    if (useAnd)
                    {
                        query = $"{query} AND Account.Name LIKE '%{lookupPerson.LookupAccountName}%'";
                    }
                    else
                    {
                        useAnd = true;
                        query  = $"{query} WHERE Account.Name LIKE '%{lookupPerson.LookupAccountName}%'";
                    }
                }

                if (!string.IsNullOrWhiteSpace(queryParams.Obu))
                {
                    if (useAnd)
                    {
                        query = $"{query} AND Originating_Business_Unit__c = '{queryParams.Obu}'";
                    }
                    else
                    {
                        //useAnd = true;
                        query = $"{query} WHERE Originating_Business_Unit__c = '{queryParams.Obu}'";
                    }
                }
            }

            query = $"{query} ORDER BY name";
            var contacts = await client.QueryAsync <Person>(query);

            foreach (var c in contacts.Records)
            {
                if (string.IsNullOrWhiteSpace(c.AccountId))
                {
                    continue;
                }

                var accountQuery = $"SELECT id, name FROM Account WHERE id = '{c.AccountId}'";
                var account      = await client.QueryAsync <Account>(accountQuery);

                c.AccountName = account.Records.First().Name;
            }
            return(contacts.Records);
        }