Get only one value from the table using LINQ - linq

I have a Customer Table and a Address Table (customer_id, address_forename, address_surname, address_street, address_city, address_zip,
address_storedtime) where customer_id as a foreign key.
One customer can have several address.
Now I am trying to get only the last entered address using LINQ as bellow which should allow me put the address in a string and return that:
CODE:
var customerAddress = (from c in myDB.address
where (c.customer_id == customerId)
select new
{
c.customer_id,
c.address_forename,
c.address_surname,
c.address_street,
c.address_city,
c.address_zip,
c.address_storedtime
}).GroupBy(g => new
{
Customer = .customer_id,
Address = g.address_forename + " " + g.address_surname + " " + g.address_street + " " + g.address_city + " " + g.address_zip
}).Select(g => new
{
g.Key.Customer,
g.Key.Address,
StoredTime = g.Max(x => x.address_storedtime)
}).Disinct();/*First();*/
string result = "";
foreach (var ad in customerAddress)
{
if (ad.Address != null)
{
result = ad.Address;
}
break;
}
return result;
I am getting same address string for different addresses in DB for the Customer whereas I am trying to get only one.

Since you're already filtering by customer id, the grouping clause isn't necessary. You should be able to just order the results for the customer descending and project the address much more simply.
var customerAddress = (from c in myDB.address
where (c.customer_id == customerId)
orderby c.address_storedtime descending
select c.address_forename + " " + c.address_surname + " " + c.address_street + " " + c.address_city + " " + c.address_zip)
.FirstOrDefault();

Replace your foreach by
var result =
customerAdress.Any(ad => ad.Address != null)
? customerAdress.Last(ad => ad.Address != null).Address
: default(string);

Related

Output SQL Table to existing Excel file/ new worksheet in SSIS / C# in script task

Good day,
I had a request to create a SSIS package that would output an SQL table to an Excel file. I had no problem creating this. However, the client came back asking that they wanted to be able to output the SQL table content to an existing Excel file in a new worksheet. If the worksheet does not exists in my following script, it is being created. However, it just goes back in the loop and fail because now it exists.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
string currentTab;
DataTable ExcelFileTabs;
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
string FullExcelFilePath = FolderPath + ExcelFileName + ".xlsx";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FullExcelFilePath + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
// Verify if file exists
if (File.Exists(FullExcelFilePath))
{
//Verify if the sheet exists
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
currentTab = excelTable["TABLE_NAME"].ToString();
if (currentTab == SheetName)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine("The sheet " + SheetName + " that your are trying to create in " + FullExcelFilePath + " already exists.");
sw.WriteLine("Please enter another sheet name or delete the Excel file and try again.");
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Failure;
}
else
{
// Create the worksheet in the existing Excel file
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
}
}
else
{
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Can somebody please help me with this ? I am pretty new to C#, and English is not my primary language. Please let me know if this is not clear enough.
Thanks in advance for you time :-)
Mylene
You know when you are trying to find the solution way to fare when it is just in front of you ?
My code, before wanting to catch the error if the user was trying to add a worksheet that already exists, already was trowing an exception in those cases...
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
Error log :
System.Data.OleDb.OleDbException (0x80040E14): Table 'Test9' already exists.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ST_a21007570143466693913591932c30b7.ScriptMain.Main()
Problem resolved.

Database column data having linebreaks are ignored when retrieved from Hibernate?

A CLOB database column data has linebreaks :
When I retrieve it and display the data inside a html table cell then the linebreaks are ignored :
#Override
#Transactional
public String getPrevisionRessourceAutreForProduit(Objectif produit) {
String hql = "select to_char(r.ress_comment_1) " +
"from ressource r join type_ressource t on r.type_ress_code = t.type_ress_code " +
"left join objectif o on r.obj_code = o.obj_code " +
"where o.obj_code = " + produit.getCode().toString() + " and upper(t.type_ress_code) = 'AUT'";
Session sessionDynamic = Utils.createDynamicSession(env);
Query query = sessionDynamic.createSQLQuery(hql);
#SuppressWarnings("unchecked")
List<String> list = (List<String>) query.list();
sessionDynamic.close();
if (list.isEmpty())
return "";
else
return list.get(0) == null ? "" : list.get(0);
}
So how to fix it ?
I found the solution by enclosing the data inside the tags <pre>...</pre>

