NullReference When Attempting to Store in Variable's String [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have two projects in my solution: HomeworkCalendar (VB.net Windows Forms Application) and HWLib (C# .dll Class Library). In the CurrentUser class in the library I have a variable defines as HWLib.User currentUser. This comes from the User class in HWLib:
namespace HWLib
{
public class User
{
/// <summary>
/// The Name of the User
/// </summary>
public String name = null;
/// <summary>
/// The Age of the User
/// </summary>
public int age = 0;
/// <summary>
/// The School Type of the User
/// </summary>
public String school = null;
/// <summary>
/// The Amount of Classes the User
/// </summary>
public int classesCount = 0;
/// <summary>
/// The String Array that holds all the classes
/// </summary>
public string[] classes;
}
}
Here is as it is in the CurrentUser class
public class CurrentUser
{
/// <summary>
/// The current User using the program
/// </summary>
public static HWLib.User currentUser;
}
So I attempted to store the user information into this variable, but this is where I get a NullReferenceException
Try
If intClasses <= 11 Then
CurrentUser.currentUser.name = txtName.Text
CurrentUser.currentUser.classesCount = intClasses
CurrentUser.currentUser.school = cboSchool.SelectedItem
CurrentUser.currentUser.age = Convert.ToInt32(cboAge.SelectedItem)
End if
Catch exx As NullReferenceException
'It does catch! This is the issue! Why does it catch here and how do I fix it?
File.Delete(Base.filePath)
MsgBox(exx.ToString())
End Try

Well, to get it to run you'll need to initialize currentUser:
public class CurrentUser
{
/// <summary>
/// The current User using the program
/// </summary>
public static HWLib.User currentUser = new HWLib.User() ;
}
but:
Why do you have a non-static class with just a static property? Just make CurrentUser static
It is a better practice to use properties (with getters/setters) instead of fields. THat allows you to add logic to the get/set without breaking client code.

Related

Avoid non-readonly static fields - Immutability NDepend

