Dynamic query to perform SOQL action not working - salesforce

I'm trying to make a dynamic soql query with few parameters, but have not been able to execute it properly
string knowledgeQuery = '';
string publishStatusOnline = 'Online';
// At the moment 'Knowledge__kav' only supports two languages 'is-is' and 'en-us'
if(language == 'is-is'){
language = 'is';
knowledgeQuery = 'SELECT Id, Customer_Facing_Instruction__c FROM Knowledge__kav WHERE UrlName = :name AND PublishStatus = :publishStatusOnline AND language = :language ORDER BY VersionNumber DESC LIMIT 1';
} else {
knowledgeQuery = 'SELECT Id, Customer_Facing_Instruction__c FROM Knowledge__kav WHERE UrlName = :name AND PublishStatus = :publishStatusOnline ORDER BY VersionNumber DESC LIMIT 1';
}
System.debug(knowledgeQuery);
Knowledge__kav article = Database.query(knowledgeQuery);
return article;
Tke knowledgeQuery string looks like this SELECT Id, Customer_Facing_Instruction__c FROM Knowledge__kav WHERE UrlName = :name AND PublishStatus = :publishStatusOnline ORDER BY VersionNumber DESC LIMIT 1

After checking the code, because there is really nothing dynamic, I was wondering the need for the dynamic query. I guess you could achieve basically the same by doing:
Knowledge__kav article;
String publishStatusOnline = 'Online';
// At the moment 'Knowledge__kav' only supports two languages 'is-is' and 'en-us'
if(language == 'is-is'){
language = 'is';
article = [SELECT Id, Customer_Facing_Instruction__c FROM Knowledge__kav WHERE UrlName = :name AND PublishStatus = :publishStatusOnline AND language = :language ORDER BY VersionNumber DESC LIMIT 1];
} else {
article = [SELECT Id, Customer_Facing_Instruction__c FROM Knowledge__kav WHERE UrlName = :name AND PublishStatus = :publishStatusOnline ORDER BY VersionNumber DESC LIMIT 1];
}
return article;

Related

Salesforce REST API Create an order class with Wrapper Not working

anyone can solve this issue as im getting Error - Method does not exist or incorrect signature: void productMAp(String) from the type CreateOrders
Order ord = new Order(
AccountId = oderWrap.AccountId,
EffectiveDate = EffectiveDate,
Status = oderWrap.Status,
PriceBook2Id = PricebookList[0].id,
contractid = contractMap.get(oderWrap.AccountId).id,
ShippingStreet = contractMap.get(oderWrap.AccountId).Account.ShippingStreet,
ShippingCity = contractMap.get(oderWrap.AccountId).Account.ShippingCity,
ShippingpostalCode = contractMap.get(oderWrap.AccountId).Account.ShippingpostalCode,
ShippingCountry = contractMap.get(oderWrap.AccountId).Account.ShippingCountry,
ShippingState = contractMap.get(oderWrap.AccountId).Account.ShippingState
);
for(OrderWrapper.OrderLineItems oderLineItem : oderWrap.OrderLineItems){
product2 pro = productMAp(oderLineItem.LineItemCode);
PricebookEntry pbe = PricebookEntryMAp(pro.id);
OrderItemList.add(createOrderLineItimes(ord,integer.valueof(oderLineItem.Quantity),pro,pbe));
}
if(ord!=null){
insert ord ;
for(OrderItem poLine : OrderItemList) {
poLine.orderid =poLine.order.Id;
}
insert OrderItemList;
}
Hard to say, what's the type of "productMap"?
Did you mean to use productMap.get(oderLineItem.LineItemCode)?

Salesforce- retrieve Contact.opportunites

