DropDownList value into Linq query where clause - asp.net

I am facing following problem. I want a search field with a DropDowList next to it, where user can pick an item for which he wants to search. I have to make it with this LINQ code not just a SQL query.
Here's my code:
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
where (m. { Here would i have the selected value from the dropdownlist. } .ToString().Contains(textboxvalue) ||
mm. { Here would i have the selected value from the dropdownlist. } .ToString().Contains(textboxvalue))
&& mm.filetype.ToString().Contains(radiobuttonvalue)
I want to put something like: "Dropdownlist.selectedvalue" into the area { Here would i have the selected value from the dropdownlist. }
I hope you guys understand my idea and problem.

I am not sure why you are doing join on in your linq statement. That is not necessary if you Linq already knows about the relationship between the objects because there is a foreign key relationship setup in the database.
What you can do is this:
var Metedata = db.Metadatas;
switch(Dropdownlist.selectedvalue)
{
case "one":
Metadata = Metadata.Where(m => m.{selected value field}.Contains(textboxvalue));
break;
case "two":
Metadata = Metadata.Where(m => m.{selected value field}.Contains(textboxvalue));
break;
//More use cases
}
I am not sure what you will be selecting out of the list when you are done, but if it involves related objects (e.g. Multimedias) then you might want to look into DataLoadOptions (LinqToSQL) or .Include() (EntityFrameworks).

Just change your sql query:
if(supportgrp.SelectedItem.Text == "All")
sql ="SELECT * FROM QlyData where Date >='" + txtstartdate.Text + "' and Date<='" + txtenddate.Text + "'";
else
sql ="SELECT * FROM QlyData where Date >='" + txtstartdate.Text + "' and Date<='" + txtenddate.Text + "' and suppgrp = '" + supportgrp.Text + "'";

Related

Pass a value from a form to a method in a view

I have a View with a data source of the shipment table. This view has a method that contains a query. This query takes a shipment id and returns the sales id from the sales line table for this shipment. This view has a computed field that is the output of the query. The computed field is then used on a form.
If I hard code the shipment id the process works correctly. My question is how do I get the shipment id dynamically from a list of shipment ids. For instance, I have a form that lists all shipments. I want to place a field next to the shipment id that contains the calculated sales id from the process above.
Bottom line: I want the first column of a grid to be a shipment id and the second column to be the sales id for the shipment in the first column.
This is an example of the method described above that contains the query:
private static server str findSalesLine()
{
WMSShipment wmsShipment;
WMSOrderTrans wmsOrderTrans;
SalesLine salesLine;
select wmsShipment
join wmsOrderTrans
where wmsShipment.shipmentId == '1040383'
&& wmsShipment.shipmentId == wmsOrderTrans.shipmentId
join salesId from salesLine
where salesLine.LineNum == wmsOrderTrans.inventTransRefLineNum
&& salesLine.SalesID == wmsOrderTrans.inventTransRefID
&& salesLine.ExternalItemId != '';
return salesLine.SalesId;
}
I would use a computed column similar to the below. I'm in a different environment than you so the SQL is not valid on my box but it should work on yours.
Add a new string computed column to your view, then set this method as the datamethod.
public static server str getSalesId()
{
tableName viewName = tableStr(testView);//name of your view
DataSourceName wmsShipmentDsName = identifierStr(WMSShipment);//change if your dsname is different on your view
str returnStr;
returnStr =
" SELECT G1.SALESID FROM SALESLINE G1 " + //don't use "T1 T2" etc as aliases on computed columns
" JOIN WMSORDERTRANS G2 ON " +
" G1.LINENUM = G2.INVENTTRANSREFLINENUM AND " +
" G1.SALESID = G2.INVENTTRANSREFID AND " +
" SALESLINE.EXTERNALITEMID <> '' " +
" WHERE G2.SHIPMENTID == " +
SysComputedColumn::returnField(viewName, wmsShipmentDsName, fieldStr(WMSShipment, ShipmentId));
return returnStr;
}
I think what you're looking for is a query range (https://msdn.microsoft.com/en-us/library/aa638454.aspx) or a display method (https://msdn.microsoft.com/en-us/library/aa595058.aspx)
Do you have any more detail or sample code?