I am using NDepend for code analysis and got this warning:
https://www.ndepend.com/default-rules/NDepend-Rules-Explorer.html?ruleid=ND1901#!
This rule warns about static fields that are not declared as read-only.
In Object-Oriented-Programming the natural artifact to hold states that can be modified is instance fields. Such mutable static fields create confusion about the expected state at runtime and impairs the code testability since the same mutable state is re-used for each test.
My code is as follows:
using Cosmonaut;
using Microsoft.Azure.Documents.Client;
using System.Configuration;
using LuloWebApi.Entities;
namespace LuloWebApi.Components
{
/// <summary>
/// Main class that encapsulates the creation of instances to connecto to Cosmos DB
/// </summary>
public sealed class CosmosStoreHolder
{
/// <summary>
/// Property to be initiated only once in the constructor (singleton)
/// </summary>
private static CosmosStoreHolder instance = null;
/// <summary>
/// To block multiple instance creation
/// </summary>
private static readonly object padlock = new object();
/// <summary>
/// CosmosStore object to get tenants information
/// </summary>
public Cosmonaut.ICosmosStore<SharepointTenant> CosmosStoreTenant { get; }
/// <summary>
/// CosmosStore object to get site collection information
/// </summary>
public Cosmonaut.ICosmosStore<SiteCollection> CosmosStoreSiteCollection { get; }
/// <summary>
/// CosmosStore object to get page templates information
/// </summary>
public Cosmonaut.ICosmosStore<PageTemplate> CosmosStorePageTemplate { get; }
/// <summary>
/// CosmosStore object to get pages information
/// </summary>
public Cosmonaut.ICosmosStore<Page> CosmosStorePage { get; }
/// <summary>
/// CosmosStore object to get roles information
/// </summary>
public Cosmonaut.ICosmosStore<Role> CosmosStoreRole { get; }
/// <summary>
/// CosmosStore object to get clients information
/// </summary>
public Cosmonaut.ICosmosStore<Client> CosmosStoreClient { get; }
/// <summary>
/// CosmosStore object to get users information
/// </summary>
public Cosmonaut.ICosmosStore<User> CosmosStoreUser { get; }
/// <summary>
/// CosmosStore object to get partners information
/// </summary>
public Cosmonaut.ICosmosStore<Partner> CosmosStorePartner { get; }
/// <summary>
/// CosmosStore object to get super administrators information
/// </summary>
public Cosmonaut.ICosmosStore<SuperAdministrator> CosmosStoreSuperAdministrator { get; }
/// <summary>
/// Constructor
/// </summary>
CosmosStoreHolder()
{
CosmosStoreSettings settings = new Cosmonaut.CosmosStoreSettings(ConfigurationManager.AppSettings["database"].ToString(),
ConfigurationManager.AppSettings["endpoint"].ToString(),
ConfigurationManager.AppSettings["authKey"].ToString());
settings.ConnectionPolicy = new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp
};
CosmosStoreTenant = new CosmosStore<SharepointTenant>(settings);
CosmosStoreSiteCollection = new CosmosStore<SiteCollection>(settings);
CosmosStorePageTemplate = new CosmosStore<PageTemplate>(settings);
CosmosStorePage = new CosmosStore<Page>(settings);
CosmosStoreRole = new CosmosStore<Role>(settings);
CosmosStoreClient = new CosmosStore<Client>(settings);
CosmosStoreUser = new CosmosStore<User>(settings);
CosmosStorePartner = new CosmosStore<Partner>(settings);
CosmosStoreSuperAdministrator = new CosmosStore<SuperAdministrator>(settings);
}
/// <summary>
/// Instance access, singleton
/// </summary>
public static CosmosStoreHolder Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new CosmosStoreHolder();
}
return instance;
}
}
}
}
}
However I am not sure how to fix this warning.
This is a guide, not a hard rule. Usually, non-readonly static fields are hard to intuit about. But in this case you're doing lazy deferred loading, so... a lock and mutate is indeed one way of achieving that, without causing it to be loaded prematurely.
So a pragmatic fix is: just ignore/override the warning
Another approach, however, is to move the field to another type where it is readonly, and rely on the deferred .cctor semantics:
public static CosmosStoreHolder Instance {
[MethodImpl(MethodImplOptions.NoInlining)]
get => DeferredHolder.Instance;
}
private static class DeferredHolder {
internal static readonly CosmosStoreHolder Instance = new CosmosStoreHolder();
}
Then you don't even need the lock semantics (.cctor deals with that for you).

How do I create an interactive Powershell instance from C#?

