I created a Apex Class like
Public class test_Controller
{
Public test_Controller() { }
Public void send(set<id> oppIds)
{
List<Oppurtunity> OppLst =[Select Name from Opportunity where id IN: oppIds];
Private static string integration_key = 'abcd';
Private static string account_id = 'efgh';
Public string signer_email { get; set; }
Public string signer_name { get; set; }
Public string email_message { get; set; }
Public string output { get; set; }
Public string envelope_id { get; set; }
Public string error_code { get; set; }
Public string error_message { get; set; }
Private static string ds_server = 'callout:DocuSign_Legacy_Demo/api/3.0/dsapi.asmx';
Private static string trace_value = 'SFDC_004_SOAP_email_send'; // Used for tracing API calls
Private static string trace_key = 'X-ray';
Private DocuSignTK.APIServiceSoap api_sender = new DocuSignTK.APIServiceSoap();
configure_sender();
do_send(OppLst);
}
Private void configure_sender()
{
api_sender.endpoint_x = ds_server;
api_sender.inputHttpHeaders_x = new Map<String, String>();
String auth = '<DocuSignCredentials><Username>{!$Credential.Username}</Username>'
+ '<Password>{!$Credential.Password}</Password>'
+ '<IntegratorKey>' + integration_key + '</IntegratorKey></DocuSignCredentials>';
api_sender.inputHttpHeaders_x.put('X-DocuSign-Authentication', auth);
}
Private void do_send(List<Oppurtunity> OppurLst)
{
if (integration_key == 'xxx-xxxx-xxxx' ||
account_id == 'xxxx-xxxx-xxxx')
{
error_message = 'Please configure the Apex class DS_Recipe_Send_Env_Email_Controller with your integration key and account id.';
error_code = 'CONFIGURATION_PROBLEM';
return;
}
String file_contents = '<html><h1>Quote Document</h1>' + get_lorem(OppurLst)
+ '<p> </p>'
+ '<p>Signature: <span style="color:white;">signer1sig</span></p>'
+ '<p>Date: <span style="color:white;">signer1date</span></p></html>';
DocuSignTK.Document document = new DocuSignTK.Document();
document.ID = 1;
document.Name = 'Quote Document';
document.FileExtension = 'html';
document.pdfBytes = EncodingUtil.base64Encode(Blob.valueOf(file_contents));
DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
recipient.Email = '';
recipient.UserName = '';
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
DocuSignTK.Tab signHereTab = new DocuSignTK.Tab();
signHereTab.Type_x = 'SignHere';
signHereTab.AnchorTabItem = new DocuSignTK.AnchorTab();
signHereTab.AnchorTabItem.AnchorTabString = 'signer1sig'; // Anchored for doc 1
signHereTab.AnchorTabItem.XOffset = 8;
signHereTab.RecipientID = 1;
signHereTab.Name = 'Please sign here';
signHereTab.ScaleValue = 1;
signHereTab.TabLabel = 'signer1sig';
DocuSignTK.Tab dateSignedTab = new DocuSignTK.Tab();
dateSignedTab.Type_x = 'DateSigned';
dateSignedTab.AnchorTabItem = new DocuSignTK.AnchorTab();
dateSignedTab.AnchorTabItem.AnchorTabString = 'signer1date'; // Anchored for doc 1
dateSignedTab.AnchorTabItem.YOffset = -6;
dateSignedTab.RecipientID = 1;
dateSignedTab.Name = 'Date Signed';
dateSignedTab.TabLabel = 'date_signed';
DocuSignTK.Envelope envelope = new DocuSignTK.Envelope();
envelope.Subject = 'Please sign the Quote Document';
envelope.AccountId = account_id;
envelope.Tabs = new DocuSignTK.ArrayOfTab();
envelope.Tabs.Tab = new DocuSignTK.Tab[2];
envelope.Tabs.Tab.add(signHereTab);
envelope.Tabs.Tab.add(dateSignedTab);
envelope.Recipients = new DocuSignTK.ArrayOfRecipient();
envelope.Recipients.Recipient = new DocuSignTK.Recipient[1];
envelope.Recipients.Recipient.add(recipient);
envelope.Documents = new DocuSignTK.ArrayOfDocument();
envelope.Documents.Document = new DocuSignTK.Document[1];
envelope.Documents.Document.add(document);
if (String.isNotBlank(email_message))
{
envelope.EmailBlurb = email_message;
}
try
{
DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
envelope_id = result.EnvelopeID;
System.debug('Returned successfully, envelope_id = ' + envelope_id);
}
catch (CalloutException e)
{
System.debug('Exception - ' + e);
error_code = 'Problem: ' + e;
error_message = error_code;
}
}
Private Boolean no_error()
{
return (String.isEmpty(error_code));
}
Private static String get_lorem(List<Oppurtunity> OLst)
{
String lorem = 'Hello World';
return lorem;
}
}
And I am trying to call the send Method from the Apex from the Custom Button like
{!REQUIRESCRIPT("/soap/ajax/41.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/41.0/apex.js")}
sforce.apex.execute("test_Controller","send",{oppIds:"{!Opportunity.Id}"});
When I try to execute the button I get the following error message:
A Problem with the OnClick JavaScript for this button or link was
encountered: {faultcode:''soapenv:Client', faultstring:'No operation
available for request
{http://soap.sforce.com/schemas/package/test_Controller}send, please
check the WSDL for the service.'}'
I am new to Salesforce and Apex scripting. Any help is greatly appreciated.
Your method is expecting a list of Ids.
Public void send(set<id> oppIds)
So I am guessing that maybe you need to send it as an array?
sforce.apex.execute("test_Controller","send",{oppIds:["{!Opportunity.Id}"]});
You need to expose this method as a webservice and it needs to be static
webservice static void send(List<Id> oppIds) {
}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_and_ajax.htm
Related
i'm new to ASP.NET MVC
so i've been trying for the last week to create a dropdown list from sql server to view a list of the interns Names
I've tried various & different ways to solve it, i checked most of the stackoverflow solutions related to the same issue, but all is leading to is the same error 'There is no ViewData item of type 'IEnumerable' that has the key 'InternID'.'
So my question is, What am i missing?
this is my main code
Controller
public ActionResult AddTask(Add_TaskModel Add_Task, HttpPostedFileBase postedFile) {
var InternList = entities.InternsTbls.ToList();
ViewBag.internList = new SelectList(InternList, "InternID","Name");
return View();}
View
#Html.DropDownListFor(m => m.InternID, ViewBag.internList as SelectList, "--Select The Intern", new { #class = "form-cotrnol"})
Model
public class Add_TaskModel
{
[Key]
public int TaskID { get; set; }
public string TaskTitle { get; set; }
public string TaskType { get; set; }
public string TaskDes { get; set; }
public string DueDate { get; set; }
public int SupID { get; set; }
public string TaskStatus { get; set; }
public int FileID { get; set; }
public int InternID { get; set; }
public string Name { get; set; }
}
Note- this one of many ways i tried, but same error.
Code 2
//var myList = new List<SelectListItem>();
//var list = entities.InternsTbls.ToList();
//var items = from g in list
// select new SelectListItem
// {
// Value = g.InternID.ToString(),
// Text = g.Name.ToString()
// };
//foreach (var item in items)
// myList.Add(item);
//ViewBag["In_List"] = myList;
Code 3
//string mainconn = ConfigurationManager.ConnectionStrings["TaskTrackerDBEntities"].ConnectionString;
//if (mainconn.ToLower().StartsWith("metadata="))
//{
// System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(mainconn);
// mainconn = efBuilder.ProviderConnectionString;
//}
//using (SqlConnection sqlconn = new SqlConnection(mainconn))
//{
// string sqlquery = "select * from [dbo].[InternsTbl]";
// using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
// {
// sqlconn.Open();
// SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
// DataSet ds = new DataSet();
// sda.Fill(ds);
// ViewBag.internname = ds.Tables[0];
// List<SelectListItem> getinternname = new List<SelectListItem>();
// foreach (System.Data.DataRow dr in ViewBag.internname.Rows)
// {
// getinternname.Add(new SelectListItem { Text = #dr["Name"].ToString(), Value = #dr["Name"].ToString() });
// }
// ViewData ["Interns"] = getinternname;
// //new SelectList(getinternname, "Name", "Name");
// sqlconn.Close();
// }
//}
Code 4
//TaskTrackerDBEntities entities1 = new TaskTrackerDBEntities();
//var getInternName = entities1.InternsTbls.ToList();
//SelectList list = new SelectList(getInternName, "InternID", "Name");
// ViewBag["InternListName"] = list;
//ViewBag.SubNames = new SelectList(entities1.InternsNames, "InternID", "Name");
I created a personal info page to display all the data according to specific username entered. Unfortunately, the edit text didn't display all the data from the SQL Server. It only shows 2/8 data. I'm using a WEB API to retrieve the data and the data is stored in SQL Server. Can you help me to fix this problem please!!
I obtained this code from a website and i follow step by step according to the website. I've tried using Web services, it didn't work ass well.
VehicleRecord.cs
public class VehicleRecord
{
public string clFullName{ get; set; }
public string clGender{ get; set; }
public string clICNo { get; set; }
public string clAddress { get; set; }
public string clPhoneNo { get; set; }
public string clEmail { get; set; }
public string clUsername { get; set; }
public string clPwd { get; set; }
public string clVehicPlateNo { get; set; }
public string clVehicModel { get; set; }
public string clVehicCol { get; set; }
public string clPaymentMethod { get; set; }
public VehicleRecord()
{
this.clFullName = "";
this.clGender = "";
this.clICNo = "";
this.clAddress = "";
this.clPhoneNo = "";
this.clEmail = "";
this.clUsername = "";
this.clPwd = "";
this.clVehicPlateNo = "";
this.clVehicModel = "";
this.clVehicCol = "";
this.clPaymentMethod = "";
}
}
Service.cs
public class Service
{
public static async Task<dynamic> getServiceData(string queryString)
{
dynamic acc = null;
HttpClient client = new HttpClient();
var response = await client.GetAsync(queryString);
if(response != null)
{
string json = response.Content.ReadAsStringAsync().Result;
acc = JsonConvert.DeserializeObject(json);
}
return acc;
}
}
Acc.cs
public class Acc
{
public static async Task<VehicleRecord> GetAcc(string username)
{
string queryString = "http://xxx.xxx.x.xxx/PMSAPI1/api/users/" + username;
dynamic results = await Service.getServiceData(queryString).ConfigureAwait(false);
if(results != null)
{
VehicleRecord vehicleRecord = new VehicleRecord();
vehicleRecord.clFullName = (string)results["clFullName"];
vehicleRecord.clGender = (string)results["clGender"];
vehicleRecord.clICNo = (string)results["clICNo"];
vehicleRecord.clAddress = (string)results["clAddress"];
vehicleRecord.clPhoneNo = (string)results["clPhoneNo"];
vehicleRecord.clEmail = (string)results["clEmail"];
vehicleRecord.clPwd = (string)results["clPwd"];
vehicleRecord.clVehicPlateNo = (string)results["clVehicPlateNo"];
vehicleRecord.clVehicModel = (string)results["clVehicModel"];
vehicleRecord.clVehicCol = (string)results["clVehicCol"];
vehicleRecord.clPaymentMethod = (string)results["clPaymentMethod"];
return vehicleRecord;
}
else
{
return null;
}
}
}
PersonalInfoActivity.cs
private async void BtnGetAcc_Click(object sender, EventArgs e)
{
EditText username = FindViewById<EditText>(Resource.Id.txtUsername);
if (!String.IsNullOrEmpty(username.Text))
{
VehicleRecord vehicleRecord = await Acc.GetAcc(username.Text);
FindViewById<EditText>(Resource.Id.txtFullName).Text = vehicleRecord.clFullName;
FindViewById<EditText>(Resource.Id.txtGender).Text = vehicleRecord.clGender;
FindViewById<EditText>(Resource.Id.txtIC).Text = vehicleRecord.clICNo;
FindViewById<EditText>(Resource.Id.txtAddress).Text = vehicleRecord.clAddress;
FindViewById<EditText>(Resource.Id.txtPhoneNo).Text = vehicleRecord.clPhoneNo;
FindViewById<EditText>(Resource.Id.txtEmail).Text = vehicleRecord.clEmail;
FindViewById<EditText>(Resource.Id.txtPwd).Text = vehicleRecord.clPwd;
FindViewById<EditText>(Resource.Id.txtPayMethod).Text = vehicleRecord.clPaymentMethod;
}
}
The expected output should display all the data according to the username entered, but the actual output only displayed 2/8 data.
The error that i get is System.NullReferenceException:Object reference not set to an instance of an object.
The output displayed on screen
It seems to me that the issue starts at this line
vehicleRecord.clICNo = (string)results["clICNo"];
IMO results does not contains "clICNo". Check this by surrounding this line in try - catch block.
I need help here with part of my code so here it is:
I have 6 methods as you can see below that parse incoming data and then returns it as a list, so my issue is to send that list data to my database table SerialNumber, each method of the lists is a separate field that will fill a database column.
So for example the parse material will fill the database materiallookupcode column and the same for the others.
Here is an image of the database table
Here is the code of all 5 methods that reads the data and then returns it and I need this data send to my database
private List<string> ParseMaterial()
{
var materialList = new List<string>();
foreach (var material in _connection.GetBarcodeList())
{
materialList.Add(material.Substring(10, 5));
}
return materialList;
}
private List<string> ParseLot()
{
var lotList = new List<string>();
var establishmentList = GetEstablishmentCode();
foreach (var lot in _connection.GetBarcodeList())
{
if (establishmentList.Contains("038"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LoganSport038Property);
}
if (establishmentList.Contains("072"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LouisaCounty072Property);
}
if (establishmentList.Contains("086"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Madison086Property);
}
if (establishmentList.Contains("089"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Perry089Property);
}
if (establishmentList.Contains("069"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.StormLake069Property);
}
if (establishmentList.Contains("088"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Waterloo088Property);
}
if (establishmentList.Contains("265"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.GoodLetsVille265Property);
}
if (establishmentList.Contains("087"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.CouncilBluffs087Property);
}
if (establishmentList.Contains("064"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Sherman064Property);
}
}
return lotList;
}
private List<string> ParseSerialNumber()
{
var serialNumberList = new List<string>();
foreach (var serialNumber in _connection.GetBarcodeList())
{
serialNumberList.Add(serialNumber.Substring(36, 10));
}
return serialNumberList;
}
public List<string> ParseNetWeight()
{
var netWeightList = new List<string>();
foreach (var netWeight in _connection.GetBarcodeList())
{
netWeightList.Add(netWeight.Substring(22, 4));
}
return netWeightList;
}
public List<string> ParseGrossWeight()
{
var grossWeightList = new List<string>();
foreach (var grossWeight in _connection.GetBarcodeList())
{
grossWeightList.Add(grossWeight.Substring(22, 4));
}
return grossWeightList;
}
public List<string> FullBarcode()
{
var receiveFullBarcodeList = new List<string>();
foreach (var fullBarcode in _connection.GetBarcodeList())
{
receiveFullBarcodeList.Add(fullBarcode);
}
return receiveFullBarcodeList;
}
public List<string> GetEstablishmentCode()
{
var establishmentList = new List<string>();
foreach (var establishmentCode in _connection.GetBarcodeList())
{
establishmentList.Add(establishmentCode.Substring(36, 3));
}
return establishmentList;
}
The issue is here the button when clicking will read all 5 methods and send it to the database, I am sure the part where I making the list of variables to a string and the separator part is wrong so I need how is the correct way to add those list to each column of the database
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methodss
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var material = "";
var lot = "";
var net = "";
var gross = "";
var serial = "";
var fullSerial = "";
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
material = materialList[i];
lot = lotList[i];
net = netWeightList[i];
gross = grossWeightList[i];
serial = serialNumberList[i];
fullSerial = fullSerialNumberList[i];
}
// database table and columns
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = serial,
NetWeight = Convert.ToDecimal(net) / 100,
GrossWeight = Convert.ToDecimal(gross) / 100,
LotLookupCode = lot,
MaterialLookupCode = material,
FullSerialNumberLookupCode = fullSerial,
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
// insert to the database
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
Here is the SerialNumber domain class that represents a database table using a code first migration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarcodeReceivingApp.Core.Domain
{
// domain class, represents a database table in sql server using code
// first migration
public class SerialNumber
{
public int Id { get; set; }
public int LicensePlateId { get; set; }
public string FullSerialNumberLookupCode { get; set; }
public string SerialNumberLookupCode { get; set; }
public decimal NetWeight { get; set; }
public decimal GrossWeight { get; set; }
public string LotLookupCode { get; set; }
public string MaterialLookupCode { get; set; }
public DateTime CreatedSysDateTime { get; set; }
public DateTime ModifiedSysDateTime { get; set; }
public string CreatedSysUser { get; set; }
public string ModifiedSysUser { get; set; }
}
}
I search other places but could not find a good solution so far, so any help is appreciate it.
I was able to resolve my question, what I did is to assign all lists in a loop and then assign them to each column in the database.
But I am still searching for a better and more clean way to this solution
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methods - represents each field of the database column
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = materialList[i],
NetWeight = Convert.ToDecimal(netWeightList[i]) / 100,
GrossWeight = Convert.ToDecimal(grossWeightList[i]) / 100,
LotLookupCode = lotList[i],
MaterialLookupCode = materialList[i],
FullSerialNumberLookupCode = fullSerialNumberList[i],
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
}
I have created a test class with 51% code coverage till line no 34.
Further, I tried to satisfy if condition but I couldn't. Now I am not getting how to do with 100% code coverage.
Here is the Apex class:
public class AssignProjectController {
public String CaseIds;
public String status {get;set;}
public List<Project__c> activeProjects {get;set;}
public String keyWordSearched {get;set;}
public Id projectId {get;set;}
public AssignProjectController (){
CaseIds = ApexPages.currentPage().getParameters().get('id');
}
public void getProjects(){
status = '';
String searchQuery = 'FIND \'' + keyWordSearched + '*\' IN ALL FIELDS RETURNING Project__c (id,Name,Description__c where Status__c =\'Active\')';
try{
List<List<Project__c >> searchList = search.query(searchQuery);
activeProjects = searchList[0];
if(activeProjects.size() == 0) status = 'No search result found.';
}catch(Exception ex){
system.debug('ex..'+ex.getMessage());
}}}
public PageReference assignProjectToCases(){
List<Case__c> customSettingList = Case__c.getall().values();
List<String> settingRecordTypeList = new List<String>();
for(Case__c caseObj:customSettingList){
settingRecordTypeList.add(caseObj.Name);
}
List<RecordType> recordTypeListData = [SELECT Id FROM RecordType WHERE SObjectType = 'Case' and Name In : settingRecordTypeList];
if(CaseIds != null){
List<String> caseIDList = new List<String>();
caseIDList = CaseIds.split(',');
if([Select id from Case where Id In : caseIDList and RecordType.Id NOT In : recordTypeListData].size() > 0){
status = 'failed';
}else{
List<Case> cases = [Select id,Project__c,RecordType.Name from Case where Id In : caseIDList and RecordType.Id In : recordTypeListData];
if(cases.size() > 0){
for(case caseOb: cases){
caseOb.Project__c = projectId ;
}
try{
update cases ;
status = 'Changes are scheduled';
}catch(Exception ex){
system.debug('AssignProjectController :::'+ex.getMessage());
status = 'Something Went Wrong';
}}}}
return null;
}}
Here is the test class- which I tried to resolve
#isTest public class TestAssignProjectController {
public static Project__c insertProject(){
Project__c proObj = new Project__c();
proObj.Name = 'testProject';
proObj.Status__c = 'Active';
proObj.Description__c = 'for testing';
proObj.Internal_Email_Alias__c = 'a#test.com';
return proObj;
}
public static Account getAccount(){
Account accoObj = new Account();
accoObj.Name = 'testAcc';
accoObj.Location__c = 'testLocation';
accoObj.Type = 'CM';
accoObj.BillingCountry = 'United States';
return accoObj;
}
public static Contact insertContact(Account accObj){
Contact conObj = new Contact();
conObj.FirstName = 'test';
conObj.LastName = 'testLastname';
conObj.AccountId = accObj.Id;
conObj.Email = 'abc#gmail.com';
return conObj;
}
public static Id getTechTypeId(){
return Schema.SObjectType.Case.getRecordTypeInfosByName().get('Tech ').getRecordTypeId();
}
public static Case insertCase(String conId, String proId){
Case caseObj = new Case();
caseObj.Project__c = proId;
caseObj.ContactId = conId;
caseObj.Status = 'Open';
caseObj.Inquiry_Type__c = 'All';
caseObj.Subject = 'TestSubject';
caseObj.Description = 'TestDescription';
caseObj.Case_Is_Reopened__c = false;
caseObj.RecordTypeId = getTechTypeId();
return caseObj;
}
public static testmethod void testMethodExecution(){
AssignController asigncon = new AssignController ();
Project__c proObj = insertProject();
insert proObj;
System.assertEquals(proObj.Status__c,'Active');
Account accObj = getAccount();
insert accObj;
System.assertNotEquals(accObj.Id,null);
Contact conObj = insertContact(accObj);
insert conObj;
System.assertNotEquals(conObj.Id,null);
Case caseObj = insertCase(conObj.Id, proObj.Id);
insert caseObj;
system.debug(caseObj);
//Set baseURL & case ID
PageReference pageRef = Page.Assign;
pageRef.getParameters().put('id',caseObj.id+',');
AssignController asigncon1 = new AssignController ();
asigncon1.getProjects();
asigncon1.assignProjectToCases();
}}
If you are referring if(cases.size() > 0) this statement, then surely there is problem of inserting the case. Make sure that insert caseObj; is working and inserts data in Salesforce backend.
If there is no data in case object, the test method cannot cover the if statement.
i have a visual force page which is used as a view to send a custom sms to the leads generated in salesforce.The year field is a number field on salesforce. Posting the controller and test class error. Also mentioning the error line.
Controller :-
//Class to send Message to Lead or Account
public class nmSendSMS
{
//Name of Lead or Account
public string strName{get;set;}
public Lead objLead {get;set;}
public String defaultNumbersToBeAdded;
public String leadYear{get;set;}
//Mobile number of lead of account
public string strMobile{get;set;}
public String messageToBeSent{get;set;}
public List<SelectOption> getYear{get;set;}
public string strSMSBody{get;set;}
//To disable fields if data is not available
String session,statusOfLead,stringOfMobileNumbers;
public nmSendSMS()
{
objLead = new Lead();
leadYear ='';
defaultNumbersToBeAdded = '9820834921,9920726538';
messageToBeSent = '';
stringOfMobileNumbers= '';
}
//Method to send SMS
public PageReference SendSMS()
{
if(leadYear!='' || messageToBeSent!='')
{
session = objLead.nm_Session__c;
integer lengthOfCommaSeperatedNumbers;
String finalString ='';
statusOfLead = objLead.Status;
list<lead> leadNumbersList = [select MobilePhone from Lead where Status=:statusOfLead and nm_Session__c=:session and nm_Year__c=:integer.valueOf(leadYear)];
for(Lead obj :leadNumbersList)
{
stringOfMobileNumbers = obj.MobilePhone+','+stringOfMobileNumbers;
}
System.debug('stringOfMobileNumbers -->'+stringOfMobileNumbers);
lengthOfCommaSeperatedNumbers = stringOfMobileNumbers.length();
finalString = stringOfMobileNumbers.substring(0,lengthOfCommaSeperatedNumbers-1);
finalString = finalString + defaultNumbersToBeAdded;
System.debug('Final String--->'+finalString+'Message To Be Sent-->'+messageToBeSent);
String response = SMSSenderWebService.sendSMSForNotContactedLead(finalString,messageToBeSent);
System.debug('Response-->'+response);
}
else
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Warning,'Please Mention all the fields For Lead Search'));
return null;
}
return null;
}
public List<SelectOption> getYear()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('2016','2016'));
options.add(new SelectOption('2017','2017'));
options.add(new SelectOption('2018','2018'));
options.add(new SelectOption('2019','2019'));
return options;
}
}
Test Class:-
#isTest
public class nmSendSMSTracker
{
public static Lead obj;
public static nm_Centers__c objLearningCenter;
public static nm_Program__c program;
public static nm_EligiblityCriteria__c eligibility ;
static testMethod void tesMethod()
{
LoadData();
PageReference pg = new PageReference('/apex/nmSendSMS');
Test.setCurrentPage(pg);
Test.StartTest();
nmSendSMS smsSend = new nmSendSMS();
smsSend.getYear();
smsSend.objLead = obj;
smsSend.messageToBeSent ='Hello Vikas';
smsSend.SendSMS();
Test.StopTest();
}
static void LoadData()
{
nm_EscalationMatrix__c objCustomSeetings3 = new nm_EscalationMatrix__c();
objCustomSeetings3.name='0-1 Week';
objCustomSeetings3.nm_LCEscalationTime__c='22:45';
objCustomSeetings3.nm_RemidertoIC__c='22:45';
objCustomSeetings3.nm_HOEscalationTime__c='20:56';
objCustomSeetings3.nm_RemidertoHO__c='22:45';
insert objCustomSeetings3;
nm_EscalationMatrix__c objCustomSeetings = new nm_EscalationMatrix__c();
objCustomSeetings.name='2-4 Months';
objCustomSeetings.nm_LCEscalationTime__c='20:45';
objCustomSeetings.nm_RemidertoIC__c='21:45';
objCustomSeetings.nm_HOEscalationTime__c='20:56';
objCustomSeetings.nm_RemidertoHO__c='21:45';
insert objCustomSeetings;
nm_EscalationMatrix__c objCustomSeetings2 = new nm_EscalationMatrix__c();
objCustomSeetings2.name='3-6 Week';
objCustomSeetings2.nm_LCEscalationTime__c='20:34';
objCustomSeetings2.nm_RemidertoIC__c='21:45';
objCustomSeetings2.nm_HOEscalationTime__c='20:56';
objCustomSeetings2.nm_RemidertoHO__c='21:45';
insert objCustomSeetings2;
nm_Holidays__c objHoliday = new nm_Holidays__c();
objHoliday.Name='Holi';
objHoliday.nm_Date__c=system.today();
insert objHoliday;
// profile objprofile =[SELECT Id FROM Profile WHERE Name='System Administrator'];
user usr = [Select id from user limit 1];
SystemConfiguration__c objSystemConfiguration=new SystemConfiguration__c();
objSystemConfiguration.name='test';
objSystemConfiguration.nm_BusinessHoursStartTime__c='012213';
objSystemConfiguration.nm_BusinessHoursEndTime__c='0234533';
insert objSystemConfiguration;
Recordtype rt=[select id from Recordtype where sobjectType='nm_Centers__c' AND name ='Learning Center'];
objLearningCenter = new nm_Centers__c();
objLearningCenter.RecordTypeID =rt.id;
objLearningCenter.nm_CenterCode__c ='002';
objLearningCenter.nm_CenterCity__c='Delhi';
objLearningCenter.nm_City__c='Delhi';
objLearningCenter.nm_StateProvince__c='Delhi';
objLearningCenter.nm_Street__c='Laxmi Ngar';
objLearningCenter.nm_PostalCode__c='110091';
insert objLearningCenter;
program = new nm_Program__c();
program.nmIsActive__c = true;
program.nm_ProgramCode__c = 'test';
program.nm_ProgramDuration__c= 2.0;
program.nm_ProgramName__c = 'Post grad diploma finance';
program.nm_ProgramValidity__c = 4;
program.nm_TotalSemesters__c = 4;
program.nm_Type__c = 'Post Graduate Diploma Program';
insert program;
eligibility = new nm_EligiblityCriteria__c();
eligibility.Name = 'Bachelors degree';
eligibility.nm_EligiblityCriteria__c = 'bjhwbghbjgw';
eligibility.Experience_Required_In_Year__c= 2;
eligibility.Graduation_Percentage__c = 6;
eligibility.Graduation_Required__c = true;
insert eligibility;
obj = new Lead();
obj.Email='amit.kumar#saasfocus.com';
obj.MobilePhone='8377985721';
obj.FirstName='sandy';
obj.LastName='babar';
obj.nm_BloodGroup__c='B+';
obj.nm_Gender__c='male';
obj.nm_FathersName__c='subhash';
obj.nm_MothersName__c='kalpana';
obj.nm_StateProvince_P__c='maharashtra';
obj.nm_Nationality__c='Indian';
obj.nm_Street_P__c='xyz';
obj.nm_LocalityName__c='mohitep';
obj.nm_SelfLearningMaterial__c='Send to my shipping address';
obj.Status='Cold';
obj.nm_Session__c = 'January';
obj.nm_NameofBoard__c='CBSE';
obj.nm_EligiblityCriteria__c = eligibility.id;
obj.nm_Program__c = program.id;
obj.nm_InformationCenter__c =objLearningCenter.id;
obj.nm_10thPercentage__c=77.00;
obj.nm_NameofBoard__c='ICSC';
obj.nm_YearofCompletion__c='2000';
obj.nm_NameofSchool__c='nutan';
obj.nm_Class12OrDiploma__c='HSC';
obj.nm_NameofBoard12__c='LCSC';
obj.nm_YearofCompletion12__c='2002';
obj.nm_NameofSchool12__c='dfg';
obj.nm_Stream__c='adw';
obj.nm_BachelorsDegreeName__c='gfc';
obj.nm_Specialization__c='gf';
obj.nm_NameofUniversity__c='G K university';
obj.nm_BachelorsDegreePercentage__c=55.00;
obj.nm_GraduationDegreeMode__c='fgc';
obj.nm_YearofCollegeCompletion__c='2006';
obj.LeadSource='Web';
obj.OwnerId=usr.id;
insert obj;
}
}
Error Message:
System.TypeException: Invalid integer:
Class.nmSendSMS.SendSMS: line 37, column 1
Class.nmSendSMSTracker.tesMethod: line 19, column 1
List<Lead> leadNumbersList = [select MobilePhone from Lead where nm_Year__c=:leadYear];
Works for me and I get the correct Lead(s) in the list