new operator returning null - C# - c#

I have this code:
public ObjectModel.Path GetPath(int pathid)
{
var path = this.DbContext.Paths.Find(pathid);
var app = GetApplicationById(path.ApplicationId.GetValueOrDefault());
var p = new Path
{
ApplicationId = path.ApplicationId,
Id = path.Id, Password = path.Password,
UserName = path.UserName,
LocalUrl = string.IsNullOrEmpty(path.LocalUrl) ? null : System.IO.Path.Combine(path.LocalUrl, app.Name)
};
return p;
}
The variable p is always null. How is this posible?
Here is a print screen of what I am talking about:
I also try with immediate windows I got this:
p CANNOT BE NULL since im creating a new instance of it while all of its properties are not null. I tried clean the project, restart windows, open visual studio as administrator and nothing happened.
Any idea why?
The application is running on .net 4.0, visual studio 2017 v15.2(26430.13) relase.

Your variable is not null.
Debugger by default try to display content of ToString() method when it's overloaded. In this case it's displaying (propably) Uri or FtpUrl value which is null.
Try to click little triangle on your variable when you hover it then you will see full contents of the variable.

Related

New to c# need to understand How can I Fix this error? "Possible null reference return" I've tried every option in visual studio and nothing fixed it

Learning C# should this be fixed or left alone? I can't seem to find an answer that works every action in VS didn't resolve the issue answer's I found online I either didn't understand or failed as well. Why I am asking here.
`
public class AdventureService : IAdventureService
{
public Adventure GetInitialAdventure()
{
var basePath = $" {AppDomain.CurrentDomain.BaseDirectory}Adventures";
var initialAdventure = new Adventure();
if (File.Exists($"{basePath}\\initial.json"))
{
var directory = new DirectoryInfo(basePath);
var initialJsonFile = directory.GetFiles("initial.json");
using (StreamReader fi = File.OpenText(initialJsonFile[0].FullName))
{
initialAdventure = JsonConvert.DeserializeObject<Adventure>(fi.ReadToEnd());
}
}
return initialAdventure;
}
`
You need to decide what the method will do if the deserialize call returns null.
One option is for the method to return null, in which case you just need to change the return type:
public Adventure? GetInitialAdventure()
{
//Etc.
If you prefer that the method never return null, you could change the return statement so that it replaces a null with a new Adventure.
//Rest of method up here
return initialAdventure ?? new Adventure();
}
There are maybe other options as well but these are the basics.

How to retrieve object instance from EnvDTE.Expression?

I try to make Visual Studio Extension. It will be extension for debug. It will work at debug mode. I need get object instance from debugged application in my extension. And I do not know how to do it.
I have follow code:
var dte = (DTE)_serviceProvider.GetService(typeof(DTE));
var debugger = dte?.Debugger;
var currentMode = debugger?.CurrentMode;
if (currentMode != dbgDebugMode.dbgBreakMode) return;
var expression = debugger.GetExpression(myExpression);
myExpression contains expression for retrieve some object, for example IDbConnection.
How can I get IDbConnection in my extension-code? expression.Value has string-value.
Is that even possible?

.NET Core: why is the result of ConfigurationBuilder["Key"] null when.ConfigurationBuilder.GertChildren has elements?

I have created a windows service using .NET Core 2.1 and added a set of environment variables:
Application_key1 = Key1
Application_key2 = Key2
Application_key3 = Key3
Application_key4 = Key4
Application_key5 = Key5
I am accessing it through:
var configuration = new ConfigurationBuilder().AddEnvironmentVariables("Application_").Build();
return new ApplicationSettings
{
Key = configuration["key1"],
//Get the rest of the keys
};
Works great when I debug using my IDE. The environment variables get pulled out of my user settings just fine. When I run, the service, it doesn't pull the data reporting back a null reference exception. I then added the environment variables to the registry in HKLM/System/CurrentControlSet/services/{Service} as a REG_MULTI_SZ:
I verified that the environment variables are correctly being pulled from the registry:
if (configuration == null)
{
eventLog.WriteEntry("Configuration is null", EventLogEntryType.Warning);
}
else
{
foreach (var child in configuration.GetChildren())
{
eventLog.WriteEntry($"Key: {child.Key} Value: {child.Value}", EventLogEntryType.Warning);
}
}
It displays correctly in the event viewer. However, when I try to access the data:
var a = configuration["key1"]
the result is null. I don't really have a clue where to go next
You have to remove the spaces between the equals signs for the environment variables to the registry:
Key1 = Value1
etc.
becomes
Key1=Value1
etc.

