CodeFluent produces either a check for 0 in the method or a check for NULL in the stored procedure - codefluent

My model contains an entity with a numeric Landcode property. The value 0 is a valid value for this property:
<cf:entity name="Land">
<cf:property name="Id" key="true" />
<cf:property name="Landcode" typeName="ushort" nullable="false" usePersistenceDefaultValue="false" />
<cf:method name="LoadByLandcode"
body="LOADONE(ushort landCode) WHERE Landcode = #landcode">
</cf:method>
</cf:entity>
The generated code for the LoadByLandcode method looks like this:
public static Land LoadByLandcode(ushort landCode)
{
if ((landCode == CodeFluentPersistence.DefaultUInt16Value))
{
return null;
}
Land land = new Land();
CodeFluent.Runtime.CodeFluentPersistence persistence = CodeFluentContext.Get(BusinessLayerStoreName).Persistence;
persistence.CreateStoredProcedureCommand(null, "Land", "LoadByLandcode");
persistence.AddParameter("#landCode", landCode);
System.Data.IDataReader reader = null;
try
{
reader = persistence.ExecuteReader();
if ((reader.Read() == true))
{
land.ReadRecord(reader, CodeFluent.Runtime.CodeFluentReloadOptions.Default);
land.EntityState = CodeFluent.Runtime.CodeFluentEntityState.Unchanged;
return land;
}
}
finally
{
if ((reader != null))
{
reader.Dispose();
}
persistence.CompleteCommand();
}
return null;
}
As you can see CodeFluent returns null if the provided landCode parameter is 0. In order to avoid this check I have indicated that the landCode parameter is nullable:
<cf:method name="LoadByLandcode" body="LOADONE(ushort landCode?) WHERE Landcode = #landcode">
</cf:method>
or
<cf:method name="LoadByLandcode" body="LOADONE(ushort landCode) WHERE Landcode = #landcode">
<cf:parameter name="landCode" nullable="true" />
</cf:method>
Now in the BOM the check for 0 has been removed, but in the stored procedure a check for null on the landCode parameter has been added:
CREATE PROCEDURE [dbo].[Land_LoadByLandcode]
(
#landCode [smallint] = NULL
)
AS
SET NOCOUNT ON
IF (#landCode IS NULL)
BEGIN
SELECT DISTINCT [Land].[Land_Id], [Land].[Landcode], ...FROM [Land]
END
ELSE
BEGIN
SELECT DISTINCT [Land].[Land_Id], [Land].[Landcode], ... FROM [Land]
WHERE ([Land].[Landcode] = #landCode)
END
RETURN
I neither want a check for 0 in the BOM nor a check for NULL in the stored procedure. How can I achieve this?

To remove the default value check in the generated BOM, set cfom:checkDefaultValue="false".
<cf:method name="LoadByLandcode" body="LOADONE(ushort landCode) WHERE Landcode = #landcode">
<cf:parameter typeName="ushort" name="landCode" nullable="False" cfom:checkDefaultValue="false" modelNullable="False" usePersistenceDefaultValue="false" />
</cf:method>
If you use the graphical interface:
This generates:
public static Land LoadByLandcode(ushort landCode)
{
Land land = new Land();
CodeFluent.Runtime.CodeFluentPersistence persistence = CodeFluentContext.Get(Constants.StoreName).Persistence;
persistence.CreateStoredProcedureCommand(null, "Land", "LoadByLandcode");
persistence.AddRawParameter("#landCode", landCode);
System.Data.IDataReader reader = null;
try
{
reader = persistence.ExecuteReader();
if ((reader.Read() == true))
{
land.ReadRecord(reader, CodeFluent.Runtime.CodeFluentReloadOptions.Default);
land.EntityState = CodeFluent.Runtime.CodeFluentEntityState.Unchanged;
return land;
}
}
finally
{
if ((reader != null))
{
reader.Dispose();
}
persistence.CompleteCommand();
}
return null;
}
CREATE PROCEDURE [dbo].[Land_LoadByLandcode]
(
#landCode [smallint]
)
AS
SET NOCOUNT ON
SELECT DISTINCT [Land].[Land_Id], [Land].[Land_Landcode]
FROM [Land]
WHERE ([Land].[Land_Landcode] = #landCode)
RETURN
GO

Related

Salesforce Trigger Test Class

below is my Apex Trigger. I am a beginner and trying to write its test class but continuously getting error "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Error: You can't select products until you've chosen a price book for this opportunity on the products related list.: []".
trigger TrgrOptyHighestCustmorePrice on Opportunity (before insert, before update)
{
public Id oid;
public String bidType;
public String BUCode;
for(Opportunity o : trigger.new)
{
oid = o.Id;
bidType = o.BidType__c;
BUCode = o.Business_Line_BU__c;
}
List<OpportunityLineItem> oliList = new list<OpportunityLineItem>([SELECT id, Customer_Price__c, ReCat_Product_Line__c
FROM OpportunityLineItem
WHERE OpportunityId =: oid ORDER BY
Customer_Price__c DESC LIMIT 1]);
for(OpportunityLineItem oli : oliList)
{
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.619';
}
if(bidType == 'Competitive' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.620';
}
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.622';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.624';
}
if(bidType == 'Sole Sourced' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.621';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.623';
}
}
for(Opportunity opt : trigger.new)
{
opt.Business_Line_BU__c = BUCode;
}
}
Test Class
#isTest(seeAllData=true)
public class Test_TrgrOptyHighestCustmorePrice {
private static testmethod void TrgrOptyHighestCustmorePriceTest(){
Test.startTest();
//Insert a test product.
Product2 p1 = new Product2(Name='Product Monthly 1111', isActive=true, CurrencyIsoCode='USD', ReCat_Product_Line__c = 'DMS');
insert p1;
// Get standard price book ID.
Id pricebookId = Test.getStandardPricebookId();
// Insert a price book entry for the standard price book.
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = p1.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(
Pricebook2Id = customPB.Id, Product2Id = p1.Id,
UnitPrice = 12000, IsActive = true);
insert customPrice;
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619',
PriceBook2 = customPB);
insert opt;
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id);
insert optLI;
update opt;
Test.stopTest();
}
}
I am unable to understand how can I test my simple trigger.
Its because u do not fill all required fields for the Opportunity Line Item. See: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_opportunitylineitem.htm for required fields.
This as an example will work:
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id, TotalPrice = 100, PricebookEntryId=customPrice.Id, Quantity =3);
First Insert the opportunity.
Then update the opportunity with the pricebookid.
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619'
);
insert opt;
opt.PriceBook2 = customPB;
update opt;

