I have a table has 2 columns
Val1 int
Val2 int
My query very simple.
I want to get collection of record have condition (val1=Val2) ,
equivalent to (Select * from table where Val1=Val2)
I try
IDataReader rdr = new Query("Table").WHERE("Val1=Val2").ExecuteReader();
tableColl.LoadAndCloseReader(rdr);
rdr.Close();
and
..WHERE (" 'Val1=Val2' ")
..WHERE (Table.Columns.Val1,IsEqualTo,Table.Columns.Val2) //This not reguler I know
..WHERE ("Val"+'='+"Val2")
.....
any help be more apricated.
Thanks.
Unfortunately you'll need to do this as an inline query as far as I know:
TableCollection tableCollection = new InlineQuery()
.ExecuteAsCollection<TableCollection>(
"SELECT * FROM " + Table.Schema.TableName " WHERE " + Table.Columns.Val1 + " = " + Table.Columns.Val2);
was in same situation recently and came up with this:
TableCollection tablecollection = new TableCollection;
Comparison comp = Comparison.Equals;
tablecollection.Where(Table.Columns.Val1, comp, Table.Columns.Val2);
tablecollection.Load();
i found this better because i don't like inline queries. and it gives
more flexibility if you wish to allow for adhoc querying in you app.
private void CreateDynamicControls()
{
panGvHolder.Controls.Clear();
Query qry = Northwind.Product.CreateQuery();
qry.Columns.AddRange(Northwind.Product.Schema.Columns);
qry.WHERE("UnitPrice > 15").AND("UnitsInStock < 20 ");
//WHERE("UnitPrice > 15").AND("UnitsInStock < 30 ");
using (IDataReader rdr = qry.ExecuteReader())
{
Response.Write("<table>");
while (rdr.Read())
{
Response.Write("<tr>");
for (int i = 0; i < rdr.FieldCount; i++)
{
Response.Write("<td>");
Response.Write(rdr[i].ToString() + " ");
Response.Write("<td>");
} //eof for
Response.Write("</br>");
Response.Write("</tr>");
}
Response.Write("<table>");
}
} //eof method
Related
I want to compare the date from a calendarView (year-month-day) to a date stored in a database. The problem is that, while they look the same, the query does not return anything from the db.
This is the date i insert into it:
Calendar calendar = Calendar.getInstance();
String mDay = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
String mMon = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String mYear = Integer.toString(calendar.get(Calendar.YEAR));
String formattedDate = mYear + "-" + mMon + "-" + mDay;
contentValues.put(COL1, item);
contentValues.put(COL2, time);
contentValues.put(COL3, formattedDate);
It looks like this : 2019-12-5 (from log)
And this is the date i'm getting from the calendarView:
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
mDatabaseHelper = new DatabaseHelper(getContext());
String dom = Integer.toString(dayOfMonth);
String mo = Integer.toString(month + 1);
String ye = Integer.toString(year);
String date = ye + "-" + mo + "-" + dom;
Cursor data = mDatabaseHelper.getData(date);
It also looks like this: 2019-12-5 (taken from log)
And here is where i query the table:
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "=" + date;
Cursor data = db.rawQuery(query,null);
return data;
}
The query doesn't return anything.
When i try to query only the day of month it works.
Your issue is that you aren't enclosing the date in single quotes, it is therefore taken as an arithmetic expression resulting in 2019 - 12 - 05 = 2002.
Instead of :-
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "=" + date;
Cursor data = db.rawQuery(query,null);
return data;
}
Use either :-
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "=?";
Cursor data = db.rawQuery(query,new String[]{date});
return data;
}
This properly escapes/encloses the date in single quotes) and in doing so protects against SQLInjection.
or instead use :-
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME,null,COL3+"=?,new String[]{date},null,null,null);
}
This uses the query convenience method (this being the typically recommended solution). This also properly encloses strings in quotes and protects against SQL Injection as well as generating the SQL on your behalf and is therefore less prone to mistakes.
I hope this helps as I've got a filter system using a SQL database and then checking that data by a input from the user.
First thing to note is in my database I store the date as a string.
When I add the date I do it like so:
date = calendar.getTime().toString();
Then I need to get the time for the user this is done via:
private Calendar Start_filter_String;
private Calendar Stop_filter_String;
private Calendar database_cal;
String parse_string_start;
String parse_string_stop;
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
parse_string_start = "Mon"+ " "
+Month_Spinner_value+" "
+Day_Spinner_value +" "
+Hour_Spinner_value +":"
+Minute_Spinner_value+":"
+"00"+" "+"GMT"+" "
+Year_Spinner_value;
Start_filter_String.setTime(sdf.parse(parse_string_start));
Then this code below check the time you pass in. Note my SQL database is done via a cursor to data. Also my time string is stored in column 8.
try {
database_cal.setTime(sdf.parse(data.getString(8)));
} catch (ParseException e) {
e.printStackTrace();
}
if(Start_filter_String.compareTo(database_cal) == 1)
{
Log.d(TAG, "Filter: Data is not after start time");
}
if(Stop_filter_String.compareTo(database_cal) == 1)
{
Log.d(TAG, "Filter: Data is not before stop time");
}
if(Start_filter_String.compareTo(database_cal) == -1)
{
Log.d(TAG, "Filter: Data is after start time");
}
if(Stop_filter_String.compareTo(database_cal) == -1)
{
Log.d(TAG, "Filter: Data is before stop time");
}
Hope this helps
I am porting Excel Interop PivotTable code to EPPlus. I'm at a sticking point in generating a calculated field value. In Excel Interop I can do it this way:
pvt.AddDataField(pvt.PivotFields("TotalQty"), "Total Packages", XlConsolidationFunction.xlSum).NumberFormat = "###,##0";
pvt.AddDataField(pvt.PivotFields("TotalPrice"), "Total Purchases", XlConsolidationFunction.xlSum).NumberFormat = "$#,##0.00";
PivotField avg = pvt.CalculatedFields().Add("Average Price", "=TotalPrice/TotalQty", true);
avg.Orientation = XlPivotFieldOrientation.xlDataField;
avg.NumberFormat = "$###0.00";
With this the "Average Price" value on the PivotTable displays the value for TotalPrice divided by TotalQty.
But how to do it in EPPlus? I can create the "plain vanilla" data fields like so:
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
...but when it comes to calculating a value, I'm baffled. My starting point was an online example for sums like so:
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function =
OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Sum();
So I tried the following, but none of them is right:
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function =
OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Average(totPriceField, totQtyField);
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function = "TotalPrice/TotalQty";
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]) = "TotalPrice/TotalQty";
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]) = totPriceField / totQtyField;
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function =
OfficeOpenXml.Table.PivotTable.
DataFieldFunctions.Product(totPriceField/totQtyField);
None of those flailings even compile. What adjustment do I need to make, or what completely new approach do I need to take?
UPDATE
I could calculate the values and put them on the data sheet and reference it that way; but is this really the only/best way to do this?
UPDATE 2
I did that (added the vals directly to the sheet that contains the source data for the Pivot Table):
var avgCell = rawDataWorksheet.Cells[_lastRowAddedRawData + 1, 9];
if ((TotalPrice < 0.0M) || (Quantity < 1))
{
avgCell.Value = 0.0;
}
else
{
avgCell.Value = TotalPrice / Quantity;
}
var prcntgCell = rawDataWorksheet.Cells[_lastRowAddedRawData + 1, 10];
if ((TotalPrice < 0.0M) || (MonthYear == String.Empty))
{
prcntgCell.Value = 0.0;
}
else
{
prcntgCell.Value = GetPercentageOfItemForMonthYear(TotalPrice, MonthYear);
}
private double GetPercentageOfItemForMonthYear(decimal totPrice, strin
monthYear)
{
decimal totalForMonthYear = monthlySales[monthYear];
double prcntg = GetPercentageOfItem(totPrice, totalForMonthYear);
return prcntg;
}
private double GetPercentageOfItem(decimal portionOfTotal, decimal
grandTotal)
{
if ((portionOfTotal <= 0.0M) || (grandTotal <= 0.0M))
{
return 0.0;
}
if (portionOfTotal == grandTotal)
{
return 100.0;
}
double d = Convert.ToDouble(portionOfTotal)
/ Convert.ToDouble(grandTotal) * 100;
return Math.Round(d, 2);
}
...but still would like to know how that's accomplishable using calculated fields while the PivotTable is being created.
EPPlus does not currently support calculated fields in PivotTables. I used the following workaround:
using System.Linq;
using System.Xml;
using OfficeOpenXml.Table.PivotTable;
using ReflectionMagic;
public static ExcelPivotTableField AddCalculatedField(this ExcelPivotTable pivotTable, string calcFieldName, string formula)
{
var dynamicPivotTable = pivotTable.AsDynamic();
var maxIndex = pivotTable.Fields.Max(f => f.Index);
const string schemaMain = #"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var cacheTopNode = dynamicPivotTable.CacheDefinition.CacheDefinitionXml.SelectSingleNode("//d:cacheFields", dynamicPivotTable.NameSpaceManager);
cacheTopNode.SetAttribute("count", (int.Parse(cacheTopNode.GetAttribute("count")) + 1).ToString());
var cacheFieldNode = dynamicPivotTable.CacheDefinition.CacheDefinitionXml.CreateElement("cacheField", schemaMain);
cacheFieldNode.SetAttribute("name", calcFieldName);
cacheFieldNode.SetAttribute("databaseField", "0");
cacheFieldNode.SetAttribute("formula", formula);
cacheFieldNode.SetAttribute("numFmtId", "0");
cacheTopNode.AppendChild(cacheFieldNode);
var topNode = dynamicPivotTable.PivotTableXml.SelectSingleNode("//d:pivotFields", dynamicPivotTable.NameSpaceManager);
topNode.SetAttribute("count", (int.Parse(topNode.GetAttribute("count")) + 1).ToString());
XmlElement fieldNode = dynamicPivotTable.PivotTableXml.CreateElement("pivotField", schemaMain);
fieldNode.SetAttribute("compact", "0");
fieldNode.SetAttribute("outline", "0");
fieldNode.SetAttribute("showAll", "0");
fieldNode.SetAttribute("defaultSubtotal", "0");
topNode.AppendChild(fieldNode);
var excelPivotTableFieldType = typeof(ExcelPivotTableField).AsDynamicType();
var excelPivotTableField = excelPivotTableFieldType.New((XmlNamespaceManager)dynamicPivotTable.NameSpaceManager, fieldNode, (ExcelPivotTable)dynamicPivotTable, maxIndex + 1, maxIndex + 1);
excelPivotTableField.SetCacheFieldNode(cacheFieldNode);
dynamicPivotTable.Fields.AddInternal(excelPivotTableField);
return pivotTable.Fields.First(f => f.Name == calcFieldName);
}
Example usage:
var calc1 = pivotTable.AddCalculatedField("Calc1", "BCol*BCol");
var dataField = pivotTable.DataFields.Add(calc1);
dataField.Function = DataFieldFunctions.Sum;
dataField.Name = "Override Name";
I want to split up a document by quotation it's marks. I see (here) that they're able to fake this answer by adding a '\' at the beginning of the quotation mark, however in my document there are hundreds of these strings I'm trying to cut string out of, so changing that manually would be a real pain and time taker.
Here's an example of the string I'm trying to cut from:
D
And here's an example of my current code:
private function onShopTextLoaded(e:Event):void
{
shopArrayOfWebsites = e.target.data.split(/\n/);
for (var i:String in shopArrayOfWebsites)
{
trace("shopArrayOriginal: " + shopArrayOfWebsites[i]);
var arrayString:String = shopArrayOfWebsites[i].split('"' /* << that won't work */ );
trace(arrayString[1]);
//shopArrayOfWebsites[i] = arrayString[1];
}
}
private function postInShopView():void
{
var iLevel:Number = 1;
var iSection:Number = 1;
var iShop:Number = 0;
for (var i:String in shopArrayOfWebsites)
{
iShop++;
if(iShop >= 5)
{
iSection++;
iShop = 0;
}
if(iSection >= 5)
{
iLevel++;
iSection = 1;
}
var shopStringEquiv:String = "L" + iLevel.toString() + "S" + iSection.toString() + "Shop" + iShop.toString();
if(global.shopTarget == shopStringEquiv)
{
var result:uint = ExternalInterface.call("showShopFrame", shopArrayOfWebsites[i]);
}
//trace(shopStringEquiv);
//trace(shopArrayOfWebsites[i]);
}
}
I get an error of:
ReferenceError: Error #1069: Property 1 not found on String and there is no default value.
So from here I'm not quite sure how I'm able to split up this document. Any ideas? Thanks!
I am trying to change all the Business Unit references I got after importing a solution to the ones in the Acceptance environment.
QueryExpression ViewQuery = new QueryExpression("savedquery");
String[] viewArrayFields = { "name", "fetchxml" };
ViewQuery.ColumnSet = new ColumnSet(viewArrayFields);
ViewQuery.PageInfo = new PagingInfo();
ViewQuery.PageInfo.Count = 5000;
ViewQuery.PageInfo.PageNumber = 1;
ViewQuery.PageInfo.ReturnTotalRecordCount = true;
EntityCollection retrievedViews = service.RetrieveMultiple(ViewQuery);
//iterate though the values and print the right one for the current user
int oldValues = 0;
int accValuesUpdated = 0;
int prodValuesUpdated = 0;
int total = 0;
foreach (var entity in retrievedViews.Entities)
{
total++;
if (!entity.Contains("fetchxml"))
{ }
else
{
string fetchXML = entity.Attributes["fetchxml"].ToString();
for (int i = 0; i < guidDictionnary.Count; i++)
{
var entry = guidDictionnary.ElementAt(i);
if (fetchXML.Contains(entry.Key.ToString().ToUpperInvariant()))
{
Console.WriteLine(entity.Attributes["name"].ToString());
oldValues++;
if (destinationEnv.Equals("acc"))
{
accValuesUpdated++;
Console.WriteLine();
Console.WriteLine("BEFORE:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.AccGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
Console.WriteLine();
Console.WriteLine("AFTER:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
}
else
{
prodValuesUpdated++;
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.ProdGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
}
service.Update(entity);
}
}
}
}
Console.WriteLine("{0} values to be updated. {1} shall be mapped to acceptance, {2} to prod. Total = {3} : {4}", oldValues, accValuesUpdated, prodValuesUpdated, total, retrievedViews.Entities.Count);
I see that the new value is corrected, but it does not get saved. I get no error while updating the record and publishing the changes in CRM does not help.
Any hint?
According to your comments, it sounds like the value you're saving the entity as, is the value that you want it to be. I'm guessing your issue is with not publishing your change. If you don't publish it, it'll still give you the old value of the FetchXml I believe.
Try calling this method:
PublishEntity(service, "savedquery");
private void PublishEntity(IOrganizationService service, string logicalName)
{
service.Execute(new PublishXmlRequest()
{
ParameterXml = "<importexportxml>"
+ " <entities>"
+ " <entity>" + logicalName + "</entity>"
+ " </entities>"
+ "</importexportxml>"
});
}
i am newbie in c#,
i want to build query string , i do some conditions , every condition add another condition to where clause
i want something like that :
// BUILD SELECT QUERY
string where = "";
string[] where_arr = new string[];
if (condition1)
{
where_arr[index++] = " field = 5 ";
}
if (condition2)
{
where_arr[index++] = " field2 = 7 ";
}
if (where_arr.Count>0)
where = " where" + String.Join(" and ", where_arr);
string sql = "select count(*) as count from mytable " + where;
but i do not know exactly how to declare all the variables like where_arr
// BUILD SELECT QUERY
string where = "";
List<string> where_arr = new List<string>();
if (condition1)
{
where_arr.Add(" field = 5 ");
}
if (condition2)
{
where_arr.Add(" field2 = 7 ");
}
if (where_arr.Count > 0)
where = " where" + String.Join(" and ", where_arr.ToArray());
string sql = "select count(*) as count from mytable " + where;