ASP.NET RDLC: Display field from another table in tablix - asp.net

I have a ASP.NET MVC 4 project with EF. I have a ASPX Web Page to display a ReportControl for RDLC reports.
There I have 2 tables : Orders and Agents. In my report I want to display (in a Tablix) all my orders.
OrderNo | OrderDate | OrderTotal | OrderStatus | Agent
(Agent column is the name of the agent : "Agent.Name")
Q : How can I display a field(Agent.Name) from another table(Agent) in a Tablix?
if (!IsPostBack)
{
var qry = FROM o in db.Orders
//JOIN a in d.Agents on o.idAgent equals a.idAgent
SELECT o; //
ReportDataSource dataSource = new ReportDataSource("DataSetOrder_Agent", qry);
ReportViewerOrders.LocalReport.DataSources.Add(dataSource);
}

Using SP:
CREATE PROCEDURE [dbo].spAgentOrders
(
#fromdate DATE,
#todate DATE
)
AS
DECLARE #from DATE = #fromdate, #to DATE = #todate
SELECT o.orderbo, o.orderdate, o.ordervalue, o.status, a.name
FROM orders o
JOIN agent a on o.id_agent = a.id_agent
WHERE o.orderdate between #from and #to
RETURN
Update the Model, add the SP as a Function Import that returns a complex type.
2. Webform codebehind:
if (!IsPostBack)
{
//...
var qry = db.spAgentOrders(tbFrom.Text, tbTo.Text);
ReportDataSource dataSource = new ReportDataSource("DataSetOrder_Agent", qry);
ReportViewerOrders.LocalReport.DataSources.Add(dataSource);
}
Update the report's DataSource .xsd. Drag the SP from Server Explorer.

Related

how to copy data to data table in linq step by step process in linq

I am fresher in linq,So please give me the link or write step by step procedure to fill data table in linq.
here is the code
var Sql = from t1 in pitbull.ACC_APP1_QuickViews.AsEnumerable()
join t2 in pitbull.OCC_VehicleGroups.AsEnumerable()
on t1.VehicleId equals t2.VehicleID
select new
{
t1.Lat,
t1.Lon,
t1.Timestamp_GPS,
t1.Speed,
t1.Location,
t1.Status,
t1.VehicleRegNo,
t1.VehicleId,
t2.VGID,
t2.VGName
};
DataTable dt = new DataTable();enter code here
dt=Sql.copytodatatable();
//copy to datatable not support.Improve question Permalink
It is because you are creating a anonymous type using select new{ } to hold the Field objects. Try this:
var Sql = from t1 in pitbull.ACC_APP1_QuickViews.AsEnumerable()
join t2 in pitbull.OCC_VehicleGroups.AsEnumerable()
on t1.VehicleId equals t2.VehicleID
select t2;
DataTable dt = Sql.copytodatatable();

Displaying LINQ query results in a DataGridView with a DataTable

I have a function which contains a LINQ query and returns the results as a DataTable. I'm having trouble using the returned DataTable to populate a DataGridView. The query should be returning some data, but the table looks to be coming back empty. My function is as follows:
public static DataTable GetEmployeeTimesheets(int employeeId)
{
DataTable table = new DataTable();
using (PTMS_DataEntities entities = new PTMS_DataEntities())
{
var timesheets = from timesheet in entities.Timesheets
join timesheetTask in entities.Timesheet_Task
on timesheet.Id equals timesheetTask.Timesheet_Id
join task in entities.Tasks
on timesheetTask.Task_Id equals task.Id
join project in entities.Projects
on task.Project_Id equals project.Id
join department in entities.Departments
on project.Department_Id equals department.Id
where timesheet.Employee_Id == employeeId
select new
{
date = timesheet.Date,
taskName = task.Name,
projectName = project.Name,
projectDesc = project.Description,
departmentName = department.Name,
taskEstimatedHours = task.Estimated_Hours,
timesheetHours = timesheetTask.Hours
};
table.Columns.Add("date");
table.Columns.Add("taskName");
table.Columns.Add("projectName");
table.Columns.Add("projectDesc");
table.Columns.Add("departmentName");
table.Columns.Add("taskEstimatedHours");
table.Columns.Add("timesheetHours");
foreach (var item in timesheets)
{
table.Rows.Add(item.date, item.taskName, item.projectName,
item.projectDesc, item.departmentName, item.taskEstimatedHours,
item.timesheetHours);
}
}
return table;
}
The code populating the DataGridView is as follows:
TimesheetGrid.DataSource = EmployeeManager.GetEmployeeTimesheets(employeeId);
TimesheetGrid.DataBind();
Am I doing something wrong in the function / LINQ query itself, or am I just not populating the DataGridView correctly?

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

DataGrid view in asp.net is not displaying data

