Stored Proceedure results in Object Reference Exception - asp.net

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.

Related

Get value from dictionary based on key throws error - syncfusion schedule

In my ASP.NET (c#) application using syncfusion schedule, I am trying to get a value from a dictionary based on the key.
When I try to do that I get this error message:
System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.
This line of code (where I try to get the value of key 'Subject' and assign it to variable sSubject) throws the error:
string sSubject = list["Subject"].ToString();
Code:
public Dictionary<string, object> Arguments { get; set; }
protected void Schedule1_ServerAppointmentEdited(object sender, Syncfusion.JavaScript.Web.ScheduleEventArgs e)
{
Arguments = e.Arguments["appointment"] as Dictionary<string, object>;
dynamic list = Arguments as Dictionary<string, object>;
string sSubject = list["Subject"].ToString();
}
If I debug my code to look what's in my dictionary, I do see that key 'Subject' is present:
What am I doing wrong? How can I get value 'test subject' from key 'subject'?
Project: http://www.syncfusion.com/downloads/support/forum/119417/ze/ScheduleCRUDWithWebServices-728709208
Documentation: https://www.syncfusion.com/kb/5182/how-to-perform-the-crud-operation-in-the-schedule-control-with-webservices-datasource
Thank you
Your dictionary is inside a list, namely the 2nd element. You should access it as follows:
string sSubject = list[1]["Subject"].ToString();
This is how I finally retrieved the value of key 'subject':
Arguments = e.Arguments["appointment"] as Dictionary<string, object>;
//dynamic list = Arguments as Dictionary<string, object>;
System.Collections.ArrayList list2 = (System.Collections.ArrayList)Arguments["changed"];
Dictionary<string, object> dic = (Dictionary<string,object>)list2[0];
string sSubject2 = dic["Subject"].ToString();
Usually the server-side arguments will receive only the appointment details while performing the edit action. Can you share the details on which particular scenario, you are getting the arguments with “added” and “changed” options as depicted in your screenshot.
Regards,
Dharani

ASP.NET System.NullReferenceException: Object reference not set to an instance of an object

I have the following code
private string conn(string name)
{
return ConfigurationManager.ConnectionStrings[String.Format("{0}ConnectionString", name)].ConnectionString;
}
But I keep getting the error below on the return statement.
System.NullReferenceException: Object reference not set to an instance of an object
Can you please tell me what is wrong with this?
Your code looks for connection string named name + "ConnectionString".
It look's your web.config does not have connection string with this name.
Add connection string with generated name or change the code like this:
private string conn(string name)
{
var coll = ConfigurationManager.ConnectionStrings[String.Format("{0}ConnectionString", name)];
if (coll != null)
{
return coll.ConnectionString;
}
else
{
return null;
}
}
This error arises if connectionstring return null, means you not setup connectionstring which normally setup in web.config file under
<connectionStrings>
<add name="connectionString" connectionString="Server= (local);Database=sampledb;Trusted_Connection=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
What happens if the name passed in parameter to your method is null ??
You should look at this post, and other answers already provided on SO.

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

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.

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();
}
}

Writing my own Provider Class in ASP.NET

