how to convert Date(2019/5/10) to shamsiDate(1398/4/12) - web-services

I had called a web service in my code that contains Deadline Date . the problem is the response in swagger shows like this :
{
"id": "289",
"serviceName": "خدمت 1",
"deadLine": "2024/05/06",
...
...
}
and I want to show deadline in Shamsi Date like 1398/4/12.
i have used a lot of convertors but it did not worked for me and still shows the "deadLine": "2024/05/06",
this is my view :
public String setDeadLine(Date deadLine) {
this.deadLine = deadLine;
String dateFa;
//String dateFa= DateConvertor.miladi2date(deadLine);
dateFa= this.ConvertToPersianToShow(deadLine);
return dateFa;
}
public String ConvertToPersianToShow(Date deadLine)
{
CalendarTool cl = new CalendarTool();
String date;
String year = cl.getIranianYearInCentury();
String Month = cl.getIranianMonthStr();
String day = cl.getIranianWeekDayStr();
date = year+"/" + Month + "/" + day;
return date;
}
should I type any code in my controller ?

RESOLVE :
I just need to add some code in ConvertToPersianToShow :
calendarTool should be filled .mine was empty
I added this code :
String[] date = deadLine.split("/");
if(date.length != 3)
return null;
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Integer.parseInt(date[0]),Integer.parseInt(date[1]),Integer.parseInt(date[2]));
and filled the calendar :
CalendarTool cl = new CalendarTool(calendar);

Related

How to write test class for salesforce email template

I'm struggling to write a test class for visualforce email template that I have created as per business requirements but I don't know who to cover "get' methods in the test class.. I spent long hours doing research on google unfortunately I haven't found anything helpful.
I tried many ways to cover 'get' method in test class like below
myClass cls = new myClass;
cls.getMethod();
cls.getProperty = 'test';
but it's giving me the error message "List index out of bounds: 0" because I'm calling another method in getter and that methods takes list of records
Controller Class:
public class JobChangesEmail_ComplianceTeam_Cls {
public string jobId {get; set;}
// public string jUrl{get; }
// public string clientUrl {get; }
// public string endclientUrl {get;}
public static list<job__c> jobs;
public JobChangesEmail_ComplianceTeam_Cls()
{
jobs = [select j.Id,j.name,j.other_location__c,j.account__c,j.account__r.id, j.account__r.name,j.Job_Start_Date__c,j.Job_End_Date__c,j.Job_Status__c,j.account__r.Spreadsheet_SOPs__c,
j.account__r.Facility_SOPs__c,j.End_Client__c,End_Client__r.id,j.End_Client__r.name,j.End_Client__r.Spreadsheet_SOPs__c, j.End_Client__r.Facility_SOPs__c from Job__c j where Id=:jobId];
system.debug('-------------------------------------jobId '+jobId);
}
public list<job__c> getjbs()
{
jobs = [select j.Id,j.name,j.other_location__c,j.account__c, j.account__r.name,j.Job_Start_Date__c,j.Job_End_Date__c,j.Job_Status__c,j.account__r.Spreadsheet_SOPs__c,
j.account__r.Facility_SOPs__c,j.End_Client__c,j.End_Client__r.name,j.End_Client__r.Spreadsheet_SOPs__c, j.End_Client__r.Facility_SOPs__c from Job__c j where Id=:jobId];
system.debug('-------------------------------------jobId '+jobId);
return jobs;
}
Public static string generatejobUrl(list<job__c> jobs)
{
string jurl = System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
return jurl;
}
Public static string generateclientUrl(list<job__c> jobs)
{
string cUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].account__r.id;
return cUrl;
}
Public static string generateEndclientUrl(list<job__c> jobs)
{
string endCUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].end_client__r.id;
return endCUrl;
}
public String getjUrl()
{
string jbUrl;
list<job__c> jobs = [select Id,name from Job__c where Id=:jobId];
jbUrl= System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
return jbUrl;
}
public string clientUrl
{
get { return generateclientUrl(jobs); }
}
public string endclientUrl
{
get { return generateEndclientUrl(jobs); }
}
}
Test class I have written so far:
#isTest(seeAllData= true)
Public class JobChangesEmail_ComplianceTeam_Cls_test {
#isTest
public static void createJob()
{
string clienturl;
string endClienturl;
string joburl;
list<job__c> jobs = new list<job__c>();
Account a = new account(name='ghghghg',type='Other', Account_Status__c='Active',phone='9090909090');
insert a;
Contact contact = new Contact(FirstName='John',LastName='Adams',email='test#gamil.com',phone='14243443', accountid = a.id);
insert contact;
// Opportunity o = [Select id, Name, CloseDate ,Location__c ,AccountId from opportunity limit 1];
Job__c job = new Job__c();
job.Name = 'NewJob'; // Set to match test record
job.X_KOL__c = false; // Set to match test record
job.DE_Job_Type__c = null; // Set to match test record
job.Job_Name_Subject__c = 'TestJob';
job.Job_Start_Date__c = Date.today();
job.End_Client__c = a.Id;
job.Other_Location__c = 'SOS'; // Set to match test record
job.PM__c = 'Amber Anderson';
job.Booked_By__c = UserInfo.getUserId();
job.Account_Manager_COE__c = UserInfo.getUserId();
job.Account__c = a.Id;
job.Contact__c = contact.Id;
job.Respondent_Type__c = 'Acne';
job.Job_Status__c = 'Tentative';
job.Job_Qualification__c = 'Qualitative';
job.Recruitment_Method__c = 'Client List';
job.On_Site_Recruits__c = 5;
job.Off_Site_Recruits__c = 5;
job.London_Project_Number__c = 'Valyria';
job.Recruiting_Begin_Date__c = Date.today();
jobs.add(job);
if(jobs.size()>0)
{
insert jobs;
}
test.startTest();
clienturl = JobChangesEmail_ComplianceTeam_Cls.generateclientUrl(jobs);
endClienturl = JobChangesEmail_ComplianceTeam_Cls.generateEndclientUrl(jobs);
joburl = JobChangesEmail_ComplianceTeam_Cls.generatejobUrl(jobs);
Test.stopTest();
string cUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].account__r.id;
string Eurl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].end_client__r.id;
string jUrl = System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
system.assertEquals(clienturl, cUrl);
system.assertEquals(endClienturl, Eurl);
system.assertEquals(joburl, jUrl);
JobChangesEmail_ComplianceTeam_Cls cls = new JobChangesEmail_ComplianceTeam_Cls();
cls.getjbs();
string id = cls.jobId;
id = [select id from job__c limit 1].id;
system.assertNotEquals(id,job.id);
}
}
above test class is not covering get methods or properties