I have a Powershell script that requires user interaction. I can call powershell.exe from C# using System.Diagnostics.Process and pass the scripts path as a parameter but I would like the script to be an embedded resource of the project. I tried creating a Runspace (see below) and running the script but because the script requires user interaction I receive an exception.
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "mynamespace.myscriptfile.ps1";
string result = "";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
Console.WriteLine(result);
}
//Create Powershell Runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(result);
// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
runspace.Close();
Console.ReadKey();
Is there a way to either pass the embedded resource to powershell.exe using System.Diagnostics.Process or is there a way to Invoke the script from C# where the user can interact?
UPDATE:
It seems to me that I may be able to use an implementation of the abstract class PSHost along with using the PSHostUserInterface property correctly, I may be able to create a Runspace that takes the PSHost implementation as a parameter to use the native Powershell console. I have been trying to test the idea but I'm not quite sure how to implement the abstract class.
Below is a sample of code that I obtained from Microsoft. I am confused with a couple of things. If it matters I will be creating the Runspace in a console application with a namespace called: WebRequirements in the Program class.
private Host01 program; (Would Host01 be Program?)
PSHostUserInterface (Is this where I would dictate that I want to use a native Powershell host and if so how would I do that?)
internal class MyHost : PSHost
{
///
/// A reference to the PSHost implementation.
///
private Host01 program;
/// <summary>
/// The culture information of the thread that created
/// this object.
/// </summary>
private CultureInfo originalCultureInfo =
System.Threading.Thread.CurrentThread.CurrentCulture;
/// <summary>
/// The UI culture information of the thread that created
/// this object.
/// </summary>
private CultureInfo originalUICultureInfo =
System.Threading.Thread.CurrentThread.CurrentUICulture;
/// <summary>
/// The identifier of this PSHost implementation.
/// </summary>
private Guid myId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the MyHost class. Keep
/// a reference to the host application object so that it
/// can be informed of when to exit.
/// </summary>
/// <param name="program">
/// A reference to the host application object.
/// </param>
public MyHost(Host01 program)
{
this.program = program;
}
/// <summary>
/// Return the culture information to use. This implementation
/// returns a snapshot of the culture information of the thread
/// that created this object.
/// </summary>
public override System.Globalization.CultureInfo CurrentCulture
{
get { return this.originalCultureInfo; }
}
/// <summary>
/// Return the UI culture information to use. This implementation
/// returns a snapshot of the UI culture information of the thread
/// that created this object.
/// </summary>
public override System.Globalization.CultureInfo CurrentUICulture
{
get { return this.originalUICultureInfo; }
}
/// <summary>
/// This implementation always returns the GUID allocated at
/// instantiation time.
/// </summary>
public override Guid InstanceId
{
get { return this.myId; }
}
/// <summary>
/// Return a string that contains the name of the host implementation.
/// Keep in mind that this string may be used by script writers to
/// identify when your host is being used.
/// </summary>
public override string Name
{
get { return "MySampleConsoleHostImplementation"; }
}
/// <summary>
/// This sample does not implement a PSHostUserInterface component so
/// this property simply returns null.
/// </summary>
public override PSHostUserInterface UI
{
get { return null; }
}
/// <summary>
/// Return the version object for this application. Typically this
/// should match the version resource in the application.
/// </summary>
public override Version Version
{
get { return new Version(1, 0, 0, 0); }
}
/// <summary>
/// Not implemented by this example class. The call fails with
/// a NotImplementedException exception.
/// </summary>
public override void EnterNestedPrompt()
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
/// <summary>
/// Not implemented by this example class. The call fails
/// with a NotImplementedException exception.
/// </summary>
public override void ExitNestedPrompt()
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
/// <summary>
/// This API is called before an external application process is
/// started. Typically it is used to save state so the parent can
/// restore state that has been modified by a child process (after
/// the child exits). In this example, this functionality is not
/// needed so the method returns nothing.
/// </summary>
public override void NotifyBeginApplication()
{
return;
}
/// <summary>
/// This API is called after an external application process finishes.
/// Typically it is used to restore state that a child process may
/// have altered. In this example, this functionality is not
/// needed so the method returns nothing.
/// </summary>
public override void NotifyEndApplication()
{
return;
}
/// <summary>
/// Indicate to the host application that exit has
/// been requested. Pass the exit code that the host
/// application should use when exiting the process.
/// </summary>
/// <param name="exitCode">The exit code to use.</param>
public override void SetShouldExit(int exitCode)
{
this.program.ShouldExit = true;
this.program.ExitCode = exitCode;
}
}

C# Custom Code Coverage Integration in Visual Studio 2013

