What is significance getDml code below in Salesforce Test code - salesforce

Can anyone explain me significance getDml code below in Salesforce Test code
#isTest static void TestContactWithInvalidNameNotInserted(){
String inputLastName = 'INVALIDNAME';
Contact newcontact = new Contact(LastName=inputLastName);
Test.startTest();
try{
insert newcontact;
}
catch(DmlException dmlEx){
String expectedMessage = 'The Last Name' +newcontact.LastName+'is not allowed for DML';
System.assertEquals(expectedMessage, dmlEx.getDmlMessage(0));
}
Test.stopTest();
}
}

In this instance the catch block only catches exceptions of type DmlException. getDmlMessage() is how you can get the message property of the exception.
Thanks,
Matt

Related

Salesforce : Apex test class for the getting trending articles of Knowledge from Community

I need to get trending articles from the community. I created a apex class for that by using ConnectApi.Knowledge.getTrendingArticles(communityId, maxResult).
I need to create a test class for that. I am using test class method provided by Salesforce for that. setTestGetTrendingArticles(communityId, maxResults, result) but I am getting this error "System.AssertException: Assertion Failed: No matching test result found for Knowledge.getTrendingArticles(String communityId, Integer maxResults). Before calling this, call Knowledge.setTestGetTrendingArticles(String communityId, Integer maxResults, ConnectApi.KnowledgeArticleVersionCollection result) to set the expected test result."
public without sharing class ConnectTopicCatalogController {
#AuraEnabled(cacheable=true)
public static List<ConnectApi.KnowledgeArticleVersion> getAllTrendingArticles(){
string commId = [Select Id from Network where Name = 'Customer Community v5'].Id;
ConnectApi.KnowledgeArticleVersionCollection mtCollection = ConnectApi.Knowledge.getTrendingArticles(commId, 12);
System.debug('getAllTrendingTopics '+JSON.serializePretty(mtCollection.items));
List<ConnectApi.KnowledgeArticleVersion> topicList = new List<ConnectApi.KnowledgeArticleVersion>();
for(ConnectApi.KnowledgeArticleVersion mtopic : mtCollection.items)
{
topicList.add(mtopic);
}
return topicList;
}
}
Test class that I am using for this
public class ConnectTopicCatalogControllerTest {
public static final string communityId = [Select Id from Network where Name = 'Customer Community v5'].Id;
#isTest
static void getTrendingArticles(){
ConnectApi.KnowledgeArticleVersionCollection knowledgeResult = new ConnectApi.KnowledgeArticleVersionCollection();
List<ConnectApi.KnowledgeArticleVersion> know = new List<ConnectApi.KnowledgeArticleVersion>();
know.add(new ConnectApi.KnowledgeArticleVersion());
know.add(new ConnectApi.KnowledgeArticleVersion());
system.debug('know '+know);
knowledgeResult.items = know;
// Set the test data
ConnectApi.Knowledge.setTestGetTrendingArticles(null, 12, knowledgeResult);
List<ConnectApi.KnowledgeArticleVersion> res = ConnectTopicCatalogController.getAllTrendingArticles();
// The method returns the test page, which we know has two items in it.
Test.startTest();
System.assertEquals(12, res.size());
Test.stopTest();
}
}
I need help to solve the test class
Thanks.
Your controller expects the articles to be inside the 'Customer Community v5' community, but you are passing the communityId parameter as null to the setTestGetTrendingArticles method.

Test Class in Salesforce for a Trigger

Good day Everybody,
I am attempting to write a test class for a trigger I helped write. The trigger uses a field called trigger_help__c, a formula field derived from adding the opportunity Type and Account ID, and fires before insert if an Opportunity of that type has been created on that account within the last 90 days. Unless the profile is a system admin. Here is my trigger:
trigger leadDuplicatePreventer on opportunity(before insert) {
set<string> settgs = new set<string>();
list<opportunity> opps = [select id,Trigger_Help__c from opportunity WHERE CreatedDate = LAST_N_DAYS:90];
Profile p=[SELECT ID, Name FROM Profile WHERE Id=:userinfo.getProfileId() Limit 1];
for(opportunity opp : opps){
if(opp.Trigger_Help__c != null && p.Name <> 'System Administrator'){
settgs.add(opp.Trigger_Help__c);
}
}
for(opportunity op : trigger.new){
if(settgs.contains(op.Trigger_Help__c)){
op.adderror('An Opportunity of this type already exists on this Account. Please contact a system administrator with questions.');
}
}
}​
I am having trouble writing the test class and I am clueless as always. I have the following written, but I am lost as to what I actually need to be doing:
#isTest
private class TestleadDuplicatePreventer {
#isTest static void TestleadDuplicatePreventerwithOneOpp() {
Account acct = new Account(Name='Test Account');
insert acct;
Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(1),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
AccountID=acct.Id);
insert opp;
Test.startTest();
opp= new Opportunity(Name='Opportunity Test',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(2),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
Account=[SELECT ID from Account WHERE Account.Name='Test Account']);
try
{
insert opp;
}
catch(Exception duplicate)
{
}
Test.stopTest();
}
}​
Any and all help is appreciated!!
Not sure exactly what your requirements were for your project, you can probably get this done without code doing a rollup sum field that counts the opportunities tied to an account that has the type used in Trigger_Help__c and then put a validation on opportunity that when ISNEW() if Account.Count_Of_Type__c > 0 causes the validation to fire OR on opportunity create a hidden field that is unique that is the concatenation of the account id and the Opportunity type which can be set by workflow or the process builder. Tis would prevent duplicate types from being added for a given account.
But to your original question: In your test I dont see you set the Trigger_Help__c field unless that is set by automation. Also when creating your second opp you dont need to do the query of account you can just use the acct.Id from earlier in the code.
For your catch you need to assert that the e.getMessage() is the message you expect from your add error in the trigger.
You probably also need to do a separate where you runAs(admin_user) where admin_user is a user that you create with the System administrator profile to ensure that you dont get an error when you run as the admin user, along the lines of:
#isTest
private class TestleadDuplicatePreventer {
#isTest static void TestleadDuplicatePreventerwithOneOpp() {
Account acct = new Account(Name='Test Account');
insert acct;
Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(1),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
AccountID=acct.Id);
insert opp;
Test.startTest();
opp= new Opportunity(Name='Opportunity Test',
StageName='Open Opportunity',
CloseDate=System.today().addMonths(2),
Facility__c='Tacoma WA',
Oppty_Type__c='UCO Service',
AccountId=acct.Id);
try
{
insert opp;
}
catch(Exception duplicate)
{
System.assertEquals('An Opportunity of this type already exists on this Account. Please contact a system administrator with questions.', duplicate.getMessage())
}
//this should probably be in a separate test method
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u2 = new User(Alias = 'newUser', Email='newuser#testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='newuser#testorg.com');
System.runAs(u2) {
insert opp;
}
Test.stopTest();
}
}​