Linq on datatable no datasource exception

dataSet = clsDb.MailData("SELECT * FROM CM_Mail cm WHERE cm.[ActualTime] < '" + DateTimeOffset.UtcNow + "' ", CommandType.Text);
DataTable datatablepending = (from ds in dataSet.Tables[0].AsEnumerable() where ds.Field<string>("Status") == MailStatus.Pending.ToString() select ds).CopyToDataTable();
DataTable datatableInprogress = (from ds in dataSet.Tables[0].AsEnumerable() where ds.Field<string>("Status") == MailStatus.Inprogress.ToString() select ds).CopyToDataTable();
if (datatablepending.Rows.Count != 0)
{
for (int i = 0; i < datatablepending.Rows.Count; i++)
{
dataSet = clsDb.MailData("UPDATE CM_Mail SET [Status] = '" + updateStatus + "',LastProccessedTime = '" + DateTimeOffset.UtcNow.ToString() + "' WHERE Id='" + datatablepending.Rows[i]["Id"].ToString() + "'", CommandType.Text);
}
}
if (datatableInprogress.Rows.Count != 0)
{
for (int i = 0; i < datatableInprogress.Rows.Count; i++)
{
dataSet = clsDb.MailData("UPDATE CM_Mail SET [Status] = '" + updateStatus + "',SentTime = '" + DateTimeOffset.UtcNow + "',LastProccessedTime = '" + DateTimeOffset.UtcNow.ToString() + "' WHERE Id='" + datatableInprogress.Rows[i]["Id"].ToString() + "'", CommandType.Text);
}
}
When I try to do this datatableInprogress may not have any rows all the time. At run time, I get an exception saying "no datasource". Why? And what should I do to fix this issue?
Just clone DataTable structure if there is no rows for your condition:
var pendingRows =
dataSet.Tables[0].AsEnumerable()
.Where(r => r.Field<string>("Status") == MailStatus.Pending.ToString());
DataTable datatablepending = pendingRows.Any() ? pendingRows.CopyToDataTable() :
dataSet.Tables[0].Clone();
BTW why you need DataTable? You can get ids!
var pendingIds =
from r in dataSet.Tables[0].AsEnumerable()
where r.Field<string>("Status") == MailStatus.Pending.ToString()
select r.Field<int>("Id");
Sorry, I don't know why are you assigning dataSet in a loop, but here is code which reproduces yours:
string updateStringFormat =
"UPDATE CM_Mail SET [Status] = '{0}',LastProccessedTime = '{1}' WHERE Id='{2}'";
foreach(var id in pendingIds)
{
var commandText = String.Format(updateStringFormat, updateStatus, DateTimeOffset.UtcNow, id);
dataSet = clsDb.MailData(commandText, CommandType.Text);
}

Converting from dataset to list in linq

