Apex test method error - testing

we are having an issue with apex test method. we have an http request in my apex method. i have to creates a test method for this. but we are having an issue
Apex code:
public void ReceiveBestAnswer(Id repID){
reply = GlobalFunctions.getReplyCreatorDetails(repID);
System.debug(reply);
String bestReplyUser = reply.CreatedById;
profileUser = [select Username,Email from User where Id = :bestReplyUser];
System.debug('profileUser.Name-->'+profileUser.Username);
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://sandbox.v2.badgeville.com/api/berlin/b95839370dca983955e550296450ec03/activities.json');
req.setMethod('GET');
req.setBody('activity[verb]=receive best answer&site=www.grazitti.com&user='+ profileUser.Email );
try {
http.send(req);
System.debug('res-->');
} catch(System.CalloutException e) {
System.debug('Callout error: '+ e);
System.debug(res.toString());
}
}
Test method :
public static testMethod void testReceiveBestAnswer() {
Reply reply = new Reply();
String replyId = reply[0].Id;
// Id questionID = '906P0000000010KIAQ';
// String sql = 'SELECT Id, Title FROM Question';
// Question[] ques = [SELECT Id FROM Question];
// Question quest = ques[0];
BadgeVilleWebServiceCallout bv = new BadgeVilleWebServiceCallout();
bv.badgvilleReceiveBestAnswer(replyId );
}
2nd test method:
public static testmethod void testReceiveBestAnswer1()
{
ID ProfileID = [ Select id from Profile where name = 'Named Marketo Community Portal'].id;
System.debug('ProfileID --->'+ProfileID );
Account A1 = new Account(Name = 'Test Account');
insert A1;
List<Contact> ContactList = new List<Contact>();
Contact C1 = new Contact( AccountID = A1.id, FirstName = 'Test', LastName = 'User',
email = 'test-user#fakeemail.com' );
insert C1;
User u1 = new User( email='test-user#fakeemail.com', contactid = c1.id, profileid = profileid,
UserName='test-user#fakeemail.com', alias='tuser1', CommunityNickName='tuser1', TimeZoneSidKey='America/New_York', LocaleSidKey='en_US', EmailEncodingKey='ISO-8859-1', LanguageLocaleKey='en_US', FirstName = 'Test', LastName = 'User' );
insert u1;
System.debug('u1--->'+u1 );
/* User[] users = [SELECT Id FROM User];
User u1 = users[0];
// Question[] ques = [SELECT Id FROM Question];
//System.debug('ques --->'+ques );
// Question quest = ques[0];
// BadgeVilleWebServiceCallout bv = new BadgeVilleWebServiceCallout();
// bv.badgvilleReceiveBestAnswer(quest.Id);
Id questId ;
Test.startTest();
System.RunAs(u1)
{
Question question = new Question();
question.Title = 'Test';
question.Body = 'Test';
question.CommunityId = '09a50000000PNNr';//GlobalFunctions.communityId;
insert question;
System.debug('question-->'+question);
questId = question.Id;
System.debug('questId --->'+questId );
Reply reply1 = new Reply();
reply1.Body = 'reply no 1 ques 1';
reply1.QuestionId = question.Id;
System.debug('reply1--->'+reply1);
insert reply1;
}
// BadgeVilleWebServiceCallout bv = new BadgeVilleWebServiceCallout();
// bv.badgvilleReceiveBestAnswer(questId);
Test.stopTest();
}
We are trying to implement this with both test methods. but we are unable to do it. can nay body have any idea how to do this or where i am doing wrong??

Salesforce doesn't allow you to Test external WebServices.
Here, you have an idea of how to test WebServices.
And here you have a Salesforce Idea.
I hope this help you.

Related

How to send api request from test class to Main class in salesforce?

Class :
#RestResource(urlMapping='/api/fetch_status/*')
global class RestDemo{
#HttpGet
global static Account getResult(){
Account account;
String accountId = '';
RestRequest restReq = RestContext.request;
RestResponse restRes = RestContext.response;
// reading url
try{
//accountId = restReq.params.get('accountId');
accountId = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('/') + 1);
account = [SELECT Id, Name FROM Account WHERE Id = :accountId Limit 1];
if(account != null){ //checked whether any record is returned or not
restRes.responseBody = Blob.valueOf(JSON.serialize(account));
restRes.statusCode = 200;
}else{
/* String account_not_found= '{"message":"Not Found"}';
restRes.responseBody = Blob.valueOf(account_not_found); */
restRes.statusCode = 404;
}
}
catch(Exception ex){
restRes.responseBody = Blob.valueOf(ex.getMessage());
restRes.statusCode = 500;
}
return account;
}
}
Test Class :
private class RestDemoTest {
#testSetup
static void dataSetup() {
Account acc = new Account(Name = 'Testing5');
insert acc;
}
static testMethod void testGet() {
//case 1 when the id is valid
Account acc = [ SELECT Id FROM Account LIMIT 1 ];
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/api/fetch_status/' + acc.Id;
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response= res;
Account acct1 = RestDemo.getResult();
system.assertEquals(acct1.Name, 'Testing5');
// case 2 when the id is not present
String str_id = '0012x000004UjZX';
Id id = Id.valueOf(str_id);
req.requestURI = '/services/apexrest/api/fetch_status/' + id;
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response= res;
Account acct2 = RestDemo.getResult();
system.assertEquals(acct2, null);
}
}
I want to test the test case 2 where the account with the random id is not present.
But while testing the test class (in test case 2 )it is giving exception.
In this i used an existing id and changed it a little.So while test case2 runs it should go through the else statement of the main class but it is throwing exception (catch statement,Tested it in salesforce developer console).
account = [SELECT Id, Name FROM Account WHERE Id = :accountId Limit 1];
The way you written it account will never be null. It'll just throw "List has no rows for assignment to SObject".
Change to this
List<Account> accs = [SELECT Id, Name FROM Account WHERE Id = :accountId Limit 1];
if(!accs.isEmpty()){
// return 200;
} else {
// return 400;
}
If you query that way it'll always come as List. It can be empty list but it will be a list (not null). Assign query results to single Account/Contact/... only if you're 100% sure it'll return something. Or catch the exceptions