insert whole list of data into sql database table in xamarin.android

i'm trying to create an application where data in a list must be inserted into a database table at once. I made some research and found out that this is possible using user-defined table types where in c# a datatable is used and passed to a stored procedure that is executed. now my problem is that there are no data tables in Xamarin.Android. so I thought to use a list instead. my idea was to create a list in the application and pass it to the webservice method, and in my webservice method I receive the list and convert it to a datatable then pass it as a parameter to the stored procedure. I wrote the following codes:
in my webservice:
[WebMethod]
public bool insrt_dt(List<Class1> lst)
{
SqlParameter param;
SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
DataTable dt = list_to_dt(lst);
SqlCommand cmd = new SqlCommand("Insert_Customers", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
param = new SqlParameter("#tblcustomers", dt);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
cmd.CommandTimeout = 300;
int a=cmd.ExecuteNonQuery();
if (a > 0)
{
return true;
}
else return false;
}
}
Class1:
public class Class1
{
public int id { get; set; }
public string name { get; set; }
public string country { get; set; }
}
in my Xamarin.Android app
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById<Button>(Resource.Id.button1);
btn.Click += delegate
{
wr.WebService1 ws = new wr.WebService1();
wr.Class1 class1 = new wr.Class1();
List<wr.Class1> lst = new List<wr.Class1>(){
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
ws.insrt_dt(lst);
ws.insrt_dtCompleted += Ws_insrt_dtCompleted;
};
}
private void Ws_insrt_dtCompleted(object sender, wr.insrt_dtCompletedEventArgs e)
{
bool l = e.Result;
if (l == true)
Toast.MakeText(this, "khh", ToastLength.Long).Show();
else
Toast.MakeText(this, "ijo'pioo", ToastLength.Long).Show();
}
}
but I keep getting this error:
Argument 1: cannot convert from 'System.Collections.Generic.List<app_dt.wr.Class1>' to 'app_dt.wr.Class1[]
so I used these lines instead
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
wr.Class1[] class1s = lst.ToArray();
ws.insrt_dt(class1s);
now I don't get an error, but it doesn't work, I mean why does it say that the webservice method input must be an array and I've created it as a list. any suggestions for this?
As i know, Xamarin do not support System.Data.SqlClient. If you want to use the database for the Xamarin android project, you could use the SQLite.NET.
Install the package from the NuGet.
NuGet: sqlite-net-pcl https://www.nuget.org/packages/sqlite-net-pcl/
For the code sample about how to use the database in Xamarin, you could check the link below. https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
For Xamarin.Android, you could check the sample code in the link below. https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm

aws glue maches dynamic record

Could anyone explain code below for matching record in Aws glue
from manual https://aws.amazon.com/ru/blogs/big-data/work-with-partitioned-data-in-aws-glue/
I printed the full schema using githubEvents.printSchema():
id: string
type: string
actor: struct
repo: struct
payload: struct
public: boolean
created_at: string
year: string
month: string
day: string
org: struct
def filterWeekend(rec: DynamicRecord): Boolean = {
def getAsInt(field: String): Int = {
rec.**getField(field**) match {
case Some(strVal: String) => strVal.toInt
// The filter transformation will catch exceptions and mark the record as an error.
case _ => throw new IllegalArgumentException(s"Unable to extract field $field")
}
}
val (year, month, day) = (getAsInt("year"), getAsInt("month"), getAsInt("day"))
val cal = new GregorianCalendar(year, month - 1, day) // Calendar months start at 0.
val dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
**dayOfWeek** == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY
}
val filteredEvents = githubEvents.filter(filterWeekend)
filteredEvents.count
I think that day should be ingested in getField(field) how glue knows that day should be compared but not other field so I mean we should compare day of the schema with dayofWeek?

The query could not be run because the criteria for field '<?>' contained an invalid arithmetic expression

The query could not be run because the criteria for field '' contained an invalid arithmetic expression
Hi,
I faced some issue when i try to pass a value in Server Script and it keep come out with this error " doesnt support operator sbl-dat-00479". When i try to remove one of my value which is PRS Account No and it successfully come out. My value for PRS Account No = P-35971. Below is my server script.
function Print()
{
try
{
TheApplication().TraceOn("C:\\spool\\PRS SOA.txt", "Allocation", "All");
var Account = "";
var Year = "";
var Period = "";
var LPeriod = "";
var ContactID = "";
var Bookmark = "";
var ReportId = "";
var ReportName = "Customer Portal PRS Statement of Account";
//Active Field
this.BusComp().ActivateField("PRSAccountNo");
this.BusComp().ActivateField("Year2");
this.BusComp().ActivateField("Period2");
this.BusComp().ActivateField("LPeriod");
this.BusComp().ActivateField("CONTACT_ID");
//Get Account Row Id
Account = this.BusComp().GetFieldValue("PRSAccountNo");
Year = this.BusComp().GetFieldValue("Year2");
Period = this.BusComp().GetFieldValue("Period2");
LPeriod = this.BusComp().GetFieldValue("LPeriod");
ContactID = this.BusComp().GetFieldValue("CONTACT_ID");
//Construct Bookmark Query
Bookmark = "'cwa CustPortal PRS SOA Account'.Search = \"([PRS Account No] = '"+ Account +"') AND ([Year] = '"+ Year +"') AND ([Period] = '"+ LPeriod +"') AND ([CONTACT_ID] = '"+ ContactID +"')\"";
TheApplication().Trace("Bookmark: " + Bookmark);
//Retrieve Report Row Id
var boReport = TheApplication().GetBusObject("cwa CustPortal Report Administration");
var bcReport = boReport.GetBusComp("Report Standard Templates");
with(bcReport)
{
ActivateField("Report Name");
SetViewMode(AllView);
ClearToQuery();
SetSearchSpec("Report Name", ReportName);
ExecuteQuery(ForwardOnly);
if(FirstRecord())
{
ReportId = GetFieldValue("Id");
}
}
//Generate BIP Report
var GenReport = TheApplication().GetService("Workflow Process Manager");
var GenInput = TheApplication().NewPropertySet();
var GenOutput = TheApplication().NewPropertySet();
GenInput.SetProperty("ProcessName", "cwa CustPortal Generate BIP Report Workflow");
GenInput.SetProperty("Report Id", ReportId);
GenInput.SetProperty("Bookmark", Bookmark);
GenReport.InvokeMethod("RunProcess", GenInput, GenOutput);
var ErrMsg = GenOutput.GetProperty("Error Message");
if(ErrMsg == "")
{
//BIP Report successful generated, redirect to view report page
TheApplication().GotoView("cwa CustPortal PRS SOA Report View");
}
else
{
Popup(ErrMsg);
return(CancelOperation);
}
TheApplication().TraceOff();
}
catch(e)
{
Popup(e);
}
finally
{
}
}
Code looks ok, would be data issue or calc field logic error.
I think "Year2", "Period2" are Calculated fields & could be returning the special character ("/") leading to render the searchspec incorrectly.