Log row update in GridView

I have asp.net grid view with default update and select columns (they are not converted to template columns)
Now I want to record whenever a user updates a row (i have a column in table: userlog which
can be displayed in the grid view but it is readonly)
I have tried to write my own update statement in GridView_RowUpdated event
but I am not getting the thing done, I wanted to append logged in user id, with
date post stamp, at the end of existing value in userlog column
Please help, currently I am doing the following, in RowUpdated event:
string sqlEL = "Select userlog from Schedule Where rowid=" + e.Keys[0].ToString();
string tmp = dao.GetSingle(sqlEL);
if (tmp == null || tmp == String.Empty)
tmp = ".";
string sqlUp = "Update Schedule set userlog='" + tmp + "' + '"
+ LogthisUser() + "' Where rowid=" + e.Keys[0].ToString();
dao.UpdateDB(sqlUp);
it was due to the fact that readonly column was a simple bound field
and in Asp.Net if you want to limit a column value in edit mode, still showing it
to the user in normal view, then it has to be template field, with EditItemTemplate
being removed

Selected value from dropdownlist has to be tablename from linq query

I have a problem with my linq query. I want a search field (textbox) with a dropdownlist next to it. When i set the dropdownlist on "ProductID" he has to search only in the table "ProductID", And when i put it on "Productinformation", he has to search in the table "productinformation", i hope somebody understand this?
So what i want is the following query:
var textboxvalue = TextBox1.Text;
var dropdownsearch = DropDownList1.SelectedValue;
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
where (m. {{{Here i want the dropdownsearch}}} .ToString().Contains(textboxvalue) ||
mm. {{{Here i want the dropdownsearch}}} .ToString().Contains(textboxvalue))
select new
{
mm.ProductID,
mm.filename,
mm.filetype,
mm.filesize
};
So, how can i get the selected value from the dropdownlist, as a table in the query? Normally you would put m.ProductID into the query, but i want the Selected value in it, something like m.(Dropdownlist1.Selectedvalue)... or m.dropdownsearch..
Is that possible? And how?
Thanks :)
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
select new { m, mm };
var filtered = Metadata.Where("m." + dropdownsearch + " like '#0'", textboxvalue);
var filtered = Metadata.Where("mm." + dropdownsearch + " like '#0'", textboxvalue);
var result = filtered.Select(f => new
{
f.mm.ProductID,
f.mm.filename,
f.mm.filetype,
f.mm.filesize
};

Convert Linq to SQL

I have researched on the net and most result are converting from sql to linq and seldom have linq to sql.
this is the code which I want to convert to SQL :
using (CommerceEntities db = new CommerceEntities())
{
try
{
var query = (from ProductOrders in db.OrderDetails
join SelectedProducts in db.Products on ProductOrders.ProductID
equals SelectedProducts.ProductID
group ProductOrders by new
{
ProductId = SelectedProducts.ProductID,
ModelName = SelectedProducts.ModelName
} into grp
select new
{
ModelName = grp.Key.ModelName,
ProductId = grp.Key.ProductId,
Quantity = grp.Sum(o => o.Quantity)
} into orderdgrp where orderdgrp.Quantity > 0
orderby orderdgrp.Quantity descending select orderdgrp).Take(5);
RepeaterItemsList.DataSource = query;
RepeaterItemsList.DataBind();
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Load Popular Items - " +
exp.Message.ToString(), exp);
}
}
You can attempt to run the LINQ statement in LinqPad. For examples on how to use LinqPad, check the answer here.
It has a tab to show the generated SQL statement.
Here's an article on logging in LINQ to SQL. It lets you specify a TextWriter to which to send the query.
Basically, you can write something like this:
db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
... where db is your data context.
In SQL you'd write something like this (although the produced code will look a lot different, since it is auto-generated):
SELECT TOP 5 Products.ModelName, Products.ProductID, SUM(OrderDetails.Quantity) qty
FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
GROUP BY Products.ProductID, Products.ModelName
HAVING qty > 0
ORDER BY qty DESC

