Problem with Object Data Source in ASP.NET (GetData method) - asp.net

I want to create a report viewer in ASP.NET that presents to the users their data.
the data for all the users is located in the same table.
for now I created DBDataSet and in the TableAdapter there is this method
GetData(#idNumber, #userNumber)
in code behind of the screen that I want to show the report viewer I wrote:
FlightsDBDataSetTableAdapters.ReservationsTableAdapter ReservationsTableAdapter;
ReservationsTableAdapter = new FlightsDBDataSetTableAdapters.ReservationsTableAdapter();
FlightsDBDataSet.ReservationsDataTable newReservationTable;
newReservationTable = ReservationsTableAdapter.GetData(userId, userName);
ObjectDataSource1.SelectParameters.Add("userName", userName);
ObjectDataSource1.SelectParameters.Add("idNumber", userId);
when I run this I get the next error
An error has occurred during report processing. ObjectDataSource
'ObjectDataSource1' could not find a non-generic method
'GetData(idNumber, userName)' that has parameters: userName, idNumber.
SO, my question is where do I need to write the method GetData and how can I generate the report with the right data.
thanks a lot.

Try this out.
1.Create a method which will return db null if parameter is not passed in the stored procedure
public static object GetDataValue(object o)
{
if (o == null || String.Empty.Equals(o))
return DBNull.Value;
else
return o;
}
2.Create a method which will called the stored procedure and fill the dataset.
public DataSet GetspTest(string userName, string userId) {
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[2];
oParam[0] = new SqlParameter("#userName", GetDataValue(userName));
oParam[1] = new SqlParameter("#idNumber", GetDataValue(userId));
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "spTest", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
Now you add the dataset let us say 'DataSet1.xsd'
Drag and Drop the TableAdapter and it will ask you the following details
3.1 Connection String (Either Select the existing connection string or create new connection string)
3.2 Choose Command Type (Now select the existing stored Procedure, specify the stored procedure with you have create earlier to display details in the report
3.3 Choose Methods to Generate (check both Fill a Datatable and Return a datatable
3.4 Click on Next and Submit ( Now your dataset is really to use in the report)
Create a report and use this DataSet1 as datasource.

Related

Stored Proceedure results in Object Reference Exception

I have tried the following code for login check in windows programming.
My .cs file's Code is:
public DataTable logincheck(String UserName, String Password)
{
object[] param = new object[2];
param[0] = UserName;
param[1] = Password;
return SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["cn"].ConnectionString, "proc_LoginChec", param).Tables[0];
}
I am getting the object null error on the return line the error is
"Object reference not set to an instance of an object.
i dont know why this is happening.. please help me.
My App.config file is:
<add name="cn" providerName="System.Data.SqlClient" connectionString="Data Source=.; Intial Catalog=dbRam; User id=sa; Password=xyz123#"/>
If I were you I would avoid chaining your code like you have, it will be hard to debug as several object could throw an exception on that line and you wouldn't be able to pint-point which one
return SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["cn"].ConnectionString, "proc_LoginChec", param).Tables[0];
could be re-written
string connString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
DataSet ds = SqlHelper.ExecuteDataset(connString, "proc_LoginChec", param);
return ds.Tables[0];
Now, you have three lines from which exception can be thrown and you'll easily spot the culprit
Most likely cause is ExecuteDataset returning null when it finds no records.
You have no null check on the DataSet returned before accessing Tables[0].
Correct it like this:
public DataTable logincheck(String UserName, String Password)
{
DataTable dt = null;
var ds = SqlHelper.ExecuteDataset(
ConfigurationManager.ConnectionStrings["cn"].ConnectionString,
"proc_LoginChec",
param);
if(null != ds && ds.Tables.Count > 0)
dt = ds.Tables[0];
return dt;
}
Note: you will need to do null checks later too since this function returns a null if no data was found.

passing parameter to report viewer

I want to pass a parameter to my report view. I have a drop down list with values from database and a button for displaying the report after selecting an item from the drop down list.
here is the code I wrote for adding the parameter
protected void Button1_Click(object sender, EventArgs e)
{
RenderReport();
}
protected void RenderReport()
{
try
{
ServerReport serverReport = ReportViewer1.ServerReport;
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
try
{
serverReport.ReportServerUrl = new Uri("http://hedinaily-pc/Reports_HEDI");
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
serverReport.ReportPath = "~/Diagrammes/PresenceTotale.rdlc";
ReportParameter employe = new ReportParameter();
employe.Name = "Employe";
employe.Values.Add(DropDownList1.SelectedValue);
ReportViewer1.ServerReport.SetParameters( new ReportParameter[] { employe });
ReportViewer1.Visible = true;
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
}
Here is the data set of my report
When I check my log file I find this error :
The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
Can anyone tell me where doe's this error come from. I spent hours searching on google I found this LINK but I couldn't resolve it.
Try it like this...
ReportViewer1.ServerReport.ReportPath = "FooReport.rdlc";
ReportParameter[] reportParameter = new ReportParameter[2];
reportParameter[0] = new ReportParameter("fooFromDate", dateFrom.ToShortDateString());
reportParameter[1] = new ReportParameter("fooDateTo", dateTo.ToShortDateString());
ReportViewer1.ServerReport.SetParameters(reportParameter);
ReportViewer1.ServerReport.Refresh();
Also .Refresh() method must be called so that...report is displayed..
You can test with this code
ReportParameter[] yourParams = new ReportParameter[1];
yourParams [0] = new ReportParameter("Employe", DropDownList1.SelectedValue);//Adjust value
this.ReportViewer1.ServerReport.SetParameters(yourParams );
One way of doing the same is by using the Report Parameters dialog box to define parameters for a report that is processed in local mode. You can define parameters to support conditional formatting or to use in expressions or code. You cannot use the Report Parameters dialog box to map report parameters to query parameters or use them in data source filters.
So you can pass the parameters to the SP as we can do it in normal operation, by usign sqlParameters. Then execute the SP bind it to report viewer datasource.
For the "The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version." error try:
serverReport.ReportPath = "/Diagrammes/PresenceTotale";
instead of:
serverReport.ReportPath = "~/Diagrammes/PresenceTotale.rdlc";

Cannot Perform Linq-To-Sql Stored Procedures with MVC-Mini-Profiler

I am using the MVC-Mini-Profiler in my ASP.net 4.0 C# environment along with MSSQL and Linq-to-SQL. I am having an issue with using L2S with the profiler. Whenever I return new DataClassesDataContext(), it allows me to get data from L2S stored procedures. But if try to return the Mvc-Mini-Profiler ProfilesDbConnection, I can get the data from the stored procedure on the first time after I build, but then ever time after that, zero data is returned. When it returns the DataClassesDataContext using ProfiledDbConnection, I can still iterate through the Db tables, but for some reason, the stored procedures do not allow me to send/receive data. Any ideas on why this might be?
try
{
var miniProfiler = MiniProfiler.Current;
var connstring = new DataClassesDataContext().Connection.ConnectionString;
SqlConnection connection = new SqlConnection(connstring);
var profiledConnection = ProfiledDbConnection.Get(connection);
var context = new DataClassesDataContext(profiledConnection);
return context;
}
catch
{
return new DataClassesDataContext();
}

Retrieving a record from a stored procedure in asp.net

I am very new to ASP.NET so I apologize for the naive question but I was just wondering how do I retrieve the data from a stored procedure I am calling from within ASP.NET .The stored procedure is supposed to return a single row and I want to retrieve the record fields returned.
So this is what I have come up with so far
The stored Procedure
ALTER PROCEDURE dbo.StoredProcedure6
#LoginName varchar(50)
AS
SELECT username ,Password FROM dbo.Users
Where username = #LoginName
RETURN
The code to get access to the specific record within the asp.net.cs file
var user = dbcontext.returnuserdetails(txtEmailAddress.Text);
where returnuserdetails is the function I added via the model browser in Visual studio 2010
Now the question is how do I get and store the values of the username and password which are returned ?
I am working in ASP.NET 4.0 if it helps.
Thanks
if you are in 4.0 you can easily just use the LINQ to SQL stuff, no need for stored procedure here.
private void GetUser(string emailAddress){
using(DataContext dbcontext = new DataContext()){
var AppData.user = dbcontext.users
.Select(u => u.email_address == emailAddress).SingleOrDefault();
// access entity properties as needed
// user.email_address, user.first_name, etc..
}
}
That said you aren't really stating what it is you are trying to do with the user entity and passwords should NEVER be stored as plain text.
if you are forced to use Stored Procedures then the return in LINQ-to-SQL will always be a set.
ALTER PROCEDURE dbo.ReturnUserDetails
#LoginName varchar(50)
AS
SELECT * -- Get whole row so you have all info that is possibly needed
FROM dbo.Users
Where username = #LoginName
RETURN
C# Code
private void GetUser(string userName){
using(DataContext dbcontext = new DataContext()){
var user = dbcontext.ReturnUserDetails(userName).SingleOrDefault();
// access entity properties as needed
string userName = user.username;
var password = user.Password;
}
}
Use SqlDataReader Class
Edit:
This is a code sample from the link, now the difference between this sample and your case is that you should specify you command type as StoredProcedure.
If it still doesn't help let me know.
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}

Storing data from database in static property

I have got an ASP.Net website, where the data is brought in from ISeries.
The data connection to ISeries is quite slow and the speed is quite important for this website. Because of the slow speed of data retrieval from ISeries, I want to make as less database connections as possible.
So, I was thinking about storing tables from the database which rarely changes as static properties in my website. Whenevera user logs in I submit a thread which refreshes the data in the static property.
Is this approach correct? If not, what are the problems with this approach and what are the possible alternatives?
Example:-
For list of ports, I submit the below thread when user logs on:-
// Get Ports list
Thread threadPorts = new Thread(delegate()
{
Ports.getPortList();
});
threadPorts.Start();
Session["threadPorts"] = threadPorts;
In class Ports, there are 2 methods -
one for populating the static property PortList,
and the other checks if the thread is alive and waits for the thread to complete and retrieve the list of ports, once it is complete. The second method is the one which I use in my application whenever I need the list of ports (populating a dropdown, etc).
public static void getPortList()
{
DataTable dt = new DataTable();
DB2Connection conn = new DB2Connection(ConfigurationManager.ConnectionStrings["db2IBM"].ConnectionString);
conn.Open();
string query = query to get ports from ISeries;
DB2Command cmd = new DB2Command(query, conn);
cmd.CommandType = CommandType.Text;
DB2DataAdapter adp = new DB2DataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
conn.Close();
List<Port> list = new List<Port>();
foreach (DataRow row in dt.Rows)
{
list.Add(new Port(row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString()));
}
StaticProp.PortList = list;
}
public static List<Port> getPortListfromSession()
{
List<Port> portList = new List<Port>();
if (System.Web.HttpContext.Current.Session["threadPorts"] != null)
{
Thread t = (Thread)System.Web.HttpContext.Current.Session["threadPorts"];
if (t != null)
{
if (t.IsAlive)
{
t.Join();
}
}
}
if (System.Web.HttpContext.Current.Session["threadPorts"] != null)
System.Web.HttpContext.Current.Session.Remove("threadPorts");
portList = StaticProp.PortList;
return portList;
}
I take it that ISeries, is an external database!
Why not take data from that database and stick it in your own, and update it separately?
You can then query your own database quickly, and update your database, as often as you see fit, alternatively you can use a file, I personally my preferred file data format is Json, over XML - but database is much better.

Resources