I would like to enhance efficiency in our software department by providing a VS extension or add in to perform custom code coverage using VS 2013.
The special point in that enterprise is the coverage of special code snippet actually marked by a comment like //INDISPENSABLE_STUFF document comment that is defined as a task token.
I was thinking of introducing a new attribute RiskAttribute to qualify methods for instance but could not separate the corresponding code coverage result from the rest for reporting how much of the indispensable stuff has been covered.
/// <summary>
/// Risk Attribute
/// </summary>
public class RiskAttribute : Attribute
{
private readonly string _document;
private readonly string _comment;
/// <summary>
/// Constructor
/// </summary>
/// <param name="doc"></param>
/// <param name="comment"></param>
public RiskAttribute(string doc, string comment)
{
_document = doc;
_comment = comment;
}
/// <summary>
/// Document
/// </summary>
public string Document { get { return _document; } }
/// <summary>
/// Comment
/// </summary>
public string Comment { get { return _comment; } }
}
I turned to implement an add in but do not figure out in the 1. step how to launch the vs code coverage tool programmatically for a project using my add-in. The 2. step would be to customize the code coverage in order to parse the custom task token and return a result like xy% of defined task token INDISPENSABLE_STUFF is covered.
For development, I implemented a calculator class with unit test to exercise both variations:
The class
/// <summary>
/// Calculator
/// </summary>
public class Calculator
{
/// <summary>
/// Addition
/// INDISPENSABLE_STUFF (DOC #2150) Test
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static decimal Add(decimal a, decimal b) { return a + b; }
/// <summary>
/// Substraction
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[RiskAttribute("DOC #2150", "Test")]
public static decimal Sub(decimal a, decimal b) { return a - b; }
}
The unit test
/// <summary>
/// Test class for Calculator
/// </summary>
[TestClass]
public class CalculatorTest
{
/// <summary>
/// Tests addition
/// </summary>
[TestMethod]
public void Test_Sub()
{
decimal a = 1;
decimal b = 2;
Assert.AreEqual((a - b), Calculator.Sub(a, b));
}
}
So now, for the question, I already have to add-in code for the integration but miss the main content to start the customized code coverage. Does anybody know :
how to adapt the code coverage to consider task token?
how to start the code coverage programmatically?
Sorry if these are "big" points for only "one" question.
Thanks

Is there any difference between Cache.Insert("Key", "Value") and Cache["Key"] = "Value"? [duplicate]

This question already has answers here:
ASP.NET cache add vs insert
(3 answers)
Closed 9 years ago.
I know the difference between Cache.Insert and Cache.Add, but what about Cache["Key"] = "Value"?
According to the documentation of the Cache.Item property, there is no difference:
REMARKS:
You can use this property to retrieve the value of a specified cache item, or to add an item and a key for it to the cache. Adding a cache item using the Item property is equivalent to calling the Cache.Insert method.
(emphasis is mine).
Here is an example of writing a very simple wrapper (in response to comment Is there any difference between Cache.Insert("Key", "Value") and Cache["Key"] = "Value"?) for setting the defaults when adding items to the cache using the index methods. This is very basic.
public class CacheHandler
{
/// <summary>
/// static cache dependencies
/// </summary>
readonly static CacheDependency dependecies = null;
/// <summary>
/// sliding expiration
/// </summary>
readonly static TimeSpan slidingExpiration = TimeSpan.FromMinutes(5);
/// <summary>
/// absolute expiration
/// </summary>
readonly static DateTime absoluteExpiration = System.Web.Caching.Cache.NoAbsoluteExpiration;
/// <summary>
/// private singleton
/// </summary>
static CacheHandler handler;
/// <summary>
/// gets the current cache handler
/// </summary>
public static CacheHandler Current { get { return handler ?? (handler = new CacheHandler()); } }
/// <summary>
/// private constructor
/// </summary>
private CacheHandler() { }
/// <summary>
/// Gets \ Sets objects from the cache. Setting the object will use the default settings above
/// </summary>
/// <param name="key">the cache key</param>
/// <returns>the object stored in the cache</returns>
public object this[string key]
{
get
{
if (HttpContext.Current == null)
throw new Exception("The current HTTP context is unavailable. Unable to read cached objects.");
return HttpContext.Current.Cache[key];
}
set
{
if (HttpContext.Current == null)
throw new Exception("The current HTTP context is unavailable. Unable to set the cache object.");
HttpContext.Current.Cache.Insert(key, value, dependecies, absoluteExpiration , slidingExpiration);
}
}
/// <summary>
/// the current HTTP context
/// </summary>
public Cache Context
{
get
{
if (HttpContext.Current == null)
throw new Exception("The current HTTP context is unavailable. Unable to retrive the cache context.");
return HttpContext.Current.Cache;
}
}
}
Again this is super simple and basic but requires a call to another service to insert the cache something like.
protected void Page_Load(object sender, EventArgs e)
{
CacheHandler.Current["abc"] = "123";
}
If you are just starting your application you could replace the Cache property of an ASP.Net page with your new cache handler such as.
public partial class BasePage : Page
{
protected new CacheHandler Cache
{
get { return CacheHandler.Current; }
}
}
Then all your pages can be changed to the following.
public partial class _Default : **BasePage**
{
}
And calling the cache handler is a simple as
protected void Page_Load(object sender, EventArgs e)
{
Cache["abc"] = "123";
}
Which will be your cache handler instead of the default Cache object.
These are just options and really up to you how you wish to handle your caching within your application and if this is really worth the effort.
Cheers.