Salesforce Webservice Error

I am receiving the following error from a class that invokes a webservice.
"You have uncommitte​d work pending. Please commit or rollback before calling out"
Here is the class that is calling the webservice:
global class myWS
{
WebService static string invokeExternalWs(string childValue, string parentValue)
{
HttpRequest req = new HttpRequest();
req.setEndpoint('https://externalURL/Services');
req.setMethod('POST');
req.setHeader('Content-Type', 'text/xml; charset=utf-8');
req.setHeader('SOAPAction', 'http://externalService/externalMethod');
string b = '--soap request goes here--';
req.setBody(b);
Http http = new Http();
try {
//Execute web service call here
String xObjectID ='';
HTTPResponse res = http.send(req);
Dom.Document doc = res.getBodyDocument();
String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
Dom.XmlNode root = doc.getRootElement();
for(dom.XmlNode node1 : root.getChildElements()) {
for(dom.XmlNode node2 : node1.getChildElements()) {
for(dom.XmlNode node3 : node2.getChildElements()) {
for(dom.XmlNode node4 : node3.getChildElements()) {
xObjectID = node4.getText();
}
}
}
}
return xObjectID;
} catch(System.CalloutException e){
return 'ERROR:' + e;
}
}
}
UPDATE: Here is my class that is executing myWS
public void applyURLString(ID ArgBuildID) {
Builder__c current_build = [SELECT id, name, LLURL__c, column1, column2, Opportunity__c
FROM Builder__c
WHERE id = :ArgBuildID];
if(current_build.LLURL__c == null || current_build.LLURL__c.trim().length() == 0)
{
String tmpFolderName = current_build.column1 + ' - ' + current_build.column2;
String LLWSResultPattern = '[0-9]{2,}';
String myWSXMLResult = myWS.invokeExternalWs(tmpFolderName,'test');
Boolean LLWSPatternMatched = pattern.matches(LLWSResultPattern,myWSXMLResult);
if(LLWSPatternMatched)
{
Opportunity oppt = [SELECT Id,Name
FROM Opportunity
WHERE Id = :current_build.Opportunity__c
LIMIT 1];
oppt.LLURL__c = 'https://someService/' + myWSXMLResult;
update oppt;
}
}
}
UPDATE #2 - Here is where applyURLString() is executed. This is the only place that DML is executed prior to my HTTP request. Yet I need the ID of the new Builder record.
Builder__c insertBuild = new Builder__c();
insertBuild.Opportunity__c = opportunityId;
insertBuild.Product_Group__c = selectedBuild.Product_Group__c;
insertBuild.Manual_Build_Product__c = selectedBuild.Manual_Build_Product__c;
insert insertBuild;
applyURLString(insertBuild.Id);
Any ideas why this error would occur?
#JCD's suggestion to use an #future annotation solved my problem. Thanks again!