public List<SelectOption> getYearList(){
Integer year = Date.Today().year();
String s1=string.valueof(year).right(2);
Integer Year1= Integer.valueof(s1);
List<SelectOption> YearListOptions = new List<SelectOption>();
YearListOptions .add(new SelectOption('','YY'));
for(Integer i=Year1;i<=Year1+8;i++)
{
string j=string.valueof(i);
YearListOptions .add(new SelectOption(j,j));
}
return YearListOptions ;
}
I tried but Getting error like AuraEnabled methods do not support return type of List
I have Changed this but anyone have any suggestion or comments please feel free to add
#AuraEnabled
public List<String> getYearList(){
Integer year = Date.Today().year();
String s1=string.valueof(year).right(2);
Integer Year1= Integer.valueof(s1);
List<SelectOption> YearListOptions = new List<SelectOption>();
List<String> yearValueList = new List<String>();
YearListOptions .add(new SelectOption('','YY'));
for(Integer i=Year1;i<=Year1+8;i++)
{
string j=string.valueof(i);
YearListOptions .add(new SelectOption(j,j));
}
for (SelectOption sO : YearListOptions){
yearValueList.add(sO.getValue());
}
return yearValueList ;
}
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 write a function that gets the list of object in my database
public List<T> GetList<T>() where T: new()
{
IDbCommand dbCmd = dbcon.CreateCommand();
dbCmd.CommandText = "SELECT * FROM " + typeof(T).FullName;
IDataReader reader = dbCmd.ExecuteReader();
DataTable schemaTable = reader.GetSchemaTable();
List<T> returnList = new List<T>();
foreach (DataRow row in schemaTable.Rows)
{
T obj = new T();
foreach(var prop in obj.GetType().GetProperties())
{
prop.SetValue(obj, row[prop.Name], null);
}
returnList.Add(obj);
}
return returnList;
}
However forexamle if I run this for my Weapon class which has
public int ID { get; set;}
public int Cost { get; set; }
public int Power { get; set; }
public int Distance { get; set; }
I get 25 columns and I if run for Monster class I got same 25 columns which goes by "ColumnName", "ColumnOrdinal", "ColumnSize", "NumericPrecision" etc...
So that I cannot set my "Cost" property since this dataset does not has the Cost column name.
How can I get SchemaTable correctly?
I solve my problem without using SchemaTable
public List<T> GetList<T>() where T: new()
{
IDbCommand dbCmd = dbcon.CreateCommand();
dbCmd.CommandText = String.Format("SELECT * FROM {0}", typeof(T).FullName);
IDataReader reader = dbCmd.ExecuteReader();
List<T> returnList = new List<T>();
while (reader.Read())
{
T obj = new T();
foreach(var prop in obj.GetType().GetProperties())
{
prop.SetValue(obj, Convert.ChangeType(reader[prop.Name], prop.PropertyType), null);
}
returnList.Add(obj);
}
return returnList;
}
This script gets all the items in given table successfully.
My Requirement:
I have a JSON request in a table column which is like below.
{
"customerData": [{ "primaryData":[ {
"HNo": "8-10-2",
"APTNM": "SRSENCLAVE",
"STRT": "MGCLNY"
}],
"officeData":{
"ADDR": "1/7-25",
"STRT": "FINDIST",
"LM": "JBE"
},
"ContactData": {
"PHNO":"XXXXXXXXX",
"ZIP":"XXXXXX",
"MAILCD": "XXXX"},
}
]}
I need to read it from DB and map the JSON values into three different class properties.i.e. PrimaryData.java. OfficeData.java,ContactData.java.
I'm able to successfully read the request from DB but struck on how to map the values to properties in my three POJO classes. I tried using faster xml, google Gson, org.json but I could not get it well. Can someone give me an idea or part of code snippet?
How I'm trying to achieve above (not sure if this approach is correct at all)
List<Map<String, PrimaryData>> cxData = new ArrayList<Map<String,PrimaryData>>();
JSONObject jSONObject = new JSONObject(query.getResultList().get(0).toString());
JSONArray jsonArray = jSONObject.getJSONArray("customerData");
int length = jsonArray.length();
for (int i=0; i<length; i++)
{
// FOR EACH ENTRY
JSONObject OneEntry = jsonArray.getJSONObject(i);
int OneEntrySize = OneEntry.length();
JSONArray EntKey = OneEntry.names();
Map<String, PrimaryData> map = new HashMap<String, PrimaryData>();
for (int j=0; j<OneEntrySize;j++)
{ // FOR EACH ITEM IN AN ENTRY
String key = EntKey.getString(j);
PrimaryData val = (PrimaryData)OneEntry.opt(key);;--unable to cast (can not cast JsonArray to PrimaryData)
map.put(key, val);
}
cxData.add(map);
}
With GSON
public class Data {
#SerializedName("customerData") #Expose private List<CustomerData> customerData = null;
}
public class CustomerData {
#SerializedName("primaryData") #Expose private List<PrimaryData> primaryData = null;
#SerializedName("officeData") #Expose private OfficeData officeData;
#SerializedName("ContactData") #Expose private ContactData contactData;
}
public class PrimaryData {
#SerializedName("HNo") #Expose private String hNo;
#SerializedName("APTNM") #Expose private String aPTNM;
#SerializedName("STRT") #Expose private String sTRT;
}
public class OfficeData {
#SerializedName("ADDR") #Expose private String aDDR;
#SerializedName("STRT") #Expose private String sTRT;
#SerializedName("LM") #Expose private String lM;
}
public class ContactData {
#SerializedName("PHNO") #Expose private String pHNO;
#SerializedName("ZIP") #Expose private String zIP;
#SerializedName("MAILCD") #Expose private String mAILCD;
}
Gson gson = new Gson();
Data data = gson.fromJson(dataJSON, Data.class);
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
i have a class in dev org with code is
name of class is ManageRules.cls
/**
* This class is used for creating and editing Rule
**/
public with sharing class ManageRules{
public Rule__c newrule {get;set;}
public String objType {get;set;}
public string SearchEvalRule {get;set;}
public string Descr {get;set;}
public List<SelectOption> objOptions {get;set;}
// public String descr {get;set;}
public boolean edit {get;set;}
String ruleId;
public ManageRules(Apexpages.StandardController stdcon){
ruleId = stdcon.getId();
newrule = new Rule__c();
objOptions = new List<SelectOption>();
edit=false;
/**
* Add standard Objects
*/
objOptions.add(new SelectOption('',''));
objOptions.add(new SelectOption('Account','Account'));
objOptions.add(new SelectOption('Contact','Contact'));
objOptions.add(new SelectOption('Opportunity','Opportunity'));
objOptions.add(new SelectOption('Case','Case'));
objOptions.add(new SelectOption('Lead','Lead'));
objOptions.add(new SelectOption('Campaign','Campaign'));
objOptions.add(new SelectOption('Quote','Quote'));
objOptions.add(new SelectOption('Product2','Product'));
//objOptions.add(new SelectOption('ForeCast','Forecast'));
Map<String, Schema.SObjectType> mapObj = Schema.getGlobalDescribe();
for(String objname:mapObj.keySet()){
Schema.SObjectType sobj = mapObj.get(objname);
Schema.DescribeSObjectResult descRes = sobj.getDescribe();
/**
* Add custom objects
*/
if(descRes.isCustom() && !descRes.isCustomSetting()){
String objLabel = descRes.getLabel();
objOptions.add(new SelectOption(objName,objLabel));
}
}
/* Edit Rule */
if(ruleId!=null){
edit=true;
newrule = [select name,object__c,Rule_Execution_Plan__c,Available__c,Evaluation_Rule__c,Description__c from rule__c where id=:ruleId];
if(newrule!=null){
objtype=newrule.object__c;
Descr =newrule.Description__c;
SearchEvalRule =newrule.Evaluation_Rule__c ;
}
}
}
Public List<SelectOption> getEvalRule() {
List<selectOption> options = new List<selectOption>();
options.add(new selectOption('', '- None -'));
Schema.DescribeFieldResult field = Rule__c.Evaluation_Rule__c.getDescribe();
for (Schema.Picklistentry picklistEntry : field.getPicklistValues())
{
options.add(new SelectOption(pickListEntry.getValue(),pickListEntry.getLabel()));
}
return options;
}
public PageReference saveRule(){
newrule.object__c = objtype;
newrule.Evaluation_Rule__c=SearchEvalRule;
newrule.Description__c= Descr;
try{
Database.upsert(newrule);
return(new PageReference('/'+newrule.id));
}
catch(Exception e){
ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,e.getDMLMessage(0));
ApexPages.addMessage(msg);
return null;
}
}
public PageReference saveAndNewRule(){
newrule.object__c = objtype;
newrule.Evaluation_Rule__c=SearchEvalRule;
newrule.Description__c= Descr;
edit=false;
try{
Database.upsert(newrule);
newrule = new Rule__c();
return(new PageReference('/apex/manageRules'));
}
catch(Exception e){
ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,e.getDMLMessage(0));
ApexPages.addMessage(msg);
return null;
}
}
}
i created an object its giving me error
Description Resource Path Location Type
Save error: Rule_c : managerules does not exist or is not a valid override for action Edit. Rule_c.object /RuleCriteria/src/objects line 0 Force.com save problem
my Rule__c object code segment where i am getting this error is :
<actionOverrides>
<actionName>Edit</actionName>
<content>ManageRules</content>
<skipRecordTypeSelect>false</skipRecordTypeSelect>
<type>Visualforce</type>
</actionOverrides>
i am unable to figure why its showing me this error its an existing project so i have to deploy it on my dev org .on others org its working perfectly fine.i first save this class code and then try to save this object code and getting this error.can any one please how to resolve this issue??