How to create a apex test class for my apex class

It is my first apex class and i don't really know how to implement a proper test class.
My goal is to achieve test coverage of 75%.
I updated based on the comments but i managed to achieve only 70 %. I don't have other idea how to improve this more.
Here is what i did :
Apex class:
public with sharing class AccountController {
#AuraEnabled
public static List<Account> findAll() {
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
where Id=:userinfo.getUserId() ];
// Theme4t is theme that is used by mobille app for android or iphone
if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non')
|| (userDetails.UserRole.Name).contains('go')) && UserInfo.getUiTheme() != 'Theme4t'){
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
FROM Account
WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL
LIMIT:22000];
}else {
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
FROM Account
WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL
LIMIT:5000];
}
}
Apex test class:
#isTest
public class AccountControllerTest
{
static testMethod void testMethod1()
{
Account acc = new Account();
acc.Name='Test';
insert acc;
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
where Id=:userinfo.getUserId() ];
List<Account> lstAcc = AccountController.findAll();
UserRole ur =new UserRole();
userDetails.UserRoleId=[select Id from UserRole where Name='yon'].Id;
System.runAs(userDetails){
List<Account> lstAcc1 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='bon'].Id;
System.runAs(userDetails){
List<Account> lstAcc2 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='non'].Id;
System.runAs(userDetails){
List<Account> lstAcc3 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='go'].Id;
System.runAs(userDetails){
List<Account> lstAcc4 = AccountController.findAll();
}
}
Please complete the below trailhead to learn the unit test in Salesforce.
https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_intro
And also as you are trying to create a user after account insertion it will throw Mixed DML error. you need to use system.runAs() method. follow the below URL for using the method.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm
Let me know if still, you need any help on this.
Here is the code for your class and test class. Please follow the best practices from http://blog.shivanathd.com/2013/11/Best-Practices-Test-Class-in-Salesforce.html
This time I am providing the code to you to understand how to create a test class, but next time onwards please follow the steps and documents I have shared.
public with sharing class AccountController {
//using a test visible variable for setting the ui theme check.
#TestVisible static Boolean isTheme4t = UserInfo.getUiThemeDisplayed() == 'Theme4t';
#AuraEnabled
public static List<Account> findAll() {
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User where Id=:userinfo.getUserId()];
// Theme4t is theme that is used by mobille app for android or iphone
if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non') || (userDetails.UserRole.Name).contains('go')) && !isTheme4t){
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity FROM Account WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL LIMIT 22000];
}else {
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity FROM Account WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL LIMIT 5000];
}
}
}
#isTest
public class AccountControllerTest
{
//Use setup data method to create data and query it in testmethod
#testSetup static void setup() {
UserRole r = new UserRole(DeveloperName = 'yon', Name = 'yon');
insert r;
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000#amamama.com',
Username = 'puser000#amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
UserRoleId = r.Id
);
insert u;
System.runAs(u){
Account acc = new Account();
acc.Name = 'Test Account';
acc.ShippingLatitude = 75.46;
acc.ShippingLongitude = 45.46;
acc.AccountStatus__c = 'test';
insert acc;
}
}
static testMethod void testMethod1(){
user u = [select Id from User where email = 'puser000#amamama.com' limit 1];
system.runAs(u){
Test.startTest();
List<Account> acc = [select Id,AccountStatus__c,ShippingLatitude,ShippingLongitude from Account where Name = 'Test Account'];
List<Account> lstAcc4 = AccountController.findAll();
system.assert(lstAcc4.size()>0);
Test.stopTest();
}
}
static testMethod void testMethod2(){
user u = [select Id from User where email = 'puser000#amamama.com' limit 1];
system.runAs(u){
AccountController.isTheme4t = true;
Test.startTest();
List<Account> acc = [select Id,AccountStatus__c,ShippingLatitude,ShippingLongitude from Account where Name = 'Test Account'];
List<Account> lstAcc4 = AccountController.findAll();
system.assert(lstAcc4.size()>0);
Test.stopTest();
}
}
}