LoadBy method returns null if provided parameter is 0

My model contains an entity with a numeric property:
<cf:entity name="Land">
<cf:property name="Id" key="true" />
<cf:property name="Landcode" typeName="ushort" nullable="false" usePersistenceDefaultValue="false" />
<cf:method name="LoadByLandcode"
body="LOADONE(ushort landCode) WHERE Landcode = #landcode">
</cf:method>
</cf:entity>
The generated code for the LoadByLandcode method looks like this:
public static Land LoadByLandcode(ushort landCode)
{
if ((landCode == CodeFluentPersistence.DefaultUInt16Value))
{
return null;
}
Land land = new Land();
CodeFluent.Runtime.CodeFluentPersistence persistence = CodeFluentContext.Get(BusinessLayerStoreName).Persistence;
persistence.CreateStoredProcedureCommand(null, "Land", "LoadByLandcode");
persistence.AddParameter("#landCode", landCode);
System.Data.IDataReader reader = null;
try
{
reader = persistence.ExecuteReader();
if ((reader.Read() == true))
{
land.ReadRecord(reader, CodeFluent.Runtime.CodeFluentReloadOptions.Default);
land.EntityState = CodeFluent.Runtime.CodeFluentEntityState.Unchanged;
return land;
}
}
finally
{
if ((reader != null))
{
reader.Dispose();
}
persistence.CompleteCommand();
}
return null;
}
Why does CodeFluent return null if the provided landCode parameter is 0?
I do not want this to happen, because landCode 0 is also a valid value in the database.
How can I change this behaviour?
The parameter of the method uses the persistence default value (0 by default). So to avoid the default value check, you have to indicate the parameter is nullable:
<cf:method name="LoadByLandcode"
body="LOADONE(Landcode?) WHERE Landcode = #Landcode">
</cf:method>
public static Land LoadByLandcode(ushort landcode)
{
Land land = new Land();
CodeFluent.Runtime.CodeFluentPersistence persistence = CodeFluentContext.Get(Constants.StoreName).Persistence;
persistence.CreateStoredProcedureCommand(null, "Land", "LoadByLandcode");
persistence.AddRawParameter("#Landcode", landcode);
System.Data.IDataReader reader = null;
try
{
reader = persistence.ExecuteReader();
if ((reader.Read() == true))
{
land.ReadRecord(reader, CodeFluent.Runtime.CodeFluentReloadOptions.Default);
land.EntityState = CodeFluent.Runtime.CodeFluentEntityState.Unchanged;
return land;
}
}
finally
{
if ((reader != null))
{
reader.Dispose();
}
persistence.CompleteCommand();
}
return null;
}