I have dataset function which is as below,
public DataSet GetUpodBrandList(string criteria, string locationId)
{
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
string query;
if (criteria == "")
query = "select distinct brandDesc " +
"from arabia_upod_item_master " +
"where locationId = '" + locationId +
"' order by brandDesc";
else
query = "select distinct brandDesc " +
"from arabia_upod_item_master " +
"where brandDesc like '%" + criteria + "%' " +
"and locationId = '" + locationId + "'
order by brandDesc";
conn.Open();
SqlCommand command = new SqlCommand(query, conn);
return this.ExecuteDatasetStoredProc(command);
}
}
I am trying to convert it into linq as follow,
public static List<DataContext.arabia_upod_item_master> GetUpodBrandList(
string criteria,
string locationId)
{
List<DataContext.arabia_upod_item_master> m =
new List<DataContext.arabia_upod_item_master>();
using (var db = UpodDatabaseHelper.GetUpodDataContext())
{
db.ObjectTrackingEnabled = false;
if (criteria == "")
m = db.arabia_upod_item_masters.Where(
i => i.locationId == Convert.ToInt32(locationId))
.OrderBy(i => i.brandDesc)
.Distinct()
.ToList();
else
m = db.arabia_upod_item_masters.Where(
i => i.brandDesc.Contains(criteria) &&
i.locationId == Convert.ToInt32(locationId))
.OrderBy(i => i.brandDesc)
.Distinct()
.ToList();
return m;
}
}
But I don't know how to select distinct brandDesc in the above function (as in the previous function). I am simply using Distinct(). Is it right? or is there any other way to achieve it? Also, if there was 'case' in query in my old function (i.e the first one above) then how will i convert it to linq in the second function. Any other things to worry about while converting to linq?
Put a .Select(i => i.brandDesc) just before each Distinct call. You'll also need to change your List<x> so x is whatever the type of brandDesc is.
If I were to refactor you whole method, I'd do something like the following. I've pulled out code that is common to both forms of the query, and tweaked in a couple of other places.
public static IList<string/* I assume*/>GetUpodBrandList(
string criteria, string locationId)
{
// only do this once, not once per item.
int locatId = Convert.ToInt32(locationId);
using (var db = UpodDatabaseHelper.GetUpodDataContext())
{
db.ObjectTrackingEnabled = false;
// This is a common start to both versions of the query.
var query = db.arabia_upod_item_masters
.Where(i => i.locationId == locatId);
// This only applies to one version of the query.
if (criteria != "")
{
query = query.Where(i => i.brandDesc.Contains(criteria));
}
// This is a common end to both version of the query.
return query
.Select(i => i.brandDesc)
.Distinct()
// Do the ordering after the distinct as it will
// presumably take less effort?
.OrderBy(i => i.brandDesc)
.ToList();
}
}

Date fiIter Issues in LINQ

I have an ASPX page that collects 5 optional search criteria from a user and returns the result in a grid. Once the criteria are collected and the view button clicked, the code behind generates the filter like we have below
// aSearchCriteria is a class that holds the criteria
...
string filter = string.Empty;
if (!string.IsNullOrEmpty(aSearchCriteria.RegistrationNumber)) filter =
"f.BusinessRegistrationNumber = '" +
aSearchCriteria.BusinessRegistrationNumber + "'";
if (aSearchCriteria.ChangedStartDate != null && aSearchCriteria.ChangedEndDate != null)
{
if (!string.IsNullOrEmpty(filter))
{
filter += " && f.ChangedDate >= '" +
aSearchCriteria.ChangedStartDate.ToShortDateString() +
"' && f.ChangedDate <= '" +
aSearchCriteria.ChangedEndDate.ToShortDateString() + "'";
}
else
{
...
}
}
...
Using (CustomerEntities db = new CustomerEntities())
{
if (!string.IsNullOrEmpty(filter))
{
filter = "f => " + filter;
**return db.Customers.Where(filter).ToList();**
}
else
...
}
...
Sample:
"filter" value: f => f.ChangedDate > '01/01/2012' && f.ChangedDate < '14/01/2012'
Anytime I execute this I get this error message:
The query syntax is not valid. Near term '>', line 6, column 5.
you don't want to make the filter a string. What you should do instead is apply the filtering to the IQueryable you get. Something like:
var customers = db.Customers.AsQueryable();
if (aSearchCriteria.ChangedStartDate != null && aSearchCriteria.ChangedEndDate != null)
{
customers = customers
.Where(c => c.ChangedDate >= aSearchCriteria.ChangedStartDate &&
c.ChangedDate >= aSearchCriteria.ChangedEndDate);
}
// ... apply other filters as necessary
return customers.ToList();
Assuming you are using ObjectQuery.Where(string)
the string predicate should look like
"it.ChangedDate > '01/01/2012' && it.ChangedDate < '14/01/2012'"
(no f=> and the alias of the table is it)
Please confirm it helped :)

Resources