Datepicker Input in Lightning Web Component - salesforce

I want to any pass date value from Datepicker input of lightning web component to PostingDate variable in LWCcontroller.cls
import { LightningElement,api ,track} from 'lwc';
import getInvoiceData from '#salesforce/apex/CustomerRefundLwcController.getInvoiceData';
import getBankAccounts from '#salesforce/apex/CustomerRefundLwcController.getBankAccounts';
import processCustomerRefund from '#salesforce/apex/CustomerRefundLwcController.processCustomerRefund';
export default class CustomerRefund extends LightningElement {
#api recordId; /*Sales Credit Id*/
#track invoiceData;
#track invoiceLinesData;
#api headerText;
#api recordProcessing;
#api bankAccounts = new Array();
#track selectedBankId;
#track allocateToSalesCredit;
#track referenceDetail;
#track bShowModal = false;
#track PostingDate;
/*Toast Event Variables*/
#api isError = false;
#api iswarning = false;
#api issuccess = false;
#api ToastMessage;
PostingDateChange(event)
{
this.PostingDate = event.target.value;
this.invoiceData.PostingDate = this.PostingDate;
}
processRefundHandler() {
this.recordProcessing = true;
//console.log('this.formData----'+JSON.stringify(this.invoiceLinesData));
console.log('this.formData----'+JSON.stringify(this.invoiceData));
processCustomerRefund({ lstInvoiceLines : this.invoiceLinesData, bankId : this.selectedBankId, allocateToSalesCredit : this.allocateToSalesCredit, reference : this.referenceDetail, postingdate : this.PostingDate })
.then(result => {
var responseMessage = result;
this.recordProcessing = false;
this.ToastMessage = responseMessage;
if(responseMessage == "Success"){
//this.issuccess = true;
this.isError = false;
this.ToastMessage = "Your Bank Customer Refund has been created";
this.bShowModal = true;
}else{
this.isError = true;
}
})
.catch(error => {
this.isError = true;
this.ToastMessage = error ;
console.log(error);
});
}
<div class="slds-col">
<label class="slds-form-element__label slds-no-flex">Posting Date</label>
<lightning-input type="date"
name="Postingdate"
value={PostingDate}
onchange={PostingDateChange}
>
</lightning-input>
</div>
CRLWC.cls
#AuraEnabled
public static string processCustomerRefund(List lstInvoiceLines,string bankId,boolean allocateToSalesCredit,string reference){
system.debug('start update');
string successMessage = 'Success';
string responseMessage = 'Success';
Savepoint spTran = database.setSavePoint();
try{
List<Sales_Invoice_Line_Item__c> lstLinesToUpdate = new List<Sales_Invoice_Line_Item__c>();
decimal amount=0;
Id taxRate;
Id salesinvoiceid;
boolean isValid = true;
boolean allocateToInvoice = allocateToSalesCredit;
map<id,Sales_Invoice_Line_Item__c> mapOfSelectedLines = new map<id,Sales_Invoice_Line_Item__c>();
for(ScLineWrapper lineWrapper : lstInvoiceLines){
system.debug('isselect>> ' + lineWrapper.isSelected);
if(lineWrapper.isSelected){
salesinvoiceid = lineWrapper.InvoiceLine.Sales_Invoice__c;
decimal lineAmount = lineWrapper.InvoiceLine.Foreign_Gross__c;
if(lineAmount != null && lineAmount > 0){
amount += lineAmount;
mapOfSelectedLines.put(lineWrapper.InvoiceLine.id,lineWrapper.InvoiceLine);
}
if(lineWrapper.InvoiceLine.Tax_Rate__c != null){
taxRate = lineWrapper.InvoiceLine.Tax_Rate__c;
}
}
}
if(salesinvoiceid == null){
isValid = false;
responseMessage = 'Please select at least one sales invoice line';
}else if(bankId == null){
isValid = false;
responseMessage = 'Please select bank account';
}else if(amount <= 0){
isValid = false;
responseMessage = 'Refund amount should be greater than zero';
}
system.debug('updatelst>> ' + lstLinesToUpdate);
//update lstLinesToUpdate;
if(isValid){
Sales_Invoice__c siInfo = [select id,Status__c,Account__c,Name from Sales_Invoice__c where id=: salesinvoiceid];
BankCustomerRefundService objCustomerRefundService = new BankCustomerRefundService();
BankCustomerRefundService.BankCustomerRefundWrapper objRefundWrapper = new BankCustomerRefundService.BankCustomerRefundWrapper();
Id accountId = siInfo.Account__c;
objRefundWrapper.AccountId = accountId;
objRefundWrapper.PostingDate = Date.Today()+(-216);
objRefundWrapper.BankAccountId = bankId;
objRefundWrapper.TaxRate = taxRate;
objRefundWrapper.Amount = amount;
objRefundWrapper.Reference = reference;
BankCustomerRefundService.Response objResponse = objCustomerRefundService.CreateBankCustomerRefund(objRefundWrapper);
responseMessage = objResponse.ResponseMessage;
if(allocateToInvoice && responseMessage == successMessage){
Bank_Payment__c objBankPayment = objResponse.BankPayments.get(accountId);
List<Ledger__c> listofLedgers = [Select id,name,Foreign_Gross_Total__c,Type__c
FROM Ledger__c
Where Customer_Supplier_Account_Name__c =: accountId AND Show_On_Transaction__c=1
AND Paid__c = 'N' AND Is_Deleted__c = false
AND (Sales_Invoice_Line_Item__c IN: mapOfSelectedLines.keyset() OR Bank_Payment__c =: objBankPayment.id) ];
if(!listofLedgers.isEmpty()){
BankAllocateCreditsAndPaymentsService objAllocateCreditsAndPaymentService = new BankAllocateCreditsAndPaymentsService();
BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsWrapper objAllocateCreditWrapper = new BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsWrapper();
objAllocateCreditWrapper.AccountId = accountId;
objAllocateCreditWrapper.PostingDate = Date.Today()+(-216);
List<BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper> BankAllocateCreditsAndPaymentsLines = new List<BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper>();
for(Ledger__c ledger : listofLedgers){
BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper objPaymentLine = new BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper();
objPaymentLine.LedgerName = ledger.Name;
objPaymentLine.Amount = ledger.Foreign_Gross_Total__c;
BankAllocateCreditsAndPaymentsLines.add(objPaymentLine);
}
objAllocateCreditWrapper.BankAllocateLines = BankAllocateCreditsAndPaymentsLines;
BankAllocateCreditsAndPaymentsService.Response objAllocateResponse = objAllocateCreditsAndPaymentService.BankAllocateCustomerBalance(objAllocateCreditWrapper);
responseMessage = objAllocateResponse.ResponseMessage;
system.debug('Response>>' + objAllocateResponse.ResponseMessage);
}
}
}
}catch(Exception ex){
responseMessage = ex.getStackTraceString();
}
if(responseMessage != successMessage){
Database.rollback(spTran);
}
system.debug('Response>>' + responseMessage);
return responseMessage;
}

You need to add the new parameter postingdate to the Apex Method
#AuraEnabled
public static string processCustomerRefund (
List lstInvoiceLines,
String bankId,
Boolean allocateToSalesCredit,
String reference,
Long postingdate
) {
I'm not sure long is the correct type thought, maybe DateTime or Date, I don't remember how Salesforce handle this. If it's long, it would be a timestamp.

Lightning input (type="date") returns a string in YYYY-MM-DD format.
Here's what I did:
public static Date convertDate(String datestr){
List<String> dateSplit = datestr.split('-');
return Date.newInstance(Integer.valueOf(dateSplit[0]), Integer.valueOf(dateSplit[1]), Integer.valueOf(dateSplit[2]));
}
You could also simply use Date as a parameter type in the apex method and that should work as well.

Related

Apex Specialist Challenge 1

I cannot resolve this error.
Closing a Maintenance Request of type 'Routine Maintenance' or 'Repair' did not create of a new Maintenance Request with the correct due date. The challenge is expecting the due date to be calculated using the maintenance cycle defined on the related equipment records. If multiple equipments are used in the maintenance request, choose the shortest maintenance cycle to define the service date.
I'm having a really hard time finishing this challenge. I want to know that which part of my code is wrong, not just answer.
// TriggerHandler
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(Map<Id, Case> oldCases) {
// TODO: Complete the method to update workorders
Map<Id, Integer> toGetDueDateMap = new Map<Id, Integer>();
AggregateResult[] results = [SELECT Id, MIN(Maintenance_Cycle__c) minMC FROM Product2 GROUP BY Id];
for (AggregateResult ar : results) {
if (ar != null) {
toGetDueDateMap.put(ar.Id, Integer.valueOf(ar.get('minMC')));
}
}
List<Case> newCases = new List<Case>();
for (Case c : oldCases.values()) {
Case newCase = new Case();
newCase.Status = 'New';
newCase.Origin = 'web';
newCase.Vehicle__c = c.Vehicle__c;
newCase.ProductId = c.ProductId;
newCase.Type = 'Routine Maintenance';
newCase.Subject = 'Routine Maintenance';
newCase.Date_Reported__c = Date.today();
newCase.Date_Due__c = (toGetDueDateMap.get(c.Id) != null) ? Date.today().addDays(toGetDueDateMap.get(c.Id)) : Date.today();
newCases.add(newCase);
}
insert newCases;
}
}
// Trigger
trigger MaintenanceRequest on Case (after update) {
// ToDo: Call MaintenanceRequestHelper.updateWorkOrders
Map<Id, Case> caseToEvaluate = new Map<Id, Case>();
if(Trigger.isAfter && Trigger.isUpdate) {
for(Case c : Trigger.New) {
if(c.Status == 'Closed' && (c.Type == 'Repair' || c.Type == 'Routine Maintenance')) {
caseToEvaluate.put(c.Id, c);
}
}
}
MaintenanceRequestHelper.updateWorkOrders(caseToEvaluate);
}
I create correct algoritm to find less maintenance cycle days.
Try it.
newCase.Date_Due__c = Date.today() + suchEarlyDay(newMaintenanceRequest).get(cases.Id);
newCases.add(newCase);
}
}
if (newCases.size() > 0) {
insert newCases;
}
}
private static Map<Id, Integer> suchEarlyDay(List<Case> cases) {
Map<Id, Case> caseMap = new Map<Id, Case>(cases);
Map<Id, Integer> lessDate = new Map<Id, Integer>();
List<Equipment_Maintenance_Item__c> relatedList = [
SELECT Maintenance_Request__c,
Equipment__r.Maintenance_Cycle__c
FROM Equipment_Maintenance_Item__c
WHERE Maintenance_Request__c = :caseMap.keySet()
];
for (Id caseId : caseMap.keySet()) {
for (Equipment_Maintenance_Item__c equip : relatedList) {
if (!lessDate.containsKey(caseId) && caseId == equip.Maintenance_Request__c) {
lessDate.put(caseId, (Integer) equip.Equipment__r.Maintenance_Cycle__c);
} else if (lessDate.containsKey(caseId) && lessDate.get(caseId) > (Integer) equip.Equipment__r.Maintenance_Cycle__c) {
lessDate.put(caseId, (Integer) equip.Equipment__r.Maintenance_Cycle__c);
}
}
}
return lessDate;
}
This link helped me, so I modified the code like this:
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<Case> updWorkOrders, Map<Id,Case> nonUpdCaseMap) {
Set<Id> validIds = new Set<Id>();
For (Case c : updWorkOrders){
if (nonUpdCaseMap.get(c.Id).Status != 'Closed' && c.Status == 'Closed'){
if (c.Type == 'Repair' || c.Type == 'Routine Maintenance'){
validIds.add(c.Id);
}
}
}
if (!validIds.isEmpty()){
List<Case> newCases = new List<Case>();
Map<Id,Case> closedCasesM = new Map<Id,Case>([SELECT Id, Vehicle__c, ProductId, Product.Maintenance_Cycle__c,(SELECT Id,Equipment__c,Quantity__c FROM Equipment_Maintenance_Items__r)
FROM Case WHERE Id IN :validIds]);
Map<Id,Decimal> maintenanceCycles = new Map<ID,Decimal>();
AggregateResult[] results = [SELECT Maintenance_Request__c, MIN(Equipment__r.Maintenance_Cycle__c)cycle FROM Equipment_Maintenance_Item__c WHERE Maintenance_Request__c IN :ValidIds GROUP BY Maintenance_Request__c];
for (AggregateResult ar : results){
maintenanceCycles.put((Id) ar.get('Maintenance_Request__c'), (Decimal) ar.get('cycle'));
}
for(Case cc : closedCasesM.values()){
Case nc = new Case (
ParentId = cc.Id,
Status = 'New',
Subject = 'Routine Maintenance',
Type = 'Routine Maintenance',
Vehicle__c = cc.Vehicle__c,
ProductId =cc.ProductId,
Origin = 'Web',
Date_Reported__c = Date.Today()
);
If (maintenanceCycles.containskey(cc.Id)){
nc.Date_Due__c = Date.today().addDays((Integer) maintenanceCycles.get(cc.Id));
} else {
nc.Date_Due__c = Date.today().addDays((Integer) cc.Product.maintenance_Cycle__c);
}
newCases.add(nc);
}
insert newCases;
List<Equipment_Maintenance_Item__c> clonedWPs = new List<Equipment_Maintenance_Item__c>();
for (Case nc : newCases){
for (Equipment_Maintenance_Item__c wp : closedCasesM.get(nc.ParentId).Equipment_Maintenance_Items__r){
Equipment_Maintenance_Item__c wpClone = wp.clone();
wpClone.Maintenance_Request__c = nc.Id;
ClonedWPs.add(wpClone);
}
}
insert ClonedWPs;
}
}
}
And the trigger:
trigger MaintenanceRequest on Case (before update, after update) {
if(Trigger.isUpdate && Trigger.isAfter){
MaintenanceRequestHelper.updateWorkOrders(Trigger.New, Trigger.OldMap);
} }
Apex Trigger :
trigger MaintenanceRequest on Case (before update, after update) {
// ToDo: Call MaintenanceRequestHelper.updateWorkOrders
if(Trigger.isAfter && Trigger.isUpdate){
MaintenanceRequestHelper.updateWorkOrders(Trigger.new);
}
}
Apex Handler:
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<Case> existingMainReq) {
// TODO: Complete the method to update workorders
Integer count = 0;
Map<Id, Integer> toGetDueDateMap = new Map<Id, Integer>();
Map<Id,Case> newCasesToIdsMap = new Map<Id,Case>();
List<Case> createNewMainReq = new List<Case>();
List<Case> caseIdsList = new List<Case>();
Map<Equipment_Maintenance_Item__c,Id> EquipMainItemsToProdIds = new Map<Equipment_Maintenance_Item__c,Id>();
if(!existingMainReq.isEmpty()){
for(Case cc : existingMainReq){
if((cc.Type == 'Repair' || cc.Type == 'Routine Maintenance') && cc.Status == 'Closed'){
caseIdsList.add(cc);
}
}
}
List<Equipment_Maintenance_Item__c> equipMainList = [Select id,Equipment__c,Maintenance_Request__c from Equipment_Maintenance_Item__c where Maintenance_Request__c IN : caseIdsList];
if(!equipMainList.isEmpty()){
for(Equipment_Maintenance_Item__c equipMainn : equipMainList){
EquipMainItemsToProdIds.put(equipMainn,equipMainn.Equipment__c);
system.debug(EquipMainItemsToProdIds.size());
if(EquipMainItemsToProdIds.size() > 1){
count = EquipMainItemsToProdIds.size();
}
}
}
List<Equipment_Maintenance_Item__c> EMIList = [Select Equipment__r.Maintenance_Cycle__c,Equipment__c from Equipment_Maintenance_Item__c where Equipment__r.Id IN :EquipMainItemsToProdIds.values() AND Maintenance_Request__c IN:caseIdsList order By Equipment__r.Maintenance_Cycle__c ASC limit 1];
for(Equipment_Maintenance_Item__c equip : EMIList){
toGetDueDateMap.put(equip.Id,Integer.valueOf(equip.Equipment__r.Maintenance_Cycle__c));
for(Case c : caseIdsList){
Case mainRe = new Case();
mainRe.Vehicle__c = c.Vehicle__c;
mainRe.status = 'New';
mainRe.Type = 'Routine Maintenance';
mainRe.Subject = 'New Main Request For Vehicle for Apex Specialist';
mainRe.Date_Reported__c = date.today();
if(count > 1){
mainRe.Date_Due__c = Date.today().addDays(toGetDueDateMap.get(equip.Id));
}
else{
mainRe.Date_Due__c = Date.today();
}
createNewMainReq.add(mainRe);
newCasesToIdsMap.put(c.Id,mainRe);
}
insert createNewMainReq;
if(caseIdsList.size()>0 && newCasesToIdsMap.size()>0){
cloneEquipItems(caseIdsList,newCasesToIdsMap);
}
}
}
public static void cloneEquipItems(List<case> closedCaseRecords, Map<Id,case> newCreatedCasesMapp){
List<Equipment_Maintenance_Item__c> newEquipItems = new List<Equipment_Maintenance_Item__c>();
try{
if(!closedCaseRecords.isEmpty() && newCreatedCasesMapp.size()>0){
List<Equipment_Maintenance_Item__c> oldEquipItems = [SELECT Equipment__c, Maintenance_Request__c, Quantity__c,Maintenance_Request__r.Id
FROM Equipment_Maintenance_Item__c
WHERE Maintenance_Request__c IN :closedCaseRecords];
for(Equipment_Maintenance_Item__c equipItem : oldEquipItems) {
Equipment_Maintenance_Item__c newItem = equipItem.clone(false, true, false, false);
newItem.Maintenance_Request__c = newCreatedCasesMapp.get(equipItem.Maintenance_Request__c).id;
newEquipItems.add(newItem);
}
insert newEquipItems;
}
}
catch(Exception e){
System.debug('Exception is'+ e);
}
}
}

