Retrieve a value from SQLParameter in C# - c#

I am trying to retrieve a value from a List. The list is already filled but I keep getting an error saying Object reference not set to an instance of an object when I try to execute this code:
I created a global variable
private static readonly string _isDevItemParamName = "#DevItem";
In my method I call:
var devItem = sqlParams.Where(p => p.ParameterName == _isDevItemParamName).First();
This is where the error seems to occur when I do breakpoints.

Check sqlParams is null or contains any parameters and also use firstordefault instead of first because if the parameter is not available it should not through any exception.

Related

How to check if deserealized class members have value?

I have an initial snippet which deserealized parameters, checks for value and handles the error:
var param = js.Deserialize<int?>(jqData.Params);
if (param.HasValue)
{
resp.ReturnValue = param.Value;
}
else
{
//handle error code
}
Now, during my modification, I have changed the method to accept a list of class parameters instead of nullable integers
var param = js.Deserialize<ClassName>(jqData.Params);
Now it invalidates .HasValue and .Value methods.
My question is: How do I properly modify these two lines so it would hold the same meaning as initial if statement?
Thus far I only thought about switching to if (param != null), but I cannot think of proper equivalent to .Value.
As soon as ClassName is a class (see - a reference type) you just need to check if it is not null.
If it is not - then the variable holds a reference to an object that you use as-is.

Anonymous Type "Nullable object must have a value" Error

I am using an anonymous type to represent an object so that I can convert it into JSON format using the Json() method. Here is a sample of my code below.
The "MoviesList" variable is just a list of objects of type Objects.Movie.
var result = new List<object>();
foreach (Objects.Movie movie in MoviesList)
{
result.Add(new
{
CompletedTime = (movie.CompletedTime == null ? new Nullable<DateTime>() : movie.CompletedTime),
Genre = movie.Genre,
Title = movie.Title,
Director = movie.Director
});
}
return Json(result, JsonRequestBehavior.AllowGet);
Before, I had the code written so that the CompletedTime property in the anonymous type is equal to the CompletedTime Property in the Movie object.
However, when I ran that and there were Movie objects in MoviesList where the CompletedTime Property was null (as the movie wasn't watched and therefore not finished yet), I got a System.InvalidOperationException saying: Nullable object must have a value.
So, I tried changing it to the code I have above, and I still get the same error.
I want a null value to be there if the movie has not been finished yet but I am getting this error. Is there any way to fix this or should I try a different approach?
movie.CompletedTime is of type "DateTime?"
EDIT: Whenever I debug this code, the debugger goes into the foreach loop, and iterates. However, when it is on an iteration where an Objects.Movie object contains the property CompletedTime (movie.CompletedTime) where the value is null, it catches an error and returns me to the JsonResult type method that called the above code and returns the caught error
StackTrace is below:
at System.Nullable`1.get_Value()
at WebService.Controllers.DataController.GenerateMovieList(DateTime date, String classID) in C:\WebService\Controllers\DataController.cs:line 212
at WebService.Controllers.DataController.GetMovieList(String Date, String ClassID) in C:\WebService\Controllers\DataController.cs:line 133
After looking at your stack trace it does look like you are doing a .Value on a nullable object that does not have a value. Try changing that one line to this:
CompletedTime = movie.CompletedTime, // just pass in the nullable object as is
It would also help to include the complete methods as you have them if this is not the answer.

How to display the return value from a non static method in C#

I am working with a non static class and want to display the answer of the method to the console window.
When I change the method to static and call from Main() an error stating "Object reference not set to an instance of an object" appears.
http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k(EHNullReference);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true
Why can't you call a non-static method from a static method?
According to this article I need to create an instance of the object using the "new" keyword. My understanding is that you have to create an object for a class and not a method.
http://msdn.microsoft.com/en-us/library/ms173110.aspx
So, I created a new object but it does not return the result.
GetSingleAsset Foo = new GetSingleAsset();
Console.WriteLine(Foo);
The output just gives the name of the method.
How can I see the return value of this non static method?
public Asset GetSingleAsset()
{
var memberId = Oid.FromToken("Member:20", _context.MetaModel);
var query = new Query(memberId);
var nameAttribute = _context.MetaModel.GetAttributeDefinition("Member.Name");
var emailAttribute = _context.MetaModel.GetAttributeDefinition("Member.Email");
query.Selection.Add(nameAttribute);
query.Selection.Add(emailAttribute);
var result = _context.Services.Retrieve(query);
var member = result.Assets[0];
LogResult(member.Oid.Token,
GetValue(member.GetAttribute(nameAttribute).Value),
GetValue(member.GetAttribute(emailAttribute).Value));
return member;
}
You need to do this:
NameOfYourClass instanceOfClass = new NameOfYourClass();
Console.WriteLine(instanceOfClass.NameOfMethod());
The "answer of the method to the console window" - in this case, is an object - and if you attempt to Console.WriteLine() an object, you will only see the object type written out to the Console - not its values.
Yes, Robert is correct - GetSingleAsset() is a method, not a class - because it returns a value of 'Asset' type - a class's constructor will have no return - and Patrick is correct if you want to see (via Console output) what the return is from that particular method - if it wasn't an object.
However, since 'Asset' is an object itself, if you simply did a Console.WriteLine(Asset) it would show you what the type of Asset deviates from .. not its values. For example, "System.Collection.Asset" would be printed and not the values that you are interested in.
You will need to put a breakpoint in the code at the point of class instantiation and look through the Locals Window to see the values that type 'Asset' contains and print out exactly the values that you are interested in ... chances are what values you are actually interested in are contained within another object within the Asset class .. perhaps a for loop is in order here.

Object reference is not set into instance of an object

I am retrieving data from database table.
By giving input as 1 in
textbox1(voucherno)-->damagedetail =
web.getdamageddetail(Convert.ToInt32(voucherno.Text));
I want get branchno as output in textbox2(branchno)
branchno.Text = damagedetail.branchno.ToString();
but am getting error
Object reference is not set into instance of an object.
Check my second line.
Is second line coding correct?
damagedetail.branchno is null.
Try this:
if (damagedetail.branchno != null)
branchno.Text = damagedetail.branchno;
else
branchno.Text = "abcd";
Either your object property is not filled thus when you retrive the value "branchno" from the object the value is equal to null, or your not filling the property in your "getdamageddetail" method

passing a null datetime to reportparameter class?

How can I put a null value on datetime variable type?
I tried to make it nullable value, but I need to use it in ReportParameter() method to send it to my report but ReportParameter() constructor cannot take a nullable value and the ReportParameter() take just a string values!
The various constructor overloads for ReportParameter only take in a string or string array as acceptable input.
And the ReportParameter.Values property itself is actually a StringCollection in order to force the serialization to happen at compile time.
But you can pass a null value with string typing per this thread on Passing NULL parameter from aspx page to Report Server like this:
var rp = new ReportParameter("ServiceType_cd", new string[] { null });
Or per this question Report Viewer: Set null value to Report Parameters having allow null true, you can pass in a value like this:
string str = null;
var rp = new ReportParameter("ServiceType_cd", str));
you can create FailIfNull() extension method for this purpose. Please look here for more information about extension methods.

Categories