[RuntimeException: No EntityManager bound to this thread. Try to annotate your action method with #play.db.jpa.Transactional]

this is the problem once i try to save data into db with sql statement insert.
my function is this:
public void save(){
JPA.em().persist(this);
}
and
public static Result registered() {
Form<User> requestform = form(User.class).bindFromRequest();
if(requestform.hasErrors()){
return badRequest("<p>fehlerhafte eingabe!</p>").as("text/html");
} else {
User user = requestform.get();
String fullname = user.fullname;
String email = user.email;
String password = user.password;
String username = user.username;
new User(username, password, fullname, email).save();
}
return redirect(controllers.routes.Application.index());
}
thanks for help
It is just like the debugging message says, you do not have an entity manager bound to your methods because they are not marked as transactions.
#play.db.jpa.Transactional
public static Result registered() {
Also, if you are using EBean, you could just extend Model for your User class, which comes with many handy built in functions for database use, see documentation here: http://www.playframework.org/documentation/2.0.1/JavaEbean

How to catch return value from service method?

I am completely new to silverlight and WCF. Still reading online stuff and trying to write some code to get going. :)
My question is, I want to insert data into database and my insert method returns a bool. How would I catch the return value in silverlight in the button click event and display confirmation message to the user.
My Service code is:
[OperationContract]
public bool insertData(string Name, string Address, string cType, string postcode, string city, string phone, string email)
{
bussAppDataContext dc = new bussAppDataContext();
TestTable tt = new TestTable();
tt.CompanyName = Name;
tt.Address = Address;
tt.CompanyType = cType;
tt.Postcode = postcode;
tt.City = city;
tt.Telephone = phone;
tt.Email = email;
dc.TestTables.InsertOnSubmit(tt);
dc.SubmitChanges();
return true;
}
And the silverlight client code is:
private void btnSend_Click(object sender, System.Windows.RoutedEventArgs e)
{
FirstServiceReference.FirstServiceClient webServc = new FirstServiceReference.FirstServiceClient();
webServc.insertDataAsync(txtCName.Text.Trim(), txtAddress.Text.Trim(), cmbCType.SelectedValue.ToString(), txtPostcode.Text.Trim(), txtCity.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim());
}
all webservice calls are async in silverlight so you need to add a handler to the insertDataCompleted event. This event is called when the operation is done.
Something like this:
webServc.insertDataCompleted += MyHandler;
webServc.insertDataAsync(txtCName.Text.Trim(), txtAddress.Text.Trim(), cmbCType.SelectedValue.ToString(), txtPostcode.Text.Trim(), txtCity.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim());
}
private void MyHandler(object sender, MyEventArgs args) {}
The args have the boolean as result.
Have a look here Calling web services with Silverlight Tim Heuer.
Hope this helps.
BR,
TJ

winforms datagridview sorting using LINQ

Im using Linq...more specifically, PLINQO. anyway the following is an example of a query I have bound to a datagridview (winforms):
public static List<Task> GetUserTasks( Guid userID ) {
using (myDataContext ctx = new myDataContext()) {
try {
return ctx.Manager.Task.GetByUserID( userID ).ToList();
} catch (Exception) {
throw;
}
}
}
In my UI, I have the following setup to bind:
BindingSource bs = new BindingSource();
bs.DataSource = DUtasks.GetUserTasks( User.Current.UserID );
dgvTasks.DataSource = bs;
It works, but no sorting is possible. I tried "AsEnumerable()" instead of "ToList()" but that for some reason, throws an "objection reference" error. Any ideas as to how I can proceed on this front?
Many thanks!
OK, problem sorted!!! :)
found the following link: SortableBindingList... (my comment is at the bottom with converted C# working code).
Now all my query methods that return List<(ENTITY)> simply get used like this:
SortableBindingList<Task> sortedTasks = new SortableBindingList<Task>( DUtasks.GetUserTasks( User.Current.UserID ) );
dgvTasks.DataSource = sortedTasks;
dgvTasks.Sort( colTaskDue, ListSortDirection.Ascending );
Hope this helps someone!
Have you tried returning an IOrderedEnumerable? Not sure if it will help but that is designed to handle ordered LINQ results.
use only MySortableBindingList class in this page Implementing-a-Sortable-BindingList-
then
var yourLinqList = ...;
MySortableBindingList sortList = new MySortableBindingList(yourLinqList);
dataGridView1.DataSource = sortList;
then your dataGridView must be sort when cell header click.

Resources