Not able to update the data in more than one table in Asp .net MVC5

Here I am able to add the data in more than one table. Let i have 3 tables User, Franchise and Fee.
I am not able to update the data in more than one table,it throwing the exception:
A referential integrity constraint violation occurred: The property value(s) of 'User.Id' on one end of a relationship do not match the property value(s) of 'Franchise.UserId' on the other end.
Code:
public MessageResult SaveAndUpdateFranchisee(UserViewModel model)
{
var result = new MessageResult();
try
{
User userData = new User();
Franchise franchiseData = new Franchise();
var ExistUser = db.Users.Where(a => a.Id == model.Id).FirstOrDefault();
//Update record
if (model.Id > 0)
{
Fee feeData = new Fee
{
FranchiseeFee = model.FranchiseeFee,
PaymentTermsFranchiseFee = model.PaymentTermsFranchiseFee,
EquipmentCost = model.EquipmentCost,
PaymentTermsEquipmentCost = model.PaymentTermsEquipmentCost,
OtherFee = model.OtherFee,
PaymentTermsOtherFee = model.PaymentTermsOtherFee,
ConsumableStock = model.ConsumableStock,
PaymentTermsConsumableStock = model.PaymentTermsConsumableStock,
FrozenFoodStock = model.FrozenFoodStock,
PaymentTermsFrozenFoodStock = model.PaymentTermsFrozenFoodStock,
TotalAmountDue = model.TotalAmountDue,
TotalAmountPaid = model.TotalAmountPaid,
BalanceAmount = model.BalanceAmount,
LoyaltyFeePercentage = model.LoyaltyFeePercentage,
FixedMonthlyFee = model.FixedMonthlyFee,
Note = model.Note,
UserId = model.CurrentUserId,
LOIDocUrl = model.LOIDocUrl,
ModifiedDate = DateTime.Now
};
ExistUser.Email = model.Email;
//var pwd = SecutiryServices.EncodePasswordToBase64(model.Password);
//userData.Password = pwd;
ExistUser.Password = model.Password;
ExistUser.FirstName = model.FirstName;
ExistUser.MiddleName = model.MiddleName;
ExistUser.LastName = model.LastName;
ExistUser.FullName = model.FullName;
ExistUser.MobileNo = model.MobileNo;
ExistUser.ModifyDate = DateTime.Now;
franchiseData.Name = model.FullName;
franchiseData.MobileNo = model.MobileNo;
franchiseData.AlternateNo = model.AlternetNo;
franchiseData.CompanyPhoneNo = model.PhoneNo;
franchiseData.Address = model.Address;
franchiseData.City = model.City;
franchiseData.State = model.State;
franchiseData.PinCode = model.PinCode;
franchiseData.CompanyName = model.CompanyName;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyCity = model.CompanyCity;
franchiseData.CompanyState = model.CompanyState;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyPinCode = model.CompanyPinCode;
franchiseData.ModifiedDate = DateTime.Now;
userData.Franchises.Add(franchiseData);
foreach (var item in userData.Franchises)
{
item.Fees.Add(feeData);
}
db.Users.Attach(userData);
db.Entry(userData).State = System.Data.Entity.EntityState.Modified;
//db.Users.Add(userData);
db.SaveChanges();
result.Message = "Your franchise has been updated successfully..";
result.Status = true;
}
//For Insert recored..
else
{
Fee feeData = new Fee
{
FranchiseeFee = model.FranchiseeFee,
PaymentTermsFranchiseFee = model.PaymentTermsFranchiseFee,
EquipmentCost = model.EquipmentCost,
PaymentTermsEquipmentCost = model.PaymentTermsEquipmentCost,
OtherFee = model.OtherFee,
PaymentTermsOtherFee = model.PaymentTermsOtherFee,
ConsumableStock = model.ConsumableStock,
PaymentTermsConsumableStock = model.PaymentTermsConsumableStock,
FrozenFoodStock = model.FrozenFoodStock,
PaymentTermsFrozenFoodStock = model.PaymentTermsFrozenFoodStock,
TotalAmountDue = model.TotalAmountDue,
TotalAmountPaid = model.TotalAmountPaid,
BalanceAmount = model.BalanceAmount,
LoyaltyFeePercentage = model.LoyaltyFeePercentage,
FixedMonthlyFee = model.FixedMonthlyFee,
Note = model.Note,
UserId = model.CurrentUserId,
LOIDocUrl = model.LOIDocUrl,
CreatedDate = DateTime.Now
};
userData.Email = model.Email;
//var pwd = SecutiryServices.EncodePasswordToBase64(model.Password);
//userData.Password = pwd;
userData.Password = model.Password;
userData.FirstName = model.FirstName;
userData.FullName = model.FirstName + " " + model.LastName;
userData.LastName = model.LastName;
userData.MobileNo = model.MobileNo;
userData.IsActive = true;
userData.IsDelete = false;
userData.CreatedDate = DateTime.Now;
userData.UserTypeId = 2;
franchiseData.CompanyId = model.CurrentUserId;
franchiseData.Name = userData.FullName;
franchiseData.MobileNo = model.MobileNo;
franchiseData.AlternateNo = model.AlternetNo;
franchiseData.Address = model.Address;
franchiseData.City = model.City;
franchiseData.State = model.State;
franchiseData.PinCode = model.PinCode;
franchiseData.CompanyName = model.CompanyName;
franchiseData.CompanyPhoneNo = model.PhoneNo;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyCity = model.CompanyCity;
franchiseData.CompanyState = model.CompanyState;
franchiseData.CompanyAddress = model.CompanyAddress;
franchiseData.CompanyPinCode = model.CompanyPinCode;
franchiseData.CreatedDate = DateTime.Now;
franchiseData.IsActive = true;
userData.Franchises.Add(franchiseData);
foreach (var item in userData.Franchises)
{
item.Fees.Add(feeData);
}
db.Users.Add(userData);
db.SaveChanges();
//db.AddUserRole(userData.Id, 4);
result.Message = "Your franchisee has been created successfully..";
result.Status = true;
}
return result;
}
catch (Exception ex)
{
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
return result;
}
}
The error message is straightforward - your code is creating a new Franchise object but it never sets the franchiseData.UserId property.
Add this to your franchiseData population code before you call db.SaveChanges():
franchiseData.UserId = model.CurrentUserId;
BTW, you should add code verify that the current user has permission to set foreign-key reference properties (like UserId) directly from values read from submitted forms because otherwise any user could enter Id values belonging to other users and gain access to information they shouldn't have access to - or otherwise alter with your database.