I want to dispaly column in datagrid view using custom query statement
but i want to send value to parametrized data in query
how can i do this ?
my code is below
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'cus0010' and a.account_number = 'acc0010'
this above code working properly in sql server 2005
but the code below which is modified as per asp.net page for grid view is not showing
any result
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'Label1.Text' and a.account_number = 'Label2.Text'
the above is placed in my custom sql query section it
is triggered by button click in my asp page or any other
idea to display it will be welcomed
Use:
string.Format("c.customer_id = '{0}' and a.account_number = '{1}'", Label1.Text, Label2.Text);
Consider this query:
string query = "insert into TestTable (Column1, Column2) values (#p1, #p2)";
p1 & p2 are parameters, in order to set the value for the parameters you need to use:
queryParameters[0] = new SqlCeParameter("p1", SqlDbType.NVarChar);
queryParameters[0].Value = Label1.Text;
queryParameters[1] = new SqlCeParameter("p2", SqlDbType.NVarChar);
queryParameters[1].Value = Label2.Text;
SqlCeCommand command = new SqlCeCommand(query);
command.Parameters.AddRange(queryParameters);
When the wizard is generating the query you need to use place holders/parameters for customer_ID and account_number and set their values by using parameters.
Edit:
In order to make the wizard create a parameter to use in the query, add a ? in the filter column in the query builder wizard.
Well, I may misunderstand, but...you are not actually sending the string 'Label1.Text' I guess? You should send the value of the textbox, something like this (if you are building the SQL as a string?):
...[SQL]... + "c.customer_id = '"+ Label1.Text + "'" ...[rest of the SQL]

asp.net Dynamic Data Site with own MetaData

I'm searching info about configuring own MetaData in asp.NET Dynamic Site.
For example. I have a table in MS Sql Server with structure shown below:
CREATE TABLE [dbo].[someTable](
[id] [int] NOT NULL,
[pname] [nvarchar](20) NULL,
[FullName] [nvarchar](50) NULL,
[age] [int] NULL)
and I there are 2 Ms Sql tables (I've created), sysTables and sysColumns.
sysTables:
ID sysTableName TableName TableDescription
1 | someTable |Persons |All Data about Persons in system
sysColumns:
ID TableName sysColumnName ColumnName ColumnDesc ColumnType MUnit
1 |someTable | sometable_pname| Name | Persona Name(ex. John)| nvarchar(20) | null
2 |someTable | sometable_Fullname| Full Name | Persona Name(ex. John Black)| nvarchar(50) | null
3 |someTable | sometable_age| age | Person age| int | null
I want that, in Details/Edit/Insert/List/ListDetails pages use as MetaData sysColumns and sysTableData. Because, for ex. in DetailsPage fullName, it is not beatiful as Full Name .
someIdea, is it possible?
thanks
Updated::
In List Page to display data from sysTables (metaData table) I've modified <h2 class="DDSubHeader"><%= tableName%></h2>.
public string tableName;
protected void Page_Init(object sender, EventArgs e)
{
table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
//added by me
uqsikDataContext sd=new uqsikDataContext();
tableName = sd.sysTables.Where(n => n.sysTableName == table.DisplayName).FirstOrDefault().TableName;
//end
GridView1.SetMetaTable(table, table.GetColumnValuesFromRoute(Context));
GridDataSource.EntityTypeName = table.EntityType.AssemblyQualifiedName;
if (table.EntityType != table.RootEntityType)
{
GridQueryExtender.Expressions.Add(new OfTypeExpression(table.EntityType));
}
}
so, what about sysColums? How can I get Data from my sysColumns table?
In a word, yes, it is possible. However, I do not believe this is a good idea. What you are really talking about is storing presentation data in your database, when really the best place to put this is in your aspx pages themselves. That being said, if you want to store data dictionary type information in your DB, I'd recommend making use of the built in sys.tables, sys.columns, and sys.types views that are built into MS SQL Server, and adding a table called ObjectDescriptions to store the display name and type.
create table ObjectDescriptions (
object_id int not null,
column_id null, --leave this column null if the record describes the table itself
ObjectDisplayName nvarchar(20),
ObjectDescription nvarchar(200)
);
Then, you could create a view based on object ID to retrieve the meta data of your table, and either directly bind or dynamically populate your asp.net FormView.
create view TableData as
select
t.name as table_name
,td.ObjectDisplayName as table_display_name
,td.ObjectDescription as table_description
,c.name as column_name
,cd.ObjectDisplayName as column_display_name
,cd.ObjectDescription as column_description
,c.column_id
,ty.name as [type_name]
,c.max_length
,c.scale
,c.[precision]
from sys.tables t
left join ObjectDescriptions td on td.object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
left join ObjectDescriptions cd on cd.column_id = c.column_id and cd.object_id = c.object_id
join sys.types ty on c.user_type_id = ty.user_type_id
EDIT:
You can then leverage this view in your ASP code by writing a class that holds your meta data about a single table, and writing a method in your DAL to retrieve an instance of this class based on object or table name. When you populate your page, the page could retrieve both the record you are looking for, as well as the table's meta-data, and bind that meta data to either grid headers (in list view) or to individual label's accompanying text boxes in single record mode.
I've found useful article, than can be used for solution my problem

Resources