consume int result returned from stored procedure in MVC4

I have created stored procedure like this:
ALTER procedure [dbo].[takeOrder]
(
#id int = 0,
#userid int = 0,
#diningid int,
#amount float
)
as
begin
declare #countt as int
select #countt = COUNT(*)
from Order_master
where dining_Id = #diningid and isActive = 1
if #countt <> 0
begin
update Order_master
set amount = #amount
where dining_Id = #diningid and isActive = 1;
end
else
begin
insert into Order_master(userid, dining_Id, amount, [date], isActive)
values (#userid, #diningid, #amount, GETDATE(), 1)
end
--select amount from Order_master where dining_Id=#diningid and isActive=1
select oid
from Order_master
where dining_Id = #diningid and isActive = 1
end
In controller I am trying to get return result as mention below:
[HttpPost]
public ActionResult takeOrder(Order_master order,List<Menu_info> menu)
{
String msg = "";
int oid;
if (ModelState.IsValid)
{
try
{
Order_master objOreder = new Order_master
{
amount = order.amount,
isActive = 1,
date = order.date,
dining_Id = order.dining_Id,
userId = order.userId
};
object orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount);
oid = (int)orderId;
msg = "success..!!";
}
catch (Exception ex)
{
msg = "error...";
}
}
else
{
msg = "please provide info";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
{
return View();
}
}
But it returns an exception
Cannot convert type 'System.Data.Objects.ObjectResult' to 'int'
I am not able to get single return value from stored procedure.
Hope I get the right solution.
object orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount);
oid = (int)orderId;
Try this conversion method.
oid = Convert.ToInt32(orderId);
You can use like
public int InsertWebProperty(int orgid, int? userid, string address, string property_Id, string latitude, string longitude, int? compamyid)
{
return Convert.ToInt32((db.InsertWebProperty(orgid, userid, address, property_Id, latitude, longitude, 0)).FirstOrDefault().recidentity.Value);
}
Please let me know if it not worked for you..
Thanks
db.TakeOrder().FirstOrDefault().ToString() = One value returned as a string
db.TakeOrder().FirstOrDefault().ToList() = Row returned as a list.
Create view as
CREATE VIEW [dbo].[vScalar]
AS
SELECT '' AS Value
In Stored Procedure return
SELECT CAST(orderId AS VARCHAR(10)) AS value
In Entity Framework, set function return use entity vScalar
In code
vScalar orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount).FirstOrDefault;
oid = (int)orderId.value;

Strange behaviour with Plugin on Update of activity

I'm creating a plugin on creating a phonecall activity to update a field in the recipients contact entities. This plugin runs on Create and on Update of a phonecall activity.
On Create AND "new_targetfield" is null => Updates correctly
On Update AND "new_targetfield" not null => Updates correctly
On Update AND "new_targetfield" is null => Nothing happens
I tried running the Plugin Profiler but I keep getting an error:
<ErrorCode>-2147220970</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic
Here's a part of my code :
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = context.InputParameters["Target"] as Entity;
if (entity.LogicalName != "phonecall")
{
return;
}
DateTime activitydate=entity.GetAttributeValue<DateTime>("actualstart");
if (activitydate ==null && context.MessageName =="Update")
{
activitydate=((Entity)context.PostEntityImages["PhoneCallPostImage"]).GetAttributeValue<DateTime>("actualstart");
}
if (activitydate != null)
{
// update recipients
EntityCollection Recipients = entity.GetAttributeValue<EntityCollection>("to");
if (Recipients == null && context.MessageName == "Update")
{
Recipients = ((Entity)context.PostEntityImages["PhoneCallPostImage"]).GetAttributeValue<EntityCollection>("to");
}
if (Recipients != null)
{
foreach (Entity recipient in Recipients.Entities)
{
EntityReference partyId = recipient.GetAttributeValue<EntityReference>("partyid");
if (partyId != null)
{
// get recipient id
if (partyId.LogicalName == "contact")
{
Guid contactid = partyId.Id;
// update the recipient Last Contacted with Phone call date
string fetch = #"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='contact'>
<attribute name='contactid' />
<attribute name='new_targetfield' />
<filter type='and'>
<condition attribute='contactid' operator='eq' uitype='contact' value='"+contactid+#"' />
</filter>
</entity>
</fetch>";
EntityCollection result = service.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetch));
if (result.Entities.Count > 0)
{
DateTime lasttouched = result.Entities[0].GetAttributeValue<DateTime>("new_targetfield");
if (lasttouched != null)
{
if (activitydate > lasttouched)
{
Entity contact = new Entity();
contact.LogicalName = "contact";
contact.Id = contactid;
contact.Attributes = new AttributeCollection();
contact.Attributes.Add("new_targetfield", activitydate);
service.Update(contact);
}
else
{
continue;
}
}
else
{
Entity contact = new Entity();
contact.LogicalName = "contact";
contact.Id = contactid;
contact.Attributes = new AttributeCollection();
contact.Attributes.Add("new_targetfield", activitydate);
service.Update(contact);
}
}
}
else
{
continue;
}
}
else
{
continue;
}
}
}
The problem was that a DateTime variable will never be null but equal to the MinValue of DateTime. That's why parts of the code weren't approached.