Assigns me no mail after user creation - Does Logic Apps make a mistake?

This is the case, for example, if a user now creates a page. So the next day I need Azure Logic apps to send an email after 1 day.
The problem is: right now, it is by no means sending any email to me if I sign up yesterday. But it sends me an email that now it has gone through with succe.
I would like to know what goes wrong since it by no means email me as I set up yesterday.
My Logic app (From Azure) - Images
However, be aware that the code can be made short but I just need to find out if Logic apps are making mistakes or if thus my code previously works without problems.
[Route("/api/cronjob")]
[HttpGet]
public async Task<IActionResult> NewSletterUserEmail()
{
await Newsletter();
return Ok("Godkendt!");
}
public async Task<IActionResult> Newsletter()
{
var m = new Settings.ArdklarMail();
var dtt = DateTime.Now;
var days = _dbContext.OfferUser.Max(i => i.Days);
var MaxDays = DateTime.Now.AddDays(-days);
var userlist = _dbContext.Users.Where(i => i.Opretdate >= MaxDays && i.TilmeldtNyhedsbrev == true).ToList();
if (userlist != null)
{
foreach (var item in userlist)
{
string mail = item.Brugernavn;
string fullname = item.Navn;
var memberData = _dbContext.MemberShipValue.FirstOrDefault(r => r.UserId == item.UserId);
if (memberData == null)
{
//alm bruger
var result = _dbContext.OfferUser.Where(x => x.Value == 1).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
else
{
var result = _dbContext.OfferUser.Where(x => x.Value == 2).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
}
}
//Det er til dem fra nyhedsbrevet som få tilsendt nyhedsbrev omkring div ting.
var newsletterlist = _dbContext.NewsletterList.Where(i => i.Tilmeldtdato >= MaxDays).ToList();
if (newsletterlist != null)
{
foreach (var item in newsletterlist)
{
string mail = item.Email;
string fullname = item.Email;
//til de nyhedsbrevet område
var result = _dbContext.OfferUser.Where(x => x.Value == 3).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Tilmeldtdato.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(mail);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(3500);
}
}
}
}
}
return Ok("Godkendt!");
}
No, I don't see mistake in Azure Logic Apps. Since the Logic App uses a recurrence trigger, it triggers the Logic App at the defined interval of time.
As there was send email action both side on the parallel branch, it will somehow send you an email by no means.