Here is snippet I am using in my anonymous window . Purpose is to retrieve Opportunities of a contact. Even after adding opportunity contact role , contact.Opportunities.size is resulting in zero (last debug line). Am I missing something ? you may use the below code directly.
Update: able to get size now but same logic doesn't work for code coverage in test class . details listed below:
Only 'if' part of controller is covered and 'else' part is never covered even though size of contact.opportunities is more than 0.
Controller method :
public PageReference sendingEmail() {
//contact1 has query records
sizeVar = contact1.Opportunities.size();
if(contact1.npo02__OppAmountLastYear__c>0 ) {
if(sizeVar==0) {
// if size is 0 then navigate to a particular vf page
PageReference pr = Page.NoDonationOrNoEmail;
pr.getParameters().put('id',(String)contact1.id);
pr.setRedirect(true);
return pr;
}
else
{ //when contact.opportunities size is more than 0 then navigate to
other vf page.
PageReference pr1 = Page.NoPrint;
pr1.getParameters().put('id',(String)contact1.id);
pr1.setRedirect(true);
return pr1;
}
} return null;
}
Test Class:
//creating account
Account a = new Account();
a.Name = 'Test Co.';
a.BillingStreet = '298 S. Ringo Street';
a.BillingCity = 'Little Rock';
insert a;
//Creating contact
Contact contact1 = new Contact();
contact1.FirstName = 'Paul';
contact1.LastName = 'Test';
contact1.AccountId = a.id;
contact1.npo02__OppAmountLastYear__c=100;
insert contact1;
//creating opportunity
Opportunity o = new Opportunity();
o.RecordType = [SELECT Id, Name, DeveloperName FROM RecordType
WHERE Name = 'Membership' LIMIT 1];
o.Name = 'New Record';
o.StageName = 'Posted';
o.AccountId = contact1.AccountId;
o.CloseDate = Date.today();
o.Description = 'Test Record';
insert o;
//creating opportunity contact role
OpportunityContactRole ocr = new OpportunityContactRole();
ocr.ContactId = contact1.Id;
ocr.OpportunityId = o.Id;
ocr.IsPrimary = TRUE;
ocr.Role = 'Decision Maker';
insert ocr;
System.debug('created opportunity contact role for primary');
Update o;
contact1 = [SELECT Id, Name,(SELECT id FROM opportunities) FROM
Contact WHERE Id=:contact1.Id];
PageReference pr = Page.NoPrint;
pr.getParameters().put('id', String.valueOf(contact1.id));
Test.setCurrentPage(pr);
ApexPages.StandardController cont5 = new
ApexPages.StandardController(contact1);
BulkEmailController testAccPlan = new
BulkEmailController(cont5);
testAccPlan.sendingEmail();
When you create and insert a record, you don't get formula fields nor you can navigate lookup. The same goes with child relationship.
You have to query the fields you need.
Change Update contact1; to contact1 = [SELECT Id, (SELECT Id FROM Opportunities) FROM Contact WHERE Id = :contact1.Id]; and the last debug line will print 1.

Entity Framework Core write MSSQL Server Extended Properties

Is it possible to create the MSSQL Server specific extended properties via Fluent-API or DataAnnotation for a Table / Schema? I would like to include my documentation into the sql server tables to satisfy our DBA.
Kind Regards
I started on an implementation using EntityFrameworkCore.Scaffolding.Handlebars but ran out of time. These are the findings:
Add
public class ScaffoldingDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection services)
{
services.AddSingleton<IDatabaseModelFactory, SqlServerDatabaseModelFactory2>();
var options = ReverseEngineerOptions.DbContextAndEntities;
services.AddHandlebarsScaffolding(options);
// https://github.com/TrackableEntities/EntityFrameworkCore.Scaffolding.Handlebars/issues/30
Handlebars.RegisterHelper("f-pn", FormatPropertyName);
}
void FormatPropertyName(TextWriter writer, object context, object[] args)
{
writer.WriteSafeString(args[0].ToString());
}
}
Copy SqlServerDatabaseModelFactory from
SqlServerDatabaseModelFactory and customize it with a function going like this
DbConnection connection,
IReadOnlyList<DatabaseTable> tables,
string tableFilter,
IReadOnlyDictionary<string, (string storeType, string typeName)> typeAliases)
{
using (var command = connection.CreateCommand())
{
var commandText = #"
SELECT u.name AS [table_schema],
t.name AS [table_name],
td.value AS [table_desc],
c.name AS [column_name],
cd.value AS [column_desc]
FROM sysobjects t
INNER JOIN sysusers u
ON u.uid = t.uid
LEFT OUTER JOIN sys.extended_properties td
ON td.major_id = t.id
AND td.minor_id = 0
AND td.name = 'MS_Description'
INNER JOIN syscolumns c
ON c.id = t.id
LEFT OUTER JOIN sys.extended_properties cd
ON cd.major_id = c.id
AND cd.minor_id = c.colid
AND cd.name = 'MS_Description'
WHERE t.type = 'u'
ORDER BY t.name, c.colorder";
command.CommandText = commandText;
using (var reader = command.ExecuteReader())
{
var tableColumnGroups = reader.Cast<DbDataRecord>()
.GroupBy(
ddr => (tableSchema: ddr.GetValueOrDefault<string>("table_schema"),
tableName: ddr.GetValueOrDefault<string>("table_name")));
foreach (var tableColumnGroup in tableColumnGroups)
{
var tableSchema = tableColumnGroup.Key.tableSchema;
var tableName = tableColumnGroup.Key.tableName;
var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName);
foreach (var dataRecord in tableColumnGroup)
{
var columnName = dataRecord.GetValueOrDefault<string>("column_name");
var tableDesc = dataRecord.GetValueOrDefault<string>("table_desc");
var columnDesc = dataRecord.GetValueOrDefault<string>("column_desc");
//_logger.ColumnFound(
// DisplayName(tableSchema, tableName),
// columnName,
// ordinal,
// DisplayName(dataTypeSchemaName, dataTypeName),
// maxLength,
// precision,
// scale,
// nullable,
// isIdentity,
// defaultValue,
// computedValue);
table.Description = tableDesc; ???
table.Columns.FirstOrDefault(x => x.Name == columnName)?.Description = columnDesc; ???;
}
}
}
}
}
Make a dictionary of the table and column descriptions and use Handlebars Helpers/Transformers EntityFrameworkCore.Scaffolding.Handlebars