creating a sufficient query search sql

I am writing a query to allow a user to search on what they provide keywords in asp.net, C# and mssql:
string projectPart = null;
string categoryPart = null;
string descriptionPart = null;
if (this.Textbox_ProjectNr.Text.Trim().Length > 0)
projectPart = " AND Number='" + this.Textbox_ProjectNr.Text.Trim() + "' ";
if (this.Textbox_Category.Text.Trim().Length > 0)
categoryPart = " AND Category LIKE '%" + this.Textbox_Category.Text.Trim() + "%' ";
if (this.Textbox_pDescription.Text.Trim().Length > 0)
descriptionPart = " AND ProductDescription LIKE '%" + this.Textbox_pDescription.Text.Trim() + "%' ";
string query = "SELECT * from Project = p.ID " + projectPart + descriptionPart + categoryPart;
I dont know whether this query is sufficient for a traditional query search. Because I see there are some bottlenecks of this search:
if the user does not type anything, it returns all of the data => For this I only do the query when one of the fields are filled.
if the user provides some keywords "P" for each field, the result will be millions of data.
I dont know how to improve the search query basically. any suggestions are appreciated.
Thanks in adavance.
The most important improvement is to protect you code against SQL injection attacks.
You should not concatenate the raw input in the SQL string. If someone searches for the following text for example:
Bwah ha ha'; DROP DATABASE northwind; PRINT'
This will be added to your query to produce
SELECT *
FROM mytable
WHERE category LIKE '%Bwah ha ha'; DROP DATABASE northwind; PRINT'%'
This is a valid SQL command and will happily execute and drop your database (or do anything else the attacker wants)
For more information see SQL Injection and Santitizng Inputs.
You must make this query injection proof! Do not concatenate user entered values, but use parameters, like this:
SqlCommand cmd = new SqlCommand(#"
SELECT * from Project
WHERE
( Number = #Number OR #Number IS NULL ) AND
( Category LIKE #Category OR #Category IS NULL ) AND
( ProductDescription LIKE #ProductDescription OR #ProductDescription IS NULL )", conn);
if(!String.IsNullOrEmpty(this.Textbox_ProjectNr.Text.Trim()))
cmd.Parameters.AddWithValue("#Number", this.Textbox_ProjectNr.Text.Trim());
if(!String.IsNullOrEmpty(this.Textbox_Category.Text.Trim()))
cmd.Parameters.AddWithValue("#Category", this.Textbox_Category.Text.Trim());
if(!String.IsNullOrEmpty(this.Textbox_pDescription.Text.Trim()))
cmd.Parameters.AddWithValue("#ProductDescription", this.Textbox_pDescription.Text.Trim());
Also, you can add some client validation on user entered values. For instance, ask for more than three (?) characaters before running that query.
<asp:TextBox ID="Textbox_ProjectNr" runat="server" />
<asp:RegularExpressionValidator ID="Textbox_ProjectNr_Validator" runat="server"
ControlToValidate="Textbox_ProjectNr"
ErrorMessage="Minimum length is 3"
ValidationExpression=".{3,}" />
First of all, you must protect yourself from sql injections. You haven't specified what connection to the database you are using but most libraries allow adding the parameters in a different field, so they are sanitized automatically.
Secondly, you can (and should) limit the results count using the "LIMIT" (for mysql) or "TOP X" Like so:
Select * from TableName LIMIT 100 or Select TOP 100 * from TableName

Resources