Note: I DON't want to write custom membership provider.
I want to write my own Provider class so I can define it in web.config and access it like Membership class.
Here is a sample of my class (it has many other static methods):
public static class MySqlHelper
{
private static string constring = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
public static int ExecuteNonQuery(string mysqlquery)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(mysqlquery, conn);
int result;
try
{
conn.Open();
result= cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
return result;
}
}
Usage: MySqlHelper.ExecuteNonQuery("select * from customers");
Now as you see I have hard-coded the name of connectionstring i.e. "MyConnString". I am planning to make it dynamic.
So I was wondering if I can make it like static built-in Membership class, where I can define the connectionStringName in web.config. This way the class can be made re-usable without always naming my connectionstring in web.config to "MyConnString".
1: I DON'T want to pass connectionstring in every static method as a parameter.
2: I must be able to access the methods similar to Membership.CreateUser i.e. static.
I am looking over the web in parallel but any inputs/guidance will help.
Edited: I have updated my code sample, to clear some confusion about issues using static class. Here is a new question I posted to clarify that. Sorry about confusion.
the only thing i can think of that meets the qualifications you laid out is to use dependency injection, a static constructor, and inject in an something like an IConnectionStringProvider. this seems like about the most convoluted thing i can think of, so you might like it. :)
edit
after reading your comment, it seems like you just want to be able to reference any connection string, but only one connection string per application. i'd say just add an element to appSettings named MySqlProviderConnection with the value being the name of the connection string you want to use.
then in your helper, check for the existence of the appsetting, get its value, and pass it in to your ConfigurationManager.ConnectionStrings call. that way your provider could use any connection you want, without changing any code.
I typically discourage sharing one SqlConnection instance across several requests. Even if you enable MARS, you can run into performance issues. I think when your connection receives a non-read command, the connection buffer will pause all current reads until the write finishes. The only thing you're really saving is the time it takes to establish a connection.
SqlConnections are pooled so you can configure the provider to have a min / max number of instances available to soliciting clients. Keep in mind this is also controlled by whatever database you're connecting to; assuming you're connecting to a SQL Server instance, SQL Server has its own maximum connections allowed setting.
Instead of allowing clients to determine when to open/close a shared SqlConnection instance, I suggest having your public members take in either a command string or command parameters. Then, similar to what your sample has suggested, open a connection from the pool and execute the command.
public IEnumerable<SqlResults> ExecuteStoredProcedure(string procedure, params SqlParameter[] parameters) {
using(SqlConnection connection = new SqlConnection(MyConnectionStringProperty)) {
try {
connection.Open();
using(SqlCommand command = new SqlCommand(procedure, connection)) {
command.CommandType = CommandType.StoredProcedure;
if(parameters != null) {
command.Parameters.AddRange(parameters);
}
// yield return to handle whatever results from proc execution
// can also consider expanding to support reader.NextResult()
using(SqlDataReader reader = command.ExecuteReader()) {
yield return new SqlResults {
Reader = reader;
};
}
}
}
finally {
if(connection.State != ConnectionState.Closed) {
connection.Close();
}
}
}
}
The sample code above is just that - a sample of a concept I use at work. The sample does now have maximized error handling but is very flexible in how results are returned and handled. The SqlResults class simply contains a SqlDataReader property and can be expanded to include errors.
As far as making any of this static, it should be fine as long as you enable a way to make a singleton instance of the provider class and continue to not have any mutable properties be shared (potentially across various requests/threads). You may want to consider some sort of IoC or Dependency Injection approach for providing the connection string given your request.
EDIT
Yield allows the caller to use the returned object before the execution context returns to the method yielding the return for continued execution. So in the sample above, a caller can do something like this:
// Since it's an IEnumerable we can handle multiple result sets
foreach(SqlResults results in MySqlHelper.ExecuteStoredProcedure(myProcedureName, new SqlParameter("myParamName", myParamValue)) {
// handle results
}
without the connection closing while we handle the results. If you notice in the sample, we have using statements for our SqlClient objects. This approach allows result set handling to be decoupled from MySqlHelper as the provider class will take care of the would-be-duplicate SQL provision code, delegate result handling to the caller, then continue with what it has to do (i.e. close the connection).
As for IoC/DI, I personally use Castle Windsor. You can inject dependency objects as properties or construction parameters. Registering an Inversion of Control container as your dependency resource manager will allow you to (among other things) return the same object when a type of resource is requested. Basically, for every caller class that needs to use MySqlHelper, you can inject the same instance when the caller class is instantiated or when the caller class references its public MySqlHelper property. I, personally, prefer constructor injection whenever possible. Also, when I say inject, I mean you don't have to worry about setting the property value as your IoC/DI does it for you (if configured properly). See here for a more in depth explanation.
As another note, the IoC/DI approach would really only come into play if your class is non-static such that each application can have its own singleton instance. If MySqlHelper is static, then you could only support one connection string unless you pass it in, which in your original question, you'd prefer not to do so. IoC/DI will allow you to use your MySqlHelper property member as if it were static though since the registered container would ensure that the property has a proper instance.
Here is the complete code of a SqlHelper that I'd used on some small projects.
But carefull with static for this kind of class. If you will use it for Web project, remember that the connection will be shared at the same instance for all users, which can cause bad problems...
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class SqlHelper
{
private SqlConnection connection;
public SqlHelper()
{
connection = new SqlConnection();
}
public void OpenConnection()
{
// Updated code getting the ConnectionString without hard naming it.
// Yes, if you have more than 1 you'll have problems... But, how many times it happens?
if (WebConfigurationManager.ConnectionStrings.Length == 0)
throw new ArgumentNullException("You need to configure the ConnectionString on your Web.config.");
else
{
connection.ConnectionString = WebConfigurationManager.ConnectionStrings[0].ConnectionString;
connection.Open();
}
}
public void CloseConnection()
{
if (connection != null && connection.State != ConnectionState.Closed)
connection.Close();
}
public DataTable ExecuteToDataTable(string sql)
{
DataTable data;
SqlCommand command = null;
SqlDataAdapter adapter = null;
try
{
if (connection.State != ConnectionState.Open)
OpenConnection();
command = new SqlCommand(sql, connection);
adapter = new SqlDataAdapter(command);
retorno = new DataTable();
adapter.Fill(data);
}
finally
{
if (command != null)
command.Dispose();
if (adapter != null)
adapter.Dispose();
CloseConnection();
}
return data;
}
public int ExecuteNonQuery(string sql)
{
SqlCommand command = null;
try
{
if (connection.State != ConnectionState.Open)
OpenConnection();
command = new SqlCommand(sql, connection);
return command.ExecuteNonQuery();
}
finally
{
if (command != null)
command.Dispose();
CloseConnection();
}
}
public object ExecuteScalar(string sql)
{
SqlCommand command = null;
try
{
if (connection.State != ConnectionState.Open)
OpenConnection();
command = new SqlCommand(sql, connection);
return command.ExecuteScalar();
}
finally
{
if (command != null)
command.Dispose();
CloseConnection();
}
}
}
Sample usage:
SqlHelper sql = new SqlHelper();
DataTable data = sql.ExecuteToDataTable("SELECT * FROM Customers");
int affected = sql.ExecuteNonQuery("INSERT Customers VALUES ('Test')");
But if you really want static (if you is on a single user enviroment), just put static on all methods.

Resources