DocuSign does not pass values to Salesforce

DocuSign doesn't pass values back into Salesforce. And Even doesn't give me any errors in the logs.
I used a Custom Field like source ID and MergeFieldXml tab option with the write-back = true. But it doesn't work.
Please advise what is wrong?
Merge fields are enabled for the DocuSign account.
My code example:
global class AnnualContract
{
webService static string AM_SendToDocuSign(String id, string strObjType)
{
Docusign_API_Setting__c APISetting = Docusign_API_Setting__c.getInstance('API Settings');
String envelopeId = '';
string DealerName = '';
string DealerId = '';
String accountId = APISetting.AccountId__c;
String userId = APISetting.UserId__c;
String password = APISetting.Password__c;
String integratorsKey = APISetting.IntegratorsKey__c;
String webServiceUrl = APISetting.WebServiceUrl__c;
list<Lead> lstLead = new list<Lead>();
list<Contact> lstContact = new list<Contact>();
if(strObjType == 'Lead')
{
lstLead = [SELECT Name,Status,Email,FirstName,LastName,Owner.Name,Title,FROM Lead where id = : Id limit 1];
}
StaticResource objSR = [SELECT Id,name, SystemModStamp FROM StaticResource WHERE Name = 'AnnualContractPDF' LIMIT 1];
String url_file_ref = '/resource/' + String.valueOf(((DateTime)objSR.get('SystemModStamp')).getTime())+ '/' + objSR.get('Name');
if(strObjType == 'Lead')
{
DealerName = lstLead[0].Name;
}
DocuSignAPI.APIServiceSoap dsApiSend = new DocuSignAPI.APIServiceSoap();
dsApiSend.endpoint_x = webServiceUrl;
//Set Authentication
String auth = '<DocuSignCredentials><Username>'+ userId
+'</Username><Password>' + password
+ '</Password><IntegratorKey>' + integratorsKey
+ '</IntegratorKey></DocuSignCredentials>';
System.debug('Setting authentication to: ' + auth);
dsApiSend.inputHttpHeaders_x = new Map<String, String>();
dsApiSend.inputHttpHeaders_x.put('X-DocuSign-Authentication',
auth);
DocuSignAPI.Envelope envelope = new DocuSignAPI.Envelope();
envelope.Subject = 'Please Sign this Contract' + lstLead[0].Name;
envelope.EmailBlurb = 'This is my new eSignature service, it allows me to get your signoff without having to fax, scan, retype, refile and wait forever';
envelope.AccountId = accountId;
// Render the contract
System.debug('Rendering the contract');
PageReference pageRef = new PageReference(url_file_ref);
Blob pdfBlob = pageRef.getContent();
DocuSignAPI.CustomField field = new DocuSignAPI.CustomField ();
field.Name = '##SFLead';
field.Value = lstLead[0].Id; //value of the external source Id
field.Show = 'false';
field.CustomFieldType = 'Text';
envelope.CustomFields = new DocuSignAPI.ArrayOfCustomField();
envelope.CustomFields.CustomField = new DocuSignAPI.CustomField[1];
envelope.CustomFields.CustomField[0] = field;
// Document
DocuSignAPI.Document document = new DocuSignAPI.Document();
document.ID = 1;
document.pdfBytes = EncodingUtil.base64Encode(pdfBlob);
document.Name = 'Annual Contract';
document.FileExtension = 'pdf';
envelope.Documents = new DocuSignAPI.ArrayOfDocument();
envelope.Documents.Document = new DocuSignAPI.Document[1];
envelope.Documents.Document[0] = document;
// Recipient
System.debug('Building up the recipient');
DocuSignAPI.Recipient recipient = new DocuSignAPI.Recipient();
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
recipient.Email = lstLead[0].Email;
recipient.UserName = lstLead[0].FirstName + ' ' + lstLead[0].LastName;
recipient.RequireIDLookup = false;
envelope.Recipients = new DocuSignAPI.ArrayOfRecipient();
envelope.Recipients.Recipient = new DocuSignAPI.Recipient[1];
envelope.Recipients.Recipient[0] = recipient;
// Tab
DocuSignAPI.Tab tab1 = new DocuSignAPI.Tab();
tab1.Type_x = 'SignHere';
tab1.RecipientID = 1;
tab1.DocumentID = 1;
tab1.AnchorTabItem = new DocuSignAPI.AnchorTab();
tab1.AnchorTabItem.AnchorTabString = '/t1/';
tab1.AnchorTabItem.XOffset = 100;
DocuSignAPI.Tab tab2 = new DocuSignAPI.Tab();
tab2.Type_x = 'DateSigned';
tab2.RecipientID = 1;
tab2.DocumentID = 1;
tab2.AnchorTabItem = new DocuSignAPI.AnchorTab();
tab2.AnchorTabItem.AnchorTabString = '/d1/';
DocuSignAPI.Tab tab3 = new DocuSignAPI.Tab();
tab3.CustomTabType = 'Text';
tab3.Name = 'Title';
tab3.Type_x = 'Custom';
tab3.RecipientID = 1;
tab3.DocumentID = 1;
tab3.TabLabel = 'Title';
if(strObjType == 'Lead')
{
if(lstLead[0].Title != null)
{
tab3.Value = ''+lstLead[0].Title+'';
}
}
else
{
if(lstContact[0].Title != null)
{
tab3.Value = ''+lstContact[0].Title+'';
}
}
tab3.CustomTabWidth=100;
tab3.CustomTabRequired=false;
tab3.CustomTabLocked=false;
tab3.CustomTabDisableAutoSize=false;
tab3.TemplateLocked=false;
tab3.TemplateRequired=false;
tab3.ConditionalParentLabel='';
tab3.ConditionalParentValue='';
tab3.SharedTab=true;
tab3.RequireInitialOnSharedTabChange=false;
tab3.ConcealValueOnDocument=false;
tab3.AnchorTabItem = new DocuSignAPI.AnchorTab();
tab3.AnchorTabItem.AnchorTabString = '/t2/';
tab3.AnchorTabItem.XOffset = 42;
tab3.AnchorTabItem.YOffset = -5;
tab3.MergeFieldXml = '<mergeField><allowSenderToEdit>true</allowSenderToEdit><configurationType>salesforce</configurationType><path>Lead.Title</path><row>1</row><writeBack>true</writeBack></mergeField>';
envelope.Tabs = new DocuSignAPI.ArrayOfTab();
envelope.Tabs.Tab = new DocuSignAPI.Tab[3];
envelope.Tabs.Tab[0] = tab1;
envelope.Tabs.Tab[1] = tab2;
envelope.Tabs.Tab[2] = tab3;
System.debug('Calling the API');
try {
DocuSignAPI.EnvelopeStatus es = dsApiSend.CreateAndSendEnvelope(envelope);
envelopeId = es.EnvelopeID;
System.debug('Returned successfully, envelope id = ' + envelopeId );
return '';
} catch ( CalloutException e) {
System.debug('Exception - ' + e );
envelopeId = 'Exception - ' + e;
return '';
}
return '';
}
}
I resolved the issue with the DocuSign support.
MergeFieldXml for SOAP should be like this:
tab3.MergeFieldXml ='<mergefieldconfig configversion="1.0" service="salesforce"><mergefield><writeenabled>true</writeenabled><sendercanedit>true</sendercanedit><queryfrom><obj><type>Lead</type><name>Lead</name><field><fieldtype>string</fieldtype><name>Title</name></field></obj></queryfrom></mergefield></mergefieldconfig>';

