WebMethod returning multiple line (list<>) from SQL query in WCF with Entity Framework Linq - list

Creating a WCF in VisualStudio 2017, I need to create a WebMethod that will return multiple rows from a SQL query. Here is the code that is not working...
code
[WebMethod]
public List<TABLE_NAME> GetAllLineInfoDetailes(string OrderNumberSM)
{
string #OrdNumLG = OrderNumberSM;
List<TABLE_NAME> OrdNo = new List<TABLE_NAME>();
using (CONNECTION_NAME pubs = new CONNECTION_NAME())
{
var OrdNo_LINES = (from p in pubs.TABLE_NAME select p.OrderNumber == #OrdNumLG);
foreach (TABLE_NAME OrderLine in OrdNo_LINES)
{
TABLE_NAME a = new TABLE_NAME();
a.ItemNumber = OrderLine.ItemNumber;
a.LineNumber = OrderLine.LineNumber;
a.OrderNumber = OrderLine.OrderNumber;
OrdNo.Add(a);
}
}
return OrdNo;
}
code
The foreach is giving error "Cannot convert type 'bool' to 'CONNECTION_NAME.TABLE_NAME'"
Any help with this, or a better way to return the full result set, would be appreciated.

As the error says, it's a type conversion problem.
You need to
var OrdNo_LINES = (from p in pubs.TABLE_NAME select p.OrderNumber = #OrdNumLG);
replace
var OrdNo_LINES = (from p in pubs.TABLE_NAME select p.OrderNumber == #OrdNumLG);

Found what will work...
[WebMethod]
public List<TABLE_NAME> GetAllLineInfoDetailes(string OrderNumberSM)
{
string #OrdNumSM = OrderNumberSM;
using (CONNECTION_NAME pubs = new CONNECTION_NAME())
{
var query = (from c in pubs.TABLE_NAME
where c.OrderNumber == #OrdNumSM
orderby c.LineNumber ascending
select c).ToList();
return query;
}
}

Related

Unit Test for Apex Trigger that Concatenates Fields

I am trying to write a test for a before trigger that takes fields from a custom object and concatenates them into a custom Key__c field.
The trigger works in the Sandbox and now I am trying to get it into production. However, whenever I try and do a System.assert/assertEquals after I create a purchase and perform DML, the value of Key__c always returns null. I am aware I can create a flow/process to do this, but I am trying to solve this with code for my own edification. How can I get the fields to concatenate and return properly in the test? (the commented out asserts are what I have tried so far, and have failed when run)
trigger Composite_Key on Purchases__c (before insert, before update) {
if(Trigger.isBefore)
{
for(Purchases__c purchase : trigger.new)
{
String eventName = String.isBlank(purchase.Event_name__c)?'':purchase.Event_name__c+'-';
String section = String.isBlank(purchase.section__c)?'':purchase.section__c+'-';
String row = String.isBlank(purchase.row__c)?'':purchase.row__c+'-';
String seat = String.isBlank(String.valueOf(purchase.seat__c))?'':String.valueOf(purchase.seat__c)+'-';
String numseats = String.isBlank(String.valueOf(purchase.number_of_seats__c))?'':String.valueOf(purchase.number_of_seats__c)+'-';
String adddatetime = String.isBlank(String.valueOf(purchase.add_datetime__c))?'':String.valueOf(purchase.add_datetime__c);
purchase.Key__c = eventName + section + row + seat + numseats + adddatetime;
}
}
}
#isTest
public class CompositeKeyTest {
public static testMethod void testPurchase() {
//create a purchase to fire the trigger
Purchases__c purchase = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c=1.0,number_of_seats__c='test',add_datetime__c='test');
Insert purchase;
//System.assert(purchases__c.Key__c.getDescribe().getName() == 'testesttest1testtest');
//System.assertEquals('testtesttest1.0testtest',purchase.Key__c);
}
static testMethod void testbulkPurchase(){
List<Purchases__c> purchaseList = new List<Purchases__c>();
for(integer i=0 ; i < 10; i++)
{
Purchases__c purchaserec = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c= i+1.0 ,number_of_seats__c='test',add_datetime__c='test');
purchaseList.add(purchaserec);
}
insert purchaseList;
//System.assertEquals('testtesttest5testtest',purchaseList[4].Key__c,'Key is not Valid');
}
}
You need to requery the records after inserting them to get the updated data from the triggers/database

DataSource attribute for unit test method

I try to use CSV data source in Device unit test (WinCE/Pocket PC2003 Emulator)
I have added source in using wizard in Data Connection String property:
using Microsoft.VisualStudio.TestTools.UnitTesting;
....
[TestMethod()]
[DeploymentItem("Options.txt")]
[DeploymentItem("Options_1.txt")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "C:\\...\\Tests\\Data\\LoadSettingsTest.csv", "LoadSettingsTest#csv", DataAccessMethod.Sequential)]
public void LoadSettingsTest()
{
...
}
I have following compiler error:
Error 1 The type or namespace name 'DataSource' could not be found
(are you missing a using directive or an assembly reference?)
Error 2 The type or namespace name 'DataSourceAttribute' could not be
found (are you missing a using directive or an assembly reference?)
What's? Where DataSource is defined? Is data DataSource attribute supported in device unit tests?
DataSource is not supported by Device Unit Testing Framework, see Unit Testing Framework (Devices).
It looks like you are trying to use a Comma Separated Values (CSV) file as a DataSource.
You should convert your CSV data into something a Data Control is familiar with first.
Here is an example:
private const string FIELD_SEP = "\t";
private const string LINE_BREAK = "\r\n";
private const int ONE_KB = 1024;
private System.Data.DataTable GenerateData(string csvDataFile) {
var sb = new System.Text.StringBuilder();
using (var file = File.Open(csvDataFile, FileMode.Open, FileAccess.Read)) {
byte[] buffer = new byte[ONE_KB];
int len = file.Read(buffer, 0, ONE_KB);
while (-1 < len) {
string oneK = Encoding.UTF8.GetString(buffer, 0, len);
sb.Append(oneK);
len = file.Read(buffer, 0, ONE_KB);
}
}
var table = new System.Data.DataTable();
var col1 = table.Columns.Add("ID", typeof(int));
var col2 = table.Columns.Add("Name", typeof(string));
var col3 = table.Columns.Add("Date", typeof(DateTime));
var col4 = table.Columns.Add("Cost", typeof(decimal));
var lines = sb.ToString().Split(LINE_BREAK.ToArray());
foreach (var line in lines) {
System.Data.DataRow row = table.NewRow();
var fields = line.Split(FIELD_SEP.ToArray());
row[col1] = int.Parse(fields[0]);
row[col2] = fields[1];
row[col3] = DateTime.Parse(fields[2]);
row[col4] = decimal.Parse(fields[3]);
table.Rows.Add(row);
}
return table;
}
Of course, I have no idea what kind of data you are trying to extract from this CSV file, and there is no error checking. If field[3] were an empty string, decimal.Parse(field[3]) would throw an exception.