Sorting on multiple column header in liferay searchcontainer

i done with sorting on single column header of liferay searchcontainer in liferay 6.0.6.
now i want to apply sorting on multiple fields i.e FirstName,LastName,Date either in asc or desc order.
can anybody help me out..
Thanks in advance....
view.jsp
<%
PortalPreferences portalPrefs = PortletPreferencesFactoryUtil.getPortalPreferences(request);
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");
System.out.println("Col "+ orderByCol);
if (Validator.isNotNull(orderByCol) && Validator.isNotNull(orderByType)) {
portalPrefs.setValue("NAME_SPACE", "order-by-col", orderByCol);
portalPrefs.setValue("NAME_SPACE", "order-by-type", orderByType);
} else {
orderByCol = portalPrefs.getValue("NAME_SPACE", "order-by-col", "Date");
orderByType = portalPrefs.getValue("NAME_SPACE", "order-by-type", "asc");
}
%>
<liferay-ui:search-container delta='20' emptyResultsMessage="No Form Submitted" orderByCol="<%= orderByCol %>" orderByType="<%= orderByType %>">
<liferay-ui:search-container-results>
<%
List<User> userList = UserLocalServiceUtil.getUsers(-1,-1);
OrderByComparator orderByComparator =
CustomComparatorUtil.getUserOrderByComparator(orderByCol, orderByType);
Collections.sort(userList,orderByComparator);
results = ListUtil.subList(userList, searchContainer.getStart(),
searchContainer.getEnd());
if (userList.size()< total)
{total = userList.size();
}
pageContext.setAttribute("results", results);
pageContext.setAttribute("total", total);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="com.liferay.portal.model.User"
modelVar="user">
<liferay-ui:search-container-column-text
name="Screen Name"
property="screenName"
orderable="<%= true %>"
orderableProperty="screenName"
/>
<liferay-ui:search-container-column-text
name="Email"
property="emailAddress"
orderable="<%= true %>"
orderableProperty="emailAddress"
/>
<liferay-ui:search-container-column-text
name="Date"
property="createDate"
orderable="<%= true %>"
/>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
CustomComparatorUtil
public static OrderByComparator getUserOrderByComparator(
String orderByCol, String orderByType) {
boolean orderByAsc = false;
if (orderByType.equals("asc")) {
orderByAsc = true;
}
OrderByComparator orderByComparator = null;
System.out.println("Custom "+ orderByCol);
if (orderByCol.equalsIgnoreCase("screenName")) {
System.out.println("1");
orderByComparator = new FirstNameComparator(orderByAsc);
}
else if (orderByCol.equalsIgnoreCase("emailAddress")) {
System.out.println("2");
orderByComparator = new EmailComparator(orderByAsc);
}
else if (orderByCol.equalsIgnoreCase("Date")) {
System.out.println("3");
orderByComparator = new DateComparator(orderByAsc);
}/*
else if (orderByCol.equalsIgnoreCase("Job Title")) {
orderByComparator = new JobTitleComparator(orderByAsc);
}*/
return orderByComparator;
}
FirstNameComparator
public static String ORDER_BY_ASC = "status ASC";
public static String ORDER_BY_DESC = "status DESC";
public FirstNameComparator()
{
this(false);
}
public FirstNameComparator(boolean asc) {
_asc = asc;
}
public int compare(Object obj1, Object obj2) {
User instance1 = (User) obj1;
User instance2 = (User) obj2;
int value = instance1.getFirstName().toLowerCase().compareTo(instance2.getFirstName().toLowerCase());
if(_asc)
{
return value;
} else
{
return -value;
}
}
public String getOrderBy() {
if (_asc) {
return ORDER_BY_ASC;
}
else {
return ORDER_BY_DESC;
}
}
private boolean _asc;
}
similarly u can make class for emailaddress and date..