WCF method's breakpoint not being hit

I am new to WCF and I am building a service to do CRUD operations. I have created a new void method that takes two parameters. I have set a breakpoint and in debugging mode I have pasted this URL:
http://localhost:55152/WcfDataService.svc/AddNewNote()?ParamNoteTitle='dfdfdf'&ParamNoteText='dfdfdfdf'
This is my code:
[WebGet]
public void AddNewNote(string ParamNoteTitle, string ParamNoteText)
{
//My hardcoded values for now...
int ParentID = 8879;
int JobID = 1000088150;
int ContactID = 309;
Guid UserID = Guid.NewGuid();
string RelatedType = "Advertiser Contact";
bool IsShared = true;
tblNote N = new tblNote
{
NotesTitle = ParamNoteTitle,
NotesText = ParamNoteText,
ParentID = ParentID,
ContactID = ContactID,
JobID = JobID,
UserID = UserID,
GroupID = null,
RelatedType = RelatedType,
IsShared = IsShared
};
this.CurrentDataSource.tblNotes.Add(N);
this.CurrentDataSource.SaveChanges();
}
I am getting a 404 error. Is there a problem with my query string/URL?
First of all, check if the service itself is running correctly by pasting this URL in your browser:
http://localhost:55152/WcfDataService.svc
If so, I would recommend you to have a look at this similar SO question.
Hope that helps!
I ended up changing my method type to IQueryable and calling a method to retrieve the new row with my ID after the insert. I originally wanted to return an integer or bool so in my Javascript I can handle success or failure by looking at the return value.
[WebGet]
public IQueryable<vw_Note> AddNewNote(string ParamNoteTitle, string ParamNoteText)
{
//My hardcoded values for now...
int ParentID = 8879;
int JobID = 1000088150;
int ContactID = 309;
Guid UserID = new Guid("8b0e303a-68aa-49a5-af95-d994e2bdd5ac");
Guid NoteID = Guid.NewGuid();
string RelatedType = "Advertiser Contact";
bool IsShared = true;
tblNote N = new tblNote
{
NotesID = NoteID,
NotesTitle = ParamNoteTitle,
NotesText = ParamNoteText,
ParentID = ParentID,
ContactID = ContactID,
JobID = JobID,
UserID = UserID,
GroupID = null,
RelatedType = RelatedType,
IsShared = IsShared
};
try
{
this.CurrentDataSource.tblNotes.Add(N);
this.CurrentDataSource.SaveChanges();
return GetNoteByID(NoteID);
}
catch (Exception ex)
{
return GetNoteByID(NoteID);
}
}
As you can see it will return a set of data. I was stuck on how to handle inserting data using WCF and then responding to a client request but I managed to solve it. Thanks anyway!

Why does this controller double the inserts when I try to archive the results of the Bing Search API?

I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.