Upload File (image/audio/video) to FeedItem in chunks

​public static String upload(String folderId, String documentId, String fileName, String base64BlobValue) {
if(documentId == '' || documentId == null) {
Document document = new Document(Name=fileName, FolderId=folderId, Body=EncodingUtil.Base64Decode(base64BlobValue), IsPublic=true);
insert document;
return document.Id;
} else {
Document document = [select Id, Body from Document where Id = :documentId];
update new Document(Id = documentId, Body = EncodingUtil.Base64Decode(EncodingUtil.Base64Encode(document.Body) + base64BlobValue));
return documentId;
}
}
I'm trying to upload files (image/audio/video) to FeedItem in chunks, the above example shows how I'm doing the same while writing to a document. But If try to do the same with FeedItem it says "FeedItem.ContentData is not writeable" so I've tried the following code:
FeedItem imageFeedItem = [select Id, ContentData, RelatedRecordId from FeedItem where Id = :imageFeedItemId];
ContentVersion content = new ContentVersion();
content.versionData = EncodingUtil.Base64Decode(EncodingUtil.Base64Encode(imageFeedItem.ContentData) + base64BlobValue);
content.pathOnClient = fileName;
content.ContentDocumentId = [Select ContentDocumentId from ContentVersion where id=:imageFeedItem.RelatedRecordId].ContentDocumentId;
insert content;
But this creates ContentVersions of incomplete chunks. Any pointers on how can I achieve this more neat.
Thanks
You can try setting IsMajorVersion to false
ContentVersion content = new ContentVersion();
content.versionData = EncodingUtil.Base64Decode(EncodingUtil.Base64Encode(imageFeedItem.ContentData) + base64BlobValue);
content.pathOnClient = fileName;
content.IsMajorVersion = false;
content.ContentDocumentId = [Select ContentDocumentId from ContentVersion where id=:imageFeedItem.RelatedRecordId].ContentDocumentId;
insert content;
I hope this help!

LINQ orderby int array index value

Using LINQ I would like to sort by the passed in int arrays index.
So in the code below attribueIds is my int array. I'm using the integers in that array for the where clause but I would like the results in the order that they were in while in the array.
public List BuildTable(int[] attributeIds)
{
using (var dc = new MyDC())
{
var ordering = attributeIds.ToList();
var query = from att in dc.DC.Ecs_TblAttributes
where attributeIds.Contains(att.ID)
orderby(ordering.IndexOf(att.ID))
select new Common.Models.Attribute
{
AttributeId = att.ID,
DisplayName = att.DisplayName,
AttributeName = att.Name
};
return query.ToList();
}
}
I would recommend selecting from the attributeIDs array instead. This will ensure that your items will be correctly ordered without requiring a sort.
The code should go something like this:
var query =
from id in attributeIds
let att = dc.DC.Ecs_TblAttributes.FirstOrDefault(a => a.ID == id)
where att != null
select new Common.Models.Attribute
{
AttributeId = att.ID,
DisplayName = att.DisplayName,
AttributeName = att.Name
};
Why don't you join:
public List BuildTable(int[] attributeIds)
{
using (var dc = new MyDC())
{
var query = from attID in attributeIds
join att in dc.DC.Ecs_TblAttributes
on attID equals att.ID
select new Common.Models.Attribute
{
AttributeId = attID,
DisplayName = att.DisplayName,
AttributeName = att.Name
};
return query.ToList();
}
}

Resources