I am using the attached test class which contains one method (testManualApprovalProcessManuallyApproved) to debug my code.
I have turned on/off the apex debugger then got the debug logs and run the replay debugger to check my code, I have put a lot of break points between the Test.startTest(); and test.stopTest(); in the code below however when I run my replay debugger and step into the Test.startTest(); the debugger jump all the break points and finish the whole unit test method.
Is there a way to debug line by line between Test.startTest(); and test.stopTest();
#isTest
public class PPAndLoanApprovalProcessTest_NEW {
/**
* #name setup
* #parm
* #desc test set up method
* #version 1.0
* #author : Someone
**/
#testsetup
private static void setUp() {
Test.startTest();
LogSeverityLevelValue__c logLevelSettings = TestDataFactorySFN.createLoggingLevel();
Database.upsert(logLevelSettings);
//Switch on the triggers
List<Trigger_Bypass__c> tSwitch = TestDataFactorySFN.createTriggerSwitch();
Database.insert(tSwitch);
List<Account> listAccBus = new List<Account>();
List<Account> listAccInd = new List<Account>();
Profile p= [SELECT Id From Profile WHERE Name='nTest' OR Name='nTest2' LIMIT 1];
User smevsde = [SELECT Id FROM user WHERE profileid = : p.Id and IsActive = true LIMIT 1];
system.debug('setup smevsde-->' + smevsde.Id);
//insert Product structure matrix
Product_StructureMatrix__c prdstm = new Product_StructureMatrix__c();
prdstm.Name='987654321';
prdstm.Product__c='Commercial (VR)';
prdstm.Product_Type__c='SME - Term loan';
prdstm.Product_Type_ID__c='123456789';
prdstm.Segment__c='SME';
insert prdstm;
Product_StructureMatrix__c prdstm2 = new Product_StructureMatrix__c();
prdstm2.Name='987654321';
prdstm2.Product__c='Commercial';
prdstm2.Product_Type__c='SME - Line of credit';
prdstm2.Product_Type_ID__c='123456789';
prdstm2.Segment__c='SME';
insert prdstm2;
system.runAs(smevsde){
//Create Business Accounts
listAccBus = SystemTestDataFactory.createTestAccounts(1);
//Create Opportunity from Business Account
/**Method Definition : SystemTestDataFactory.oppcreate(Account Id,Name,Stage,Loss Reason,Product Line, Product Type,
Product, Amount, Source, Type)
**/
Integer NoOfOpps = 0;
List<Opportunity> oppList = new List<Opportunity>();
oppList.add(SystemTestDataFactory.oppcreate(listAccBus[0].Id, 'TestOpportunity', 'Proposed',
'NBC – Risk','SME','SME - Term loan','Commercial (VR)',500.00,'Prospecting','Increase'));
oppList.add(SystemTestDataFactory.oppcreate(listAccBus[0].Id, 'TestOpportunity', 'Proposed',
'NBC – Risk','SME','SME - Line of credit','Commercial',500.00,'Prospecting','Increase'));
NoOfOpps=oppList.size();
if(!oppList.isEmpty()){
Database.insert(oppList);
}
//Create Disbusrement Forecast
List<Disbursement_Forecast__c> disbForecast = TestDataFactorySFN.createDisbursementForecast(1,oppList.get(0).Id);
List<Disbursement_Forecast__c> disbForecast2 = TestDataFactorySFN.createDisbursementForecast(1,oppList.get(1).Id);
//Create Product Package
List<LLC_BI__Product_Package__c> prodpackaglist = SystemTestDataFactory.createProdPkg(1);
Database.insert(prodpackaglist);
//Create Loan linked and link it to PP
StaticTriggerValues.isLoanUpdateFromUI = false;
List<LLC_BI__Loan__c> loanList = new List<LLC_BI__Loan__c>();
loanList = SystemTestDataFactory.createLoans(noOfOpps,prodpackaglist.get(0).Id,oppList,listAccBus.get(0).Id);
//Update the opportunities with created loans
for(integer i=0;i<noOfOpps;i++){
oppList.get(i).LLC_BI__Loan__c = loanList.get(i).Id;
}
if(!oppList.isEmpty()){
Database.update(oppList);
}
}
}
/**
*Method Name: testManualApprovalProcessManuallyApproved
*Description: This method will test approval process manually approved scenario.
**/
#isTest
private static void testManualApprovalProcessManuallyApproved(){
//Given
Profile p= [SELECT Id From Profile WHERE Name='nTest' OR Name='nTest2' LIMIT 1];
Profile p1= [SELECT Id From Profile WHERE Name='nTest3'];
User smevsde = [SELECT Id FROM user WHERE profileid = : p.Id and IsActive = true LIMIT 1];
system.debug('method smevsde-->' + smevsde.Id);
User credoff = [SELECT Id FROM user WHERE profileid = : p1.Id and IsActive = true LIMIT 1];
Id crdOffQId = [SELECT Id from Group where Name =: System.Label.SFN_Credit_Team_Queue and Type
=: System.Label.SFN_Queue limit 1][0].Id;
LLC_BI__Product_Package__c pplist = [SELECT Id,LLC_BI__Status__c, OwnerId, Assigned_to_Me__c FROM
LLC_BI__Product_Package__c LIMIT 1];
pplist.LLC_BI__Status__c = 'Open';
pplist.LLC_BI__Reviewable_Loan_Facilities_Count__c = 1;
ProductPackages.isFirstTime = true;
StaticTriggerValues.ppAfterUpdate = true;
Database.update(pplist);
List<LLC_BI__Loan__c> loansList = [SELECT Id, LLC_BI__Stage__c, LLC_BI__Status__c,LLC_BI__Is_Review_Ready__c, OwnerId, LLC_BI__Product_Package__c
FROM LLC_BI__Loan__c WHERE LLC_BI__Product_Package__c =: pplist.Id ];
for(Integer i=0;i<loansList.size();i++){
loansList.get(i).LLC_BI__Stage__c = 'Underwriting';
}
//Loans.isCalledFirstTime = true;
Database.update(loansList);
Test.startTest();
//Create an approval request
//When
System.runAs(smevsde){
Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(pplist.Id);
StaticTriggerValues.ppAfterUpdate = true;
Approval.ProcessResult result = Approval.process(req1);
System.assert(result.isSuccess());
List<Id> newWorkItemIds = result.getNewWorkItemIds();
List<Id> newWorkItemIds2 = new List<Id>();
List<Id> newWorkItemIds3 = new List<Id>();
Approval.ProcessSubmitRequest req2 = new Approval.ProcessSubmitRequest();
Approval.ProcessSubmitRequest req21 = new Approval.ProcessSubmitRequest();
for(Integer i=0;i<1;i++){
req2.setComments('Submitting request for approval.');
req2.setObjectId(loansList[i].Id);
Loans.isCalledFirstTime = true;
Approval.ProcessResult result2 = Approval.process(req2);
System.assert(result2.isSuccess());
newWorkItemIds2 = result2.getNewWorkitemIds();
req21.setComments('Submitting request for approval.');
req21.setObjectId(loansList[i+1].Id);
Loans.isCalledFirstTime = true;
Approval.ProcessResult result21 = Approval.process(req21);
System.assert(result21.isSuccess());
newWorkItemIds3 = result21.getNewWorkitemIds();
}
system.debug('newWorkItemIds2-->' + newWorkItemIds2);
system.debug('newWorkItemIds3-->' + newWorkItemIds3);
System.debug('Loans stage after approval submit-->' + loansList.get(0).LLC_BI__Stage__c);
//System.debug('Loans stage after approval submit-->' + loansList.get(1).LLC_BI__Stage__c);
ProductPackages.isFirstTime = true;
system.debug('newWorkItemIds-->' + newWorkItemIds);
System.runAs(credoff){
system.debug('credoff user Id' + credoff.Id);
pplist.Assigned_to_Me__c = credoff.Id;
ppList.OwnerId = credoff.Id;
Database.update(pplist);
system.debug('Assigned owner PP--' + pplist.OwnerId);
system.debug('Assigned owner Loan--' + loansList.get(0).OwnerId);
system.debug('Assigned owner Loan--' + loansList.get(1).OwnerId);
Approval.ProcessWorkItemRequest req3 = new Approval.ProcessWorkItemRequest();
req3.setComments('Approving request.');
req3.setAction('Approve');
req3.setWorkItemId(newWorkItemIds.get(0));
system.debug('req3.setWorkItemId-->' + newWorkItemIds.get(0));
StaticTriggerValues.ppAfterUpdate = true;
Approval.ProcessResult result3 = Approval.process(req3);
System.assert(result3.isSuccess(), 'Result Status 3:'+result3.isSuccess());
system.debug('Result Status 3: ' + result3);
system.debug('newWorkItemIds2 size--' + newWorkItemIds2.size());
for(Integer i=0;i<newWorkItemIds2.size();i++){
Approval.ProcessWorkItemRequest req4 = new Approval.ProcessWorkItemRequest();
req4.setComments('Approving request.');
req4.setAction('Approve');
req4.setWorkItemId(newWorkItemIds2.get(i));
system.debug('req4.setWorkItemId-->' + newWorkItemIds2.get(i));
//Loans.isCalledFirstTime = true;
Approval.ProcessResult result4 = Approval.process(req4);
system.debug('result4-->' + result4);
System.assert(result4.isSuccess(), 'Result Status 4:'+result4.isSuccess());
}
for(Integer i=0;i<newWorkItemIds3.size();i++){
Approval.ProcessWorkItemRequest req5 = new Approval.ProcessWorkItemRequest();
req5.setComments('Approving request.');
req5.setAction('Approve');
req5.setWorkItemId(newWorkItemIds3.get(i));
system.debug('req5.setWorkItemId-->' + newWorkItemIds3.get(i));
//Loans.isCalledFirstTime = true;
Approval.ProcessResult result5 = Approval.process(req5);
system.debug('result4-->' + result5);
System.assert(result5.isSuccess(), 'Result Status 5:'+result5.isSuccess());
}
}
}
//Then
test.stopTest();
LLC_BI__Product_Package__c ppNewList = [SELECT Id, LLc_BI__Status__c, OwnerId FROM LLC_BI__Product_Package__c
LIMIT 1];
system.assertEquals('Manually Approved', ppNewList.LLC_BI__Status__c);
system.assertEquals(smevsde.Id, ppNewList.OwnerId);
List<LLC_BI__Loan__c> loanListNew = [SELECT Id, LLC_BI__Stage__c, OwnerId, LLC_BI__Product_Package__c
FROM LLC_BI__Loan__c WHERE LLC_BI__Product_Package__c =: ppNewList.Id LIMIT 100];
for(Integer i=0;i<loanListNew.size();i++){
system.assertEquals('Pre-Closing', loanListNew.get(i).LLC_BI__Stage__c);
system.assertEquals(smevsde.Id, loanListNew.get(i).OwnerId);
}
}
Related
I have a SQL table called Apuntes:
codigo (PK)
nombre
Proveedor (FK)
Materia
Costo
Precio
Stock Minimo
I got this code on mi LINQ DAL Layer:
public static Apuntes UpdateByCodigo(Apuntes LLevarDatos)
{
Apuntes Update = (from u in db.Apuntes
where u.Codigo.Equals(LLevarDatos.Codigo)
select u).FirstOrDefault();
//Update = LLevarDatos;
Update.Nombre = LLevarDatos.Nombre;
Update.Proveedor = LLevarDatos.Proveedor;
Update.Materia = LLevarDatos.Materia;
Update.Costo = LLevarDatos.Costo;
Update.Precio = LLevarDatos.Precio;
Update.StockMinimo = LLevarDatos.StockMinimo;
db.SubmitChanges();
return Update;
}
and in my Winforms Layer:
string CUITPK = DAL_Apuntes_Stock.BuscaCUIT(cmbProveedor.Text).CUIT;
Apuntes LlevarDatos = new Apuntes();
LlevarDatos.Codigo = txtCodigo.Text;
LlevarDatos.Nombre = txtNombre.Text;
LlevarDatos.Proveedor = CUITPK;
LlevarDatos.Materia = cmbMateria.Text;
LlevarDatos.Costo = txtCosto.Text;
LlevarDatos.Precio = txtPrecio.Text;
LlevarDatos.StockMinimo = Convert.ToInt32(txtStockMinimo.Text);
DAL_Apuntes_Stock.UpdateByCodigo(LlevarDatos);
MessageBox.Show("OK", "info");
the error I am receiving is
ForeignKeyReferenceAlreadyHasValueException in the following line:
LlevarDatos.Proveedor = CUITPK;
Anyone have any ideas on this?
You likely need to assign the entity, not just the value.
Something like the below:
//Assuming your Proveedor foreignKey is a string and not an int
LlevarDatos.Proveedor = yourDataSource.Proveedor.Single(x.Id == CUITPK);
I have an Account object, which has many Transactions related to it.
In one method, I get all transactions for a particular account.
var transactionlines = (from p in Context.account_transaction
.Include("account_transaction_line")
// .Include("Account")
.Include("account.z_account_type")
.Include("account.institution")
.Include("third_party")
.Include("third_party.z_third_party_type")
.Include("z_account_transaction_type")
.Include("account_transaction_line.transaction_sub_category")
.Include("account_transaction_line.transaction_sub_category.transaction_category")
.Include("z_account_transaction_entry_type")
.Include("account_transaction_line.cost_centre")
where p.account_id == accountId
&& p.deleted == null
select p).ToList();
This is meant to return me a list of transactions, with their related objects. I then pass each object to a Translator, which translates them into data transfer objects, which are then passed back to my main application.
public TransactionDto TranslateTransaction(account_transaction source)
{
LogUserActivity("in TranslateTransaction");
var result = new TransactionDto
{
Id = source.id,
Version = source.version,
AccountId = source.account_id,
// Account = TranslateAccount(source.account, false),
ThirdPartyId = source.third_party_id,
ThirdParty = TranslateThirdParty(source.third_party),
Amount = source.transaction_amount,
EntryTypeId = source.account_transaction_entry_type_id,
EntryType = new ReferenceItemDto
{
Id = source.account_transaction_entry_type_id,
Description = source.z_account_transaction_entry_type.description,
Deleted = source.z_account_transaction_entry_type.deleted != null
},
Notes = source.notes,
TransactionDate = source.transaction_date,
TransactionTypeId = source.account_transaction_type_id,
TransactionType = new ReferenceItemDto
{
Id = source.z_account_transaction_type.id,
Description = source.z_account_transaction_type.description,
Deleted = source.z_account_transaction_type.deleted != null
}
};
... return my object
}
The problem is:
An account has Transactions, and a Transaction therefore belongs to an Account. It seems my translators are being called way too much, and reloading a lot of data because of this.
When I load my transaction object, it's 'account' property has a'transactions' propery, which has a list of all the transactions associated to that account. Each transaction then has an account property... and those account peroprties again, have a list of all the transactions... and on and on it goes.
Is there a way I can limit the loading to one level or something?
I have this set:
Context.Configuration.LazyLoadingEnabled = false;
I was hoping my 'Includes' would be all that is loaded... Don't load 'un-included' related data?
As requested, here is my TranslateAccount method:
public AccountDto TranslateAccount(account p, bool includeCardsInterestRateDataAndBalance)
{
LogUserActivity("in TranslateAccount");
if (p == null)
return null;
var result =
new AccountDto
{
Id = p.id,
Description = p.description,
PortfolioId = p.institution.account_portfolio_id,
AccountNumber = p.account_number,
Institution = TranslateInstitution(p.institution),
AccountType = new ReferenceItemDto
{
Id = p.account_type_id,
Description = p.z_account_type.description
},
AccountTypeId = p.account_type_id,
InstitutionId = p.institution_id,
MinimumBalance = p.min_balance,
OpeningBalance = p.opening_balance,
OpeningDate = p.opening_date
};
if (includeCardsInterestRateDataAndBalance)
{
// Add the assigned cards collection
foreach (var card in p.account_card)
{
result.Cards.Add(new AccountCardDto
{
Id = card.id,
AccountId = card.account_id,
Active = card.active,
CardHolderName = card.card_holder_name,
CardNumber = card.card_number,
ExpiryDate = card.expiry
});
}
// Populate the current interest rate
result.CurrentRate = GetCurrentInterestRate(result.Id);
// Add all rates to the account
foreach (var rate in p.account_rate)
{
result.Rates.Add(
new AccountRateDto
{
Id = rate.id,
Description = rate.description,
Deleted = rate.deleted != null,
AccountId = rate.account_id,
EndDate = rate.end_date,
Rate = rate.rate,
StartDate = rate.start_date
});
}
result.CurrentBalance = CurrentBalance(result.Id);
}
LogUserActivity("out TranslateAccount");
return result;
}
The entity framework context maintains a cache of data that has been pulled out of the database. Regardless of lazy loading being enabled/disabled, you can call Transaction.Account.Transactions[0].Account.Transactions[0]... as much as you want without loading anything else from the database.
The problem is not in the cyclical nature of entity framework objects - it is somewhere in the logic of your translation objects.
I was trying to change the table names in the entity model or database but the old names are already use in many places in the application. Is there any way to auto reflect renamed entities or tables in the LINQ query or code.
Let say I have tables tblDepartment, tblEmployee and tblEmployeeDepartment. These tables are used in the code(LINQ) on many places. I like to change these tables names to Department, Employee and EmployeeDepartment. So, is there anyway to auto reflect name in LINQ or code when I change table names either using Database First or Model First approach.
P.S. The application is based on .Net 3.5
Working With linq and Entity Framework plus excel reports|Enjoy
public static string strMessage = "";
public SchoolEntities dbContext;
public string login(string strUsername, string strPassword)
{
dbContext = new SchoolEntities();
var linqQuery = from User in dbContext.People
where User.FirstName == strUsername && User.LastName == strPassword
select User;
if (linqQuery.Count() == 1)
{
strMessage = "Good";
}
else
{
strMessage = "Bad";
}
return strMessage;
}
public Object LoadPersonDetails()
{
dbContext = new SchoolEntities();
//DataTable dtPerson = new DataTable();
var linqQuery = from users in dbContext.People
select users;
//List<Person> Users = linqQuery.ToList();
//dtPerson = linqQuery.ToList();
return linqQuery;
}
public void InsertPerson(string strLName, string strFName, string strHireDate, string EnrollmentDate)
{
dbContext = new SchoolEntities();
Person NewPerson = dbContext.People.Create();
NewPerson.LastName = strLName;
NewPerson.FirstName = strFName;
NewPerson.HireDate = Convert.ToDateTime(strHireDate);
NewPerson.EnrollmentDate = Convert.ToDateTime(EnrollmentDate);
dbContext.People.Add(NewPerson);
dbContext.SaveChanges();
}
public void DeleteUser(int intPersonID)
{
//dbContext = new SchoolEntities();
using (dbContext = new SchoolEntities())
{
Person Person = dbContext.People.Where(c => c.PersonID == intPersonID).FirstOrDefault();
if (Person != null)
{
dbContext.People.Remove(Person);
dbContext.SaveChanges();
}
}
}
public void ModifyPerson(int intPersonID, string strLName, string strFName, string strHireDate, string EnrollmentDate)
{
var UpdatePerson = dbContext.People.FirstOrDefault(s => s.PersonID == intPersonID);
UpdatePerson.LastName = strLName;
UpdatePerson.FirstName = strFName;
UpdatePerson.HireDate = Convert.ToDateTime(strHireDate);
UpdatePerson.EnrollmentDate = Convert.ToDateTime(EnrollmentDate);
dbContext.SaveChanges();
}
private Excel.Application XApp = null; //Creates the Excel Document
private Excel.Workbook XWorkbook = null; //create the workbook in the recently created document
private Excel.Worksheet XWorksheet = null; //allows us to work with current worksheet
private Excel.Range XWorkSheet_range = null; // allows us to modify cells on the sheet
public void Reports()
{
dbContext = new SchoolEntities();
var linqQuery = (from users in dbContext.StudentGrades
group users by new { users.EnrollmentID, users.CourseID, users.StudentID, users.Grade }
into UserGroup
orderby UserGroup.Key.CourseID ascending
select new { UserGroup.Key.EnrollmentID, UserGroup.Key.CourseID, UserGroup.Key.StudentID, UserGroup.Key.Grade }).ToList();
var RatingAverage = dbContext.StudentGrades.Average(r => r.Grade);
var GradeSum = dbContext.StudentGrades.Sum(r => r.Grade);
/*var linqQuery = (from users in dbContext.StudentGrades
orderby users.CourseID descending
select users).ToList();*/
//Array Motho = linqQuery.ToArray();
XApp = new Excel.Application();
XApp.Visible = true;
XWorkbook = XApp.Workbooks.Add(1);
XWorksheet = (Excel.Worksheet)XWorkbook.Sheets[1];
//Create column headers
XWorksheet.Cells[2, 1] = "EnrollmentID";
XWorksheet.Cells[2, 2] = "CourseID";
XWorksheet.Cells[2, 3] = "StudentID";
XWorksheet.Cells[2, 4] = "Grade";
//XWorksheet.Cells[2, 5] = "Enrollment Date";
int row = 3;
foreach (var Mothos in linqQuery)
{
XWorksheet.Cells[row, 1] = Mothos.EnrollmentID.ToString();
XWorksheet.Cells[row, 2] = Mothos.CourseID.ToString();
XWorksheet.Cells[row, 3] = Mothos.StudentID.ToString();
XWorksheet.Cells[row, 4] = Mothos.Grade.ToString();
row++;
}
int rows = linqQuery.Count();
XWorksheet.Cells[rows + 4, 3] = "Grades Average";
XWorksheet.Cells[rows + 4, 4] = RatingAverage.Value.ToString();
XWorksheet.Cells[rows + 5, 3] = "Grades Sum";
XWorksheet.Cells[rows + 5, 4] = GradeSum.Value.ToString();
//XWorkSheet_range.ColumnWidth = 30;
//XWorksheet.Cells.AutoFit();
}
Working with xml | add, modify and delete xml data
string conn = "E:/School/Development Sftware/2014/ReadWriteUpdateDeleteXML/DataService/Profiles.xml";
public string InsertProfile(string fname, string lname, string phone, string gender)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
XmlElement subRoot = xmlDoc.CreateElement("Profile");
//add first name
XmlElement appendedElementFname = xmlDoc.CreateElement("FirstName");
XmlText xmlTextFname = xmlDoc.CreateTextNode(fname.Trim());
appendedElementFname.AppendChild(xmlTextFname);
subRoot.AppendChild(appendedElementFname);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add last name
XmlElement appendedElementLname = xmlDoc.CreateElement("LastName");
XmlText xmlTextLname = xmlDoc.CreateTextNode(lname.Trim());
appendedElementLname.AppendChild(xmlTextLname);
subRoot.AppendChild(appendedElementLname);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add phone
XmlElement appendedElementPhone = xmlDoc.CreateElement("Phone");
XmlText xmlTextPhone = xmlDoc.CreateTextNode(phone.Trim());
appendedElementPhone.AppendChild(xmlTextPhone);
subRoot.AppendChild(appendedElementPhone);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add gender
XmlElement appendedElementGender = xmlDoc.CreateElement("Gender");
XmlText xmlTextGender = xmlDoc.CreateTextNode(gender.Trim());
appendedElementGender.AppendChild(xmlTextGender);
subRoot.AppendChild(appendedElementGender);
xmlDoc.DocumentElement.AppendChild(subRoot);
xmlDoc.Save(conn);
return "Profile Saved";
}
public DataSet LoadXML()
{
DataSet dsLog = new DataSet();
dsLog.ReadXml(conn);
return dsLog;
}
public string DeleteProfile(string fname)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
//XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/Profiles/Profile[#FirstName=" + fname + "]");
//if (nodeToDelete != null)
//{
// nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
//}
//xmlDoc.Save("C:/Users/Shazzy/Documents/Visual Studio 2010/Projects/ReadWriteUpdateDeleteXML/DataService/Profiles.xml");
//return "Deleted";
foreach (XmlNode node in xmlDoc.SelectNodes("Profiles/Profile"))
{
if (node.SelectSingleNode("FirstName").InnerText == fname)
{
node.ParentNode.RemoveChild(node);
}
}
xmlDoc.Save(conn);
return "Deleted";
}
public string ModifyProfile(string fname, string lname, string phone, string gender)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
foreach (XmlNode node in xmlDoc.SelectNodes("Profiles/Profile"))
{
if (node.SelectSingleNode("FirstName").InnerText == fname)
{
node.SelectSingleNode("FirstName").InnerText = fname;
node.SelectSingleNode("LastName").InnerText = lname;
node.SelectSingleNode("Phone").InnerText = phone;
node.SelectSingleNode("Gender").InnerText = gender;
}
}
xmlDoc.Save(conn);
return "Updated";
}
Working with edm and Excel-grouped report
public void Function_Create_Sales()
{
DBContext = new PubsEntities();
var linqStores = from Sales in DBContext.sales
orderby Sales.stor_id
select Sales;
var lstStore = linqStores.ToList();
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlBook = xlApp.Workbooks.Add(1);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
int GroupTotal = 0;
int GrandTotal = 0;
int ExcelRow = 5;
string intTemp = lstStore[0].stor_id;
xlSheet.Cells[4, 1] = lstStore[0].stor_id;
//Create column headers
xlSheet.Cells[1, 1] = "Sales Grouped By Store";
xlSheet.Cells[3, 1] = "Group header";
xlSheet.Cells[3, 2] = "Store ID";
xlSheet.Cells[3, 3] = "Order Number";
xlSheet.Cells[3, 4] = "Order Date";
xlSheet.Cells[3, 5] = "Quantity";
xlSheet.Cells[3, 6] = "payments";
xlSheet.Cells[3, 7] = "title ID";
for (int count = 0; count < lstStore.Count; count++)
{
if (intTemp == lstStore[count].stor_id)
{
xlSheet.Cells[ExcelRow, 2] = lstStore[count].stor_id.ToString();
xlSheet.Cells[ExcelRow, 3] = lstStore[count].ord_date.ToString();
xlSheet.Cells[ExcelRow, 4] = lstStore[count].qty.ToString();
xlSheet.Cells[ExcelRow, 5] = lstStore[count].payterms.ToString();
xlSheet.Cells[ExcelRow, 5] = lstStore[count].title_id.ToString();
ExcelRow++;
GroupTotal++;
GrandTotal++;
}
else
{
xlSheet.Cells[ExcelRow, 5] = "Total for: " + intTemp + " = " + GroupTotal.ToString();
ExcelRow++;
intTemp = lstStore[count].stor_id;
xlSheet.Cells[ExcelRow, 1] = lstStore[count].stor_id;
count--;
GroupTotal = 0;
ExcelRow++;
}
}
xlSheet.Cells[ExcelRow, 5] = "Total for: " + intTemp + " = " + GroupTotal.ToString();
ExcelRow++;
xlSheet.Cells[ExcelRow, 5] = "Grand Total = " + GrandTotal.ToString();
xlSheet.Rows.Columns.AutoFit();
}
I have this linq statement that returns result and i wanted to add the specifications of how many items are displayed per page. I know the default is 10 per page how can i change it to 40?
var _roster = DataCBase.StoredProcedures.GetUser<Users>(userID, r => new Users
{
Name = RosterColumnMap.Name(r),
Email = RosterColumnMap.Email(r)
});
Get User
public virtual IEnumerable<T> GetUser<T>(int userId, Func<IDataRecord, T> modelBinder, int resultsPerPage = 10, int pageNumber = 1)
{
if (userId < 1)
throw new NullReferenceException("The sectionId cannot be null, when retreiving an element");
if (resultsPerPage < 1)
resultsPerPage = 1; // enforce bare minimum result set
if (pageNumber < 1)
pageNumber = 1; // enforce one-based page numbering
SqlCommand _command = new SqlCommand("dbo.GetUser");
_command.CommandType = CommandType.StoredProcedure;
_command.Parameters.Add(new SqlParameter { ParameterName = "userId", SqlDbType = SqlDbType.Int, Value = userId });
_command.Parameters.Add(new SqlParameter { ParameterName = "resultsPerPage", SqlDbType = SqlDbType.Int, Value = resultsPerPage });
_command.Parameters.Add(new SqlParameter { ParameterName = "pageNumber", SqlDbType = SqlDbType.Int, Value = pageNumber });
return DbInstance.ExecuteAs<T>(_command, modelBinder);
}
Neither Linq nor entity framework have any default number of records 'per page'. But since your GetUser function includes a resultsPerPage parameter, you can just do this:
var _roster = DataCBase.StoredProcedures.GetUser<Users>(userID, r => new Users
{
Name = RosterColumnMap.Name(r),
Email = RosterColumnMap.Email(r)
}, 40);
To limit the number of results in Linq use the the Enumerable.Take method:
var _roster = DataCBase.StoredProcedures.GetUser<Users>(userID, r => new Users
{
Name = RosterColumnMap.Name(r),
Email = RosterColumnMap.Email(r)
}).Take(40);
I have 2 objects (lists loaded from XML) report and database (showed bellow in code) and i should analyse them and mark items with 0, 1, 2, 3 according to some conditions
TransactionResultCode = 0; // SUCCESS (all fields are equivalents: [Id, AccountNumber, Date, Amount])
TransactionResultCode = 1; // Exists in report but Not in database
TransactionResultCode = 2; // Exists in database but Not in report
TransactionResultCode = 3; // Field [Id] are equals but other fields [AccountNumber, Date, Amount] are different.
I'll be happy if somebody could found time to suggest how to optimize some queries.
Bellow is the code:
THANK YOU!!!
//TransactionResultCode = 0 - SUCCESS
//JOIN on all fields
var result0 = from d in database
from r in report
where (d.TransactionId == r.MovementID) &&
(d.TransactionAccountNumber == long.Parse(r.AccountNumber)) &&
(d.TransactionDate == r.MovementDate) &&
(d.TransactionAmount == r.Amount)
orderby d.TransactionId
select new TransactionList()
{
TransactionId = d.TransactionId,
TransactionAccountNumber = d.TransactionAccountNumber,
TransactionDate = d.TransactionDate,
TransactionAmount = d.TransactionAmount,
TransactionResultCode = 0
};
//*******************************************
//JOIN on [Id] field
var joinedList = from d in database
from r in report
where d.TransactionId == r.MovementID
select new TransactionList()
{
TransactionId = d.TransactionId,
TransactionAccountNumber = d.TransactionAccountNumber,
TransactionDate = d.TransactionDate,
TransactionAmount = d.TransactionAmount
};
//Difference report - database
var onlyReportID = report.Select(r => r.MovementID).Except(joinedList.Select(d => d.TransactionId));
//TransactionResultCode = 1 - Not Found in database
var result1 = from o in onlyReportID
from r in report
where (o == r.MovementID)
orderby r.MovementID
select new TransactionList()
{
TransactionId = r.MovementID,
TransactionAccountNumber = long.Parse(r.AccountNumber),
TransactionDate = r.MovementDate,
TransactionAmount = r.Amount,
TransactionResultCode = 1
};
//*******************************************
//Difference database - report
var onlyDatabaseID = database.Select(d => d.TransactionId).Except(joinedList.Select(d => d.TransactionId));
//TransactionResultCode = 2 - Not Found in report
var result2 = from o in onlyDatabaseID
from d in database
where (o == d.TransactionId)
orderby d.TransactionId
select new TransactionList()
{
TransactionId = d.TransactionId,
TransactionAccountNumber = d.TransactionAccountNumber,
TransactionDate = d.TransactionDate,
TransactionAmount = d.TransactionAmount,
TransactionResultCode = 2
};
//*******************************************
var qwe = joinedList.Select(j => j.TransactionId).Except(result0.Select(r => r.TransactionId));
//TransactionResultCode = 3 - Transaction Results are different (Amount, AccountNumber, Date, )
var result3 = from j in joinedList
from q in qwe
where j.TransactionId == q
select new TransactionList()
{
TransactionId = j.TransactionId,
TransactionAccountNumber = j.TransactionAccountNumber,
TransactionDate = j.TransactionDate,
TransactionAmount = j.TransactionAmount,
TransactionResultCode = 3
};
you may try something like below:
public void Test()
{
var report = new[] {new Item(1, "foo", "boo"), new Item(2, "foo2", "boo2"), new Item(3, "foo3", "boo3")};
var dataBase = new[] {new Item(1, "foo", "boo"), new Item(2, "foo22", "boo2"), new Item(4, "txt", "rt")};
Func<Item, bool> inBothLists = (i) => report.Contains(i) && dataBase.Contains(i);
Func<IEnumerable<Item>, Item, bool> containsWithID = (e, i) => e.Select(_ => _.ID).Contains(i.ID);
Func<Item, int> getCode = i =>
{
if (inBothLists(i))
{
return 0;
}
if(containsWithID(report, i) && containsWithID(dataBase, i))
{
return 3;
}
if (report.Contains(i))
{
return 2;
}
else return 1;
};
var result = (from item in dataBase.Union(report) select new {Code = getCode(item), Item = item}).Distinct();
}
public class Item
{
// You need also to override Equals() and GetHashCode().. I omitted them to save space
public Item(int id, string text1, string text2)
{
ID = id;
Text1 = text1;
Text2 = text2;
}
public int ID { get; set; }
public string Text1 { get; set; }
public string Text2 { get; set; }
}
Note that you need to either implement Equals() for you items, or implement an IEqualityComparer<> and feed it to Contains() methods.