EWS - appointment.body created by outlook365 client returns empty

I have a problem: cannot get appointment body if it was created by outlook365 client.
When i run the code all properties values are being received except body.
After some searching i've found out that appointment bodies are not being received if appointments were made by outlook365.
Please, help!
The code:
public static List<Appointment> SetupConnection()
{
ServicePointManager.ServerCertificateValidationCallback = CallbackMethods.CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("Someuser#somedomain.com", "SomePassword");
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
Folder calendarFolder = GetCalendarFolder(service, #"\");
return GetMeetings(calendarFolder, service);
}
public static List<Appointment> GetMeetings(Folder calendarFolder, ExchangeService service)
{
if (calendarFolder == null)
{
return null;
}
SearchFilter.SearchFilterCollection filters = new SearchFilter.SearchFilterCollection(LogicalOperator.And)
{
new SearchFilter.IsGreaterThan(AppointmentSchema.Start, DateTime.Today)
};
List<Appointment> meetings = new List<Appointment>();
const Int32 pageSize = 30;
ItemView itemView = new ItemView(pageSize);
PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly);
itemView.PropertySet = propertySet;
FindItemsResults<Item> findResults = null;
do
{
findResults = calendarFolder.FindItems(filters, itemView);
itemView.Offset += pageSize;
meetings.AddRange(findResults.Cast<Appointment>());
} while (findResults.MoreAvailable);
PropertySet propertySet1 = new PropertySet(BasePropertySet.IdOnly);
propertySet1.Add(ItemSchema.Body);
propertySet1.Add(ItemSchema.Subject);
propertySet1.Add(AppointmentSchema.Organizer);
propertySet1.Add(AppointmentSchema.Start);
propertySet1.Add(AppointmentSchema.End);
propertySet1.Add(AppointmentSchema.Duration);
propertySet1.Add(AppointmentSchema.AppointmentType);
propertySet1.Add(AppointmentSchema.ConferenceType);
propertySet1.Add(AppointmentSchema.IsOnlineMeeting);
propertySet1.Add(AppointmentSchema.IsMeeting);
propertySet1.Add(AppointmentSchema.IsRecurring);
propertySet1.Add(AppointmentSchema.HasAttachments);
propertySet1.Add(AppointmentSchema.RequiredAttendees);
propertySet1.Add(AppointmentSchema.Resources);
propertySet1.Add(AppointmentSchema.InternetMessageHeaders);
propertySet1.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.Text;
service.LoadPropertiesForItems(meetings, propertySet1);
return meetings;
}
}
Your code is only returning IdOnly
Try changing BasePropertySet.IdOnly to BasePropertySet.FirstClassProperties