How do I query multiple IDs via the ContentSearchManager?

When I have an array of Sitecore IDs, for example TargetIDs from a MultilistField, how can I query the ContentSearchManager to return all the SearchResultItem objects?
I have tried the following which gives an "Only constant arguments is supported." error.
using (var s = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
rpt.DataSource = s.GetQueryable<SearchResultItem>().Where(x => f.TargetIDs.Contains(x.ItemId));
rpt.DataBind();
}
I suppose I could build up the Linq query manually with multiple OR queries. Is there a way I can use Sitecore.ContentSearch.Utilities.LinqHelper to build the query for me?
Assuming I got this technique to work, is it worth using it for only, say, 10 items? I'm just starting my first Sitecore 7 project and I have it in mind that I want to use the index as much as possible.
Finally, does the Page Editor support editing fields somehow with a SearchResultItem as the source?
Update 1
I wrote this function which utilises the predicate builder as dunston suggests. I don't know yet if this is actually worth using (instead of Items).
public static List<T> GetSearchResultItemsByIDs<T>(ID[] ids, bool mustHaveUrl = true)
where T : Sitecore.ContentSearch.SearchTypes.SearchResultItem, new()
{
Assert.IsNotNull(ids, "ids");
if (!ids.Any())
{
return new List<T>();
}
using (var s = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
var predicate = PredicateBuilder.True<T>();
predicate = ids.Aggregate(predicate, (current, id) => current.Or(p => p.ItemId == id));
var results = s.GetQueryable<T>().Where(predicate).ToDictionary(x => x.ItemId);
var query = from id in ids
let item = results.ContainsKey(id) ? results[id] : null
where item != null && (!mustHaveUrl || item.Url != null)
select item;
return query.ToList();
}
}
It forces the results to be in the same order as supplied in the IDs array, which in my case is important. (If anybody knows a better way of doing this, would love to know).
It also, by default, ensures that the Item has a URL.
My main code then becomes:
var f = (Sitecore.Data.Fields.MultilistField) rootItem.Fields["Main navigation links"];
rpt.DataSource = ContentSearchHelper.GetSearchResultItemsByIDs<SearchResultItem>(f.TargetIDs);
rpt.DataBind();
I'm still curious how the Page Editor copes with SearchResultItem or POCOs in general (my second question), am going to continue researching that now.
Thanks for reading,
Steve
You need to use the predicate builder to create multiple OR queries, or AND queries.
The code below should work.
using (var s = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
var predicate = PredicateBuilder.True<SearchResultItem>();
foreach (var targetId in f.Targetids)
{
var tempTargetId = targetId;
predicate = predicate.Or(x => x.ItemId == tempTargetId)
}
rpt.DataSource = s.GetQueryable<SearchResultItem>().Where(predicate);
rpt.DataBind();
}

subsonic 3.0 active record update

I am able to retrieve database values and insert database values, but I can't figure out what the Update() syntax should be with a where statement.
Environment -> ASP.Net, C#
Settings.ttinclude
const string Namespace = "subsonic_db.Data";
const string ConnectionStringName = "subsonic_dbConnectionString";
//This is the name of your database and is used in naming
//the repository. By default we set it to the connection string name
const string DatabaseName = "subsonic_db";
Retreive example
var product = equipment.SingleOrDefault(x => x.id == 1);
Insert Example
equipment my_equipment = new equipment();
try
{
// insert
my_equipment.parent_id = 0;
my_equipment.primary_id = 0;
my_equipment.product_code = product_code.Text;
my_equipment.product_description = product_description.Text;
my_equipment.product_type_id = Convert.ToInt32(product_type_id.SelectedItem.Value);
my_equipment.created_date = DateTime.Now;
my_equipment.serial_number = serial_number.Text;
my_equipment.Save();
}
catch (Exception err)
{
lblError.Text = err.Message;
}
Edit: Think that I was just too tired last night, it is pretty easy to update. Just use the retrieve function and use the Update() on that.
var equip = Equipment.SingleOrDefault(x => x.id == 1);
lblGeneral.Text = equip.product_description;
equip.product_description = "Test";
equip.Update();
Resolved. View answer above.

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.