Cannot obtain value of local or argument possibly because it has been optimized away

I am making a call to a service reference
using (FeeService.FeeSvcClient svc = new FeeService.FeeClient())
{
response = svc.Retrieve(arg);
}
However when debugging from the FeeService side, the arg parameter becomes
"Cannot obtain value of local or argument 'args' as it is not available at this instruction pointer, possibly because it has been optimized away."
but the value is really null when it was passed a two letter code. This is the definition.
public void Retrieve(Dictionary<string, string> arg, out string docVariables)
{
if (null != _calc)
_calc = null;
docVariables = string.Empty;
if (string.IsNullOrEmpty(_stateAbbreviation) == false)
{
string transType = "", vehClass = "", vehUse = "", dealType = "", purchaseStateCode = "";
arg.TryGetValue("StateCode", out purchaseStateCode);
arg.TryGetValue("trans", out transType);
arg.TryGetValue("Class", out vehClass);
arg.TryGetValue("Use", out vehUse);
arg.TryGetValue("deal", out dealType);
docVariables = Utility.GetDocument(_stateAbbreviation, transType, vehClass, vehUse, dealType, purchaseStateCode);
}
}
I have tried all six methods to turn off optimized code:
1. Checking off the optimized code in the build tab for project
properties.
2. Setting debug info mode to full in advance option of the build tab.
3. Turning off Visual Studio hosting process in the debug tab
4. Checking if the active solution configuration is in debug and not release.
5. Clean and rebuilt the solution.
6. Doesn't appear I can check if the module is optimized since this is a service reference.

Unexplained delay when assigning a string to an SPListItem field

I am using the SharePoint Object Model via a console app on the same server as the SharePoint installation, and using the following code:
SPSite MySite = new SPSite("http://server/");
SPWeb MyWeb = MySite.OpenWeb();
MyWeb.AllowUnsafeUpdates = true;
SPList MyList = MyWeb.Lists["Test"];
const string EmptyQuery = "0";
SPQuery q = new SPQuery { Query = EmptyQuery };
String Source = "Test String";
for( int i = 1; i < 1000; i++)
{
Console.WriteLine("Creating new item");
SPListItem MyItem = MyList.GetItems(q).Add();
Console.WriteLine("Created new item");
Console.WriteLine("Assigning Title Value");
MyItem["Title"] = Source.ToString();
Console.WriteLine("Assigned Title Value");
MyItem.Update();
}
I am getting a several second pause between "Assigning Title Value" and "Assigned Title Value".
When I deploy the code as a Web Part, its instantaneous, the delay only seems to be when the code is deployed as a console application.
Edit: More information! When I have more than one field being assigned, its always the first field that is slow, any subsequent assignments are as fast as expected. If I switch the order of fields around, it has no effect on the delay - the first field is always slow.
Any thoughts?
It looks like this is because you're not accessing any fields before using the setter. If you read at least one field first, you'd probably see a slight delay there, and no delay on the setter, because under the hood SetValue() calls EnsureFieldCollection(), which - if the fields for the list item haven't already been populated - has to check back to the SPList's fields collection.
Also, this is not in your code snippet, but make sure you are disposing of your SPWeb and SPSite objects when you're done. A good pattern is to use using:
using(SPSite site = new SPSite("url"))
{
using(SPWeb web = site.OpenWeb())
{
//do stuff
}
}
First of all I would suggest making use of
using (SPSite MySite = new SPSite("http://server/"))
{
using (SPWeb MyWeb = MySite.OpenWeb())
{
//do your stuff here
}
}
You can check the EnsureFieldCollection by reading all the fields of the item before updating the field. If after that your first field is updated instantly you can be pretty sure that that is the reason.
It may be a difference between Release and Debug builds, or the fact it has the debugger attatched. Try changing to a Release build, and if that doesn't work try running it without the debugger (Ctrl+F5 in Visual Studio)

Categories

Resources