How to retrieve parentaccountid from account using queryexpression and silverlight

My query returns account.name, account.account and account.parentaccountid.
I'm using Silverlight and CRM2011.
Now I'm having trouble to find out how to extract value from parentaccountid attribute.
I have silverlightextensionmethods.cs file included in my VS project, and I'm using GetAttributeValue<Guid>("parentaccountid") to get the value from parentaccountid.
The value returned is empty.
Has anyone any ideas how to accomplish this?
I can get any other attribute value, but parentaccountid in account and parentcustomerid in contact are making my life very difficult.
Code:
FIRST I CREATE QUERYEXPRESSION:
string temp="name;accountid;parentaccountid";
string[] fields = temp.Split(';');
QueryExpression query = new QueryExpression()
{
EntityName = entity,
ColumnSet = new ColumnSet { Columns = new System.Collections.ObjectModel.ObservableCollection<string>(fields) },
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = parentidfield,
Operator = ConditionOperator.Equal,
Values = { id }
}
}
}
};
OrganizationRequest req = new OrganizationRequest();
req.RequestName = "RetrieveMultiple";
req["Query"] = query;
service.BeginExecute(req, new AsyncCallback(GetChildren_ExecuteCallBack), service);
NEXT I TY TO READ VALUES FORM RESPONSE
void GetChildren_ExecuteCallBack(IAsyncResult childresult)
{
List<TreeRecord> listc = new List<TreeRecord>();
try
{
OrganizationResponse childresponse = ((IOrganizationService)childresult.AsyncState).EndExecute(childresult);
EntityCollection childresults = (EntityCollection)childresponse["EntityCollection"];
if (childresults.Entities.Count > 0)
{
TreeConfig sitm = new TreeConfig();
string sdisplay = "";
string[] fields = "".Split(';');
string sid = "";
string pid = "";
foreach (Entity childentity in childresults.Entities)
{
foreach (TreeConfig sitem in Configs)
{
if (sitem.EntityName == childentity.LogicalName)
{
sitm = sitem;
}
}
TreeRecord childitem = new TreeRecord();
string sValue = "";
sdisplay = "name;accountid;parentaccountid";
fields = sdisplay.Split(';');
sid = "accountid";
pid = "parentaccountid";
int i = sdisplay.Split(';').Length;
for (int j = 0; j < i; j++)
{
try { sValue += childentity.GetAttributeValue<string>(fields[j]) + " "; }
catch (Exception ex)
{
//s = "sValue haku: " + ex.Message.ToString();
//this.ReportMessage(s.ToString());
}
}
childitem.Name = sValue;
childitem.EntityName = childentity.LogicalName;
childitem.Level = sitm.Level;
childitem.ParentEntityName = sitm.EntityName;
childitem.Color = sitm.Color;
childitem.RecordId = childentity.GetEntityId<Guid>(sid);
try { childitem.ParentId = childentity.GetAttributeValue<Guid>(pid); }
catch
{
//sb.AppendLine("guid: parentid tietoa ei löydy");
//this.ReportMessage(sb.ToString());
}
listc.Add(childitem);
}
}
}
Instead of
childentity.GetAttributeValue<Guid>(pid)
use
childentity.GetAttributeValue<EntityReference>(pid)

Resources