Create an Xml file from an object

I work as a web developer with a web designer and we usually do like this :
- I create the system , I generate some Xml files
- the designer display the xml files with xslt
Nothing new.
My problem is that I use Xml Serialization to create my xml files, but I never use Deserialization. So I'd like to know if there is a way to avoid fix like these :
empty setter for my property
empty parameter-less constructor
implement IXmlSerializable and throw "notimplementedexception" on deserialization
do a copy of the class with public fields
Ok mis-read your question first time around! Pretty sure there is no way to avoid this. There has to be a parameterless constructor and you can't serialize readonly properties. I think your only other option is DataContractSerializer.
http://blogs.mastronardi.be/Sandro/2007/08/22/CustomXMLSerializerBasedOnReflectionForSerializingPrivateVariables.aspx
This article describes creating a custom XML serialiser so you can serialise private fields - it may take a little bit of moulding to the form that you want, but it's easier than it looks (honest!) and it's a good start to writing your own serialiser / deserialiser that will serialise exactly what you want - and doesn't care about parameterless constructors or writeable properties.
The only other solution I can think of is to make a wrapper class for every serialisable class - but I don't know how good that would be in the long run. I just get the impression it's not good.
I know you don't want to add a parameterless constructor nor setters, but that's the only way to go with using the XmlSerializer. The good news is the parameterless constructor can be private and the setters can be empty and serialization will work. See thus:
namespace Aesop.Dto
{
using System;
using System.Xml.Serialization;
/// <summary>
/// Represents an Organization ID/Name combination.
/// </summary>
[Serializable]
public sealed class Org
{
/// <summary>
/// The organization's name.
/// </summary>
private readonly string name;
/// <summary>
/// The organization's ID.
/// </summary>
private readonly int id;
/// <summary>
/// Initializes a new instance of the <see cref="Org"/> class.
/// </summary>
/// <param name="name">The organization's name.</param>
/// <param name="id">The organization's ID.</param>
public Org(string name, int id)
{
this.name = name;
this.id = id;
}
/// <summary>
/// Prevents a default instance of the <see cref="Org"/> class from
/// being created.
/// </summary>
private Org()
{
}
/// <summary>
/// Gets or sets the organization's name.
/// </summary>
/// <value>The organization's name.</value>
[XmlAttribute]
public string Name
{
get
{
return this.name;
}
set
{
}
}
/// <summary>
/// Gets or sets the organization's ID.
/// </summary>
/// <value>The organization's ID.</value>
[XmlAttribute]
public int ID
{
get
{
return this.id;
}
set
{
}
}
}
}
Ok now i understand it. I don't think there can be any way to do it with XMLSerialization.
XMLSerialization need these information to re-populate the object. It does not know that some user never deserialize data. You might have to write some code to generate XML for your objects.
class Preferences
{
private const string filePreferences = "preferences.xml";
public Preferences() { }
public static Preferences Load()
{
Preferences pref = null;
if (File.Exists(Preferences.FileFullPath))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Preferences));
using (var xmlReader = new System.Xml.XmlTextReader(Preferences.FileFullPath))
{
if (serializer.CanDeserialize(xmlReader))
{
pref = serializer.Deserialize(xmlReader) as Preferences;
}
}
}
return ((pref == null) ? new Preferences() : pref);
}
public void Save()
{
var preferencesFile = FileFullPath;
var preferencesFolder = Directory.GetParent(preferencesFile).FullName;
using (var fileStream = new FileStream(preferencesFile, FileMode.Create))
{
new System.Xml.Serialization.XmlSerializer(typeof(Preferences)).Serialize(fileStream, this);
}
}
}

Categories

Resources